TypeTrait   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 2
dl 0
loc 39
ccs 14
cts 14
cp 1
rs 10
c 0
b 0
f 0

1 Method

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