Completed
Push — ezp25003-trash_subitems_count_... ( c4ee15...9f71a1 )
by
unknown
60:38 queued 26:57
created

Role::updateRole()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 14
rs 9.4285
cc 1
eloc 8
nc 1
nop 2
1
<?php
2
3
/**
4
 * File containing the Role controller class.
5
 *
6
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
7
 * @license For full copyright and license information view LICENSE file distributed with this source code.
8
 *
9
 * @version //autogentag//
10
 */
11
namespace eZ\Publish\Core\REST\Server\Controller;
12
13
use eZ\Publish\API\Repository\Exceptions\LimitationValidationException;
14
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
15
use eZ\Publish\Core\Base\Exceptions\ForbiddenException;
16
use eZ\Publish\Core\Base\Exceptions\InvalidArgumentException;
17
use eZ\Publish\Core\Base\Exceptions\UnauthorizedException;
18
use eZ\Publish\Core\REST\Common\Message;
19
use eZ\Publish\Core\REST\Common\Exceptions;
20
use eZ\Publish\Core\REST\Server\Exceptions\BadRequestException;
21
use eZ\Publish\Core\REST\Server\Values;
22
use eZ\Publish\Core\REST\Server\Controller as RestController;
23
use eZ\Publish\API\Repository\RoleService;
24
use eZ\Publish\API\Repository\UserService;
25
use eZ\Publish\API\Repository\LocationService;
26
use eZ\Publish\API\Repository\Values\User\RoleCreateStruct;
27
use eZ\Publish\API\Repository\Values\User\RoleUpdateStruct;
28
use eZ\Publish\API\Repository\Exceptions\NotFoundException as APINotFoundException;
29
use Symfony\Component\HttpFoundation\Request;
30
31
/**
32
 * Role controller.
33
 */
34
class Role extends RestController
35
{
36
    /**
37
     * Role service.
38
     *
39
     * @var \eZ\Publish\API\Repository\RoleService
40
     */
41
    protected $roleService;
42
43
    /**
44
     * User service.
45
     *
46
     * @var \eZ\Publish\API\Repository\UserService
47
     */
48
    protected $userService;
49
50
    /**
51
     * Location service.
52
     *
53
     * @var \eZ\Publish\API\Repository\LocationService
54
     */
55
    protected $locationService;
56
57
    /**
58
     * Construct controller.
59
     *
60
     * @param \eZ\Publish\API\Repository\RoleService $roleService
61
     * @param \eZ\Publish\API\Repository\UserService $userService
62
     * @param \eZ\Publish\API\Repository\LocationService $locationService
63
     */
64
    public function __construct(
65
        RoleService $roleService,
66
        UserService $userService,
67
        LocationService $locationService
68
    ) {
69
        $this->roleService = $roleService;
70
        $this->userService = $userService;
71
        $this->locationService = $locationService;
72
    }
73
74
    /**
75
     * Create new role.
76
     *
77
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedRole
78
     */
79
    public function createRole(Request $request)
80
    {
81
        $publish = ($request->query->has('publish') && $request->query->get('publish') === 'true');
82
83
        try {
84
            $roleDraft = $this->roleService->createRole(
85
                $this->inputDispatcher->parse(
0 ignored issues
show
Compatibility introduced by
$this->inputDispatcher->...request->getContent())) of type object<eZ\Publish\API\Re...ory\Values\ValueObject> is not a sub-type of object<eZ\Publish\API\Re...\User\RoleCreateStruct>. It seems like you assume a child class of the class eZ\Publish\API\Repository\Values\ValueObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
86
                    new Message(
87
                        [
88
                            'Content-Type' => $request->headers->get('Content-Type'),
89
                            // @todo Needs refactoring! Temporary solution so parser has access to get parameters
90
                            '__publish' => $publish,
91
                        ],
92
                        $request->getContent()
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, eZ\Publish\Core\REST\Common\Message::__construct() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
93
                    )
94
                )
95
            );
96
        } catch (InvalidArgumentException $e) {
97
            throw new ForbiddenException($e->getMessage());
98
        } catch (UnauthorizedException $e) {
99
            throw new ForbiddenException($e->getMessage());
100
        } catch (LimitationValidationException $e) {
101
            throw new BadRequestException($e->getMessage());
102
        } catch (Exceptions\Parser $e) {
103
            throw new BadRequestException($e->getMessage());
104
        }
