Completed
Pull Request — master (#1787)
by Stefano
21:31
created

DateType::getDateTime()   B

Complexity

Conditions 9
Paths 13

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 9

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 35
ccs 23
cts 23
cp 1
rs 8.0555
c 1
b 0
f 0
cc 9
nc 13
nop 1
crap 9
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\ODM\MongoDB\Types;
6
7
use MongoDB\BSON\UTCDateTime;
8
use function date_default_timezone_get;
9
use function explode;
10
use function get_class;
11
use function gettype;
12
use function is_numeric;
13
use function is_scalar;
14
use function is_string;
15
use function sprintf;
16
use function str_pad;
17
use function strpos;
18
19
/**
20
 * The Date type.
21
 *
22
 */
23
class DateType extends Type
24
{
25
    /**
26
     * Converts a value to a DateTime.
27
     * Supports microseconds
28
     *
29
     * @throws InvalidArgumentException If $value is invalid.
30
     * @param  mixed $value \DateTimeInterface|\MongoDB\BSON\UTCDateTime|int|float
31
     * @return \DateTime
32
     */
33 195
    public static function getDateTime($value)
34
    {
35 195
        $datetime = false;
36 195
        $exception = null;
37
38 195
        if ($value instanceof \DateTimeInterface) {
39 179
            return $value;
40 109
        } elseif ($value instanceof UTCDateTime) {
0 ignored issues
show
Bug introduced by
The class MongoDB\BSON\UTCDateTime does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
41 97
            $datetime = $value->toDateTime();
42 97
            $datetime->setTimezone(new \DateTimeZone(date_default_timezone_get()));
43 16
        } elseif (is_numeric($value)) {
44 5
            $seconds = $value;
45 5
            $value = (string) $value;
46 5
            $microseconds = 0;
47
48 5
            if (strpos($value, '.') !== false) {
49 3
                list($seconds, $microseconds) = explode('.', $value);
50 3
                $microseconds = str_pad($microseconds, 6, '0'); // ensure microseconds
51
            }
52
53 5
            $datetime = static::craftDateTime((int) $seconds, $microseconds);
0 ignored issues
show
Bug introduced by
Since craftDateTime() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of craftDateTime() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
54 11
        } elseif (is_string($value)) {
55
            try {
56 8
                $datetime = new \DateTime($value);
57 2
            } catch (\Throwable $e) {
58 2
                $exception = $e;
59
            }
60
        }
61
62 109
        if ($datetime === false) {
63 5
            throw new \InvalidArgumentException(sprintf('Could not convert %s to a date value', is_scalar($value) ? '"' . $value . '"' : gettype($value)), 0, $exception);
64
        }
65
66 104
        return $datetime;
67
    }
68
69 5
    private static function craftDateTime(int $seconds, $microseconds = 0)
70
    {
71
        // @todo fix typing for $microseconds
72 5
        $datetime = new \DateTime();
73 5
        $datetime->setTimestamp($seconds);
74 5
        if ($microseconds > 0) {
75 3
            $datetime = \DateTime::createFromFormat('Y-m-d H:i:s.u', $datetime->format('Y-m-d H:i:s') . '.' . $microseconds);
76
        }
77
78 5
        return $datetime;
79
    }
80
81 183
    public function convertToDatabaseValue($value)
82
    {
83 183
        if ($value === null || $value instanceof UTCDateTime) {
0 ignored issues
show
Bug introduced by
The class MongoDB\BSON\UTCDateTime does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
84 15
            return $value;
85
        }
86
87 182
        $datetime = static::getDateTime($value);
88
89 177
        return new UTCDateTime((int) $datetime->format('Uv'));
90
    }
91
92 9
    public function convertToPHPValue($value)
93
    {
94 9
        if ($value === null) {
95 1
            return null;
96
        }
97
98 8
        return static::getDateTime($value);
99
    }
100
101
    public function closureToMongo()
102
    {
103
        return 'if ($value === null || $value instanceof \MongoDB\BSON\UTCDateTime) { $return = $value; } else { $datetime = \\' . get_class($this) . '::getDateTime($value); $return = new \MongoDB\BSON\UTCDateTime((int) $datetime->format(\'Uv\')); }';
104
    }
105
106 13
    public function closureToPHP()
107
    {
108 13
        return 'if ($value === null) { $return = null; } else { $return = \\' . get_class($this) . '::getDateTime($value); }';
109
    }
110
}
111