Debian Codegraph @

lib/3rdParty/composer/nesbot/carbon/src/Carbon/Traits/Macro.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\FactoryImmutable;
17
18 /**
19 * Trait Macros.
20 *
21 * Allows users to register macros within the Carbon class.
22 */
23 trait Macro
24 {
25 use Mixin;
26
27 /**
28 * Register a custom macro.
29 *
30 * Pass null macro to remove it.
31 *
32 * @example
33 * ```
34 * $userSettings = [
35 * 'locale' => 'pt',
36 * 'timezone' => 'America/Sao_Paulo',
37 * ];
38 * Carbon::macro('userFormat', function () use ($userSettings) {
39 * return $this->copy()->locale($userSettings['locale'])->tz($userSettings['timezone'])->calendar();
40 * });
41 * echo Carbon::yesterday()->hours(11)->userFormat();
42 * ```
43 *
44 * @param-closure-this static $macro
45 */
46 public static function macro(string $name, ?callable $macro): void
47 {
48 FactoryImmutable::getDefaultInstance()->macro($name, $macro);
49 }
50
51 /**
52 * Remove all macros and generic macros.
53 */
54 public static function resetMacros(): void
55 {
56 FactoryImmutable::getDefaultInstance()->resetMacros();
57 }
58
59 /**
60 * Register a custom macro.
61 *
62 * @param callable $macro
63 * @param int $priority marco with higher priority is tried first
64 *
65 * @return void
66 */
67 public static function genericMacro(callable $macro, int $priority = 0): void
68 {
69 FactoryImmutable::getDefaultInstance()->genericMacro($macro, $priority);
70 }
71
72 /**
73 * Checks if macro is registered globally.
74 *
75 * @param string $name
76 *
77 * @return bool
78 */
79 public static function hasMacro(string $name): bool
80 {
81 return FactoryImmutable::getInstance()->hasMacro($name);
82 }
83
84 /**
85 * Get the raw callable macro registered globally for a given name.
86 */
87 public static function getMacro(string $name): ?callable
88 {
89 return FactoryImmutable::getInstance()->getMacro($name);
90 }
91
92 /**
93 * Checks if macro is registered globally or locally.
94 */
95 public function hasLocalMacro(string $name): bool
96 {
97 return ($this->localMacros && isset($this->localMacros[$name])) || $this->transmitFactory(
98 static fn () => static::hasMacro($name),
99 );
100 }
101
102 /**
103 * Get the raw callable macro registered globally or locally for a given name.
104 */
105 public function getLocalMacro(string $name): ?callable
106 {
107 return ($this->localMacros ?? [])[$name] ?? $this->transmitFactory(
108 static fn () => static::getMacro($name),
109 );
110 }
111 }