1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Reflection;
4:
5: use PHPStan\Turbo\ShadowedByTurboExtension;
6: use function array_key_exists;
7:
8: /**
9: * Describes how a function/method parameter is passed: by value or by reference.
10: *
11: * Three modes:
12: * - **No**: Passed by value — the argument expression is evaluated and its value is copied.
13: * - **ReadsArgument**: Passed by reference, but the function reads the existing variable.
14: * The variable must already exist. Example: `sort(&$array)`.
15: * - **CreatesNewVariable**: Passed by reference, and the function may create the variable
16: * if it doesn't exist. Example: `preg_match($pattern, $subject, &$matches)` where
17: * `$matches` doesn't need to be defined beforehand.
18: *
19: * This distinction matters for PHPStan's scope analysis — when a function takes a
20: * parameter by reference with "creates new variable" semantics, PHPStan knows the
21: * variable will exist after the call even if it wasn't defined before.
22: *
23: * Used as the return type of ParameterReflection::passedByReference().
24: *
25: * @api
26: */
27: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/PassedByReference.cpp')]
28: final class PassedByReference
29: {
30:
31: private const NO = 1;
32: private const READS_ARGUMENT = 2;
33: private const CREATES_NEW_VARIABLE = 3;
34:
35: /** @var self[] */
36: private static array $registry = [];
37:
38: private function __construct(private int $value)
39: {
40: }
41:
42: private static function create(int $value): self
43: {
44: if (!array_key_exists($value, self::$registry)) {
45: self::$registry[$value] = new self($value);
46: }
47:
48: return self::$registry[$value];
49: }
50:
51: public static function createNo(): self
52: {
53: return self::create(self::NO);
54: }
55:
56: public static function createCreatesNewVariable(): self
57: {
58: return self::create(self::CREATES_NEW_VARIABLE);
59: }
60:
61: public static function createReadsArgument(): self
62: {
63: return self::create(self::READS_ARGUMENT);
64: }
65:
66: public function no(): bool
67: {
68: return $this->value === self::NO;
69: }
70:
71: public function yes(): bool
72: {
73: return !$this->no();
74: }
75:
76: public function equals(self $other): bool
77: {
78: return $this->value === $other->value;
79: }
80:
81: public function createsNewVariable(): bool
82: {
83: return $this->value === self::CREATES_NEW_VARIABLE;
84: }
85:
86: /** CreatesNewVariable > ReadsArgument > No. */
87: public function combine(self $other): self
88: {
89: if ($this->value > $other->value) {
90: return $this;
91: } elseif ($this->value < $other->value) {
92: return $other;
93: }
94:
95: return $this;
96: }
97:
98: }
99: