Completed
Push — asset_dump_sf_env ( 7179db...758bb0 )
by André
16:06
created

Role::deletePolicy()   C

Complexity

Conditions 8
Paths 82

Size

Total Lines 40
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 40
rs 5.3846
cc 8
eloc 22
nc 82
nop 3
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
     * Defaults to publishing the role, but you can create a draft instead by setting the POST parameter publish=false
78
     *
79
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedRole
80
     */
81
    public function createRole(Request $request)
82
    {
83
        $publish = (
84
            !$request->query->has('publish') ||
85
            ($request->query->has('publish') && $request->query->get('publish') === 'true')
86
        );
87
88
        try {
89
            $roleDraft = $this->roleService->createRole(
90
                $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...
91
                    new Message(
92
                        [
93
                            'Content-Type' => $request->headers->get('Content-Type'),
94
                            // @todo Needs refactoring! Temporary solution so parser has access to get parameters
95
                            '__publish' => $publish,
96
                        ],
97
                        $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...
98
                    )
99
                )
100
            );
101
        } catch (InvalidArgumentException $e) {
102
            throw new ForbiddenException($e->getMessage());
103
        } catch (UnauthorizedException $e) {
104
            throw new ForbiddenException($e->getMessage());
105
        } catch (LimitationValidationException $e) {
106
            throw new BadRequestException($e->getMessage());
107
        } catch (Exceptions\Parser $e) {
108
            throw new BadRequestException($e->getMessage());
109
        }
110
111
        if ($publish) {
112
            @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
113
                "Create and publish role in the same operation is deprecated, and will be removed in the future.\n" .
114
                'Instead, publish the role draft using Role::publishRoleDraft().',
115
                E_USER_DEPRECATED
116
            );
117
118
            $this->roleService->publishRoleDraft($roleDraft);
119
120
            $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...
121
122
            return new Values\CreatedRole(['role' => new Values\RestRole($role)]);
123
        }
124
125
        return new Values\CreatedRole(['role' => new Values\RestRole($roleDraft)]);
126
    }
127
128
    /**
129
     * Creates a new RoleDraft for an existing Role.
130
     *
131
     * @since 6.2
132
     *
133
     * @throws \eZ\Publish\API\Repository\Exceptions\ForbiddenException if the Role already has a Role Draft that will need to be removed first,
134
     *                                                                  or if the authenticated user is not allowed to create a role
135
     * @throws \eZ\Publish\Core\REST\Server\Exceptions\BadRequestException if a policy limitation in the $roleCreateStruct is not valid
136
     *
137
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedRole
138
     */
139
    public function createRoleDraft($roleId, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
140
    {
141
        try {
142
            $roleDraft = $this->roleService->createRoleDraft(
143
                $this->roleService->loadRole($roleId)
144
            );
145
        } catch (InvalidArgumentException $e) {
146
            throw new ForbiddenException($e->getMessage());
147
        } catch (UnauthorizedException $e) {
148
            throw new ForbiddenException($e->getMessage());
149
        } catch (LimitationValidationException $e) {
150
            throw new BadRequestException($e->getMessage());
151
        } catch (Exceptions\Parser $e) {
152
            throw new BadRequestException($e->getMessage());
153
        }
154
155
        return new Values\CreatedRole(['role' => new Values\RestRole($roleDraft)]);
156
    }
157
158
    /**
159
     * Loads list of roles.
160
     *
161
     * @return \eZ\Publish\Core\REST\Server\Values\RoleList
162
     */
163
    public function listRoles(Request $request)
164
    {
165
        $roles = array();
166
        if ($request->query->has('identifier')) {
167
            try {
168
                $role = $this->roleService->loadRoleByIdentifier($request->query->get('identifier'));
169
                $roles[] = $role;
170
            } catch (APINotFoundException $e) {
171
                // Do nothing
172
            }
173
        } else {
174
            $offset = $request->query->has('offset') ? (int)$request->query->get('offset') : 0;
175
            $limit = $request->query->has('limit') ? (int)$request->query->get('limit') : -1;
176
177
            $roles = array_slice(
178
                $this->roleService->loadRoles(),
179
                $offset >= 0 ? $offset : 0,
180
                $limit >= 0 ? $limit : null
181
            );
182
        }
183
184
        return new Values\RoleList($roles, $request->getPathInfo());
185
    }
186
187
    /**
188
     * Loads role.
189
     *
190
     * @param $roleId
191
     *
192
     * @return \eZ\Publish\API\Repository\Values\User\Role
193
     */
194
    public function loadRole($roleId)
195
    {
196
        return $this->roleService->loadRole($roleId);
197
    }
198
199
    /**
200
     * Loads 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 loadRoleDraft($roleId)
207
    {
208
        try {
209
            // First try to load the draft for given role.
210
            return $this->roleService->loadRoleDraftByRoleId($roleId);
211
        } catch (NotFoundException $e) {
212
            // We might want a newly created role, so try to load it by its ID.
213
            // loadRoleDraft() might throw a NotFoundException (wrong $roleId). If so, let it bubble up.
214
            return $this->roleService->loadRoleDraft($roleId);
215
        }
216
    }
217
218
    /**
219
     * Updates a role.
220
     *
221
     * @param $roleId
222
     *
223
     * @return \eZ\Publish\API\Repository\Values\User\Role
224
     */
225
    public function updateRole($roleId, Request $request)
226
    {
227
        $createStruct = $this->inputDispatcher->parse(
228
            new Message(
229
                array('Content-Type' => $request->headers->get('Content-Type')),
230
                $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...
231
            )
232
        );
233
234
        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...
235
            $this->roleService->loadRole($roleId),
236
            $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...
237
        );
238
    }