105
106
        if ($publish) {
107
            $this->roleService->publishRoleDraft($roleDraft);
108
109
            $role = $this->roleService->loadRole($roleDraft->id);
0 ignored issues
show
Documentation introduced by
The property $id is declared protected in eZ\Publish\API\Repository\Values\User\Role. 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...
110
111
            return new Values\CreatedRole(['role' => new Values\RestRole($role)]);
112
        }
113
114
        return new Values\CreatedRole(['role' => new Values\RestRole($roleDraft)]);
115
    }
116
117
    /**
118
     * Loads list of roles.
119
     *
120
     * @return \eZ\Publish\Core\REST\Server\Values\RoleList
121
     */
122
    public function listRoles(Request $request)
123
    {
124
        $roles = array();
125
        if ($request->query->has('identifier')) {
126
            try {
127
                $role = $this->roleService->loadRoleByIdentifier($request->query->get('identifier'));
128
                $roles[] = $role;
129
            } catch (APINotFoundException $e) {
130
                // Do nothing
131
            }
132
        } else {
133
            $offset = $request->query->has('offset') ? (int)$request->query->get('offset') : 0;
134
            $limit = $request->query->has('limit') ? (int)$request->query->get('limit') : -1;
135
136
            $roles = array_slice(
137
                $this->roleService->loadRoles(),
138
                $offset >= 0 ? $offset : 0,
139
                $limit >= 0 ? $limit : null
140
            );
141
        }
142
143
        return new Values\RoleList($roles, $request->getPathInfo());
144
    }
145
146
    /**
147
     * Loads role.
148
     *
149
     * @param $roleId
150
     *
151
     * @return \eZ\Publish\API\Repository\Values\User\Role
152
     */
153
    public function loadRole($roleId)
154
    {
155
        return $this->roleService->loadRole($roleId);
156
    }
157
158
    /**
159
     * Loads a role draft.
160
     *
161
     * @param mixed $roleId Original role ID, or ID of the role draft itself
162
     *
163
     * @return \eZ\Publish\API\Repository\Values\User\RoleDraft
164
     */
165
    public function loadRoleDraft($roleId)
166
    {
167
        try {
168
            // First try to load the draft for given role.
169
            return $this->roleService->loadRoleDraftByRoleId($roleId);
170
        } catch (NotFoundException $e) {
171
            // We might want a newly created role, so try to load it by its ID.
172
            // loadRoleDraft() might throw a NotFoundException (wrong $roleId). If so, let it bubble up.
173
            return $this->roleService->loadRoleDraft($roleId);
174
        }
175
    }
176
177
    /**
178
     * Updates a role.
179
     *
180
     * @param $roleId
181
     *
182
     * @return \eZ\Publish\API\Repository\Values\User\Role
183
     */
184
    public function updateRole($roleId, Request $request)
185
    {
186
        $createStruct = $this->inputDispatcher->parse(
187
            new Message(
188
                array('Content-Type' => $request->headers->get('Content-Type')),
189
                $request->getContent()
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, eZ\Publish\Core\REST\Common\Message::__construct() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
190
            )
191
        );
192
193
        return $this->roleService->updateRole(
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...leService::updateRole() has been deprecated with message: since 6.0, use {@see updateRoleDraft}

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...
194
            $this->roleService->loadRole($roleId),
195
            $this->mapToUpdateStruct($createStruct)
0 ignored issues
show
Compatibility introduced by
$createStruct of type object<eZ\Publish\API\Re...ory\Values\ValueObject> is not a sub-type of object<eZ\Publish\API\Re...\User\RoleCreateStruct>. It seems like you assume a child class of the class eZ\Publish\API\Repository\Values\ValueObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
196
        );
197
    }
198
199
    /**
200
     * Updates a role draft.
201
     *
202
     * @param mixed $roleId Original role ID, or ID of the role draft itself
203
     *
204
     * @return \eZ\Publish\API\Repository\Values\User\RoleDraft
205
     */
206
    public function updateRoleDraft($roleId, Request $request)
