Completed
Push — master ( ce9f52...026dd1 )
by Asmir
8s
created

onPostDeserialize()   B

Complexity

Conditions 6
Paths 11

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 27
ccs 17
cts 17
cp 1
rs 8.439
c 0
b 0
f 0
cc 6
eloc 16
nc 11
nop 1
crap 6
1
<?php
2
3
/*
4
 * Copyright 2016 Asmir Mustafic <[email protected]>
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace JMS\Serializer\EventDispatcher\Subscriber;
20
21
use JMS\Serializer\EventDispatcher\Event;
22
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
23
use JMS\Serializer\Exception\ValidationFailedException;
24
use PhpOption\None;
25
use Symfony\Component\Validator\Validator\ValidatorInterface;
26
27
class SymfonyValidatorValidatorSubscriber implements EventSubscriberInterface
28
{
29
    /**
30
     * @var ValidatorInterface
31
     */
32
    private $validator;
33
34 4
    public function __construct(ValidatorInterface $validator)
35
    {
36 4
        $this->validator = $validator;
37 4
    }
38
39 1
    public static function getSubscribedEvents()
40
    {
41
        return array(
42 1
            array('event' => 'serializer.post_deserialize', 'method' => 'onPostDeserialize'),
43 1
        );
44
    }
45
46 4
    public function onPostDeserialize(Event $event)
47
    {
48 4
        $context = $event->getContext();
49
50 4
        if ($context->getDepth() > 0) {
51 1
            return;
52
        }
53
54 4
        $validator = $this->validator;
55 4
        $groups = $context->attributes->get('validation_groups') instanceof None
56 4
            ? null
57 4
            : $context->attributes->get('validation_groups')->get();
58
59 4
        if (!$groups) {
60 1
            return;
61
        }
62
63 3
        $constraints = $context->attributes->get('validation_constraints') instanceof None
64 3
            ? null
65 3
            : $context->attributes->get('validation_constraints')->get();
66
67 3
        $list = $validator->validate($event->getObject(), $constraints, $groups);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class JMS\Serializer\EventDispatcher\Event as the method getObject() does only exist in the following sub-classes of JMS\Serializer\EventDispatcher\Event: JMS\Serializer\EventDispatcher\ObjectEvent, JMS\Serializer\EventDispatcher\PreSerializeEvent. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
68
69 3
        if ($list->count() > 0) {
70 1
            throw new ValidationFailedException($list);
71
        }
72 2
    }
73
}
74