Completed
Push — ezp-24830_REST_for_role_drafts ( 27affb...ac0f60 )
by
unknown
121:19 queued 97:08
created

Role::createRoleDraft()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 37
Code Lines 22

Duplication

Lines 37
Ratio 100 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 37
loc 37
rs 6.7272
cc 7
eloc 22
nc 12
nop 1
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 View Code Duplication
    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
     * Creates a new RoleDraft for an existing Role.
119
     *
120
     * @since 6.1
121
     *
122
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedRole
123
     */
124 View Code Duplication
    public function createRoleDraft(Request $request)
125
    {
126
        $publish = ($request->query->has('publish') && $request->query->get('publish') === 'true');
127
128
        try {
129
            $roleDraft = $this->roleService->createRoleDraft(
130
                $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...itory\Values\User\Role>. 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...
131
                    new Message(
132
                        [
133
                            'Content-Type' => $request->headers->get('Content-Type'),
134
                            // @todo Needs refactoring! Temporary solution so parser has access to get parameters
135
                            '__publish' => $publish,
136
                        ],
137
                        $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...
138
                    )
139
                )
140
            );
141
        } catch (InvalidArgumentException $e) {
142
            throw new ForbiddenException($e->getMessage());
143
        } catch (UnauthorizedException $e) {
144
            throw new ForbiddenException($e->getMessage());
145
        } catch (LimitationValidationException $e) {
146
            throw new BadRequestException($e->getMessage());
147
        } catch (Exceptions\Parser $e) {
148
            throw new BadRequestException($e->getMessage());
149
        }
150
151
        if ($publish) {
152
            $this->roleService->publishRoleDraft($roleDraft);
153
154
            $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...
155
156
            return new Values\CreatedRole(['role' => new Values\RestRole($role)]);
157
        }
158
159
        return new Values\CreatedRole(['role' => new Values\RestRole($roleDraft)]);
160
    }
161
162
    /**
163
     * Loads list of roles.
164
     *
165
     * @return \eZ\Publish\Core\REST\Server\Values\RoleList
166
     */
167
    public function listRoles(Request $request)
168
    {
169
        $roles = array();
170
        if ($request->query->has('identifier')) {
171
            try {
172
                $role = $this->roleService->loadRoleByIdentifier($request->query->get('identifier'));
173
                $roles[] = $role;
174
            } catch (APINotFoundException $e) {
175
                // Do nothing
176
            }
177
        } else {
178
            $offset = $request->query->has('offset') ? (int)$request->query->get('offset') : 0;
179
            $limit = $request->query->has('limit') ? (int)$request->query->get('limit') : -1;
180
181
            $roles = array_slice(
182
                $this->roleService->loadRoles(),
183
                $offset >= 0 ? $offset : 0,
184
                $limit >= 0 ? $limit : null
185
            );
186
        }
187
188
        return new Values\RoleList($roles, $request->getPathInfo());
189
    }
190
191
    /**
192
     * Loads role.
193
     *
194
     * @param $roleId
195
     *
196
     * @return \eZ\Publish\API\Repository\Values\User\Role
197
     */
198
    public function loadRole($roleId)
199
    {
200
        return $this->roleService->loadRole($roleId);
201
    }
202
203
    /**
204
     * Loads a role draft.
205
     *
206
     * @param mixed $roleId Original role ID, or ID of the role draft itself
207
     *
208
     * @return \eZ\Publish\API\Repository\Values\User\RoleDraft
209
     */
210
    public function loadRoleDraft($roleId)
211
    {
212
        try {
213
            // First try to load the draft for given role.
214
            return $this->roleService->loadRoleDraftByRoleId($roleId);
215
        } catch (NotFoundException $e) {
216
            // We might want a newly created role, so try to load it by its ID.
217
            // loadRoleDraft() might throw a NotFoundException (wrong $roleId). If so, let it bubble up.
218
            return $this->roleService->loadRoleDraft($roleId);
219
        }
220
    }
221
222
    /**
223
     * Updates a role.
224
     *
225
     * @param $roleId
226
     *
227
     * @return \eZ\Publish\API\Repository\Values\User\Role
228
     */
229
    public function updateRole($roleId, Request $request)
230
    {
231
        $createStruct = $this->inputDispatcher->parse(
232
            new Message(
233
                array('Content-Type' => $request->headers->get('Content-Type')),
234
                $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...
235
            )
236
        );
237
238
        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...
239
            $this->roleService->loadRole($roleId),
240
            $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...
241
        );
242
    }
243
244
    /**
245
     * Updates a role draft.
246
     *
247
     * @param mixed $roleId Original role ID, or ID of the role draft itself
248
     *
249
     * @return \eZ\Publish\API\Repository\Values\User\RoleDraft
250
     */