207
    {
208
        $createStruct = $this->inputDispatcher->parse(
209
            new Message(
210
                array('Content-Type' => $request->headers->get('Content-Type')),
211
                $request->getContent()
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, eZ\Publish\Core\REST\Common\Message::__construct() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
212
            )
213
        );
214
215
        try {
216
            // First try to load the draft for given role.
217
            $roleDraft = $this->roleService->loadRoleDraftByRoleId($roleId);
218
        } catch (NotFoundException $e) {
219
            // We might want a newly created role, so try to load it by its ID.
220
            // loadRoleDraft() might throw a NotFoundException (wrong $roleId). If so, let it bubble up.
221
            $roleDraft = $this->roleService->loadRoleDraft($roleId);
222
        }
223
224
        return $this->roleService->updateRoleDraft($roleDraft, $this->mapToUpdateStruct($createStruct));
0 ignored issues
show
Compatibility introduced by
$createStruct of type object<eZ\Publish\API\Re...ory\Values\ValueObject> is not a sub-type of object<eZ\Publish\API\Re...\User\RoleCreateStruct>. It seems like you assume a child class of the class eZ\Publish\API\Repository\Values\ValueObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
225
    }
226
227
    /**
228
     * Publishes a role draft.
229
     *
230
     * @param mixed $roleId Original role ID, or ID of the role draft itself
231
     * @return Values\RestRole
232
     */
233
    public function publishRoleDraft($roleId)
234
    {
235
        try {
236
            // First try to load the draft for given role.
237
            $roleDraft = $this->roleService->loadRoleDraftByRoleId($roleId);
238
        } catch (NotFoundException $e) {
239
            // We might want a newly created role, so try to load it by its ID.
240
            // loadRoleDraft() might throw a NotFoundException (wrong $roleId). If so, let it bubble up.
241
            $roleDraft = $this->roleService->loadRoleDraft($roleId);
242
        }
243
244
        $this->roleService->publishRoleDraft($roleDraft);
245
        $publishedRole = $this->roleService->loadRole($roleDraft->id);
0 ignored issues
show
Documentation introduced by
The property $id is declared protected in eZ\Publish\API\Repository\Values\User\Role. 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...
246
247
        return new Values\RestRole($publishedRole);
248
    }
249
250
    /**
251
     * Delete a role by ID.
252
     *
253
     * @param $roleId
254
     *
255
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
256
     */
257
    public function deleteRole($roleId)
258
    {
259
        $this->roleService->deleteRole(
260
            $this->roleService->loadRole($roleId)
261
        );
262
263
        return new Values\NoContent();
264
    }
265
266
    /**
267
     * Loads the policies for the role.
268
     *
269
     * @param $roleId
270
     *
271
     * @return \eZ\Publish\Core\REST\Server\Values\PolicyList
272
     */
273
    public function loadPolicies($roleId, Request $request)
274
    {
275
        $loadedRole = $this->roleService->loadRole($roleId);
276
277
        return new Values\PolicyList($loadedRole->getPolicies(), $request->getPathInfo());
278
    }
279
280
    /**
281
     * Deletes all policies from a role.
282
     *
283
     * @param $roleId
284
     *
285
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
286
     */
287
    public function deletePolicies($roleId)
288
    {
289
        $loadedRole = $this->roleService->loadRole($roleId);
290
291
        foreach ($loadedRole->getPolicies() as $policy) {
292
            $this->roleService->deletePolicy($policy);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...Service::deletePolicy() has been deprecated with message: since 6.0, use {@link removePolicyByRoleDraft()} 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...
293
        }
294
295
        return new Values\NoContent();
296
    }
297
298
    /**
299
     * Loads a policy.
300
     *
301
     * @param $roleId
302
     * @param $policyId
303
     *
304
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
305
     *
306
     * @return \eZ\Publish\API\Repository\Values\User\Policy
307
     */
308
    public function loadPolicy($roleId, $policyId, Request $request)
309
    {
310
        $loadedRole = $this->roleService->loadRole($roleId);
311
        foreach ($loadedRole->getPolicies() as $policy) {
312
            if ($policy->id == $policyId) {
313
                return $policy;
314
            }
315
        }
316
317
        throw new Exceptions\NotFoundException("Policy not found: '{$request->getPathInfo()}'.");
318
    }
319
320
    /**
321
     * Adds a policy to role.
322
     *
323
     * @param $roleId
324
     *
325
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedPolicy
326
     */
327
    public function addPolicy($roleId, Request $request)
