Exporter.php 16 KB

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