Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add createFromFormat static method to CarbonInterval #1921

Merged
Merged
93 changes: 92 additions & 1 deletion src/Carbon/CarbonInterval.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
namespace Carbon;

use BadMethodCallException;
use Carbon\Exceptions\ParseErrorException;
use Carbon\Traits\Mixin;
use Carbon\Traits\Options;
use Closure;
Expand Down Expand Up @@ -193,6 +194,29 @@ class CarbonInterval extends DateInterval
*/
protected static $cascadeFactors;

/**
* @var array
*/
protected static $formats = [
'y' => 'y',
'Y' => 'y',
'o' => 'y',
'm' => 'm',
'n' => 'm',
'W' => 'weeks',
'd' => 'd',
'j' => 'd',
'z' => 'd',
'h' => 'h',
'g' => 'h',
'H' => 'h',
'G' => 'h',
'i' => 'i',
's' => 's',
'u' => 'micro',
'v' => 'milli',
];

/**
* @var array|null
*/
Expand Down Expand Up @@ -293,7 +317,7 @@ public static function setCascadeFactors(array $cascadeFactors)
* @param int|null $seconds
* @param int|null $microseconds
*
* @throws Exception
* @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval.
*/
public function __construct($years = 1, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null)
{
Expand Down Expand Up @@ -429,13 +453,80 @@ public static function getMicrosecondsPerMillisecond()
* @param int $seconds
* @param int $microseconds
*
* @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval.
*
* @return static
*/
public static function create($years = 1, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null)
{
return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds);
}

/**
* Parse a string into a new CarbonInterval object according to the specified format.
*
* @example
* ```
* echo Carboninterval::createFromFormat('H:i', '1:30');
* ```
*
* @param string $format Format of the $interval input string
* @param string $interval Input string to convert into an interval
*
* @throws Exception when the $interval cannot be parsed as an interval.
*
* @return static
*/
public static function createFromFormat(string $format, ?string $interval)
{
$instance = new static(0);
$length = mb_strlen($format);

if (preg_match('/s([,.])([uv])$/', $format, $match)) {
$interval = explode($match[1], $interval);
$index = count($interval) - 1;
$interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0');
$interval = implode($match[1], $interval);
}

for ($index = 0; $index < $length; $index++) {
$expected = mb_substr($format, $index, 1);
$nextCharacter = mb_substr($interval, 0, 1);
$unit = static::$formats[$expected] ?? null;

if ($unit) {
if (!preg_match('/^-?\d+/', $interval, $match)) {
throw new ParseErrorException('number', $nextCharacter);
}

$interval = mb_substr($interval, mb_strlen($match[0]));
$instance->$unit += intval($match[0]);

continue;
}

if ($nextCharacter !== $expected) {
throw new ParseErrorException(
"'$expected'",
$nextCharacter,
'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n".
'See https://www.php.net/manual/en/function.date.php for their meaning'
);
}

$interval = mb_substr($interval, 1);
}

if ($interval !== '') {
throw new ParseErrorException(
'end of string',
$interval
);
}

return $instance;
}

/**
* Get a copy of the instance.
*
Expand Down
32 changes: 32 additions & 0 deletions src/Carbon/Exceptions/ParseErrorException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Exceptions;

use Exception;
use InvalidArgumentException;

class ParseErrorException extends InvalidArgumentException
{
/**
* Constructor.
*
* @param string $expected
* @param string $actual
* @param int $code
* @param \Exception|null $previous
*/
public function __construct($expected, $actual, $help = '', $code = 0, Exception $previous = null)
{
$actual = $actual === '' ? 'data is missing' : "get '$actual'";

parent::__construct(trim("Format expected $expected but $actual\n$help"), $code, $previous);
}
}
186 changes: 186 additions & 0 deletions tests/CarbonInterval/CreateFromFormatTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
<?php
declare(strict_types=1);

/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\CarbonInterval;

use Carbon\CarbonInterval;
use Carbon\Exceptions\ParseErrorException;
use Tests\AbstractTestCase;