239
240
    /**
241
     * Updates a role draft.
242
     *
243
     * @param mixed $roleId Original role ID, or ID of the role draft itself
244
     *
245
     * @return \eZ\Publish\API\Repository\Values\User\RoleDraft
246
     */
247
    public function updateRoleDraft($roleId, Request $request)
248
    {
249
        $createStruct = $this->inputDispatcher->parse(
250
            new Message(
251
                array('Content-Type' => $request->headers->get('Content-Type')),
252
                $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...
253
            )
254
        );
255
256
        try {
257
            // First try to load the draft for given role.
258
            $roleDraft = $this->roleService->loadRoleDraftByRoleId($roleId);
259
        } catch (NotFoundException $e) {
260
            // We might want a newly created role, so try to load it by its ID.
261
            // loadRoleDraft() might throw a NotFoundException (wrong $roleId). If so, let it bubble up.
262
            $roleDraft = $this->roleService->loadRoleDraft($roleId);
263
        }
264
265
        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...
266
    }
267
268
    /**
269
     * Publishes a role draft.
270
     *
271
     * @param mixed $roleId Original role ID, or ID of the role draft itself
272
     * @return Values\RestRole
273
     */
274
    public function publishRoleDraft($roleId)
275
    {
276
        try {
277
            // First try to load the draft for given role.
278
            $roleDraft = $this->roleService->loadRoleDraftByRoleId($roleId);
279
        } catch (NotFoundException $e) {
280
            // We might want a newly created role, so try to load it by its ID.
281
            // loadRoleDraft() might throw a NotFoundException (wrong $roleId). If so, let it bubble up.
282
            $roleDraft = $this->roleService->loadRoleDraft($roleId);
283
        }
284
285
        $this->roleService->publishRoleDraft($roleDraft);
286
        $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...
287
288
        return new Values\CreatedRole(['role' => new Values\RestRole($publishedRole)]);
289
    }
290
291
    /**
292
     * Delete a role by ID.
293
     *
294
     * @param $roleId
295
     *
296
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
297
     */
298
    public function deleteRole($roleId)
299
    {
300
        $this->roleService->deleteRole(
301
            $this->roleService->loadRole($roleId)
302
        );
303
304
        return new Values\NoContent();
305
    }
306
307
    /**
308
     * Delete a role draft by ID.
309
     *
310
     * @since 6.2
311
     *
312
     * @param $roleId
313
     *
314
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
315
     */
316
    public function deleteRoleDraft($roleId)
317
    {
318
        $this->roleService->deleteRoleDraft(
319
            $this->roleService->loadRoleDraft($roleId)
320
        );
321
322
        return new Values\NoContent();
323
    }
324
325
    /**
326
     * Loads the policies for the role.
327
     *
328
     * @param $roleId
329
     *
330
     * @return \eZ\Publish\Core\REST\Server\Values\PolicyList
331
     */
332
    public function loadPolicies($roleId, Request $request)
333
    {
334
        $loadedRole = $this->roleService->loadRole($roleId);
335
336
        return new Values\PolicyList($loadedRole->getPolicies(), $request->getPathInfo());
337
    }
