Completed
Push — master ( b61244...d93525 )
by Fèvre
14s
created

Badges::premiumBadge()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 48
Code Lines 30

Duplication

Lines 48
Ratio 100 %

Importance

Changes 0
Metric Value
dl 48
loc 48
rs 8.551
c 0
b 0
f 0
cc 5
eloc 30
nc 5
nop 1
1
<?php
2
namespace App\Event;
3
4
use App\Event\Notifications;
5
use App\Model\Entity\BlogArticlesComment;
6
use App\Model\Entity\User;
7
use Cake\Controller\ComponentRegistry;
8
use Cake\Controller\Controller;
9
use Cake\Event\Event;
10
use Cake\Event\EventListenerInterface;
11
use Cake\Event\EventManager;
12
use Cake\I18n\Time;
13
use Cake\Network\Request;
14
use Cake\Network\Response;
15
use Cake\ORM\TableRegistry;
16
17
class Badges implements EventListenerInterface
18
{
19
20
    /**
21
     * Construct method.
22
     *
23
     * @param \Cake\Controller\Controller $controller The controller instance where the Event is dispatched.
24
     */
25
    public function __construct($controller = null)
26
    {
27
        $this->Flash = $controller->loadComponent('Flash');
0 ignored issues
show
Bug introduced by
The property Flash does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Bug introduced by
It seems like $controller is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
28
    }
29
30
    /**
31
     * ImplementedEvents method.
32
     *
33
     * @return array
34
     */
35
    public function implementedEvents()
36
    {
37
        return [
38
            'Model.BlogArticlesComments.add' => 'commentsBadge',
39
            'Model.Users.register' => 'registerBadge'
40
        ];
41
    }
42
43
    /**
44
     * Unlock all badges related to comments.
45
     *
46
     * @param \Cake\Event\Event $event The Model.Users.register event that was fired.
47
     *
48
     * @return bool
49
     */
50
    public function registerBadge(Event $event)
51
    {
52
        $this->Badges = TableRegistry::get('Badges');
53
        $user = $event->getData('user');
54
55
        if (!$user instanceof User) {
56
            return false;
57
        }
58
59
        $badges = $this->Badges
0 ignored issues
show
Deprecated Code introduced by
The method Cake\ORM\Query::hydrate() has been deprecated with message: 3.4.0 Use enableHydration()/isHydrationEnabled() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
60
            ->find('all')
61
            ->select([
62
                'id',
63
                'name',
64
                'picture',
65
                'rule'
66
            ])
67
            ->where([
68
                'type' => 'registration'
69
            ])
70
            ->hydrate(false)
71
            ->toArray();
72
73
        if (empty($badges)) {
74
            return true;
75
        }
76
77
        $this->Users = TableRegistry::get('Users');
0 ignored issues
show
Bug introduced by
The property Users does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
78
79
        $userId = $event->getData('user')->id;
80
        $user = $this->Users
81
            ->find()
82
            ->where([
83
                'id' => $userId
84
            ])
85
            ->select([
86
                'created'
87
            ])
88
            ->first();
89
90
        $today = new Time();
91
        $created = $user->created;
92
        $diff = $today->diff($created)->y;
93
94
        foreach ($badges as $badge) {
95
            if ($diff >= $badge['rule']) {
96
                $this->_unlockBadge($badge, $userId);
97
            }
98
        }
99
100
        return true;
101
    }
102
103
    /**
104
     * Unlock all badges related to comments.
105
     *
106
     * @param \Cake\Event\Event $event The Model.BlogArticlesComments.add event that was fired.
107
     *
108
     * @return bool
109
     */
110
    public function commentsBadge(Event $event)
111
    {
112
        $this->Badges = TableRegistry::get('Badges');
113
        $comment = $event->getData('comment');
114
115
        if (!$comment instanceof BlogArticlesComment) {
116
            return false;
117
        }
118
119
        $badges = $this->Badges
0 ignored issues
show
Deprecated Code introduced by
The method Cake\ORM\Query::hydrate() has been deprecated with message: 3.4.0 Use enableHydration()/isHydrationEnabled() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
120
            ->find('all')
121
            ->select([
122
                'id',
123
                'name',
124
                'picture',
125
                'rule'
126
            ])
127
            ->where([
128
                'type' => 'comments'
129
            ])
130
            ->hydrate(false)
131
            ->toArray();
132
133
        if (empty($badges)) {
134
            return true;
135
        }
136
137
        $this->Users = TableRegistry::get('Users');
138
139
        $userId = $event->getData('comment')->user_id;
140
        $userComments = $this->Users
0 ignored issues
show
Deprecated Code introduced by
The method Cake\ORM\Query::hydrate() has been deprecated with message: 3.4.0 Use enableHydration()/isHydrationEnabled() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
141
            ->find()
142
            ->where([
143
                'id' => $userId
144
            ])
145
            ->select([
146
                'blog_articles_comment_count'
147
            ])
148
            ->hydrate(false)
149
            ->first();
150
151
        foreach ($badges as $badge) {
152
            if ($userComments['blog_articles_comment_count'] >= $badge['rule']) {
153
                $this->_unlockBadge($badge, $userId);
154
            }
155
        }
156
157
        return true;
158
    }
159
160
    /**
161
     * Unlock a badge and set a Flash message.
162
     *
163
     * @param array $badge The badge to unlock.
164
     * @param int $userId  The user at unlock the badge.
165
     *
166
     * @return bool
167
     */
168
    protected function _unlockBadge($badge, $userId)
169
    {
170
        $this->BadgesUsers = TableRegistry::get('BadgesUsers');
0 ignored issues
show
Bug introduced by
The property BadgesUsers does not seem to exist. Did you mean Badges?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
171
172
        $hasBadge = $this->BadgesUsers
0 ignored issues
show
Bug introduced by
The property BadgesUsers does not seem to exist. Did you mean Badges?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
173
            ->find()
174
            ->where([
175
                'badge_id' => $badge['id'],
176
                'user_id' => $userId
177
            ])
178
            ->first();
179
180
        if (!is_null($hasBadge)) {
181
            return true;
182
        }
183
184
        $data = [];
185
        $data['badge_id'] = $badge['id'];
186
        $data['user_id'] = $userId;
187
        $badgeUser = $this->BadgesUsers->newEntity($data);
0 ignored issues
show
Bug introduced by
The property BadgesUsers does not seem to exist. Did you mean Badges?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
188
189
        $badgeUser = $this->BadgesUsers->save($badgeUser);
0 ignored issues
show
Bug introduced by
The property BadgesUsers does not seem to exist. Did you mean Badges?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
190
191
        $this->Flash->badge('You have unlocked a badge !', [
192
            'key' => 'badge',
193
            'params' => [
194
                'badge' => $badge
195
            ]
196
        ]);
197
198
        EventManager::instance()->attach(new Notifications());
0 ignored issues
show
Documentation introduced by
new \App\Event\Notifications() is of type object<App\Event\Notifications>, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Deprecated Code introduced by
The method Cake\Event\EventManager::attach() has been deprecated with message: 3.0.0 Use on() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
199
        $event = new Event('Model.Notifications.new', $this, [
200
            'type' => 'badge',
201
            'badge' => $badgeUser
202
        ]);
203
        EventManager::instance()->dispatch($event);
204
205
        return true;
206
    }
207
}
208