Debian Codegraph @

lib/3rdParty/composer/nesbot/carbon/src/Carbon/Traits/Cast.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\InvalidCastException;
17 use DateTimeInterface;
18
19 /**
20 * Trait Cast.
21 *
22 * Utils to cast into an other class.
23 */
24 trait Cast
25 {
26 /**
27 * Cast the current instance into the given class.
28 *
29 * @template T
30 *
31 * @param class-string<T> $className The $className::instance() method will be called to cast the current object.
32 *
33 * @return T
34 */
35 public function cast(string $className): mixed
36 {
37 if (!method_exists($className, 'instance')) {
38 if (is_a($className, DateTimeInterface::class, true)) {
39 return $className::createFromFormat('U.u', $this->rawFormat('U.u'))
40 ->setTimezone($this->getTimezone());
41 }
42
43 throw new InvalidCastException("$className has not the instance() method needed to cast the date.");
44 }
45
46 return $className::instance($this);
47 }
48 }