328
    {
329
        $createStruct = $this->inputDispatcher->parse(
330
            new Message(
331
                array('Content-Type' => $request->headers->get('Content-Type')),
332
                $request->getContent()
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, eZ\Publish\Core\REST\Common\Message::__construct() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
333
            )
334
        );
335
336
        try {
337
            $role = $this->roleService->addPolicy(
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repository\RoleService::addPolicy() has been deprecated with message: since 6.0, use {@see addPolicyByRoleDraft}

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...
338
                $this->roleService->loadRole($roleId),
339
                $createStruct
0 ignored issues
show
Compatibility introduced by
$createStruct of type object<eZ\Publish\API\Re...ory\Values\ValueObject> is not a sub-type of object<eZ\Publish\API\Re...ser\PolicyCreateStruct>. It seems like you assume a child class of the class eZ\Publish\API\Repository\Values\ValueObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
340
            );
341
        } catch (LimitationValidationException $e) {
342
            throw new BadRequestException($e->getMessage());
343
        }
344
345
        $policies = $role->getPolicies();
346
347
        $policyToReturn = $policies[0];
348
        for ($i = 1, $count = count($policies); $i < $count; ++$i) {
349
            if ($policies[$i]->id > $policyToReturn->id) {
350
                $policyToReturn = $policies[$i];
351
            }
352
        }
353
354
        return new Values\CreatedPolicy(
355
            array(
356
                'policy' => $policyToReturn,
357
            )
358
        );
359
    }
360
361
    /**
362
     * Updates a policy.
363
     *
364
     * @param $roleId
365
     * @param $policyId
366
     *
367
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
368
     *
369
     * @return \eZ\Publish\API\Repository\Values\User\Policy
370
     */
371
    public function updatePolicy($roleId, $policyId, Request $request)
372
    {
373
        $updateStruct = $this->inputDispatcher->parse(
374
            new Message(
375
                array('Content-Type' => $request->headers->get('Content-Type')),
376
                $request->getContent()
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, eZ\Publish\Core\REST\Common\Message::__construct() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
377
            )
378
        );
379
380
        $role = $this->roleService->loadRole($roleId);
381
        foreach ($role->getPolicies() as $policy) {
382
            if ($policy->id == $policyId) {
383
                try {
384
                    return $this->roleService->updatePolicy(
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...Service::updatePolicy() has been deprecated with message: since 6.0, use {@link updatePolicyByRoleDraft()} 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...
385
                        $policy,
386
                        $updateStruct
0 ignored issues
show
Compatibility introduced by
$updateStruct of type object<eZ\Publish\API\Re...ory\Values\ValueObject> is not a sub-type of object<eZ\Publish\API\Re...ser\PolicyUpdateStruct>. It seems like you assume a child class of the class eZ\Publish\API\Repository\Values\ValueObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
387
                    );
388
                } catch (LimitationValidationException $e) {
389
                    throw new BadRequestException($e->getMessage());
390
                }
391
            }
392
        }
393
394
        throw new Exceptions\NotFoundException("Policy not found: '{$request->getPathInfo()}'.");
395
    }
396
397
    /**
398
     * Delete a policy from role.
399
     *
400
     * @param $roleId
401
     * @param $policyId
402
     *
403
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
404
     *
405
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
406
     */
407 View Code Duplication
    public function deletePolicy($roleId, $policyId, Request $request)
408
    {
409
        $role = $this->roleService->loadRole($roleId);
410
411
        $policy = null;
412
        foreach ($role->getPolicies() as $rolePolicy) {
413
            if ($rolePolicy->id == $policyId) {
414
                $policy = $rolePolicy;
415
                break;
416
            }
417
        }
418
419
        if ($policy !== null) {
420
            $this->roleService->deletePolicy($policy);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...Service::deletePolicy() has been deprecated with message: since 6.0, use {@link removePolicyByRoleDraft()} 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...
421
422
            return new Values\NoContent();
423
        }
424
425
        throw new Exceptions\NotFoundException("Policy not found: '{$request->getPathInfo()}'.");
426
    }
427
428
    /**
429
     * Assigns role to user.
430
     *
431
     * @param $userId
432
     *
433
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
434
     */
435
    public function assignRoleToUser($userId, Request $request)
