Debian Codegraph @

lib/3rdParty/composer/nesbot/carbon/src/Carbon/Traits/Mixin.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 /**
6 * This file is part of the Carbon package.
7 *
8 * (c) Brian Nesbitt <[email protected]>
9 *
10 * For the full copyright and license information, please view the LICENSE
11 * file that was distributed with this source code.
12 */
13
14 namespace Carbon\Traits;
15
16 use Carbon\CarbonInterface;
17 use Carbon\CarbonInterval;
18 use Carbon\CarbonPeriod;
19 use Closure;
20 use Generator;
21 use ReflectionClass;
22 use ReflectionException;
23 use ReflectionMethod;
24 use ReflectionNamedType;
25 use Throwable;
26
27 /**
28 * Trait Mixin.
29 *
30 * Allows mixing in entire classes with multiple macros.
31 */
32 trait Mixin
33 {
34 /**
35 * Stack of macro instance contexts.
36 */
37 protected static array $macroContextStack = [];
38
39 /**
40 * Mix another object into the class.
41 *
42 * @example
43 * ```
44 * Carbon::mixin(new class {
45 * public function addMoon() {
46 * return function () {
47 * return $this->addDays(30);
48 * };
49 * }
50 * public function subMoon() {
51 * return function () {
52 * return $this->subDays(30);
53 * };
54 * }
55 * });
56 * $fullMoon = Carbon::create('2018-12-22');
57 * $nextFullMoon = $fullMoon->addMoon();
58 * $blackMoon = Carbon::create('2019-01-06');
59 * $previousBlackMoon = $blackMoon->subMoon();
60 * echo "$nextFullMoon\n";
61 * echo "$previousBlackMoon\n";
62 * ```
63 *
64 * @throws ReflectionException
65 */
66 public static function mixin(object|string $mixin): void
67 {
68 \is_string($mixin) && trait_exists($mixin)
69 ? self::loadMixinTrait($mixin)
70 : self::loadMixinClass($mixin);
71 }
72
73 /**
74 * @throws ReflectionException
75 */
76 private static function loadMixinClass(object|string $mixin): void
77 {
78 $methods = (new ReflectionClass($mixin))->getMethods(
79 ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED,
80 );
81
82 foreach ($methods as $method) {
83 if (self::cannotBeAMixinMethod($method)) {
84 continue;
85 }
86
87 $macro = $method->invoke($mixin);
88
89 if (\is_callable($macro)) {
90 static::macro($method->name, $macro);
91 }
92 }
93 }
94
95 private static function cannotBeAMixinMethod(ReflectionMethod $method): bool
96 {
97 if ($method->isConstructor() || $method->isDestructor()) {
98 return true;
99 }
100
101 $returnType = $method->getReturnType();
102
103 if ($returnType instanceof ReflectionNamedType) {
104 $returnedTypeName = $returnType->getName();
105
106 if ($returnType->isBuiltin()) {
107 return !\in_array($returnedTypeName, [
108 'callable',
109 'object', // could have __invoke
110 'array', // could be [MyClass::class, 'myMethod']
111 'mixed', // could be one of the above
112 // The other builtin types cannot be callable, so we can skip invoking them
113 ], true);
114 }
115
116 // If it returns a non-invokable object, it cannot be a mixin method
117 if (class_exists($returnedTypeName)) {
118 return !is_a($returnedTypeName, Closure::class, true) && !\is_callable([$returnedTypeName, '__invoke']);
119 }
120 }
121
122 return false;
123 }
124
125 private static function loadMixinTrait(string $trait): void
126 {
127 $context = eval(self::getAnonymousClassCodeForTrait($trait));
128 $className = \get_class($context);
129 $baseClass = static::class;
130
131 foreach (self::getMixableMethods($context) as $name) {
132 $closureBase = Closure::fromCallable([$context, $name]);
133
134 static::macro($name, function (...$parameters) use ($closureBase, $className, $baseClass) {
135 $downContext = isset($this) ? ($this) : new $baseClass();
136 $context = isset($this) ? $this->cast($className) : new $className();
137
138 try {
139 // @ is required to handle error if not converted into exceptions
140 $closure = @$closureBase->bindTo($context);
141 } catch (Throwable) { // @codeCoverageIgnore
142 $closure = $closureBase; // @codeCoverageIgnore
143 }
144
145 // in case of errors not converted into exceptions
146 $closure = $closure ?: $closureBase;
147
148 $result = $closure(...$parameters);
149
150 if (!($result instanceof $className)) {
151 return $result;
152 }
153
154 if ($downContext instanceof CarbonInterface && $result instanceof CarbonInterface) {
155 if ($context !== $result) {
156 $downContext = $downContext->copy();
157 }
158
159 return $downContext
160 ->setTimezone($result->getTimezone())
161 ->modify($result->format('Y-m-d H:i:s.u'))
162 ->settings($result->getSettings());
163 }
164
165 if ($downContext instanceof CarbonInterval && $result instanceof CarbonInterval) {
166 if ($context !== $result) {
167 $downContext = $downContext->copy();
168 }
169
170 $downContext->copyProperties($result);
171 self::copyStep($downContext, $result);
172 self::copyNegativeUnits($downContext, $result);
173
174 return $downContext->settings($result->getSettings());
175 }
176
177 if ($downContext instanceof CarbonPeriod && $result instanceof CarbonPeriod) {
178 if ($context !== $result) {
179 $downContext = $downContext->copy();
180 }
181
182 return $downContext
183 ->setDates($result->getStartDate(), $result->getEndDate())
184 ->setRecurrences($result->getRecurrences())
185 ->setOptions($result->getOptions())
186 ->settings($result->getSettings());
187 }
188
189 return $result;
190 });
191 }
192 }
193
194 private static function getAnonymousClassCodeForTrait(string $trait): string
195 {
196 return 'return new class() extends '.static::class.' {use '.$trait.';};';
197 }
198
199 private static function getMixableMethods(self $context): Generator
200 {
201 foreach (get_class_methods($context) as $name) {
202 if (method_exists(static::class, $name)) {
203 continue;
204 }
205
206 yield $name;
207 }
208 }
209
210 /**
211 * Stack a Carbon context from inside calls of self::this() and execute a given action.
212 */
213 protected static function bindMacroContext(?self $context, callable $callable): mixed
214 {
215 static::$macroContextStack[] = $context;
216
217 try {
218 return $callable();
219 } finally {
220 array_pop(static::$macroContextStack);
221 }
222 }
223
224 /**
225 * Return the current context from inside a macro callee or a null if static.
226 */
227 protected static function context(): ?static
228 {
229 return end(static::$macroContextStack) ?: null;
230 }
231
232 /**
233 * Return the current context from inside a macro callee or a new one if static.
234 */
235 protected static function this(): static
236 {
237 return end(static::$macroContextStack) ?: new static();
238 }
239 }