Exporter.php 18 KB

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