CodeExporter.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of sebastian/global-state.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace SebastianBergmann\GlobalState;
  11. /**
  12. * Exports parts of a Snapshot as PHP code.
  13. */
  14. final class CodeExporter
  15. {
  16. public function constants(Snapshot $snapshot): string
  17. {
  18. $result = '';
  19. foreach ($snapshot->constants() as $name => $value) {
  20. $result .= \sprintf(
  21. 'if (!defined(\'%s\')) define(\'%s\', %s);' . "\n",
  22. $name,
  23. $name,
  24. $this->exportVariable($value)
  25. );
  26. }
  27. return $result;
  28. }
  29. public function globalVariables(Snapshot $snapshot): string
  30. {
  31. $result = '$GLOBALS = [];' . \PHP_EOL;
  32. foreach ($snapshot->globalVariables() as $name => $value) {
  33. $result .= \sprintf(
  34. '$GLOBALS[%s] = %s;' . \PHP_EOL,
  35. $this->exportVariable($name),
  36. $this->exportVariable($value)
  37. );
  38. }
  39. return $result;
  40. }
  41. public function iniSettings(Snapshot $snapshot): string
  42. {
  43. $result = '';
  44. foreach ($snapshot->iniSettings() as $key => $value) {
  45. $result .= \sprintf(
  46. '@ini_set(%s, %s);' . "\n",
  47. $this->exportVariable($key),
  48. $this->exportVariable($value)
  49. );
  50. }
  51. return $result;
  52. }
  53. private function exportVariable($variable): string
  54. {
  55. if (\is_scalar($variable) || null === $variable ||
  56. (\is_array($variable) && $this->arrayOnlyContainsScalars($variable))) {
  57. return \var_export($variable, true);
  58. }
  59. return 'unserialize(' . \var_export(\serialize($variable), true) . ')';
  60. }
  61. private function arrayOnlyContainsScalars(array $array): bool
  62. {
  63. $result = true;
  64. foreach ($array as $element) {
  65. if (\is_array($element)) {
  66. $result = $this->arrayOnlyContainsScalars($element);
  67. } elseif (!\is_scalar($element) && null !== $element) {
  68. $result = false;
  69. }
  70. if ($result === false) {
  71. break;
  72. }
  73. }
  74. return $result;
  75. }
  76. }