Completed
Push — master ( 7e26ec...48ac62 )
by Andreu
02:28
created

UniversalTimestampType::convertToDatabaseValue()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 2
Metric Value
c 2
b 1
f 2
dl 0
loc 10
rs 8.8571
cc 5
eloc 7
nc 5
nop 1
1
<?php
2
3
4
namespace Litipk\Jiffy\Doctrine\ODM\MongoDB;
5
6
7
use Litipk\Jiffy\UniversalTimestamp;
8
use Doctrine\ODM\MongoDB\Types\Type;
9
10
11
/**
12
 * Class UniversalTimestampType
13
 * @package Litipk\Jiffy\Doctrine\ODM\MongoDB
14
 */
15
class UniversalTimestampType extends Type
16
{
17
    /**
18
     * @param \MongoDate|\DateTimeInterface $mongoTimestamp
19
     * @return null|UniversalTimestamp
20
     */
21
    public function convertToPHPValue($mongoTimestamp)
22
    {
23
        return (null !== $mongoTimestamp) ? UniversalTimestamp::fromWhatever($mongoTimestamp) : null;
24
    }
25
26
    /**
27
     * @param UniversalTimestamp $timestamp
28
     * @return null|\MongoDate
29
     */
30
    public function convertToDatabaseValue($timestamp)
31
    {
32
        if (extension_loaded('mongo')) {
33
            return (null !== $timestamp) ? $timestamp->asMongoDate() : null;
34
        } elseif (extension_loaded('mongodb')) {
35
            return (null !== $timestamp) ? $timestamp->asMongodbUTCDateTime() : null;
36
        } else {
37
            throw new \RuntimeException('Missing MongoDB extension');
38
        }
39
    }
40
41
    /**
42
     * @return string
43
     */
44
    public function closureToPHP()
45
    {
46
        return '$return = (null !== $value) ? \Litipk\Jiffy\UniversalTimestamp::fromWhatever($value) : null;';
47
    }
48
49
    /**
50
     * @return string
51
     */
52
    public function closureToMongo()
53
    {
54
        if (extension_loaded('mongo')) {
55
            return '$return = (null !== $v) ? $v->asMongoDate() : null;';
56
        } elseif (extension_loaded('mongodb')) {
57
            return '$return (null !== $timestamp) ? $timestamp->asMongodbUTCDateTime() : null;';
58
        } else {
59
            throw new \RuntimeException('Missing MongoDB extension');
60
        }
61
    }
62
}
63