UsersPresenter::beforeRender()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace AdminModule;
4
5
use Nette\Application\UI;
6
use Nette\Mail;
7
8
/**
9
 * Users presenter.
10
 * @author Tomáš Voslař <tomas.voslar at webcook.cz>
11
 * @package WebCMS2
12
 */
13
class UsersPresenter extends \AdminModule\BasePresenter
14
{
15
    /* @var User */
16
    private $userEntity;
17
18
    /* @var Role */
19
    private $role;
20
21 4
    protected function beforeRender()
22
    {
23 4
        parent::beforeRender();
24 4
    }
25
26 4
    protected function startup()
27
    {
28 4
        parent::startup();
29 4
    }
30
31 1
    public function renderDefault()
32
    {
33 1
        $this->reloadContent();
34 1
    }
35
36 4
    protected function createComponentUserForm()
37
    {
38 1
        $roles = $this->em->getRepository("WebCMS\Entity\Role")->findAll();
39 1
        $tmp = array();
40 1
        foreach ($roles as $r) {
41 1
            $tmp[$r->getId()] = $r->getName();
42 1
        }
43 1
        $roles = $tmp;
44
45 1
        if ($this->getUser()->getRoles()[0] !== 'superadmin') {
46
            unset($roles[1]);
47
        }
48
49 1
        $infoEmail = $this->settings->get('Info email', \WebCMS\Settings::SECTION_BASIC)->getValue();
50 1
        $disableEmail = empty($infoEmail);
51
52 1
        $form = $this->createForm();
53 1
        $form->addText('username', 'Username')->setAttribute('class', 'form-control');
0 ignored issues
show
Documentation introduced by
'form-control' is of type string, but the function expects a boolean.

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...
54 1
        $form->addSelect('role', 'Role')->setTranslator(null)->setItems($roles)->setAttribute('class', 'form-control');
0 ignored issues
show
Documentation introduced by
'form-control' is of type string, but the function expects a boolean.

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...
55 1
        $form->addText('name', 'Name')->setAttribute('class', 'form-control');
0 ignored issues
show
Documentation introduced by
'form-control' is of type string, but the function expects a boolean.

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...
56 1
        $form->addText('email', 'Email')->setAttribute('class', 'form-control');
0 ignored issues
show
Documentation introduced by
'form-control' is of type string, but the function expects a boolean.

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...
57 1
        $form->addPassword('password', 'Password')->setAttribute('class', 'form-control');
0 ignored issues
show
Documentation introduced by
'form-control' is of type string, but the function expects a boolean.

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...
58 1
        $form->addCheckbox('sendInfoEmail', 'Send info email with password')->setDisabled($disableEmail);
59 1
        $form->addSubmit('save', 'Save')->setAttribute('class', 'btn btn-success');
0 ignored issues
show
Documentation introduced by
'btn btn-success' is of type string, but the function expects a boolean.

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...
60
61 1
        $form->onSuccess[] = callback($this, 'userEntityFormSubmitted');
62
63 1
        if ($this->userEntity) {
64 1
            $form->setDefaults($this->userEntity->toArray());
65 4
        }
66
67 1
        return $form;
68
    }
69
70 4
    protected function createComponentGrid($name)
71
    {
72 1
        $grid = $this->createGrid($this, $name, "User", null, array(
73 1
            'id <> 1',
74 1
        ));
75
76 1
        $grid->addColumnText('username', 'Name')->setSortable();
77
78 4
        $grid->addActionHref("updateUser", 'Edit')->getElementPrototype()->addAttributes(array('class' => array('btn', 'btn-primary', 'ajax'), 'data-toggle' => 'modal', 'data-target' => '#myModal', 'data-remote' => 'false'));
79 4
        $grid->addActionHref("deleteUser", 'Delete')->getElementPrototype()->addAttributes(array('class' => array('btn', 'btn-danger'), 'data-confirm' => 'Are you sure you want to delete the item?'));
80
81 4
        return $grid;
82 4
    }
83
84 4
    public function actionUpdateUser($id)
85 4
    {
86 4
        if ($id) {
87
            $this->userEntity = $this->em->find("WebCMS\Entity\User", $id);
88
        } else {
89 1
            $this->userEntity = new \WebCMS\Entity\User();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \WebCMS\Entity\User() of type object<WebCMS\Entity\User> is incompatible with the declared type object<AdminModule\User> of property $userEntity.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
90
        }
91 1
    }
92
93
    public function actionDeleteUser($id)
94
    {
95
        $this->userEntity = $this->em->find("WebCMS\Entity\User", $id);
96
        $this->em->remove($this->userEntity);
97
        $this->em->flush();
98
99
        $this->flashMessage('User has been removed.', 'success');
100
101
        $this->forward('Users:default');
102
    }
103
104 1
    public function renderUpdateUser($id)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
105
    {
106 1
        $this->reloadModalContent();
107
108 1
        $this->template->userEntity = $this->userEntity;
0 ignored issues
show
Documentation introduced by
The property $template is declared private in Nette\Application\UI\Control. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

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...
Bug introduced by
Accessing userEntity on the interface Nette\Templating\ITemplate suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
109 1
    }
110
111 4
    public function userEntityFormSubmitted(UI\Form $form)
112
    {
113
        $values = $form->getValues();
114
115
        $role = $this->em->find("WebCMS\Entity\Role", $values->role);
116
        $password = $this->getContext()->authenticator->calculateHash($values->password);
117
118
        $this->userEntity->setName($values->name);
119
        $this->userEntity->setEmail($values->email);
120
121
        if (array_key_exists('sendInfoEmail', $values) && $values->sendInfoEmail) {
122
            // send mail with new password
123
            $email = new Mail\Message();
124
            $email->setFrom($this->settings->get('Info email', \WebCMS\Settings::SECTION_BASIC)->getValue());
125
            $email->addTo($this->userEntity->getEmail());
126
            $email->setSubject($this->settings->get('User new password subject', \WebCMS\Settings::SECTION_EMAIL)->getValue(false));
127
            $email->setHtmlBody($this->settings->get('User new password', \WebCMS\Settings::SECTION_EMAIL)->getValue(false, array(
128
                '[PASSWORD]',
129
                '[LOGIN]',
130
                ), array(
131
                $values->password,
132
                $values->username,
133
            )));
134
135
            $email->send();
136
137
            $this->flashMessage('Info email with new password has been sent.', 'success');
138
        }
139
140
        if (!empty($values->password)) {
141
            $this->userEntity->setPassword($password);
142 4
        }
143
144
        $this->userEntity->setUsername($values->username);
145
        $this->userEntity->setRole($role);
146
147 4
        $this->em->persist($this->userEntity);
148
        $this->em->flush();
149
150
        $this->flashMessage('User has been updated.', 'success');
151
152
        $this->forward('Users:default');
153
    }
154
155
    /* ROLES */
156
157 1
    public function renderRoles()
158
    {
159 1
        $this->reloadContent();
160 1
    }
161
162 2
    public function actionUpdateRole($id)
163 2
    {
164 1
        if ($id) {
165
            $this->role = $this->em->find("WebCMS\Entity\Role", $id);
166
        } else {
167 1
            $this->role = new \WebCMS\Entity\Role();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \WebCMS\Entity\Role() of type object<WebCMS\Entity\Role> is incompatible with the declared type object<AdminModule\Role> of property $role.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
168
        }
169 1
    }
170
171 View Code Duplication
    public function actionDeleteRole($id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
172
    {
173
        $this->role = $this->em->find("WebCMS\Entity\Role", $id);
174
        $this->em->remove($this->role);
175
        $this->em->flush();
176
177
        $this->flashMessage('Role has been removed.', 'success');
178
179
        $this->forward('Users:roles');
180
    }
181
182 1
    public function renderUpdateRole($id)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
183
    {
184 1
        $this->reloadContent();
185
186 1
        $this->template->role = $this->role;
0 ignored issues
show
Documentation introduced by
The property $template is declared private in Nette\Application\UI\Control. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

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...
Bug introduced by
Accessing role on the interface Nette\Templating\ITemplate suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
187 1
    }
188
189 2
    protected function createComponentRoleForm()
190
    {
191 1
        $resources = \WebCMS\Helpers\SystemHelper::getResources();
192
193 1
        $pages = $this->em->getRepository('WebCMS\Entity\Page')->findAll();
194
195 1
        foreach ($pages as $page) {
196
            if ($page->getParent() != NULL) {
197
                $module = $this->createObject($page->getModuleName());
198
199
                foreach ($module->getPresenters() as $presenter) {
200
                    $suffix = $presenter['name'] == $page->getModuleName() ? '' : ' '.$presenter['name'];
201
202
                    $key = 'admin:'.$page->getModuleName().':'.$presenter['name'].$page->getId();
203
                    $resources[$key] = $page->getTitle().$suffix.' ('.$page->getLanguage()->getName().')';
204
                }
205
            }
206 1
        }
207
208 1
        $form = $this->createForm();
209 1
        $form->addCheckbox('automaticEnable', 'Automatic enable');
210 1
        $form->addText('name', 'Name')->setAttribute('class', 'form-control');
0 ignored issues
show
Documentation introduced by
'form-control' is of type string, but the function expects a boolean.

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...
211
212 1
        $c = 0;
213 1
        foreach ($resources as $key => $r) {
214 1
            if (strpos('$r', ':') !== FALSE) {
215
                $form->addCheckbox('res'.str_replace(':', '', $key), $r)->setAttribute('class', 'check');
0 ignored issues
show
Documentation introduced by
'check' is of type string, but the function expects a boolean.

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...
216
            } else {
217 1
                $form->addCheckbox('res'.str_replace(':', '', $key), $r)->setTranslator(null)->setAttribute('class', 'check');
0 ignored issues
show
Documentation introduced by
'check' is of type string, but the function expects a boolean.

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...
218
            }
219
220 2
            $c++;
221 1
        }
222
223
        // defaults setting
224 1
        $new = $this->role->getName();
225 1
        if (!empty($new)) {
226
            $defaultsPermissions = array();
227
            foreach ($this->role->getPermissions() as $key => $per) {
228
                $defaultsPermissions['res'.str_replace(':', '', $per->getResource())] = $per->getRead();
229
            }
230
231
            $form->setDefaults($this->role->toArray() + $defaultsPermissions);
232
        }
233
234 1
        $form->onSuccess[] = callback($this, 'roleFormSubmitted');
235 1
        $form->addSubmit('save', 'Save')->setAttribute('class', 'btn btn-success');
0 ignored issues
show
Documentation introduced by
'btn btn-success' is of type string, but the function expects a boolean.

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...
236
237 1
        return $form;
238
    }
239
240 1
    protected function createComponentRolesGrid($name)
241
    {
242 1
        $grid = $this->createGrid($this, $name, "Role", null, array(
243 1
            'id <> 1',
244 1
        ));
245
246 1
        $grid->addColumnText('name', 'Name')->setSortable();
247
248 1
        $grid->addActionHref("updateRole", 'Edit')->getElementPrototype()->addAttributes(array('class' => array('btn', 'btn-primary', 'ajax')));
249 1
        $grid->addActionHref("deleteRole", 'Delete')->getElementPrototype()->addAttributes(array('class' => array('btn', 'btn-danger'), 'data-confirm' => 'Are you sure you want to delete the item?'));
250
251 1
        return $grid;
252
    }
253
254 2
    public function roleFormSubmitted(UI\Form $form)
255
    {
256
        $values = $form->getValues();
257
258
        if (empty($values->name)) {
259
            $this->flashMessage('Please fill in at least the name.', 'danger');
260
            $this->forward('this');
261
        }
262
263
        $this->role->setName($values->name);
264
        $this->role->setAutomaticEnable($values->automaticEnable);
265
266
        if (!$this->role->getId()) {
267
            $this->em->persist($this->role);
268
        }
269
270
        $this->flashMessage('Role has been added.', 'success');
271
272
        // delete permissions
273
        $permissions = $this->role->getPermissions();
274
        foreach ($permissions as $per) {
275
            $this->em->remove($per);
276
        }
277
278
        // save permissions
279
        $perArray = array();
280
        foreach ($values as $key => $val) {
281
            if (strpos($key, 'res') !== FALSE) {
282
                $permission = new \WebCMS\Entity\Permission();
283
284
                $pageId = filter_var($key, FILTER_SANITIZE_NUMBER_INT);
285
                $page = $this->em->getRepository('WebCMS\Entity\Page')->find($pageId);
286
287
                $resource = 'admin:'.str_replace('resadmin', '', $key);
288 2
                $permission->setResource($resource);
289
                $permission->setPage($page);
290
                $permission->setRead($val);
291
292
                $perArray[] = $permission;
293
            }
294
        }
295
296
        $this->role->setPermissions($perArray);
297
298
        $this->em->flush(); // persist all changes
299
300
        $this->forward('Users:roles');
301
    }
302
}
303