338
339
    /**
340
     * Deletes all policies from a role.
341
     *
342
     * @param $roleId
343
     *
344
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
345
     */
346
    public function deletePolicies($roleId)
347
    {
348
        $loadedRole = $this->roleService->loadRole($roleId);
349
350
        foreach ($loadedRole->getPolicies() as $policy) {
351
            $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...
352
        }
353
354
        return new Values\NoContent();
355
    }
356
357
    /**
358
     * Loads a policy.
359
     *
360
     * @param $roleId
361
     * @param $policyId
362
     *
363
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
364
     *
365
     * @return \eZ\Publish\API\Repository\Values\User\Policy
366
     */
367
    public function loadPolicy($roleId, $policyId, Request $request)
368
    {
369
        $loadedRole = $this->roleService->loadRole($roleId);
370
        foreach ($loadedRole->getPolicies() as $policy) {
371
            if ($policy->id == $policyId) {
372
                return $policy;
373
            }
374
        }
375
376
        throw new Exceptions\NotFoundException("Policy not found: '{$request->getPathInfo()}'.");
377
    }
378
379
    /**
380
     * Adds a policy to role.
381
     *
382
     * @param $roleId int ID of a role or a role draft
383
     *
384
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedPolicy
385
     */
386
    public function addPolicy($roleId, Request $request)
387
    {
388
        $createStruct = $this->inputDispatcher->parse(
389
            new Message(
390
                array('Content-Type' => $request->headers->get('Content-Type')),
391
                $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...
392
            )
393
        );
394
395
        try {
396
            // First try to treat $roleId as a role draft ID.
397
            $role = $this->roleService->addPolicyByRoleDraft(
398
                $this->roleService->loadRoleDraft($roleId),
399
                $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...
400
            );
401
        } catch (NotFoundException $e) {
402
            // Then try to treat $roleId as a role ID.
403
            $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...
404
                $this->roleService->loadRole($roleId),
405
                $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...
406
            );
407
        } catch (LimitationValidationException $e) {
408
            throw new BadRequestException($e->getMessage());
409
        }
410
411
        return new Values\CreatedPolicy(
412
            array(
413
                'policy' => $this->getLastAddedPolicy($role),
414
            )
415
        );
416
    }
417
418
    /**
419
     * Adds a policy to a role draft.
420
     *
421
     * @since 6.2
422
     * @deprecated since 6.3, use {@see addPolicy}
423
     *
424
     * @param $roleId
425
     *
426
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedPolicy
427
     */
428
    public function addPolicyByRoleDraft($roleId, Request $request)
429
    {
430
        $createStruct = $this->inputDispatcher->parse(
431
            new Message(
432
                array('Content-Type' => $request->headers->get('Content-Type')),
433
                $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...
434
            )
435
        );
436
437
        try {
438
            $role = $this->roleService->addPolicyByRoleDraft(
439
                $this->roleService->loadRoleDraft($roleId),
440
                $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...
441
            );
442
        } catch (LimitationValidationException $e) {
443
            throw new BadRequestException($e->getMessage());
444
        }
445
446
        return new Values\CreatedPolicy(
447
            array(
448
                'policy' => $this->getLastAddedPolicy($role),
449
            )
450
        );
451
    }
452
453
    /**
454
     * Get the last added policy for $role.
455
     *
456
     * This is needed because the RoleService addPolicy() and addPolicyByRoleDraft() methods return the role,
457
     * not the policy.
458
     *
459
     * @param $role \eZ\Publish\API\Repository\Values\User\Role
460
     *
461
     * @return \eZ\Publish\API\Repository\Values\User\Policy
462
     */
463
    private function getLastAddedPolicy($role)
464
    {
465
        $policies = $role->getPolicies();
466
467
        $policyToReturn = $policies[0];
468
        for ($i = 1, $count = count($policies); $i < $count; ++$i) {
469
            if ($policies[$i]->id > $policyToReturn->id) {
470
                $policyToReturn = $policies[$i];
471
            }
472
        }
473
474
        return $policyToReturn;
475
    }
476
477
    /**
478
     * Updates a policy.
479
     *
480
     * @param $roleId int ID of a role or a role draft
481
     * @param $policyId int ID of a policy
482
     *
483
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
484
     *
485
     * @return \eZ\Publish\API\Repository\Values\User\Policy
486
     */
487
    public function updatePolicy($roleId, $policyId, Request $request)
