Completed
Pull Request — master (#178)
by Fèvre
02:39
created

AppController::initialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
1
<?php
2
namespace App\Controller;
3
4
use App\Event\Badges;
5
use App\I18n\Language;
6
use Cake\Controller\Controller;
7
use Cake\Event\Event;
8
use Cake\I18n\Time;
9
10
class AppController extends Controller
11
{
12
13
    /**
14
     * Initialization hook method.
15
     *
16
     * Use this method to add common initialization code like loading components.
17
     *
18
     * e.g. `$this->loadComponent('Security');`
19
     *
20
     * @return void
21
     */
22
    public function initialize()
23
    {
24
        parent::initialize();
25
26
        $this->loadComponent('RequestHandler');
27
        $this->loadComponent('Flash');
28
    }
29
30
    /**
31
     * Components.
32
     *
33
     * @var array
34
     */
35
    public $components = [
36
        'Flash',
37
        'Cookie',
38
        'Acl.Acl',
39
        'SessionsActivity',
40
    /**
41
     * If you want enable CSRF uncomment this.
42
     * I recommend to enable it. If i have disable it, it's because
43
     * CloudFlare have some problem with the header X-CSRF-Token (AJAX Request).
44
     */
45
        /*'Csrf' => [
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
46
            'secure' => true
47
        ],*/
48
        'Auth' => [
49
            'className' => 'AclAuth',
50
            'allowedActionsForBanned' => [
51
                'Pages' => [
52
                    'home'
53
                ]
54
            ],
55
            'authenticate' => [
56
                'Form',
57
                'Xety/Cake3CookieAuth.Cookie'
58
            ],
59
            'flash' => [
60
                'element' => 'error',
61
                'key' => 'flash',
62
                'params' => [
63
                    'class' => 'error'
64
                ]
65
            ],
66
            'authorize' => [
67
                'Acl.Actions' => [
68
                    'actionPath' => 'app/'
69
                ]
70
            ],
71
            'loginAction' => [
72
                'controller' => 'users',
73
                'action' => 'login',
74
                'prefix' => false
75
            ],
76
            'unauthorizedRedirect' => [
77
                'controller' => 'pages',
78
                'action' => 'home',
79
                'prefix' => false
80
            ],
81
            'loginRedirect' => [
82
                'controller' => 'pages',
83
                'action' => 'home'
84
            ],
85
            'logoutRedirect' => [
86
                'controller' => 'pages',
87
                'action' => 'home'
88
            ],
89
            'authError' => 'You are not authorized to access that location !'
90
        ]
91
    ];
92
93
    /**
94
     * Helpers.
95
     *
96
     * @var array
97
     */
98
    public $helpers = [
99
        'Form' => [
100
            'templates' => [
101
                'error' => '<div class="text-danger">{{content}}</div>',
102
                'radioWrapper' => '{{input}}{{label}}',
103
                'nestingLabel' => '<label{{attrs}}>{{text}}</label>'
104
            ]
105
        ],
106
        'Acl'
107
    ];
108
109
    /**
110
     * Before render callback.
111
     *
112
     * @param \Cake\Event\Event $event The beforeRender event.
113
     * @return \Cake\Network\Response|null|void
114
     */
115
    public function beforeRender(Event $event)
116
    {
117
        if (!array_key_exists('_serialize', $this->viewVars) &&
118
            in_array($this->response->type(), ['application/json', 'application/xml'])
119
        ) {
120
            $this->set('_serialize', true);
121
        }
122
    }
123
124
    /**
125
     * beforeFilter handle.
126
     *
127
     * @param Event $event The beforeFilter event that was fired.
128
     *
129
     * @return void
130
     */
131
    public function beforeFilter(Event $event)
132
    {
133
        //Define the language.
134
        $language = new Language($this);
135
        $language->setLanguage();
136
137
        //Check for the Premium.
138
        $premium = $this->request->session()->read('Premium.Check') ? $this->request->session()->read('Premium.Check') : null;
139
        if (!is_null($premium)) {
140
            $this->loadModel('PremiumTransactions');
141
142
            $transaction = $this->PremiumTransactions
0 ignored issues
show
Documentation introduced by
The property PremiumTransactions does not exist on object<App\Controller\AppController>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
143
                ->find()
144
                ->where([
145
                    'txn' => $this->request->session()->read('Premium.Check'),
146
                    'user_id' => $this->request->session()->read('Auth.User.id')
147
                ])
148
                ->contain(['Users'])
149
                ->first();
150
151
            if ($transaction) {
152
                //Write in the session the virtual field.
153
                $this->Auth->setUser($transaction->user->toArray());
154
                $this->request->session()->write('Auth.User.premium', $transaction->user->premium);
155
156
                $this->request->session()->delete('Premium.Check');
157
            }
158
        }
159
160
        //Set trustProxy or get the original visitor IP.
161
        $this->request->trustProxy = true;
162
163
        //Automatically Login.
164
        if (!$this->Auth->user() && $this->Cookie->read('CookieAuth')) {
165
            $this->loadModel('Users');
166
167
            $user = $this->Auth->identify();
168
            if ($user && $user['is_deleted'] == false) {
169
                $this->Auth->setUser($user);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->Auth->identify() on line 167 can also be of type boolean; however, Cake\Controller\Component\AuthComponent::setUser() does only seem to accept array|object<ArrayAccess>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
170
171
                $user = $this->Users->newEntity($user);
0 ignored issues
show
Documentation introduced by
The property Users does not exist on object<App\Controller\AppController>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
172
                $user->isNew(false);
173
174
                $user->last_login = new Time();
175
                $user->last_login_ip = $this->request->clientIp();
176
177
                $this->Users->save($user);
0 ignored issues
show
Documentation introduced by
The property Users does not exist on object<App\Controller\AppController>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
178
179
                //Write in the session the virtual field.
180
                $this->request->session()->write('Auth.User.premium', $user->premium);
181
182
                //Event.
183
                $this->eventManager()->attach(new Badges($this));
0 ignored issues
show
Documentation introduced by
new \App\Event\Badges($this) is of type object<App\Event\Badges>, 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...
184
185
                $user = new Event('Model.Users.register', $this, [
186
                    'user' => $user
187
                ]);
188
                $this->eventManager()->dispatch($user);
189
            } else {
190
                $this->Cookie->delete('CookieAuth');
191
            }
192
        }
193
194
        if (isset($this->request->params['prefix'])) {
195
            $prefix = explode('/', $this->request->params['prefix'])[0];
196
197
            switch ($prefix) {
198
                case 'admin':
199
                    $this->layout = 'admin';
0 ignored issues
show
Documentation introduced by
The property layout does not exist on object<App\Controller\AppController>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
200
                    break;
201
            }
202
        }
203
204
        $allowCookies = $this->Cookie->check('allowCookies');
205
        $this->set(compact('allowCookies'));
206
    }
207
}
208