ProxyHelper.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  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;
  11. use Symfony\Component\VarExporter\Exception\LogicException;
  12. use Symfony\Component\VarExporter\Internal\Hydrator;
  13. use Symfony\Component\VarExporter\Internal\LazyDecoratorTrait;
  14. use Symfony\Component\VarExporter\Internal\LazyObjectRegistry;
  15. /**
  16. * @author Nicolas Grekas <p@tchwork.com>
  17. */
  18. final class ProxyHelper
  19. {
  20. /**
  21. * Helps generate lazy-loading ghost objects.
  22. *
  23. * @deprecated since Symfony 7.3, use native lazy objects instead
  24. *
  25. * @throws LogicException When the class is incompatible with ghost objects
  26. */
  27. public static function generateLazyGhost(\ReflectionClass $class): string
  28. {
  29. if (\PHP_VERSION_ID >= 80400) {
  30. trigger_deprecation('symfony/var-exporter', '7.3', 'Using ProxyHelper::generateLazyGhost() is deprecated, use native lazy objects instead.');
  31. }
  32. if (\PHP_VERSION_ID < 80300 && $class->isReadOnly()) {
  33. throw new LogicException(\sprintf('Cannot generate lazy ghost with PHP < 8.3: class "%s" is readonly.', $class->name));
  34. }
  35. if ($class->isFinal()) {
  36. throw new LogicException(\sprintf('Cannot generate lazy ghost: class "%s" is final.', $class->name));
  37. }
  38. if ($class->isInterface() || $class->isAbstract() || $class->isTrait()) {
  39. throw new LogicException(\sprintf('Cannot generate lazy ghost: "%s" is not a concrete class.', $class->name));
  40. }
  41. if (\stdClass::class !== $class->name && $class->isInternal()) {
  42. throw new LogicException(\sprintf('Cannot generate lazy ghost: class "%s" is internal.', $class->name));
  43. }
  44. if ($class->hasMethod('__get') && 'mixed' !== (self::exportType($class->getMethod('__get')) ?? 'mixed')) {
  45. throw new LogicException(\sprintf('Cannot generate lazy ghost: return type of method "%s::__get()" should be "mixed".', $class->name));
  46. }
  47. static $traitMethods;
  48. $traitMethods ??= (new \ReflectionClass(LazyGhostTrait::class))->getMethods();
  49. foreach ($traitMethods as $method) {
  50. if ($class->hasMethod($method->name) && $class->getMethod($method->name)->isFinal()) {
  51. throw new LogicException(\sprintf('Cannot generate lazy ghost: method "%s::%s()" is final.', $class->name, $method->name));
  52. }
  53. }
  54. $parent = $class;
  55. while ($parent = $parent->getParentClass()) {
  56. if (\stdClass::class !== $parent->name && $parent->isInternal()) {
  57. throw new LogicException(\sprintf('Cannot generate lazy ghost: class "%s" extends "%s" which is internal.', $class->name, $parent->name));
  58. }
  59. }
  60. $hooks = '';
  61. $propertyScopes = Hydrator::$propertyScopes[$class->name] ??= Hydrator::getPropertyScopes($class->name);
  62. foreach ($propertyScopes as $key => [$scope, $name, , $access]) {
  63. $propertyScopes[$k = "\0$scope\0$name"] ?? $propertyScopes[$k = "\0*\0$name"] ?? $k = $name;
  64. $flags = $access >> 2;
  65. if ($k !== $key || !($access & Hydrator::PROPERTY_HAS_HOOKS) || $flags & \ReflectionProperty::IS_VIRTUAL) {
  66. continue;
  67. }
  68. if ($flags & (\ReflectionProperty::IS_FINAL | \ReflectionProperty::IS_PRIVATE)) {
  69. throw new LogicException(\sprintf('Cannot generate lazy ghost: property "%s::$%s" is final or private(set).', $class->name, $name));
  70. }
  71. $p = $propertyScopes[$k][4] ?? Hydrator::$propertyScopes[$class->name][$k][4] = new \ReflectionProperty($scope, $name);
  72. $type = self::exportType($p);
  73. $hooks .= "\n "
  74. .($p->isProtected() ? 'protected' : 'public')
  75. .($p->isProtectedSet() ? ' protected(set)' : '')
  76. ." {$type} \${$name}"
  77. .($p->hasDefaultValue() ? ' = '.VarExporter::export($p->getDefaultValue()) : '')
  78. ." {\n";
  79. foreach ($p->getHooks() as $hook => $method) {
  80. if ('get' === $hook) {
  81. $ref = ($method->returnsReference() ? '&' : '');
  82. $hooks .= " {$ref}get { \$this->initializeLazyObject(); return parent::\${$name}::get(); }\n";
  83. } elseif ('set' === $hook) {
  84. $parameters = self::exportParameters($method, true);
  85. $arg = '$'.$method->getParameters()[0]->name;
  86. $hooks .= " set({$parameters}) { \$this->initializeLazyObject(); parent::\${$name}::set({$arg}); }\n";
  87. } else {
  88. throw new LogicException(\sprintf('Cannot generate lazy ghost: hook "%s::%s()" is not supported.', $class->name, $method->name));
  89. }
  90. }
  91. $hooks .= " }\n";
  92. }
  93. $propertyScopes = self::exportPropertyScopes($class->name, $propertyScopes);
  94. return <<<EOPHP
  95. extends \\{$class->name} implements \Symfony\Component\VarExporter\LazyObjectInterface
  96. {
  97. use \Symfony\Component\VarExporter\LazyGhostTrait;
  98. private const LAZY_OBJECT_PROPERTY_SCOPES = {$propertyScopes};
  99. {$hooks}}
  100. // Help opcache.preload discover always-needed symbols
  101. class_exists(\Symfony\Component\VarExporter\Internal\Hydrator::class);
  102. class_exists(\Symfony\Component\VarExporter\Internal\LazyObjectRegistry::class);
  103. class_exists(\Symfony\Component\VarExporter\Internal\LazyObjectState::class);
  104. EOPHP;
  105. }
  106. /**
  107. * Helps generate lazy-loading decorators.
  108. *
  109. * @param \ReflectionClass[] $interfaces
  110. *
  111. * @throws LogicException When the class is incompatible with virtual proxies
  112. */
  113. public static function generateLazyProxy(?\ReflectionClass $class, array $interfaces = []): string
  114. {
  115. if (!class_exists($class?->name ?? \stdClass::class, false)) {
  116. throw new LogicException(\sprintf('Cannot generate lazy proxy: "%s" is not a class.', $class->name));
  117. }
  118. if ($class?->isFinal()) {
  119. throw new LogicException(\sprintf('Cannot generate lazy proxy: class "%s" is final.', $class->name));
  120. }
  121. if (\PHP_VERSION_ID < 80400) {
  122. return self::generateLegacyLazyProxy($class, $interfaces);
  123. }
  124. if ($class && !$class->isAbstract()) {
  125. $parent = $class;
  126. do {
  127. $extendsInternalClass = $parent->isInternal();
  128. } while (!$extendsInternalClass && $parent = $parent->getParentClass());
  129. if (!$extendsInternalClass) {
  130. trigger_deprecation('symfony/var-exporter', '7.3', 'Generating lazy proxy for class "%s" is deprecated; leverage native lazy objects instead.', $class->name);
  131. // throw new LogicException(\sprintf('Cannot generate lazy proxy: leverage native lazy objects instead for class "%s".', $class->name));
  132. }
  133. }
  134. $propertyScopes = $class ? Hydrator::$propertyScopes[$class->name] ??= Hydrator::getPropertyScopes($class->name) : [];
  135. $abstractProperties = [];
  136. $hookedProperties = [];
  137. foreach ($propertyScopes as $key => [$scope, $name, , $access]) {
  138. $propertyScopes[$k = "\0$scope\0$name"] ?? $propertyScopes[$k = "\0*\0$name"] ?? $k = $name;
  139. $flags = $access >> 2;
  140. if ($k !== $key || $flags & \ReflectionProperty::IS_PRIVATE) {
  141. continue;
  142. }
  143. if ($flags & \ReflectionProperty::IS_ABSTRACT) {
  144. $abstractProperties[$name] = $propertyScopes[$k][4] ?? Hydrator::$propertyScopes[$class->name][$k][4] = new \ReflectionProperty($scope, $name);
  145. continue;
  146. }
  147. $abstractProperties[$name] = false;
  148. if (!($access & Hydrator::PROPERTY_HAS_HOOKS)) {
  149. continue;
  150. }
  151. if ($flags & \ReflectionProperty::IS_FINAL) {
  152. throw new LogicException(\sprintf('Cannot generate lazy proxy: property "%s::$%s" is final.', $class->name, $name));
  153. }
  154. $p = $propertyScopes[$k][4] ?? Hydrator::$propertyScopes[$class->name][$k][4] = new \ReflectionProperty($scope, $name);
  155. $hookedProperties[$name] = [$p, $p->getHooks()];
  156. }
  157. $methodReflectors = [$class?->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) ?? []];
  158. foreach ($interfaces as $interface) {
  159. if (!$interface->isInterface()) {
  160. throw new LogicException(\sprintf('Cannot generate lazy proxy: "%s" is not an interface.', $interface->name));
  161. }
  162. $methodReflectors[] = $interface->getMethods();
  163. foreach ($interface->getProperties() as $p) {
  164. $abstractProperties[$p->name] ??= $p;
  165. $hookedProperties[$p->name] ??= [$p, []];
  166. $hookedProperties[$p->name][1] += $p->getHooks();
  167. }
  168. }
  169. $hooks = '';
  170. foreach (array_filter($abstractProperties) as $name => $p) {
  171. $type = self::exportType($p);
  172. $hooks .= "\n "
  173. .($p->isProtected() ? 'protected' : 'public')
  174. .($p->isProtectedSet() ? ' protected(set)' : '')
  175. ." {$type} \${$name};\n";
  176. }
  177. foreach ($hookedProperties as $name => [$p, $methods]) {
  178. if ($abstractProperties[$p->name] ?? false) {
  179. continue;
  180. }
  181. $type = self::exportType($p);
  182. $hooks .= "\n "
  183. .($p->isProtected() ? 'protected' : 'public')
  184. .($p->isProtectedSet() ? ' protected(set)' : '')
  185. ." {$type} \${$name} {\n";
  186. foreach ($methods as $hook => $method) {
  187. if ('get' === $hook) {
  188. $ref = ($method->returnsReference() ? '&' : '');
  189. $hooks .= <<<EOPHP
  190. {$ref}get {
  191. return \$this->lazyObjectState->realInstance->{$p->name};
  192. }
  193. EOPHP;
  194. } elseif ('set' === $hook) {
  195. $parameters = self::exportParameters($method, true);
  196. $arg = '$'.$method->getParameters()[0]->name;
  197. $hooks .= <<<EOPHP
  198. set({$parameters}) {
  199. \$this->lazyObjectState->realInstance->{$p->name} = {$arg};
  200. }
  201. EOPHP;
  202. } else {
  203. throw new LogicException(\sprintf('Cannot generate lazy proxy: hook "%s::%s()" is not supported.', $class->name, $method->name));
  204. }
  205. }
  206. $hooks .= " }\n";
  207. }
  208. $methods = [];
  209. $methodReflectors = array_merge(...$methodReflectors);
  210. foreach ($methodReflectors as $method) {
  211. if ('__get' !== strtolower($method->name) || 'mixed' === ($type = self::exportType($method) ?? 'mixed')) {
  212. continue;
  213. }
  214. $trait = new \ReflectionMethod(LazyDecoratorTrait::class, '__get');
  215. $body = \array_slice(file($trait->getFileName()), $trait->getStartLine() - 1, $trait->getEndLine() - $trait->getStartLine());
  216. $body[0] = str_replace('): mixed', '): '.$type, $body[0]);
  217. $methods['__get'] = strtr(implode('', $body).' }', [
  218. 'Hydrator' => '\\'.Hydrator::class,
  219. 'Registry' => '\\'.LazyObjectRegistry::class,
  220. ]);
  221. break;
  222. }
  223. foreach ($methodReflectors as $method) {
  224. if (($method->isStatic() && !$method->isAbstract()) || isset($methods[$lcName = strtolower($method->name)])) {
  225. continue;
  226. }
  227. if ($method->isFinal()) {
  228. throw new LogicException(\sprintf('Cannot generate lazy proxy: method "%s::%s()" is final.', $class->name, $method->name));
  229. }
  230. if (method_exists(LazyDecoratorTrait::class, $method->name)) {
  231. continue;
  232. }
  233. $signature = self::exportSignature($method, true, $args);
  234. if ($method->isStatic()) {
  235. $body = " throw new \BadMethodCallException('Cannot forward abstract method \"{$method->class}::{$method->name}()\".');";
  236. } elseif (str_ends_with($signature, '): never') || str_ends_with($signature, '): void')) {
  237. $body = <<<EOPHP
  238. \$this->lazyObjectState->realInstance->{$method->name}({$args});
  239. EOPHP;
  240. } else {
  241. $mayReturnThis = false;
  242. foreach (preg_split('/[()|&]++/', self::exportType($method) ?? 'static') as $type) {
  243. if (\in_array($type = ltrim($type, '?'), ['static', 'object'], true)) {
  244. $mayReturnThis = true;
  245. break;
  246. }
  247. foreach ([$class, ...$interfaces] as $r) {
  248. if ($r && is_a($r->name, $type, true)) {
  249. $mayReturnThis = true;
  250. break 2;
  251. }
  252. }
  253. }
  254. if ($method->returnsReference() || !$mayReturnThis) {
  255. $body = <<<EOPHP
  256. return \$this->lazyObjectState->realInstance->{$method->name}({$args});
  257. EOPHP;
  258. } else {
  259. $body = <<<EOPHP
  260. \${0} = \$this->lazyObjectState->realInstance;
  261. \${1} = \${0}->{$method->name}({$args});
  262. return match (true) {
  263. \${1} === \${0} => \$this,
  264. !\${1} instanceof \${0} || !\${0} instanceof \${1} => \${1},
  265. null !== \$this->lazyObjectState->cloneInstance =& \${1} => clone \$this,
  266. };
  267. EOPHP;
  268. }
  269. }
  270. $methods[$lcName] = " {$signature}\n {\n{$body}\n }";
  271. }
  272. $types = $interfaces = array_unique(array_column($interfaces, 'name'));
  273. $interfaces[] = LazyObjectInterface::class;
  274. $interfaces = implode(', \\', $interfaces);
  275. $parent = $class ? ' extends \\'.$class->name : '';
  276. array_unshift($types, $class ? 'parent' : '');
  277. $type = ltrim(implode('&\\', $types), '&');
  278. if (!$class) {
  279. $trait = new \ReflectionMethod(LazyDecoratorTrait::class, 'initializeLazyObject');
  280. $body = \array_slice(file($trait->getFileName()), $trait->getStartLine() - 1, $trait->getEndLine() - $trait->getStartLine());
  281. $body[0] = str_replace('): parent', '): '.$type, $body[0]);
  282. $methods = ['initializeLazyObject' => implode('', $body).' }'] + $methods;
  283. }
  284. $body = $methods ? "\n".implode("\n\n", $methods)."\n" : '';
  285. $propertyScopes = $class ? self::exportPropertyScopes($class->name, $propertyScopes) : '[]';
  286. $lazyProxyTraitStatement = [];
  287. if (
  288. $class?->hasMethod('__unserialize')
  289. && !$class->getMethod('__unserialize')->getParameters()[0]->getType()
  290. ) {
  291. // fix contravariance type problem when $class declares a `__unserialize()` method without typehint.
  292. $lazyProxyTraitStatement[] = '__unserialize as private __doUnserialize;';
  293. $body .= <<<EOPHP
  294. public function __unserialize(\$data): void
  295. {
  296. \$this->__doUnserialize(\$data);
  297. }
  298. EOPHP;
  299. }
  300. if ($lazyProxyTraitStatement) {
  301. $lazyProxyTraitStatement = implode("\n ", $lazyProxyTraitStatement);
  302. $lazyProxyTraitStatement = <<<EOPHP
  303. use \Symfony\Component\VarExporter\Internal\LazyDecoratorTrait {
  304. {$lazyProxyTraitStatement}
  305. }
  306. EOPHP;
  307. } else {
  308. $lazyProxyTraitStatement = <<<EOPHP
  309. use \Symfony\Component\VarExporter\Internal\LazyDecoratorTrait;
  310. EOPHP;
  311. }
  312. return <<<EOPHP
  313. {$parent} implements \\{$interfaces}
  314. {
  315. {$lazyProxyTraitStatement}
  316. private const LAZY_OBJECT_PROPERTY_SCOPES = {$propertyScopes};
  317. {$hooks}{$body}}
  318. // Help opcache.preload discover always-needed symbols
  319. class_exists(\Symfony\Component\VarExporter\Internal\Hydrator::class);
  320. class_exists(\Symfony\Component\VarExporter\Internal\LazyObjectRegistry::class);
  321. EOPHP;
  322. }
  323. private static function generateLegacyLazyProxy(?\ReflectionClass $class, array $interfaces): string
  324. {
  325. if (\PHP_VERSION_ID < 80300 && $class?->isReadOnly()) {
  326. throw new LogicException(\sprintf('Cannot generate lazy proxy with PHP < 8.3: class "%s" is readonly.', $class->name));
  327. }
  328. $propertyScopes = $class ? Hydrator::$propertyScopes[$class->name] ??= Hydrator::getPropertyScopes($class->name) : [];
  329. $methodReflectors = [$class?->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) ?? []];
  330. foreach ($interfaces as $interface) {
  331. if (!$interface->isInterface()) {
  332. throw new LogicException(\sprintf('Cannot generate lazy proxy: "%s" is not an interface.', $interface->name));
  333. }
  334. $methodReflectors[] = $interface->getMethods();
  335. }
  336. $extendsInternalClass = false;
  337. if ($parent = $class) {
  338. do {
  339. $extendsInternalClass = \stdClass::class !== $parent->name && $parent->isInternal();
  340. } while (!$extendsInternalClass && $parent = $parent->getParentClass());
  341. }
  342. $methodsHaveToBeProxied = $extendsInternalClass;
  343. $methods = [];
  344. $methodReflectors = array_merge(...$methodReflectors);
  345. foreach ($methodReflectors as $method) {
  346. if ('__get' !== strtolower($method->name) || 'mixed' === ($type = self::exportType($method) ?? 'mixed')) {
  347. continue;
  348. }
  349. $methodsHaveToBeProxied = true;
  350. $trait = new \ReflectionMethod(LazyProxyTrait::class, '__get');
  351. $body = \array_slice(file($trait->getFileName()), $trait->getStartLine() - 1, $trait->getEndLine() - $trait->getStartLine());
  352. $body[0] = str_replace('): mixed', '): '.$type, $body[0]);
  353. $methods['__get'] = strtr(implode('', $body).' }', [
  354. 'Hydrator' => '\\'.Hydrator::class,
  355. 'Registry' => '\\'.LazyObjectRegistry::class,
  356. ]);
  357. break;
  358. }
  359. foreach ($methodReflectors as $method) {
  360. if (($method->isStatic() && !$method->isAbstract()) || isset($methods[$lcName = strtolower($method->name)])) {
  361. continue;
  362. }
  363. if ($method->isFinal()) {
  364. if ($extendsInternalClass || $methodsHaveToBeProxied || method_exists(LazyProxyTrait::class, $method->name)) {
  365. throw new LogicException(\sprintf('Cannot generate lazy proxy: method "%s::%s()" is final.', $class->name, $method->name));
  366. }
  367. continue;
  368. }
  369. if (method_exists(LazyProxyTrait::class, $method->name) || ($method->isProtected() && !$method->isAbstract())) {
  370. continue;
  371. }
  372. $signature = self::exportSignature($method, true, $args);
  373. $parentCall = $method->isAbstract() ? "throw new \BadMethodCallException('Cannot forward abstract method \"{$method->class}::{$method->name}()\".')" : "parent::{$method->name}({$args})";
  374. if ($method->isStatic()) {
  375. $body = " $parentCall;";
  376. } elseif (str_ends_with($signature, '): never') || str_ends_with($signature, '): void')) {
  377. $body = <<<EOPHP
  378. if (isset(\$this->lazyObjectState)) {
  379. (\$this->lazyObjectState->realInstance ??= (\$this->lazyObjectState->initializer)())->{$method->name}({$args});
  380. } else {
  381. {$parentCall};
  382. }
  383. EOPHP;
  384. } else {
  385. if (!$methodsHaveToBeProxied && !$method->isAbstract()) {
  386. // Skip proxying methods that might return $this
  387. foreach (preg_split('/[()|&]++/', self::exportType($method) ?? 'static') as $type) {
  388. if (\in_array($type = ltrim($type, '?'), ['static', 'object'], true)) {
  389. continue 2;
  390. }
  391. foreach ([$class, ...$interfaces] as $r) {
  392. if ($r && is_a($r->name, $type, true)) {
  393. continue 3;
  394. }
  395. }
  396. }
  397. }
  398. $body = <<<EOPHP
  399. if (isset(\$this->lazyObjectState)) {
  400. return (\$this->lazyObjectState->realInstance ??= (\$this->lazyObjectState->initializer)())->{$method->name}({$args});
  401. }
  402. return {$parentCall};
  403. EOPHP;
  404. }
  405. $methods[$lcName] = " {$signature}\n {\n{$body}\n }";
  406. }
  407. $types = $interfaces = array_unique(array_column($interfaces, 'name'));
  408. $interfaces[] = LazyObjectInterface::class;
  409. $interfaces = implode(', \\', $interfaces);
  410. $parent = $class ? ' extends \\'.$class->name : '';
  411. array_unshift($types, $class ? 'parent' : '');
  412. $type = ltrim(implode('&\\', $types), '&');
  413. if (!$class) {
  414. $trait = new \ReflectionMethod(LazyProxyTrait::class, 'initializeLazyObject');
  415. $body = \array_slice(file($trait->getFileName()), $trait->getStartLine() - 1, $trait->getEndLine() - $trait->getStartLine());
  416. $body[0] = str_replace('): parent', '): '.$type, $body[0]);
  417. $methods = ['initializeLazyObject' => implode('', $body).' }'] + $methods;
  418. }
  419. $body = $methods ? "\n".implode("\n\n", $methods)."\n" : '';
  420. $propertyScopes = $class ? self::exportPropertyScopes($class->name, $propertyScopes) : '[]';
  421. if (
  422. $class?->hasMethod('__unserialize')
  423. && !$class->getMethod('__unserialize')->getParameters()[0]->getType()
  424. ) {
  425. // fix contravariance type problem when $class declares a `__unserialize()` method without typehint.
  426. $lazyProxyTraitStatement = <<<EOPHP
  427. use \Symfony\Component\VarExporter\LazyProxyTrait {
  428. __unserialize as private __doUnserialize;
  429. }
  430. EOPHP;
  431. $body .= <<<EOPHP
  432. public function __unserialize(\$data): void
  433. {
  434. \$this->__doUnserialize(\$data);
  435. }
  436. EOPHP;
  437. } else {
  438. $lazyProxyTraitStatement = <<<EOPHP
  439. use \Symfony\Component\VarExporter\LazyProxyTrait;
  440. EOPHP;
  441. }
  442. return <<<EOPHP
  443. {$parent} implements \\{$interfaces}
  444. {
  445. {$lazyProxyTraitStatement}
  446. private const LAZY_OBJECT_PROPERTY_SCOPES = {$propertyScopes};
  447. {$body}}
  448. // Help opcache.preload discover always-needed symbols
  449. class_exists(\Symfony\Component\VarExporter\Internal\Hydrator::class);
  450. class_exists(\Symfony\Component\VarExporter\Internal\LazyObjectRegistry::class);
  451. class_exists(\Symfony\Component\VarExporter\Internal\LazyObjectState::class);
  452. EOPHP;
  453. }
  454. public static function exportParameters(\ReflectionFunctionAbstract $function, bool $withParameterTypes = true, ?string &$args = null): string
  455. {
  456. $byRefIndex = 0;
  457. $args = '';
  458. $param = null;
  459. $parameters = [];
  460. $namespace = $function instanceof \ReflectionMethod ? $function->class : $function->getNamespaceName().'\\';
  461. $namespace = substr($namespace, 0, strrpos($namespace, '\\') ?: 0);
  462. foreach ($function->getParameters() as $param) {
  463. $parameters[] = ($param->getAttributes(\SensitiveParameter::class) ? '#[\SensitiveParameter] ' : '')
  464. .($withParameterTypes && $param->hasType() ? self::exportType($param).' ' : '')
  465. .($param->isPassedByReference() ? '&' : '')
  466. .($param->isVariadic() ? '...' : '').'$'.$param->name
  467. .($param->isOptional() && !$param->isVariadic() ? ' = '.self::exportDefault($param, $namespace) : '');
  468. if ($param->isPassedByReference()) {
  469. $byRefIndex = 1 + $param->getPosition();
  470. }
  471. $args .= ($param->isVariadic() ? '...$' : '$').$param->name.', ';
  472. }
  473. if (!$param || !$byRefIndex) {
  474. $args = '...\func_get_args()';
  475. } elseif ($param->isVariadic()) {
  476. $args = substr($args, 0, -2);
  477. } else {
  478. $args = explode(', ', $args, 1 + $byRefIndex);
  479. $args[$byRefIndex] = \sprintf('...\array_slice(\func_get_args(), %d)', $byRefIndex);
  480. $args = implode(', ', $args);
  481. }
  482. return implode(', ', $parameters);
  483. }
  484. public static function exportSignature(\ReflectionFunctionAbstract $function, bool $withParameterTypes = true, ?string &$args = null): string
  485. {
  486. $parameters = self::exportParameters($function, $withParameterTypes, $args);
  487. $signature = 'function '.($function->returnsReference() ? '&' : '')
  488. .($function->isClosure() ? '' : $function->name).'('.$parameters.')';
  489. if ($function instanceof \ReflectionMethod) {
  490. $signature = ($function->isPublic() ? 'public ' : ($function->isProtected() ? 'protected ' : 'private '))
  491. .($function->isStatic() ? 'static ' : '').$signature;
  492. }
  493. if ($function->hasReturnType()) {
  494. $signature .= ': '.self::exportType($function);
  495. }
  496. static $getPrototype;
  497. $getPrototype ??= (new \ReflectionMethod(\ReflectionMethod::class, 'getPrototype'))->invoke(...);
  498. while ($function) {
  499. if ($function->hasTentativeReturnType()) {
  500. return '#[\ReturnTypeWillChange] '.$signature;
  501. }
  502. try {
  503. $function = $function instanceof \ReflectionMethod && $function->isAbstract() ? false : $getPrototype($function);
  504. } catch (\ReflectionException) {
  505. break;
  506. }
  507. }
  508. return $signature;
  509. }
  510. public static function exportType(\ReflectionFunctionAbstract|\ReflectionProperty|\ReflectionParameter $owner, bool $noBuiltin = false, ?\ReflectionType $type = null): ?string
  511. {
  512. if (!$type ??= $owner instanceof \ReflectionFunctionAbstract ? $owner->getReturnType() : $owner->getType()) {
  513. return null;
  514. }
  515. $class = null;
  516. $types = [];
  517. if ($type instanceof \ReflectionUnionType) {
  518. $reflectionTypes = $type->getTypes();
  519. $glue = '|';
  520. } elseif ($type instanceof \ReflectionIntersectionType) {
  521. $reflectionTypes = $type->getTypes();
  522. $glue = '&';
  523. } else {
  524. $reflectionTypes = [$type];
  525. $glue = null;
  526. }
  527. foreach ($reflectionTypes as $type) {
  528. if ($type instanceof \ReflectionIntersectionType) {
  529. if ('' !== $name = '('.self::exportType($owner, $noBuiltin, $type).')') {
  530. $types[] = $name;
  531. }
  532. continue;
  533. }
  534. $name = $type->getName();
  535. if ($noBuiltin && $type->isBuiltin()) {
  536. continue;
  537. }
  538. if (\in_array($name, ['parent', 'self'], true) && $class ??= $owner->getDeclaringClass()) {
  539. $name = 'parent' === $name ? ($class->getParentClass() ?: null)?->name ?? 'parent' : $class->name;
  540. }
  541. $types[] = ($noBuiltin || $type->isBuiltin() || 'static' === $name ? '' : '\\').$name;
  542. }
  543. if (!$types) {
  544. return '';
  545. }
  546. if (null === $glue) {
  547. $defaultNull = $owner instanceof \ReflectionParameter && 'NULL' === rtrim(substr(explode('$'.$owner->name.' = ', (string) $owner, 2)[1] ?? '', 0, -2));
  548. return (!$noBuiltin && ($type->allowsNull() || $defaultNull) && !\in_array($name, ['mixed', 'null'], true) ? '?' : '').$types[0];
  549. }
  550. sort($types);
  551. return implode($glue, $types);
  552. }
  553. private static function exportPropertyScopes(string $parent, array $propertyScopes): string
  554. {
  555. uksort($propertyScopes, 'strnatcmp');
  556. foreach ($propertyScopes as $k => $v) {
  557. unset($propertyScopes[$k][4]);
  558. }
  559. $propertyScopes = VarExporter::export($propertyScopes);
  560. $propertyScopes = str_replace(VarExporter::export($parent), 'parent::class', $propertyScopes);
  561. $propertyScopes = preg_replace("/(?|(,)\n( ) |\n |,\n (\]))/", '$1$2', $propertyScopes);
  562. return str_replace("\n", "\n ", $propertyScopes);
  563. }
  564. private static function exportDefault(\ReflectionParameter $param, $namespace): string
  565. {
  566. $default = rtrim(substr(explode('$'.$param->name.' = ', (string) $param, 2)[1] ?? '', 0, -2));
  567. if (\in_array($default, ['<default>', 'NULL'], true)) {
  568. return 'null';
  569. }
  570. if (str_ends_with($default, "...'") && preg_match("/^'(?:[^'\\\\]*+(?:\\\\.)*+)*+'$/", $default)) {
  571. return VarExporter::export($param->getDefaultValue());
  572. }
  573. $regexp = "/(\"(?:[^\"\\\\]*+(?:\\\\.)*+)*+\"|'(?:[^'\\\\]*+(?:\\\\.)*+)*+')/";
  574. $parts = preg_split($regexp, $default, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY);
  575. $regexp = '/([\[\( ]|^)([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z0-9_\x7f-\xff]++)*+)(\(?)(?!: )/';
  576. $callback = (false !== strpbrk($default, "\\:('") && $class = $param->getDeclaringClass())
  577. ? static fn ($m) => $m[1].match ($m[2]) {
  578. 'new', 'false', 'true', 'null' => $m[2],
  579. 'NULL' => 'null',
  580. 'self' => '\\'.$class->name,
  581. 'namespace\\parent',
  582. 'parent' => ($parent = $class->getParentClass()) ? '\\'.$parent->name : 'parent',
  583. default => self::exportSymbol($m[2], '(' !== $m[3], $namespace),
  584. }.$m[3]
  585. : static fn ($m) => $m[1].match ($m[2]) {
  586. 'new', 'false', 'true', 'null', 'self', 'parent' => $m[2],
  587. 'NULL' => 'null',
  588. default => self::exportSymbol($m[2], '(' !== $m[3], $namespace),
  589. }.$m[3];
  590. return implode('', array_map(static fn ($part) => match ($part[0]) {
  591. '"' => $part, // for internal classes only
  592. "'" => false !== strpbrk($part, "\\\0\r\n") ? '"'.substr(str_replace(['$', "\0", "\r", "\n"], ['\$', '\0', '\r', '\n'], $part), 1, -1).'"' : $part,
  593. default => preg_replace_callback($regexp, $callback, $part),
  594. }, $parts));
  595. }
  596. private static function exportSymbol(string $symbol, bool $mightBeRootConst, string $namespace): string
  597. {
  598. if (!$mightBeRootConst
  599. || false === ($ns = strrpos($symbol, '\\'))
  600. || substr($symbol, 0, $ns) !== $namespace
  601. || \defined($symbol)
  602. || !\defined(substr($symbol, $ns + 1))
  603. ) {
  604. return '\\'.$symbol;
  605. }
  606. return '\\'.substr($symbol, $ns + 1);
  607. }
  608. }