Completed
Push — master ( 33bd04...d74de6 )
by Maciej
18:50 queued 11s
created

DateType::getNextVersion()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\ODM\MongoDB\Types;
6
7
use DateTime;
8
use DateTimeInterface;
9
use DateTimeZone;
10
use InvalidArgumentException;
11
use MongoDB\BSON\UTCDateTime;
12
use Throwable;
13
use const STR_PAD_LEFT;
14
use function abs;
15
use function date_default_timezone_get;
16
use function gettype;
17
use function is_numeric;
18
use function is_scalar;
19
use function is_string;
20
use function round;
21
use function sprintf;
22
use function str_pad;
23
24
/**
25
 * The Date type.
26
 */
27
class DateType extends Type implements Versionable
28
{
29
    /**
30
     * Converts a value to a DateTime.
31
     * Supports microseconds
32
     *
33
     * @param mixed $value \DateTimeInterface|\MongoDB\BSON\UTCDateTime|int|float
34
     *
35
     * @throws InvalidArgumentException If $value is invalid.
36
     */
37 238
    public static function getDateTime($value) : DateTimeInterface
38
    {
39 238
        $datetime  = false;
40 238
        $exception = null;
41
42 238
        if ($value instanceof DateTimeInterface) {
43 199
            return $value;
44
        }
45
46 142
        if ($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...
47 118
            $datetime = $value->toDateTime();
48 118
            $datetime->setTimezone(new DateTimeZone(date_default_timezone_get()));
49 31
        } elseif (is_numeric($value)) {
50 10
            $value         = (float) $value;
51 10
            $seconds       = (int) $value;
52 10
            $microseconds  = abs(round($value - $seconds, 6));
53 10
            $microseconds *= 1000000;
54
55 10
            $datetime = static::craftDateTime($seconds, (int) $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...
56 21
        } elseif (is_string($value)) {
57
            try {
58 15
                $datetime = new DateTime($value);
59 4
            } catch (Throwable $e) {
60 4
                $exception = $e;
61
            }
62
        }
63
64 142
        if ($datetime === false) {
65 10
            throw new InvalidArgumentException(sprintf('Could not convert %s to a date value', is_scalar($value) ? '"' . $value . '"' : gettype($value)), 0, $exception);
66
        }
67
68 132
        return $datetime;
69
    }
70
71
    /**
72
     * @return DateTime|false
73
     */
74 10
    private static function craftDateTime(int $seconds, int $microseconds = 0)
75
    {
76 10
        $datetime = new DateTime();
77 10
        $datetime->setTimestamp($seconds);
78 10
        if ($microseconds > 0) {
79 6
            $datetime = DateTime::createFromFormat('Y-m-d H:i:s.u', $datetime->format('Y-m-d H:i:s') . '.' . str_pad((string) $microseconds, 6, '0', STR_PAD_LEFT));
80
        }
81
82 10
        return $datetime;
83
    }
84
85 208
    public function convertToDatabaseValue($value)
86
    {
87 208
        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...
88 18
            return $value;
89
        }
90
91 206
        $datetime = static::getDateTime($value);
92
93 196
        return new UTCDateTime((int) $datetime->format('Uv'));
94
    }
95
96 16
    public function convertToPHPValue($value)
97
    {
98 16
        if ($value === null) {
99 2
            return null;
100
        }
101
102 14
        return static::getDateTime($value);
103
    }
104
105
    public function closureToMongo() : string
106
    {
107
        return 'if ($value === null || $value instanceof \MongoDB\BSON\UTCDateTime) { $return = $value; } else { $datetime = \\' . static::class . '::getDateTime($value); $return = new \MongoDB\BSON\UTCDateTime((int) $datetime->format(\'Uv\')); }';
108
    }
109
110 20
    public function closureToPHP() : string
111
    {
112 20
        return 'if ($value === null) { $return = null; } else { $return = \\' . static::class . '::getDateTime($value); }';
113
    }
114
115 3
    public function getNextVersion($current)
116
    {
117 3
        return new DateTime();
118
    }
119
}
120