Exporter.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Component\VarExporter\Internal;
  11. use Symfony\Component\VarExporter\Exception\NotInstantiableTypeException;
  12. /**
  13. * @author Nicolas Grekas <p@tchwork.com>
  14. *
  15. * @internal
  16. */
  17. class Exporter
  18. {
  19. /**
  20. * Prepares an array of values for VarExporter.
  21. *
  22. * For performance this method is public and has no type-hints.
  23. *
  24. * @param array &$values
  25. * @param \SplObjectStorage $objectsPool
  26. * @param array &$refsPool
  27. * @param int &$objectsCount
  28. * @param bool &$valuesAreStatic
  29. *
  30. * @return array
  31. *
  32. * @throws NotInstantiableTypeException When a value cannot be serialized
  33. */
  34. public static function prepare($values, $objectsPool, &$refsPool, &$objectsCount, &$valuesAreStatic)
  35. {
  36. $refs = $values;
  37. foreach ($values as $k => $value) {
  38. if (\is_resource($value)) {
  39. throw new NotInstantiableTypeException(get_resource_type($value).' resource');
  40. }
  41. $refs[$k] = $objectsPool;
  42. if ($isRef = !$valueIsStatic = $values[$k] !== $objectsPool) {
  43. $values[$k] = &$value; // Break hard references to make $values completely
  44. unset($value); // independent from the original structure
  45. $refs[$k] = $value = $values[$k];
  46. if ($value instanceof Reference && 0 > $value->id) {
  47. $valuesAreStatic = false;
  48. ++$value->count;
  49. continue;
  50. }
  51. $refsPool[] = [&$refs[$k], $value, &$value];
  52. $refs[$k] = $values[$k] = new Reference(-\count($refsPool), $value);
  53. }
  54. if (\is_array($value)) {
  55. if ($value) {
  56. $value = self::prepare($value, $objectsPool, $refsPool, $objectsCount, $valueIsStatic);
  57. }
  58. goto handle_value;
  59. } elseif (!\is_object($value) && !$value instanceof \__PHP_Incomplete_Class || $value instanceof \UnitEnum) {
  60. goto handle_value;
  61. }
  62. $valueIsStatic = false;
  63. if (isset($objectsPool[$value])) {
  64. ++$objectsCount;
  65. $value = new Reference($objectsPool[$value][0]);
  66. goto handle_value;
  67. }
  68. $class = \get_class($value);
  69. $reflector = Registry::$reflectors[$class] ?? Registry::getClassReflector($class);
  70. if ($reflector->hasMethod('__serialize')) {
  71. if (!$reflector->getMethod('__serialize')->isPublic()) {
  72. throw new \Error(sprintf('Call to %s method "%s::__serialize()".', $reflector->getMethod('__serialize')->isProtected() ? 'protected' : 'private', $class));
  73. }
  74. if (!\is_array($properties = $value->__serialize())) {
  75. throw new \TypeError($class.'::__serialize() must return an array');
  76. }
  77. goto prepare_value;
  78. }
  79. $properties = [];
  80. $sleep = null;
  81. $proto = Registry::$prototypes[$class];
  82. if (($value instanceof \ArrayIterator || $value instanceof \ArrayObject) && null !== $proto) {
  83. // ArrayIterator and ArrayObject need special care because their "flags"
  84. // option changes the behavior of the (array) casting operator.
  85. [$arrayValue, $properties] = self::getArrayObjectProperties($value, $proto);
  86. // populates Registry::$prototypes[$class] with a new instance
  87. Registry::getClassReflector($class, Registry::$instantiableWithoutConstructor[$class], Registry::$cloneable[$class]);
  88. } elseif ($value instanceof \SplObjectStorage && Registry::$cloneable[$class] && null !== $proto) {
  89. // By implementing Serializable, SplObjectStorage breaks
  90. // internal references; let's deal with it on our own.
  91. foreach (clone $value as $v) {
  92. $properties[] = $v;
  93. $properties[] = $value[$v];
  94. }
  95. $properties = ['SplObjectStorage' => ["\0" => $properties]];
  96. $arrayValue = (array) $value;
  97. } elseif ($value instanceof \Serializable
  98. || $value instanceof \__PHP_Incomplete_Class
  99. || $value instanceof \DatePeriod
  100. || (\PHP_VERSION_ID >= 80200 && (
  101. $value instanceof \DateTimeInterface
  102. || $value instanceof \DateTimeZone
  103. || $value instanceof \DateInterval
  104. ))
  105. ) {
  106. ++$objectsCount;
  107. $objectsPool[$value] = [$id = \count($objectsPool), serialize($value), [], 0];
  108. $value = new Reference($id);
  109. goto handle_value;
  110. } else {
  111. if (method_exists($class, '__sleep')) {
  112. if (!\is_array($sleep = $value->__sleep())) {
  113. trigger_error('serialize(): __sleep should return an array only containing the names of instance-variables to serialize', \E_USER_NOTICE);
  114. $value = null;
  115. goto handle_value;
  116. }
  117. $sleep = array_flip($sleep);
  118. }
  119. $arrayValue = (array) $value;
  120. }
  121. $proto = (array) $proto;
  122. foreach ($arrayValue as $name => $v) {
  123. $i = 0;
  124. $n = (string) $name;
  125. if ('' === $n || "\0" !== $n[0]) {
  126. $c = \PHP_VERSION_ID >= 80100 && $reflector->hasProperty($n) && ($p = $reflector->getProperty($n))->isReadOnly() ? $p->class : 'stdClass';
  127. } elseif ('*' === $n[1]) {
  128. $n = substr($n, 3);
  129. $c = $reflector->getProperty($n)->class;
  130. if ('Error' === $c) {
  131. $c = 'TypeError';
  132. } elseif ('Exception' === $c) {
  133. $c = 'ErrorException';
  134. }
  135. } else {
  136. $i = strpos($n, "\0", 2);
  137. $c = substr($n, 1, $i - 1);
  138. $n = substr($n, 1 + $i);
  139. }
  140. if (null !== $sleep) {
  141. if (!isset($sleep[$n]) || ($i && $c !== $class)) {
  142. continue;
  143. }
  144. $sleep[$n] = false;
  145. }
  146. if (!\array_key_exists($name, $proto) || $proto[$name] !== $v || "\x00Error\x00trace" === $name || "\x00Exception\x00trace" === $name) {
  147. $properties[$c][$n] = $v;
  148. }
  149. }
  150. if ($sleep) {
  151. foreach ($sleep as $n => $v) {
  152. if (false !== $v) {
  153. trigger_error(sprintf('serialize(): "%s" returned as member variable from __sleep() but does not exist', $n), \E_USER_NOTICE);
  154. }
  155. }
  156. }
  157. prepare_value:
  158. $objectsPool[$value] = [$id = \count($objectsPool)];
  159. $properties = self::prepare($properties, $objectsPool, $refsPool, $objectsCount, $valueIsStatic);
  160. ++$objectsCount;
  161. $objectsPool[$value] = [$id, $class, $properties, method_exists($class, '__unserialize') ? -$objectsCount : (method_exists($class, '__wakeup') ? $objectsCount : 0)];
  162. $value = new Reference($id);
  163. handle_value:
  164. if ($isRef) {
  165. unset($value); // Break the hard reference created above
  166. } elseif (!$valueIsStatic) {
  167. $values[$k] = $value;
  168. }
  169. $valuesAreStatic = $valueIsStatic && $valuesAreStatic;
  170. }
  171. return $values;
  172. }
  173. public static function export($value, $indent = '')
  174. {
  175. switch (true) {
  176. case \is_int($value) || \is_float($value): return var_export($value, true);
  177. case [] === $value: return '[]';
  178. case false === $value: return 'false';
  179. case true === $value: return 'true';
  180. case null === $value: return 'null';
  181. case '' === $value: return "''";
  182. case $value instanceof \UnitEnum: return ltrim(var_export($value, true), '\\');
  183. }
  184. if ($value instanceof Reference) {
  185. if (0 <= $value->id) {
  186. return '$o['.$value->id.']';
  187. }
  188. if (!$value->count) {
  189. return self::export($value->value, $indent);
  190. }
  191. $value = -$value->id;
  192. return '&$r['.$value.']';
  193. }
  194. $subIndent = $indent.' ';
  195. if (\is_string($value)) {
  196. $code = sprintf("'%s'", addcslashes($value, "'\\"));
  197. $code = preg_replace_callback("/((?:[\\0\\r\\n]|\u{202A}|\u{202B}|\u{202D}|\u{202E}|\u{2066}|\u{2067}|\u{2068}|\u{202C}|\u{2069})++)(.)/", function ($m) use ($subIndent) {
  198. $m[1] = sprintf('\'."%s".\'', str_replace(
  199. ["\0", "\r", "\n", "\u{202A}", "\u{202B}", "\u{202D}", "\u{202E}", "\u{2066}", "\u{2067}", "\u{2068}", "\u{202C}", "\u{2069}", '\n\\'],
  200. ['\0', '\r', '\n', '\u{202A}', '\u{202B}', '\u{202D}', '\u{202E}', '\u{2066}', '\u{2067}', '\u{2068}', '\u{202C}', '\u{2069}', '\n"'."\n".$subIndent.'."\\'],
  201. $m[1]
  202. ));
  203. if ("'" === $m[2]) {
  204. return substr($m[1], 0, -2);
  205. }
  206. if ('n".\'' === substr($m[1], -4)) {
  207. return substr_replace($m[1], "\n".$subIndent.".'".$m[2], -2);
  208. }
  209. return $m[1].$m[2];
  210. }, $code, -1, $count);
  211. if ($count && str_starts_with($code, "''.")) {
  212. $code = substr($code, 3);
  213. }
  214. return $code;
  215. }
  216. if (\is_array($value)) {
  217. $j = -1;
  218. $code = '';
  219. foreach ($value as $k => $v) {
  220. $code .= $subIndent;
  221. if (!\is_int($k) || 1 !== $k - $j) {
  222. $code .= self::export($k, $subIndent).' => ';
  223. }
  224. if (\is_int($k) && $k > $j) {
  225. $j = $k;
  226. }
  227. $code .= self::export($v, $subIndent).",\n";
  228. }
  229. return "[\n".$code.$indent.']';
  230. }
  231. if ($value instanceof Values) {
  232. $code = $subIndent."\$r = [],\n";
  233. foreach ($value->values as $k => $v) {
  234. $code .= $subIndent.'$r['.$k.'] = '.self::export($v, $subIndent).",\n";
  235. }
  236. return "[\n".$code.$indent.']';
  237. }
  238. if ($value instanceof Registry) {
  239. return self::exportRegistry($value, $indent, $subIndent);
  240. }
  241. if ($value instanceof Hydrator) {
  242. return self::exportHydrator($value, $indent, $subIndent);
  243. }
  244. throw new \UnexpectedValueException(sprintf('Cannot export value of type "%s".', \is_object($value) ? \get_class($value) : \gettype($value)));
  245. }
  246. private static function exportRegistry(Registry $value, string $indent, string $subIndent): string
  247. {
  248. $code = '';
  249. $serializables = [];
  250. $seen = [];
  251. $prototypesAccess = 0;
  252. $factoriesAccess = 0;
  253. $r = '\\'.Registry::class;
  254. $j = -1;
  255. foreach ($value->classes as $k => $class) {
  256. if (':' === ($class[1] ?? null)) {
  257. $serializables[$k] = $class;
  258. continue;
  259. }
  260. if (!Registry::$instantiableWithoutConstructor[$class]) {
  261. if (is_subclass_of($class, 'Serializable') && !method_exists($class, '__unserialize')) {
  262. $serializables[$k] = 'C:'.\strlen($class).':"'.$class.'":0:{}';
  263. } else {
  264. $serializables[$k] = 'O:'.\strlen($class).':"'.$class.'":0:{}';
  265. }
  266. if (is_subclass_of($class, 'Throwable')) {
  267. $eol = is_subclass_of($class, 'Error') ? "\0Error\0" : "\0Exception\0";
  268. $serializables[$k] = substr_replace($serializables[$k], '1:{s:'.(5 + \strlen($eol)).':"'.$eol.'trace";a:0:{}}', -4);
  269. }
  270. continue;
  271. }
  272. $code .= $subIndent.(1 !== $k - $j ? $k.' => ' : '');
  273. $j = $k;
  274. $eol = ",\n";
  275. $c = '['.self::export($class).']';
  276. if ($seen[$class] ?? false) {
  277. if (Registry::$cloneable[$class]) {
  278. ++$prototypesAccess;
  279. $code .= 'clone $p'.$c;
  280. } else {
  281. ++$factoriesAccess;
  282. $code .= '$f'.$c.'()';
  283. }
  284. } else {
  285. $seen[$class] = true;
  286. if (Registry::$cloneable[$class]) {
  287. $code .= 'clone ('.($prototypesAccess++ ? '$p' : '($p = &'.$r.'::$prototypes)').$c.' ?? '.$r.'::p';
  288. } else {
  289. $code .= '('.($factoriesAccess++ ? '$f' : '($f = &'.$r.'::$factories)').$c.' ?? '.$r.'::f';
  290. $eol = '()'.$eol;
  291. }
  292. $code .= '('.substr($c, 1, -1).'))';
  293. }
  294. $code .= $eol;
  295. }
  296. if (1 === $prototypesAccess) {
  297. $code = str_replace('($p = &'.$r.'::$prototypes)', $r.'::$prototypes', $code);
  298. }
  299. if (1 === $factoriesAccess) {
  300. $code = str_replace('($f = &'.$r.'::$factories)', $r.'::$factories', $code);
  301. }
  302. if ('' !== $code) {
  303. $code = "\n".$code.$indent;
  304. }
  305. if ($serializables) {
  306. $code = $r.'::unserialize(['.$code.'], '.self::export($serializables, $indent).')';
  307. } else {
  308. $code = '['.$code.']';
  309. }
  310. return '$o = '.$code;
  311. }
  312. private static function exportHydrator(Hydrator $value, string $indent, string $subIndent): string
  313. {
  314. $code = '';
  315. foreach ($value->properties as $class => $properties) {
  316. $code .= $subIndent.' '.self::export($class).' => '.self::export($properties, $subIndent.' ').",\n";
  317. }
  318. $code = [
  319. self::export($value->registry, $subIndent),
  320. self::export($value->values, $subIndent),
  321. '' !== $code ? "[\n".$code.$subIndent.']' : '[]',
  322. self::export($value->value, $subIndent),
  323. self::export($value->wakeups, $subIndent),
  324. ];
  325. return '\\'.\get_class($value)."::hydrate(\n".$subIndent.implode(",\n".$subIndent, $code)."\n".$indent.')';
  326. }
  327. /**
  328. * @param \ArrayIterator|\ArrayObject $value
  329. * @param \ArrayIterator|\ArrayObject $proto
  330. */
  331. private static function getArrayObjectProperties($value, $proto): array
  332. {
  333. $reflector = $value instanceof \ArrayIterator ? 'ArrayIterator' : 'ArrayObject';
  334. $reflector = Registry::$reflectors[$reflector] ?? Registry::getClassReflector($reflector);
  335. $properties = [
  336. $arrayValue = (array) $value,
  337. $reflector->getMethod('getFlags')->invoke($value),
  338. $value instanceof \ArrayObject ? $reflector->getMethod('getIteratorClass')->invoke($value) : 'ArrayIterator',
  339. ];
  340. $reflector = $reflector->getMethod('setFlags');
  341. $reflector->invoke($proto, \ArrayObject::STD_PROP_LIST);
  342. if ($properties[1] & \ArrayObject::STD_PROP_LIST) {
  343. $reflector->invoke($value, 0);
  344. $properties[0] = (array) $value;
  345. } else {
  346. $reflector->invoke($value, \ArrayObject::STD_PROP_LIST);
  347. $arrayValue = (array) $value;
  348. }
  349. $reflector->invoke($value, $properties[1]);
  350. if ([[], 0, 'ArrayIterator'] === $properties) {
  351. $properties = [];
  352. } else {
  353. if ('ArrayIterator' === $properties[2]) {
  354. unset($properties[2]);
  355. }
  356. $properties = [$reflector->class => ["\0" => $properties]];
  357. }
  358. return [$arrayValue, $properties];
  359. }
  360. }