Debian Codegraph @

lib/3rdParty/composer/nesbot/carbon/src/Carbon/Traits/LocalFactory.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\Factory;
17 use Carbon\FactoryImmutable;
18 use Carbon\WrapperClock;
19 use Closure;
20
21 /**
22 * Remember the factory that was the current at the creation of the object.
23 */
24 trait LocalFactory
25 {
26 /**
27 * The clock that generated the current instance (or FactoryImmutable::getDefaultInstance() if none)
28 */
29 private ?WrapperClock $clock = null;
30
31 public function getClock(): ?WrapperClock
32 {
33 return $this->clock;
34 }
35
36 private function initLocalFactory(): void
37 {
38 $this->clock = FactoryImmutable::getCurrentClock();
39 }
40
41 /**
42 * Trigger the given action using the local factory of the object, so it will be transmitted
43 * to any object also using this trait and calling initLocalFactory() in its constructor.
44 *
45 * @template T
46 *
47 * @param Closure(): T $action
48 *
49 * @return T
50 */
51 private function transmitFactory(Closure $action): mixed
52 {
53 $previousClock = FactoryImmutable::getCurrentClock();
54 FactoryImmutable::setCurrentClock($this->clock);
55
56 try {
57 return $action();
58 } finally {
59 FactoryImmutable::setCurrentClock($previousClock);
60 }
61 }
62
63 private function getFactory(): Factory
64 {
65 return $this->getClock()?->getFactory() ?? FactoryImmutable::getDefaultInstance();
66 }
67 }