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