436
    {
437
        $roleAssignment = $this->inputDispatcher->parse(
438
            new Message(
439
                array('Content-Type' => $request->headers->get('Content-Type')),
440
                $request->getContent()
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, eZ\Publish\Core\REST\Common\Message::__construct() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
441
            )
442
        );
443
444
        $user = $this->userService->loadUser($userId);
445
        $role = $this->roleService->loadRole($roleAssignment->roleId);
0 ignored issues
show
Documentation introduced by
The property roleId does not exist on object<eZ\Publish\API\Re...ory\Values\ValueObject>. 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...
446
447
        try {
448
            $this->roleService->assignRoleToUser($role, $user, $roleAssignment->limitation);
0 ignored issues
show
Documentation introduced by
The property limitation does not exist on object<eZ\Publish\API\Re...ory\Values\ValueObject>. 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...
449
        } catch (LimitationValidationException $e) {
450
            throw new BadRequestException($e->getMessage());
451
        }
452
453
        $roleAssignments = $this->roleService->getRoleAssignmentsForUser($user);
454
455
        return new Values\RoleAssignmentList($roleAssignments, $user->id);
456
    }
457
458
    /**
459
     * Assigns role to user group.
460
     *
461
     * @param $groupPath
462
     *
463
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
464
     */
465
    public function assignRoleToUserGroup($groupPath, Request $request)
466
    {
467
        $roleAssignment = $this->inputDispatcher->parse(
468
            new Message(
469
                array('Content-Type' => $request->headers->get('Content-Type')),
470
                $request->getContent()
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, eZ\Publish\Core\REST\Common\Message::__construct() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
471
            )
472
        );
473
474
        $groupLocationParts = explode('/', $groupPath);
475
        $groupLocation = $this->locationService->loadLocation(array_pop($groupLocationParts));
476
        $userGroup = $this->userService->loadUserGroup($groupLocation->contentId);
477
478
        $role = $this->roleService->loadRole($roleAssignment->roleId);
0 ignored issues
show
Documentation introduced by
The property roleId does not exist on object<eZ\Publish\API\Re...ory\Values\ValueObject>. 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...
479
480
        try {
481
            $this->roleService->assignRoleToUserGroup($role, $userGroup, $roleAssignment->limitation);
0 ignored issues
show
Documentation introduced by
The property limitation does not exist on object<eZ\Publish\API\Re...ory\Values\ValueObject>. 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...
482
        } catch (LimitationValidationException $e) {
483
            throw new BadRequestException($e->getMessage());
484
        }
485
486
        $roleAssignments = $this->roleService->getRoleAssignmentsForUserGroup($userGroup);
487
488
        return new Values\RoleAssignmentList($roleAssignments, $groupPath, true);
489
    }
490
491
    /**
492
     * Un-assigns role from user.
493
     *
494
     * @param $userId
495
     * @param $roleId
496
     *
497
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
498
     */
499
    public function unassignRoleFromUser($userId, $roleId)
500
    {
501
        $user = $this->userService->loadUser($userId);
502
        $role = $this->roleService->loadRole($roleId);
503
504
        $this->roleService->unassignRoleFromUser($role, $user);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...:unassignRoleFromUser() has been deprecated with message: since 6.0, use {@see removeRoleAssignment} 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...
505
506
        $roleAssignments = $this->roleService->getRoleAssignmentsForUser($user);
507
508
        return new Values\RoleAssignmentList($roleAssignments, $user->id);
509
    }
510
511
    /**
512
     * Un-assigns role from user group.
513
     *
514
     * @param $groupPath
515
     * @param $roleId
516
     *
517
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
518
     */
519
    public function unassignRoleFromUserGroup($groupPath, $roleId)
520
    {
521
        $groupLocationParts = explode('/', $groupPath);
522
        $groupLocation = $this->locationService->loadLocation(array_pop($groupLocationParts));
523
        $userGroup = $this->userService->loadUserGroup($groupLocation->contentId);
524
525
        $role = $this->roleService->loadRole($roleId);
526
        $this->roleService->unassignRoleFromUserGroup($role, $userGroup);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...signRoleFromUserGroup() has been deprecated with message: since 6.0, use {@see removeRoleAssignment} 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...
527
528
        $roleAssignments = $this->roleService->getRoleAssignmentsForUserGroup($userGroup);
529
530
        return new Values\RoleAssignmentList($roleAssignments, $groupPath, true);
531
    }
532
533
    /**
534
     * Loads role assignments for user.
535
     *
536
     * @param $userId
537
     *
538
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
539
     */
540
    public function loadRoleAssignmentsForUser($userId)
