blob: 5f7c7c011ab27d99fa810c99864bfe841bf9b238 [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +01003/**
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 Benkard7b2a3a12021-08-16 10:57:25 +020012namespace Carbon\Traits;
13
14use Carbon\Exceptions\InvalidCastException;
15use DateTimeInterface;
16
17/**
18 * Trait Cast.
19 *
20 * Utils to cast into an other class.
21 */
22trait 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}