488
    {
489
        $updateStruct = $this->inputDispatcher->parse(
490
            new Message(
491
                array('Content-Type' => $request->headers->get('Content-Type')),
492
                $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...
493
            )
494
        );
495
496
        try {
497
            // First try to treat $roleId as a role draft ID.
498
            $role = $this->roleService->loadRoleDraft($roleId);
499 View Code Duplication
            foreach ($role->getPolicies() as $policy) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
500
                if ($policy->id == $policyId) {
501
                    try {
502
                        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...
503
                            $policy,
504
                            $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...
505
                        );
506
                    } catch (LimitationValidationException $e) {
507
                        throw new BadRequestException($e->getMessage());
508
                    }
509
                }
510
            }
511
        } catch (NotFoundException $e) {
512
            // Then try to treat $roleId as a role ID.
513
            $role = $this->roleService->loadRole($roleId);
514 View Code Duplication
            foreach ($role->getPolicies() as $policy) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
515
                if ($policy->id == $policyId) {
516
                    try {
517
                        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...
518
                            $policy,
519
                            $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...
520
                        );
521
                    } catch (LimitationValidationException $e) {
522
                        throw new BadRequestException($e->getMessage());
523
                    }
524
                }
525
            }
526
        }
527
528
        throw new Exceptions\NotFoundException("Policy not found: '{$request->getPathInfo()}'.");
529
    }
530
531
    /**
532
     * Updates a policy.
533
     *
534
     * @since 6.2
535
     * @deprecated since 6.3, use {@see updatePolicy}
536
     *
537
     * @param $roleId
538
     * @param $policyId
539
     *
540
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
541
     *
542
     * @return \eZ\Publish\API\Repository\Values\User\Policy
543
     */
544
    public function updatePolicyByRoleDraft($roleId, $policyId, Request $request)
545
    {
546
        $updateStruct = $this->inputDispatcher->parse(
547
            new Message(
548
                array('Content-Type' => $request->headers->get('Content-Type')),
549
                $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...
550
            )
551
        );
552
553
        $role = $this->roleService->loadRoleDraft($roleId);
554 View Code Duplication
        foreach ($role->getPolicies() as $policy) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
555
            if ($policy->id == $policyId) {
556
                try {
557
                    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...
558
                        $policy,
559
                        $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...
560
                    );
561
                } catch (LimitationValidationException $e) {
562
                    throw new BadRequestException($e->getMessage());
563
                }
564
            }
565
        }
566
567
        throw new Exceptions\NotFoundException("Policy not found: '{$request->getPathInfo()}'.");
568
    }
569
570
    /**
571
     * Delete a policy from role.
572
     *
573
     * @param $roleId int ID of a role or a role draft
574
     * @param $policyId int ID of a policy
575
     *
576
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
577
     *
578
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
579
     */
580
    public function deletePolicy($roleId, $policyId, Request $request)
581
    {
582
        try {
583
            // First try to treat $roleId as a role draft ID.
584
            $roleDraft = $this->roleService->loadRoleDraft($roleId);
585
586
            $policy = null;
587
            foreach ($roleDraft->getPolicies() as $rolePolicy) {
588
                if ($rolePolicy->id == $policyId) {
589
                    $policy = $rolePolicy;
590
                    break;
591
                }
592
            }
593
594
            if ($policy !== null) {
595
                $this->roleService->removePolicyByRoleDraft($roleDraft, $policy);
0 ignored issues
show
Compatibility introduced by
$policy of type object<eZ\Publish\API\Re...ory\Values\User\Policy> is not a sub-type of object<eZ\Publish\API\Re...alues\User\PolicyDraft>. It seems like you assume a child class of the class eZ\Publish\API\Repository\Values\User\Policy 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...
596
597
                return new Values\NoContent();
598
            }
599
        } catch (NotFoundException $e) {
600
            // Then try to treat $roleId as a role ID.
601
            $role = $this->roleService->loadRole($roleId);
602
603
            $policy = null;
604
            foreach ($role->getPolicies() as $rolePolicy) {
605
                if ($rolePolicy->id == $policyId) {
606
                    $policy = $rolePolicy;
607
                    break;
608
                }
609
            }
610
611
            if ($policy !== null) {
612
                $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...
613
614
                return new Values\NoContent();
615
            }
616
        }
617
618
        throw new Exceptions\NotFoundException("Policy not found: '{$request->getPathInfo()}'.");
619
    }
