Search code examples
phplaravel-8php-carbon

Where is the implementation of all the methods (roundCentury, addDay, addDays...) in nesbot/carbon library in Laravel?


I try to look at all the files in nesbot/carbon vendor source code but still can't find the implementation of some methods likes roundCentury, addDay, addDays... except the php docblock.

Because I want to know how these methods work. I wonder where is implementation of these method?

Thanks in advance


Solution

  • The code structure of Carbon is rather complicated, including heavy use of PHP traits and a custom "macro" system, but eventually I tracked down the definition to Carbon\Traits\Date which is included into the main classes like Carbon\Carbon.

    This doesn't define the methods directly, but rather implements method overloading via __call, where the method name is passed in as a string. The Carbon code actually parses the method name to decide what it should do.

    For rounding, that calls roundMethod, which is defined in another trait, called Carbon\Traits\IntervalRounding, the main line of which is this:

    return $this->{$action.'Unit'}(substr($method, \strlen($action)), ...$parameters);
    

    For roundCentury, $action is "round", and the substr part takes the rest of the name, so you get:

    return $this->roundUnit('Century', ...$parameters);
    

    The definition of roundUnit is then in yet another trait, Carbon\Traits\Rounding.

    The "add..." methods presumably work similarly.