CodeExporter.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /*
  3. * This file is part of the GlobalState package.
  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. class CodeExporter
  15. {
  16. /**
  17. * @param Snapshot $snapshot
  18. * @return string
  19. */
  20. public function constants(Snapshot $snapshot)
  21. {
  22. $result = '';
  23. foreach ($snapshot->constants() as $name => $value) {
  24. $result .= sprintf(
  25. 'if (!defined(\'%s\')) define(\'%s\', %s);' . "\n",
  26. $name,
  27. $name,
  28. $this->exportVariable($value)
  29. );
  30. }
  31. return $result;
  32. }
  33. /**
  34. * @param Snapshot $snapshot
  35. * @return string
  36. */
  37. public function iniSettings(Snapshot $snapshot)
  38. {
  39. $result = '';
  40. foreach ($snapshot->iniSettings() as $key => $value) {
  41. $result .= sprintf(
  42. '@ini_set(%s, %s);' . "\n",
  43. $this->exportVariable($key),
  44. $this->exportVariable($value)
  45. );
  46. }
  47. return $result;
  48. }
  49. /**
  50. * @param mixed $variable
  51. * @return string
  52. */
  53. private function exportVariable($variable)
  54. {
  55. if (is_scalar($variable) || is_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. /**
  62. * @param array $array
  63. * @return bool
  64. */
  65. private function arrayOnlyContainsScalars(array $array)
  66. {
  67. $result = true;
  68. foreach ($array as $element) {
  69. if (is_array($element)) {
  70. $result = self::arrayOnlyContainsScalars($element);
  71. } elseif (!is_scalar($element) && !is_null($element)) {
  72. $result = false;
  73. }
  74. if ($result === false) {
  75. break;
  76. }
  77. }
  78. return $result;
  79. }
  80. }