251
    public function updateRoleDraft($roleId, Request $request)
252
    {
253
        $createStruct = $this->inputDispatcher->parse(
254
            new Message(
255
                array('Content-Type' => $request->headers->get('Content-Type')),
256
                $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...
257
            )
258
        );
259
260
        try {
261
            // First try to load the draft for given role.
262
            $roleDraft = $this->roleService->loadRoleDraftByRoleId($roleId);
263
        } catch (NotFoundException $e) {
264
            // We might want a newly created role, so try to load it by its ID.
265
            // loadRoleDraft() might throw a NotFoundException (wrong $roleId). If so, let it bubble up.
266
            $roleDraft = $this->roleService->loadRoleDraft($roleId);
267
        }
268
269
        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...
270
    }
271
272
    /**
273
     * Publishes a role draft.
274
     *
275
     * @param mixed $roleId Original role ID, or ID of the role draft itself
276
     * @return Values\RestRole
277
     */
278
    public function publishRoleDraft($roleId)
279
    {
280
        try {
281
            // First try to load the draft for given role.
282
            $roleDraft = $this->roleService->loadRoleDraftByRoleId($roleId);
283
        } catch (NotFoundException $e) {
284
            // We might want a newly created role, so try to load it by its ID.
285
            // loadRoleDraft() might throw a NotFoundException (wrong $roleId). If so, let it bubble up.
286
            $roleDraft = $this->roleService->loadRoleDraft($roleId);
287
        }
288
289
        $this->roleService->publishRoleDraft($roleDraft);
290
        $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...
291
292
        return new Values\RestRole($publishedRole);
293
    }
294
295
    /**
296
     * Delete a role by ID.
297
     *
298
     * @param $roleId
299
     *
300
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
301
     */
302
    public function deleteRole($roleId)
303
    {
304
        $this->roleService->deleteRole(
305
            $this->roleService->loadRole($roleId)
306
        );
307
308
        return new Values\NoContent();
309
    }
310
311
    /**
312
     * Loads the policies for the role.
313
     *
314
     * @param $roleId
315
     *
316
     * @return \eZ\Publish\Core\REST\Server\Values\PolicyList
317
     */
318
    public function loadPolicies($roleId, Request $request)
319
    {
320
        $loadedRole = $this->roleService->loadRole($roleId);
321
322
        return new Values\PolicyList($loadedRole->getPolicies(), $request->getPathInfo());
323
    }
324
325
    /**
326
     * Deletes all policies from a role.
327
     *
328
     * @param $roleId
329
     *
330
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
331
     */
332
    public function deletePolicies($roleId)
333
    {
334
        $loadedRole = $this->roleService->loadRole($roleId);
335
336
        foreach ($loadedRole->getPolicies() as $policy) {
337
            $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...
338
        }
339
340
        return new Values\NoContent();
341
    }
342
343
    /**
344
     * Loads a policy.
345
     *
346
     * @param $roleId
347
     * @param $policyId
348
     *
349
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
350
     *
351
     * @return \eZ\Publish\API\Repository\Values\User\Policy
352
     */
353
    public function loadPolicy($roleId, $policyId, Request $request)
354
    {
355
        $loadedRole = $this->roleService->loadRole($roleId);
356
        foreach ($loadedRole->getPolicies() as $policy) {
357
            if ($policy->id == $policyId) {
358
                return $policy;
359
            }
360
        }
361
362
        throw new Exceptions\NotFoundException("Policy not found: '{$request->getPathInfo()}'.");
363
    }
364
365
    /**
366
     * Adds a policy to role.
367
     *
368
     * @param $roleId
369
     *
370
     * @return \eZ\Publish\Core\REST\Server\Values\CreatedPolicy
371
     */
372
    public function addPolicy($roleId, Request $request)
373
    {
374
        $createStruct = $this->inputDispatcher->parse(
375
            new Message(
376
                array('Content-Type' => $request->headers->get('Content-Type')),
377
                $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...
378
            )
379
        );
380
381
        try {
382
            $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...
383
                $this->roleService->loadRole($roleId),
384
                $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...
385
            );
386
        } catch (LimitationValidationException $e) {
387
            throw new BadRequestException($e->getMessage());
388
        }
389
390
        $policies = $role->getPolicies();
391
392
        $policyToReturn = $policies[0];
393
        for ($i = 1, $count = count($policies); $i < $count; ++$i) {
394
            if ($policies[$i]->id > $policyToReturn->id) {
395
                $policyToReturn = $policies[$i];
396
            }
397
        }
398
399
        return new Values\CreatedPolicy(
400
            array(
401
                'policy' => $policyToReturn,
402
            )
403
        );
