1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of Railt package. |
4
|
|
|
* |
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
6
|
|
|
* file that was distributed with this source code. |
7
|
|
|
*/ |
8
|
|
|
declare(strict_types=1); |
9
|
|
|
|
10
|
|
|
namespace Railt\CarbonExtension; |
11
|
|
|
|
12
|
|
|
use Carbon\Carbon; |
13
|
|
|
use Railt\CarbonExtension\Exception\InvalidDateTimeFormat; |
14
|
|
|
use Railt\CarbonExtension\In\CarbonFormat; |
15
|
|
|
use Railt\Http\InputInterface; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Class CarbonController |
19
|
|
|
*/ |
20
|
|
|
class CarbonController |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* @param InputInterface $input |
24
|
|
|
* @return Carbon|null |
25
|
|
|
* @throws InvalidDateTimeFormat |
26
|
|
|
* @throws \InvalidArgumentException |
27
|
|
|
*/ |
28
|
|
|
private function getValue(InputInterface $input): ?Carbon |
29
|
|
|
{ |
30
|
|
|
$value = $input->getParentResponse()[$input->getFieldName()] ?? null; |
31
|
|
|
|
32
|
|
|
switch (true) { |
33
|
|
|
case $value === null: |
|
|
|
|
34
|
|
|
return null; |
35
|
|
|
case $value instanceof Carbon: |
|
|
|
|
36
|
|
|
return $value; |
37
|
|
|
case $value instanceof \DateTimeInterface: |
|
|
|
|
38
|
|
|
return Carbon::instance($value); |
39
|
|
|
case \is_string($value): |
40
|
|
|
return Carbon::parse($value); |
41
|
|
|
case \is_int($value) || \is_float($value): |
42
|
|
|
return Carbon::createFromTimestamp((int)$value); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
$error = 'Response type of field %f should be a DateTime, string or int, but %s given'; |
46
|
|
|
throw new InvalidDateTimeFormat(\sprintf($error, $input->getFieldDefinition(), \gettype($value))); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param InputInterface $input |
51
|
|
|
* @param string $format |
52
|
|
|
* @return string|null |
53
|
|
|
* @throws \InvalidArgumentException |
54
|
|
|
*/ |
55
|
|
|
public function getDateTime(InputInterface $input, string $format): ?string |
56
|
|
|
{ |
57
|
|
|
$value = $this->getValue($input); |
58
|
|
|
|
59
|
|
|
if ($value === null) { |
60
|
|
|
return null; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
if ($format === CarbonFormat::HUMAN_READABLE) { |
64
|
|
|
return $value->diffForHumans(); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return $value->format($format); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next
break
.There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.
To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.