Completed
Branch 09branch (946dde)
by Anton
05:16
created

TimestampsTrait::touch()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 0
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * spiral
4
 *
5
 * @author    Wolfy-J
6
 */
7
8
namespace Spiral\Models\Traits;
9
10
use MongoDB\BSON\UTCDateTime;
11
use Spiral\Models\Events\DescribeEvent;
12
use Spiral\Models\Events\EntityEvent;
13
use Spiral\ODM\DocumentEntity;
14
use Spiral\ORM\Events\RecordEvent;
15
use Spiral\ORM\RecordEntity;
16
use Spiral\ORM\RecordInterface;
17
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
18
19
/**
20
 * Timestamps traits adds two magic fields into model/document schema time updated and time created
21
 * automatically populated when entity being saved. Can be used in Models and Documents.
22
 *
23
 * ORM: time_created, time_updated
24
 * ODM: timeCreated, timeUpdated
25
 */
26
trait TimestampsTrait
27
{
28
    /**
29
     * Touch object and update it's time_updated value.
30
     *
31
     * @return $this
32
     */
33
    public function touch()
34
    {
35
        if ($this instanceof RecordEntity) {
36
            $this->setField('time_updated', new \DateTime());
37
        } elseif ($this instanceof DocumentEntity) {
38
            $this->setField('timeUpdated', new UTCDateTime(time()));
39
        }
40
41
        return $this;
42
    }
43
44
    /**
45
     * Called when model class are initiated.
46
     */
47
    protected static function __init__timestamps()
48
    {
49
        /**
50
         * Updates values of time_updated and time_created fields.
51
         */
52
        $listener = self::__timestamps__saveListener();
53
54
        self::events()->addListener('create', $listener);
55
        self::events()->addListener('update', $listener);
56
    }
57
58
    /**
59
     * When schema being analyzed.
60
     */
61
    protected static function __describe__timestamps()
62
    {
63
        self::events()->addListener('describe', self::__timestamps__describeListener());
64
    }
65
66
    /**
67
     * DataEntity save.
68
     *
69
     * @return \Closure
70
     */
71
    private static function __timestamps__saveListener()
72
    {
73
        return function (EntityEvent $event, $eventName) {
74
            $entity = $event->getEntity();
75
            if ($event instanceof RecordEvent && $event->isContextual()) {
76
                switch ($eventName) {
77
                    case 'create':
78
                        $entity->setField('time_created', new \DateTime());
79
                        $event->getCommand()->addContext('time_created', new \DateTime());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Spiral\ORM\CommandInterface as the method addContext() does only exist in the following implementations of said interface: Spiral\ORM\Commands\ContextualDeleteCommand, Spiral\ORM\Commands\InsertCommand, Spiral\ORM\Commands\TransactionalCommand, Spiral\ORM\Commands\UpdateCommand.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
80
81
                    //no-break
82
                    case 'update':
83
                        $entity->setField('time_updated', new \DateTime());
84
                        $event->getCommand()->addContext('time_updated', new \DateTime());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Spiral\ORM\CommandInterface as the method addContext() does only exist in the following implementations of said interface: Spiral\ORM\Commands\ContextualDeleteCommand, Spiral\ORM\Commands\InsertCommand, Spiral\ORM\Commands\TransactionalCommand, Spiral\ORM\Commands\UpdateCommand.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
85
                }
86
            }
87
88
            if ($entity instanceof DocumentEntity) {
89
                switch ($eventName) {
90
                    case 'create':
91
                        $entity->setField('timeCreated', new UTCDateTime(time() * 1000));
92
                    //no-break
93
                    case 'update':
94
                        $entity->setField('timeUpdated', new UTCDateTime(time() * 1000));
95
                }
96
            }
97
        };
98
    }
99
100
    /**
101
     * Create appropriate schema modification listener. Executed only in analysis.
102
     *
103
     * @return callable
104
     */
105
    private static function __timestamps__describeListener()
106
    {
107
        return function (DescribeEvent $event) {
108
            if ($event->getProperty() != 'schema') {
109
                return;
110
            }
111
112
            $schema = $event->getValue();
113
114
            if ($event->getReflection()->isSubclassOf(RecordInterface::class)) {
115
                $schema += [
116
                    'time_created' => 'datetime, null',
117
                    'time_updated' => 'datetime, null'
118
                ];
119
            } elseif ($event->getReflection()->isSubclassOf(DocumentEntity::class)) {
120
                $schema += [
121
                    'timeCreated' => 'timestamp',
122
                    'timeUpdated' => 'timestamp'
123
                ];
124
            }
125
126
            //Updating schema value
127
            $event->setValue($schema);
128
        };
129
    }
130
131
    /**
132
     * @return \Symfony\Component\EventDispatcher\EventDispatcherInterface
133
     */
134
    abstract public static function events(): EventDispatcherInterface;
135
}