Debian Codegraph @

lib/3rdParty/composer/nesbot/carbon/src/Carbon/Traits/Serialization.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\Exceptions\InvalidFormatException;
17 use Carbon\FactoryImmutable;
18 use DateTimeZone;
19 use ReturnTypeWillChange;
20 use Throwable;
21
22 /**
23 * Trait Serialization.
24 *
25 * Serialization and JSON stuff.
26 *
27 * Depends on the following properties:
28 *
29 * @property int $year
30 * @property int $month
31 * @property int $daysInMonth
32 * @property int $quarter
33 *
34 * Depends on the following methods:
35 *
36 * @method string|static locale(string $locale = null, string ...$fallbackLocales)
37 * @method string toJSON()
38 */
39 trait Serialization
40 {
41 use ObjectInitialisation;
42
43 /**
44 * List of key to use for dump/serialization.
45 *
46 * @var string[]
47 */
48 protected array $dumpProperties = ['date', 'timezone_type', 'timezone'];
49
50 /**
51 * Locale to dump comes here before serialization.
52 *
53 * @var string|null
54 */
55 protected $dumpLocale;
56
57 /**
58 * Embed date properties to dump in a dedicated variables so it won't overlap native
59 * DateTime ones.
60 *
61 * @var array|null
62 */
63 protected $dumpDateProperties;
64
65 /**
66 * Return a serialized string of the instance.
67 */
68 public function serialize(): string
69 {
70 return serialize($this);
71 }
72
73 /**
74 * Create an instance from a serialized string.
75 *
76 * If $value is not from a trusted source, consider using the allowed_classes option to limit
77 * the types of objects that can be built, for instance:
78 *
79 * @example
80 * ```php
81 * $object = Carbon::fromSerialized($value, ['allowed_classes' => [Carbon::class, CarbonImmutable::class]]);
82 * ```
83 *
84 * @param \Stringable|string $value
85 * @param array $options example: ['allowed_classes' => [CarbonImmutable::class]]
86 *
87 * @throws InvalidFormatException
88 *
89 * @return static
90 */
91 public static function fromSerialized($value, array $options = []): static
92 {
93 $instance = @unserialize((string) $value, $options);
94
95 if (!$instance instanceof static) {
96 throw new InvalidFormatException("Invalid serialized value: $value");
97 }
98
99 return $instance;
100 }
101
102 /**
103 * The __set_state handler.
104 *
105 * @param string|array $dump
106 *
107 * @return static
108 */
109 #[ReturnTypeWillChange]
110 public static function __set_state($dump): static
111 {
112 if (\is_string($dump)) {
113 return static::parse($dump);
114 }
115
116 /** @var \DateTimeInterface $date */
117 $date = get_parent_class(static::class) && method_exists(parent::class, '__set_state')
118 ? parent::__set_state((array) $dump)
119 : (object) $dump;
120
121 return static::instance($date);
122 }
123
124 /**
125 * Returns the values to dump on serialize() called on.
126 *
127 * @return array
128 */
129 public function __serialize(): array
130 {
131 // @codeCoverageIgnoreStart
132 if (isset($this->timezone_type, $this->timezone, $this->date)) {
133 return [
134 'date' => $this->date,
135 'timezone_type' => $this->timezone_type,
136 'timezone' => $this->dumpTimezone($this->timezone),
137 ];
138 }
139 // @codeCoverageIgnoreEnd
140
141 $timezone = $this->getTimezone();
142 $export = [
143 'date' => $this->format('Y-m-d H:i:s.u'),
144 'timezone_type' => $timezone->getType(),
145 'timezone' => $timezone->getName(),
146 ];
147
148 // @codeCoverageIgnoreStart
149 if (\extension_loaded('msgpack') && isset($this->constructedObjectId)) {
150 $timezone = $this->timezone ?? null;
151 $export['dumpDateProperties'] = [
152 'date' => $this->format('Y-m-d H:i:s.u'),
153 'timezone' => $this->dumpTimezone($timezone),
154 ];
155 }
156 // @codeCoverageIgnoreEnd
157
158 if ($this->localTranslator ?? null) {
159 $export['dumpLocale'] = $this->locale ?? null;
160 }
161
162 return $export;
163 }
164
165 /**
166 * Set locale if specified on unserialize() called.
167 */
168 public function __unserialize(array $data): void
169 {
170 // @codeCoverageIgnoreStart
171 try {
172 $this->__construct($data['date'] ?? null, $data['timezone'] ?? null);
173 } catch (Throwable $exception) {
174 if (!isset($data['dumpDateProperties']['date'], $data['dumpDateProperties']['timezone'])) {
175 throw $exception;
176 }
177
178 try {
179 // FatalError occurs when calling msgpack_unpack() in PHP 7.4 or later.
180 ['date' => $date, 'timezone' => $timezone] = $data['dumpDateProperties'];
181 $this->__construct($date, $timezone);
182 } catch (Throwable) {
183 throw $exception;
184 }
185 }
186 // @codeCoverageIgnoreEnd
187
188 if (isset($data['dumpLocale'])) {
189 $this->locale($data['dumpLocale']);
190 }
191 }
192
193 /**
194 * Prepare the object for JSON serialization.
195 */
196 public function jsonSerialize(): mixed
197 {
198 $serializer = $this->localSerializer
199 ?? $this->getFactory()->getSettings()['toJsonFormat']
200 ?? null;
201
202 if ($serializer) {
203 return \is_string($serializer)
204 ? $this->rawFormat($serializer)
205 : $serializer($this);
206 }
207
208 return $this->toJSON();
209 }
210
211 /**
212 * @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
213 * You should rather transform Carbon object before the serialization.
214 *
215 * JSON serialize all Carbon instances using the given callback.
216 */
217 public static function serializeUsing(string|callable|null $format): void
218 {
219 FactoryImmutable::getDefaultInstance()->serializeUsing($format);
220 }
221
222 /**
223 * Cleanup properties attached to the public scope of DateTime when a dump of the date is requested.
224 * foreach ($date as $_) {}
225 * serializer($date)
226 * var_export($date)
227 * get_object_vars($date)
228 */
229 public function cleanupDumpProperties(): self
230 {
231 // @codeCoverageIgnoreStart
232 if (PHP_VERSION < 8.2) {
233 foreach ($this->dumpProperties as $property) {
234 if (isset($this->$property)) {
235 unset($this->$property);
236 }
237 }
238 }
239 // @codeCoverageIgnoreEnd
240
241 return $this;
242 }
243
244 /** @codeCoverageIgnore */
245 private function dumpTimezone(mixed $timezone): mixed
246 {
247 return $timezone instanceof DateTimeZone ? $timezone->getName() : $timezone;
248 }
249 }