620
621
    /**
622
     * Remove a policy from a role draft.
623
     *
624
     * @since 6.2
625
     * @deprecated since 6.3, use {@see deletePolicy}
626
     *
627
     * @param $roleId
628
     * @param $policyId
629
     *
630
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
631
     *
632
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
633
     */
634 View Code Duplication
    public function removePolicyByRoleDraft($roleId, $policyId, Request $request)
635
    {
636
        $roleDraft = $this->roleService->loadRoleDraft($roleId);
637
638
        $policy = null;
639
        foreach ($roleDraft->getPolicies() as $rolePolicy) {
640
            if ($rolePolicy->id == $policyId) {
641
                $policy = $rolePolicy;
642
                break;
643
            }
644
        }
645
646
        if ($policy !== null) {
647
            $this->roleService->removePolicyByRoleDraft($roleDraft, $policy);
0 ignored issues
show
Compatibility introduced by
$policy of type object<eZ\Publish\API\Re...ory\Values\User\Policy> is not a sub-type of object<eZ\Publish\API\Re...alues\User\PolicyDraft>. It seems like you assume a child class of the class eZ\Publish\API\Repository\Values\User\Policy 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...
648
649
            return new Values\NoContent();
650
        }
651
652
        throw new Exceptions\NotFoundException("Policy not found: '{$request->getPathInfo()}'.");
653
    }
654
655
    /**
656
     * Assigns role to user.
657
     *
658
     * @param $userId
659
     *
660
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
661
     */
662
    public function assignRoleToUser($userId, Request $request)
663
    {
664
        $roleAssignment = $this->inputDispatcher->parse(
665
            new Message(
666
                array('Content-Type' => $request->headers->get('Content-Type')),
667
                $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...
668
            )
669
        );
670
671
        $user = $this->userService->loadUser($userId);
672
        $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...
673
674
        try {
675
            $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...
676
        } catch (LimitationValidationException $e) {
677
            throw new BadRequestException($e->getMessage());
678
        }
679
680
        $roleAssignments = $this->roleService->getRoleAssignmentsForUser($user);
681
682
        return new Values\RoleAssignmentList($roleAssignments, $user->id);
683
    }
684
685
    /**
686
     * Assigns role to user group.
687
     *
688
     * @param $groupPath
689
     *
690
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
691
     */
692
    public function assignRoleToUserGroup($groupPath, Request $request)
693
    {
694
        $roleAssignment = $this->inputDispatcher->parse(
695
            new Message(
696
                array('Content-Type' => $request->headers->get('Content-Type')),
697
                $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...
698
            )
699
        );
700
701
        $groupLocationParts = explode('/', $groupPath);
702
        $groupLocation = $this->locationService->loadLocation(array_pop($groupLocationParts));
703
        $userGroup = $this->userService->loadUserGroup($groupLocation->contentId);
704
705
        $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...
706
707
        try {
708
            $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...
709
        } catch (LimitationValidationException $e) {
710
            throw new BadRequestException($e->getMessage());
711
        }
712
713
        $roleAssignments = $this->roleService->getRoleAssignmentsForUserGroup($userGroup);
714
715
        return new Values\RoleAssignmentList($roleAssignments, $groupPath, true);
716
    }
717
718
    /**
719
     * Un-assigns role from user.
720
     *
721
     * @param $userId
722
     * @param $roleId
723
     *
724
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
725
     */
726
    public function unassignRoleFromUser($userId, $roleId)
727
    {
728
        $user = $this->userService->loadUser($userId);
729
        $role = $this->roleService->loadRole($roleId);
730
731
        $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...
732
733
        $roleAssignments = $this->roleService->getRoleAssignmentsForUser($user);
734
735
        return new Values\RoleAssignmentList($roleAssignments, $user->id);
736
    }
737
738
    /**
739
     * Un-assigns role from user group.
740
     *
741
     * @param $groupPath
742
     * @param $roleId
743
     *
744
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
745
     */
746
    public function unassignRoleFromUserGroup($groupPath, $roleId)
747
    {
748
        $groupLocationParts = explode('/', $groupPath);
749
        $groupLocation = $this->locationService->loadLocation(array_pop($groupLocationParts));
750
        $userGroup = $this->userService->loadUserGroup($groupLocation->contentId);
751
752
        $role = $this->roleService->loadRole($roleId);
753
        $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...
754
755
        $roleAssignments = $this->roleService->getRoleAssignmentsForUserGroup($userGroup);
756
757
        return new Values\RoleAssignmentList($roleAssignments, $groupPath, true);
758
    }