404
    }
405
406
    /**
407
     * Updates a policy.
408
     *
409
     * @param $roleId
410
     * @param $policyId
411
     *
412
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
413
     *
414
     * @return \eZ\Publish\API\Repository\Values\User\Policy
415
     */
416
    public function updatePolicy($roleId, $policyId, Request $request)
417
    {
418
        $updateStruct = $this->inputDispatcher->parse(
419
            new Message(
420
                array('Content-Type' => $request->headers->get('Content-Type')),
421
                $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...
422
            )
423
        );
424
425
        $role = $this->roleService->loadRole($roleId);
426
        foreach ($role->getPolicies() as $policy) {
427
            if ($policy->id == $policyId) {
428
                try {
429
                    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...
430
                        $policy,
431
                        $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...
432
                    );
433
                } catch (LimitationValidationException $e) {
434
                    throw new BadRequestException($e->getMessage());
435
                }
436
            }
437
        }
438
439
        throw new Exceptions\NotFoundException("Policy not found: '{$request->getPathInfo()}'.");
440
    }
441
442
    /**
443
     * Delete a policy from role.
444
     *
445
     * @param $roleId
446
     * @param $policyId
447
     *
448
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
449
     *
450
     * @return \eZ\Publish\Core\REST\Server\Values\NoContent
451
     */
452 View Code Duplication
    public function deletePolicy($roleId, $policyId, Request $request)
453
    {
454
        $role = $this->roleService->loadRole($roleId);
455
456
        $policy = null;
457
        foreach ($role->getPolicies() as $rolePolicy) {
458
            if ($rolePolicy->id == $policyId) {
459
                $policy = $rolePolicy;
460
                break;
461
            }
462
        }
463
464
        if ($policy !== null) {
465
            $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...
466
467
            return new Values\NoContent();
468
        }
469
470
        throw new Exceptions\NotFoundException("Policy not found: '{$request->getPathInfo()}'.");
471
    }
472
473
    /**
474
     * Assigns role to user.
475
     *
476
     * @param $userId
477
     *
478
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
479
     */
480
    public function assignRoleToUser($userId, Request $request)
481
    {
482
        $roleAssignment = $this->inputDispatcher->parse(
483
            new Message(
484
                array('Content-Type' => $request->headers->get('Content-Type')),
485
                $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...
486
            )
487
        );
488
489
        $user = $this->userService->loadUser($userId);
490
        $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...
491
492
        try {
493
            $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...
494
        } catch (LimitationValidationException $e) {
495
            throw new BadRequestException($e->getMessage());
496
        }
497
498
        $roleAssignments = $this->roleService->getRoleAssignmentsForUser($user);
499
500
        return new Values\RoleAssignmentList($roleAssignments, $user->id);
501
    }
502
503
    /**
504
     * Assigns role to user group.
505
     *
506
     * @param $groupPath
507
     *
508
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
509
     */
510
    public function assignRoleToUserGroup($groupPath, Request $request)
511
    {
512
        $roleAssignment = $this->inputDispatcher->parse(
513
            new Message(
514
                array('Content-Type' => $request->headers->get('Content-Type')),
515
                $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...
516
            )
517
        );
518
519
        $groupLocationParts = explode('/', $groupPath);
520
        $groupLocation = $this->locationService->loadLocation(array_pop($groupLocationParts));
521
        $userGroup = $this->userService->loadUserGroup($groupLocation->contentId);
522
523
        $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...
524
525
        try {
526
            $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...
527
        } catch (LimitationValidationException $e) {
528
            throw new BadRequestException($e->getMessage());
529
        }
530
531
        $roleAssignments = $this->roleService->getRoleAssignmentsForUserGroup($userGroup);
532
533
        return new Values\RoleAssignmentList($roleAssignments, $groupPath, true);
534
    }
535
536
    /**
537
     * Un-assigns role from user.
538
     *
539
     * @param $userId
540
     * @param $roleId
541
     *
542
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
543
     */
544
    public function unassignRoleFromUser($userId, $roleId)
545
    {
546
        $user = $this->userService->loadUser($userId);
547
        $role = $this->roleService->loadRole($roleId);
548
549
        $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...
550
551
        $roleAssignments = $this->roleService->getRoleAssignmentsForUser($user);
552
553
        return new Values\RoleAssignmentList($roleAssignments, $user->id);
554
    }
555
556
    /**
557
     * Un-assigns role from user group.
558
     *
559
     * @param $groupPath
560
     * @param $roleId
561
     *
562
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
563
     */
564
    public function unassignRoleFromUserGroup($groupPath, $roleId)