541
    {
542
        $user = $this->userService->loadUser($userId);
543
544
        $roleAssignments = $this->roleService->getRoleAssignmentsForUser($user);
545
546
        return new Values\RoleAssignmentList($roleAssignments, $user->id);
547
    }
548
549
    /**
550
     * Loads role assignments for user group.
551
     *
552
     * @param $groupPath
553
     *
554
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
555
     */
556
    public function loadRoleAssignmentsForUserGroup($groupPath)
557
    {
558
        $groupLocationParts = explode('/', $groupPath);
559
        $groupLocation = $this->locationService->loadLocation(array_pop($groupLocationParts));
560
        $userGroup = $this->userService->loadUserGroup($groupLocation->contentId);
561
562
        $roleAssignments = $this->roleService->getRoleAssignmentsForUserGroup($userGroup);
563
564
        return new Values\RoleAssignmentList($roleAssignments, $groupPath, true);
565
    }
566
567
    /**
568
     * Returns a role assignment to the given user.
569
     *
570
     * @param $userId
571
     * @param $roleId
572
     *
573
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
574
     *
575
     * @return \eZ\Publish\Core\REST\Server\Values\RestUserRoleAssignment
576
     */
577
    public function loadRoleAssignmentForUser($userId, $roleId, Request $request)
578
    {
579
        $user = $this->userService->loadUser($userId);
580
        $roleAssignments = $this->roleService->getRoleAssignmentsForUser($user);
581
582
        foreach ($roleAssignments as $roleAssignment) {
583
            if ($roleAssignment->getRole()->id == $roleId) {
584
                return new Values\RestUserRoleAssignment($roleAssignment, $userId);
0 ignored issues
show
Bug introduced by
It seems like $roleAssignment defined by $roleAssignment on line 582 can also be of type object<eZ\Publish\API\Re...serGroupRoleAssignment>; however, eZ\Publish\Core\REST\Ser...signment::__construct() does only seem to accept object<eZ\Publish\API\Re...ser\UserRoleAssignment>, 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...
585
            }
586
        }
587
588
        throw new Exceptions\NotFoundException("Role assignment not found: '{$request->getPathInfo()}'.");
589
    }
590
591
    /**
592
     * Returns a role assignment to the given user group.
593
     *
594
     * @param $groupPath
595
     * @param $roleId
596
     *
597
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
598
     *
599
     * @return \eZ\Publish\Core\REST\Server\Values\RestUserGroupRoleAssignment
600
     */
601
    public function loadRoleAssignmentForUserGroup($groupPath, $roleId, Request $request)
602
    {
603
        $groupLocationParts = explode('/', $groupPath);
604
        $groupLocation = $this->locationService->loadLocation(array_pop($groupLocationParts));
605
        $userGroup = $this->userService->loadUserGroup($groupLocation->contentId);
606
607
        $roleAssignments = $this->roleService->getRoleAssignmentsForUserGroup($userGroup);
608
        foreach ($roleAssignments as $roleAssignment) {
609
            if ($roleAssignment->getRole()->id == $roleId) {
610
                return new Values\RestUserGroupRoleAssignment($roleAssignment, $groupPath);
611
            }
612
        }
613
614
        throw new Exceptions\NotFoundException("Role assignment not found: '{$request->getPathInfo()}'.");
615
    }
616
617
    /**
618
     * Search all policies which are applied to a given user.
619
     *
620
     * @return \eZ\Publish\Core\REST\Server\Values\PolicyList
621
     */
622
    public function listPoliciesForUser(Request $request)
623
    {
624
        return new Values\PolicyList(
625
            $this->roleService->loadPoliciesByUserId(
626
                $request->query->get('userId')
627
            ),
628
            $request->getPathInfo()
629
        );
630
    }
631
632
    /**
633
     * Maps a RoleCreateStruct to a RoleUpdateStruct.
634
     *
635
     * Needed since both structs are encoded into the same media type on input.
636
     *
637
     * @param \eZ\Publish\API\Repository\Values\User\RoleCreateStruct $createStruct
638
     *
639
     * @return \eZ\Publish\API\Repository\Values\User\RoleUpdateStruct
640
     */
641
    protected function mapToUpdateStruct(RoleCreateStruct $createStruct)
642
    {
643
        return new RoleUpdateStruct(
644
            array(
645
                'identifier' => $createStruct->identifier,
646
            )
647
        );
648
    }
649
}
650