Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 1 | <?php |
| 2 | |
Matthias Andreas Benkard | 1ba5381 | 2022-12-27 17:32:58 +0100 | [diff] [blame^] | 3 | /** |
| 4 | * This file is part of the Carbon package. |
| 5 | * |
| 6 | * (c) Brian Nesbitt <brian@nesbot.com> |
| 7 | * |
| 8 | * For the full copyright and license information, please view the LICENSE |
| 9 | * file that was distributed with this source code. |
| 10 | */ |
| 11 | |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 12 | namespace Carbon\Traits; |
| 13 | |
| 14 | use Carbon\Exceptions\InvalidCastException; |
| 15 | use DateTimeInterface; |
| 16 | |
| 17 | /** |
| 18 | * Trait Cast. |
| 19 | * |
| 20 | * Utils to cast into an other class. |
| 21 | */ |
| 22 | trait Cast |
| 23 | { |
| 24 | /** |
| 25 | * Cast the current instance into the given class. |
| 26 | * |
| 27 | * @param string $className The $className::instance() method will be called to cast the current object. |
| 28 | * |
| 29 | * @return DateTimeInterface |
| 30 | */ |
| 31 | public function cast(string $className) |
| 32 | { |
| 33 | if (!method_exists($className, 'instance')) { |
| 34 | if (is_a($className, DateTimeInterface::class, true)) { |
| 35 | return new $className($this->rawFormat('Y-m-d H:i:s.u'), $this->getTimezone()); |
| 36 | } |
| 37 | |
| 38 | throw new InvalidCastException("$className has not the instance() method needed to cast the date."); |
| 39 | } |
| 40 | |
| 41 | return $className::instance($this); |
| 42 | } |
| 43 | } |