class CreateFromFormatTest extends AbstractTestCase
{
public function testDefaults()
{
$this->expectException(ParseErrorException::class);
$this->expectExceptionMessage('Format expected number but data is missing');
CarbonInterval::createFromFormat('H:i:s', '');
}

public function testNulls()
{
$this->expectException(ParseErrorException::class);
$this->expectExceptionMessage('Format expected number but data is missing');
CarbonInterval::createFromFormat('H:i:s', null);
}

public function testTrailingData()
{
$this->expectException(ParseErrorException::class);
$this->expectExceptionMessage("Format expected end of string but get ':25'");
CarbonInterval::createFromFormat('H:i', '01:30:25');
}

public function testInvalidSubstitute()
{
$this->expectException(ParseErrorException::class);
$this->expectExceptionMessage(
"Format expected 'N' but get '4'\n".
"Allowed substitutes for interval formats are y, Y, o, m, n, W, d, j, z, h, g, H, G, i, s, u, v\n".
'See https://www.php.net/manual/en/function.date.php for their meaning');
CarbonInterval::createFromFormat('N', '4');
}

public function testYears()
{
$ci = CarbonInterval::createFromFormat('Y', '1');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 1, 0, 0, 0, 0, 0);

$ci = CarbonInterval::createFromFormat('Y', '2');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 2, 0, 0, 0, 0, 0);
}

public function testMonths()
{
$ci = CarbonInterval::createFromFormat('m', '1');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 1, 0, 0, 0, 0);

$ci = CarbonInterval::createFromFormat('m', '2');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 2, 0, 0, 0, 0);
}

public function testWeeks()
{
$ci = CarbonInterval::createFromFormat('W', '1');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 0, 7, 0, 0, 0);

$ci = CarbonInterval::createFromFormat('W', '2');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 0, 14, 0, 0, 0);
}

public function testDays()
{
$ci = CarbonInterval::createFromFormat('d', '1');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 0, 1, 0, 0, 0);

$ci = CarbonInterval::createFromFormat('d', '2');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 0, 2, 0, 0, 0);
}

public function testWeeksAndDays()
{
$ci = CarbonInterval::createFromFormat('W d', '3 5');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 0, 26, 0, 0, 0);

$ci = CarbonInterval::createFromFormat('W d', '2 -6');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 0, 8, 0, 0, 0);
}

public function testHours()
{
$ci = CarbonInterval::createFromFormat('H', '1');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 0, 0, 1, 0, 0);

$ci = CarbonInterval::createFromFormat('H', '2');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 0, 0, 2, 0, 0);
}

public function testMinutes()
{
$ci = CarbonInterval::createFromFormat('i', '01');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 0, 0, 0, 1, 0);

$ci = CarbonInterval::createFromFormat('i', '02');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 0, 0, 0, 2, 0);
}

public function testSeconds()
{
$ci = CarbonInterval::createFromFormat('s', '01');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 1);

$ci = CarbonInterval::createFromFormat('s', '02');
$this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 2);
}

public function testDecimalSeconds()
{
$ci = CarbonInterval::createFromFormat('s.v', '1.5');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 1, 500000);

$ci = CarbonInterval::createFromFormat('s.u', '1.2534');
$this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 1, 253400);
}

public function testMilliseconds()
{
$ci = CarbonInterval::createFromFormat('v', '100');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0, 100000);
$this->assertSame(100000, $ci->microseconds);

$ci = CarbonInterval::createFromFormat('v', '200');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0, 200000);
}

public function testMicroseconds()
{
$ci = CarbonInterval::createFromFormat('u', '100000');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0, 100000);
$this->assertSame(100000, $ci->microseconds);

$ci = CarbonInterval::createFromFormat('u', '200000');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 0, 0, 0, 0, 0, 0, 200000);
}

public function testAll()
{
$ci = CarbonInterval::createFromFormat('Y-m-d H:i:s.u', '2000-01-02 3:04:05.500000');
$this->assertInstanceOfCarbonInterval($ci);
$this->assertCarbonInterval($ci, 2000, 1, 2, 3, 4, 5, 500000);
}

public function testCopy()
{
$one = CarbonInterval::createFromFormat('H:i:s', '10:10:10');
$two = $one->copy()->hours(3)->minutes(3)->seconds(3);
$this->assertCarbonInterval($one, 0, 0, 0, 10, 10, 10);
$this->assertCarbonInterval($two, 0, 0, 0, 3, 3, 3);
}
}