Exporter.php 16 KB

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