759
760
    /**
761
     * Loads role assignments for user.
762
     *
763
     * @param $userId
764
     *
765
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
766
     */
767
    public function loadRoleAssignmentsForUser($userId)
768
    {
769
        $user = $this->userService->loadUser($userId);
770
771
        $roleAssignments = $this->roleService->getRoleAssignmentsForUser($user);
772
773
        return new Values\RoleAssignmentList($roleAssignments, $user->id);
774
    }
775
776
    /**
777
     * Loads role assignments for user group.
778
     *
779
     * @param $groupPath
780
     *
781
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
782
     */
783
    public function loadRoleAssignmentsForUserGroup($groupPath)
784
    {
785
        $groupLocationParts = explode('/', $groupPath);
786
        $groupLocation = $this->locationService->loadLocation(array_pop($groupLocationParts));
787
        $userGroup = $this->userService->loadUserGroup($groupLocation->contentId);
788
789
        $roleAssignments = $this->roleService->getRoleAssignmentsForUserGroup($userGroup);
790
791
        return new Values\RoleAssignmentList($roleAssignments, $groupPath, true);
792
    }
793
794
    /**
795
     * Returns a role assignment to the given user.
796
     *
797
     * @param $userId
798
     * @param $roleId
799
     *
800
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
801
     *
802
     * @return \eZ\Publish\Core\REST\Server\Values\RestUserRoleAssignment
803
     */
804
    public function loadRoleAssignmentForUser($userId, $roleId, Request $request)
805
    {
806
        $user = $this->userService->loadUser($userId);
807
        $roleAssignments = $this->roleService->getRoleAssignmentsForUser($user);
808
809
        foreach ($roleAssignments as $roleAssignment) {
810
            if ($roleAssignment->getRole()->id == $roleId) {
811
                return new Values\RestUserRoleAssignment($roleAssignment, $userId);
0 ignored issues
show
Bug introduced by
It seems like $roleAssignment defined by $roleAssignment on line 809 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...
812
            }
813
        }
814
815
        throw new Exceptions\NotFoundException("Role assignment not found: '{$request->getPathInfo()}'.");
816
    }
817
818
    /**
819
     * Returns a role assignment to the given user group.
820
     *
821
     * @param $groupPath
822
     * @param $roleId
823
     *
824
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
825
     *
826
     * @return \eZ\Publish\Core\REST\Server\Values\RestUserGroupRoleAssignment
827
     */
828
    public function loadRoleAssignmentForUserGroup($groupPath, $roleId, Request $request)
829
    {
830
        $groupLocationParts = explode('/', $groupPath);
831
        $groupLocation = $this->locationService->loadLocation(array_pop($groupLocationParts));
832
        $userGroup = $this->userService->loadUserGroup($groupLocation->contentId);
833
834
        $roleAssignments = $this->roleService->getRoleAssignmentsForUserGroup($userGroup);
835
        foreach ($roleAssignments as $roleAssignment) {
836
            if ($roleAssignment->getRole()->id == $roleId) {
837
                return new Values\RestUserGroupRoleAssignment($roleAssignment, $groupPath);
838
            }
839
        }
840
841
        throw new Exceptions\NotFoundException("Role assignment not found: '{$request->getPathInfo()}'.");
842
    }
843
844
    /**
845
     * Search all policies which are applied to a given user.
846
     *
847
     * @return \eZ\Publish\Core\REST\Server\Values\PolicyList
848
     */
849
    public function listPoliciesForUser(Request $request)
850
    {
851
        return new Values\PolicyList(
852
            $this->roleService->loadPoliciesByUserId(
853
                $request->query->get('userId')
854
            ),
855
            $request->getPathInfo()
856
        );
857
    }
858
859
    /**
860
     * Maps a RoleCreateStruct to a RoleUpdateStruct.
861
     *
862
     * Needed since both structs are encoded into the same media type on input.
863
     *
864
     * @param \eZ\Publish\API\Repository\Values\User\RoleCreateStruct $createStruct
865
     *
866
     * @return \eZ\Publish\API\Repository\Values\User\RoleUpdateStruct
867
     */
868
    protected function mapToUpdateStruct(RoleCreateStruct $createStruct)
869
    {
870
        return new RoleUpdateStruct(
871
            array(
872
                'identifier' => $createStruct->identifier,
873
            )
874
        );
875
    }
876
}
877