briannesbitt / Carbon
1
<?php
2

3
namespace Carbon\Traits;
4

5
use Carbon\Exceptions\InvalidCastException;
6
use DateTimeInterface;
7

8
/**
9
 * Trait Cast.
10
 *
11
 * Utils to cast into an other class.
12
 */
13
trait Cast
14
{
15
    /**
16
     * Cast the current instance into the given class.
17
     *
18
     * @param string $className The $className::instance() method will be called to cast the current object.
19
     *
20
     * @return DateTimeInterface
21
     */
22 2
    public function cast(string $className)
23
    {
24 2
        if (!method_exists($className, 'instance')) {
25 2
            if (is_a($className, DateTimeInterface::class, true)) {
26 2
                return new $className($this->rawFormat('Y-m-d H:i:s.u'), $this->getTimezone());
27
            }
28

29 2
            throw new InvalidCastException("$className has not the instance() method needed to cast the date.");
30
        }
31

32 2
        return $className::instance($this);
33
    }
34
}

Read our documentation on viewing source code .

Loading