565
    {
566
        $groupLocationParts = explode('/', $groupPath);
567
        $groupLocation = $this->locationService->loadLocation(array_pop($groupLocationParts));
568
        $userGroup = $this->userService->loadUserGroup($groupLocation->contentId);
569
570
        $role = $this->roleService->loadRole($roleId);
571
        $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...
572
573
        $roleAssignments = $this->roleService->getRoleAssignmentsForUserGroup($userGroup);
574
575
        return new Values\RoleAssignmentList($roleAssignments, $groupPath, true);
576
    }
577
578
    /**
579
     * Loads role assignments for user.
580
     *
581
     * @param $userId
582
     *
583
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
584
     */
585
    public function loadRoleAssignmentsForUser($userId)
586
    {
587
        $user = $this->userService->loadUser($userId);
588
589
        $roleAssignments = $this->roleService->getRoleAssignmentsForUser($user);
590
591
        return new Values\RoleAssignmentList($roleAssignments, $user->id);
592
    }
593
594
    /**
595
     * Loads role assignments for user group.
596
     *
597
     * @param $groupPath
598
     *
599
     * @return \eZ\Publish\Core\REST\Server\Values\RoleAssignmentList
600
     */
601
    public function loadRoleAssignmentsForUserGroup($groupPath)
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
609
        return new Values\RoleAssignmentList($roleAssignments, $groupPath, true);
610
    }
611
612
    /**
613
     * Returns a role assignment to the given user.
614
     *
615
     * @param $userId
616
     * @param $roleId
617
     *
618
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
619
     *
620
     * @return \eZ\Publish\Core\REST\Server\Values\RestUserRoleAssignment
621
     */
622
    public function loadRoleAssignmentForUser($userId, $roleId, Request $request)
623
    {
624
        $user = $this->userService->loadUser($userId);
625
        $roleAssignments = $this->roleService->getRoleAssignmentsForUser($user);
626
627
        foreach ($roleAssignments as $roleAssignment) {
628
            if ($roleAssignment->getRole()->id == $roleId) {
629
                return new Values\RestUserRoleAssignment($roleAssignment, $userId);
0 ignored issues
show
Bug introduced by
It seems like $roleAssignment defined by $roleAssignment on line 627 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...
630
            }
631
        }
632
633
        throw new Exceptions\NotFoundException("Role assignment not found: '{$request->getPathInfo()}'.");
634
    }
635
636
    /**
637
     * Returns a role assignment to the given user group.
638
     *
639
     * @param $groupPath
640
     * @param $roleId
641
     *
642
     * @throws \eZ\Publish\Core\REST\Common\Exceptions\NotFoundException
643
     *
644
     * @return \eZ\Publish\Core\REST\Server\Values\RestUserGroupRoleAssignment
645
     */
646
    public function loadRoleAssignmentForUserGroup($groupPath, $roleId, Request $request)
647
    {
648
        $groupLocationParts = explode('/', $groupPath);
649
        $groupLocation = $this->locationService->loadLocation(array_pop($groupLocationParts));
650
        $userGroup = $this->userService->loadUserGroup($groupLocation->contentId);
651
652
        $roleAssignments = $this->roleService->getRoleAssignmentsForUserGroup($userGroup);
653
        foreach ($roleAssignments as $roleAssignment) {
654
            if ($roleAssignment->getRole()->id == $roleId) {
655
                return new Values\RestUserGroupRoleAssignment($roleAssignment, $groupPath);
656
            }
657
        }
658
659
        throw new Exceptions\NotFoundException("Role assignment not found: '{$request->getPathInfo()}'.");
660
    }
661
662
    /**
663
     * Search all policies which are applied to a given user.
664
     *
665
     * @return \eZ\Publish\Core\REST\Server\Values\PolicyList
666
     */
667
    public function listPoliciesForUser(Request $request)
668
    {
669
        return new Values\PolicyList(
670
            $this->roleService->loadPoliciesByUserId(
671
                $request->query->get('userId')
672
            ),
673
            $request->getPathInfo()
674
        );
675
    }
676
677
    /**
678
     * Maps a RoleCreateStruct to a RoleUpdateStruct.
679
     *
680
     * Needed since both structs are encoded into the same media type on input.
681
     *
682
     * @param \eZ\Publish\API\Repository\Values\User\RoleCreateStruct $createStruct
683
     *
684
     * @return \eZ\Publish\API\Repository\Values\User\RoleUpdateStruct
685
     */
686
    protected function mapToUpdateStruct(RoleCreateStruct $createStruct)
687
    {
688
        return new RoleUpdateStruct(
689
            array(
690
                'identifier' => $createStruct->identifier,
691
            )
692
        );
693
    }
694
}
695