1
|
|
|
<?php namespace Limoncello\Flute\Types; |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Copyright 2015-2018 [email protected] |
5
|
|
|
* |
6
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
7
|
|
|
* you may not use this file except in compliance with the License. |
8
|
|
|
* You may obtain a copy of the License at |
9
|
|
|
* |
10
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0 |
11
|
|
|
* |
12
|
|
|
* Unless required by applicable law or agreed to in writing, software |
13
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS, |
14
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
15
|
|
|
* See the License for the specific language governing permissions and |
16
|
|
|
* limitations under the License. |
17
|
|
|
*/ |
18
|
|
|
|
19
|
|
|
use DateTimeInterface; |
20
|
|
|
use Doctrine\DBAL\Types\ConversionException; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @package Limoncello\Flute |
24
|
|
|
*/ |
25
|
|
|
trait TypeTrait |
26
|
|
|
{ |
27
|
|
|
/** |
28
|
|
|
* @param string|DateTimeInterface $value |
29
|
|
|
* @param string $nonJsonFormat |
30
|
|
|
* @param string $typeName |
31
|
|
|
* |
32
|
|
|
* @return DateTimeInterface|null |
33
|
|
|
* |
34
|
|
|
* @throws ConversionException |
35
|
|
|
* |
36
|
|
|
* @SuppressWarnings(PHPMD.StaticAccess) |
37
|
|
|
* @SuppressWarnings(PHPMD.ElseExpression) |
38
|
|
|
*/ |
39
|
19 |
|
private function convertToDateTimeFromString( |
40
|
|
|
$value, |
41
|
|
|
string $nonJsonFormat, |
42
|
|
|
string $typeName |
43
|
|
|
): ?DateTimeInterface { |
44
|
19 |
|
if ($value instanceof DateTimeInterface || $value === null) { |
45
|
4 |
|
$result = $value; |
46
|
15 |
|
} elseif (is_string($value) === true) { |
47
|
13 |
|
$result = DateTime::createFromFormat($nonJsonFormat, $value); |
48
|
13 |
|
$result = $result !== false ? |
49
|
13 |
|
$result : DateTime::createFromFormat(DateTime::JSON_API_FORMAT, $value); |
50
|
13 |
|
if ($result === false) { |
51
|
13 |
|
throw ConversionException::conversionFailed($value, $typeName); |
52
|
|
|
} |
53
|
|
|
} else { |
54
|
2 |
|
throw ConversionException::conversionFailedInvalidType( |
55
|
2 |
|
$value, |
56
|
2 |
|
DateTimeInterface::class, |
57
|
2 |
|
[DateTimeInterface::class, DateTime::class, 'string'] |
58
|
|
|
); |
59
|
|
|
} |
60
|
|
|
|
61
|
15 |
|
return $result; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|