CodeExporter.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  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. declare(strict_types=1);
  11. namespace SebastianBergmann\GlobalState;
  12. /**
  13. * Exports parts of a Snapshot as PHP code.
  14. */
  15. class CodeExporter
  16. {
  17. public function constants(Snapshot $snapshot): string
  18. {
  19. $result = '';
  20. foreach ($snapshot->constants() as $name => $value) {
  21. $result .= \sprintf(
  22. 'if (!defined(\'%s\')) define(\'%s\', %s);' . "\n",
  23. $name,
  24. $name,
  25. $this->exportVariable($value)
  26. );
  27. }
  28. return $result;
  29. }
  30. public function globalVariables(Snapshot $snapshot): string
  31. {
  32. $result = '$GLOBALS = [];' . PHP_EOL;
  33. foreach ($snapshot->globalVariables() as $name => $value) {
  34. $result .= \sprintf(
  35. '$GLOBALS[%s] = %s;' . PHP_EOL,
  36. $this->exportVariable($name),
  37. $this->exportVariable($value)
  38. );
  39. }
  40. return $result;
  41. }
  42. public function iniSettings(Snapshot $snapshot): string
  43. {
  44. $result = '';
  45. foreach ($snapshot->iniSettings() as $key => $value) {
  46. $result .= \sprintf(
  47. '@ini_set(%s, %s);' . "\n",
  48. $this->exportVariable($key),
  49. $this->exportVariable($value)
  50. );
  51. }
  52. return $result;
  53. }
  54. private function exportVariable($variable): string
  55. {
  56. if (\is_scalar($variable) || \is_null($variable) ||
  57. (\is_array($variable) && $this->arrayOnlyContainsScalars($variable))) {
  58. return \var_export($variable, true);
  59. }
  60. return 'unserialize(' . \var_export(\serialize($variable), true) . ')';
  61. }
  62. private function arrayOnlyContainsScalars(array $array): bool
  63. {
  64. $result = true;
  65. foreach ($array as $element) {
  66. if (\is_array($element)) {
  67. $result = self::arrayOnlyContainsScalars($element);
  68. } elseif (!\is_scalar($element) && !\is_null($element)) {
  69. $result = false;
  70. }
  71. if ($result === false) {
  72. break;
  73. }
  74. }
  75. return $result;
  76. }
  77. }