Completed
Pull Request — master (#682)
by Asmir
07:26
created

SymfonyValidatorSubscriber::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
3
/*
4
 * Copyright 2016 Johannes M. Schmitt <[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 Symfony\Component\Validator\ValidatorInterface;
25
26
class SymfonyValidatorSubscriber implements EventSubscriberInterface
27
{
28
    private $validator;
29
30
    public function __construct(ValidatorInterface $validator)
31
    {
32
        $this->validator = $validator;
33
    }
34
35
    public static function getSubscribedEvents()
36
    {
37
        return array(
38
            array('event' => 'serializer.post_deserialize', 'method' => 'onPostDeserialize'),
39
        );
40
    }
41
42
    public function onPostDeserialize(Event $event)
43
    {
44
        $context = $event->getContext();
45
46
        if ($context->getDepth() > 0) {
47
            return;
48
        }
49
50
        $validator = $this->validator;
51
        $context->attributes->get('validation_groups')->map(
52
            function(array $groups) use ($event, $validator) {
53
                $list = $validator->validate($event->getObject(), $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...
54
55
                if ($list->count() > 0) {
56
                    throw new ValidationFailedException($list);
57
                }
58
            }
59
        );
60
    }
61
}
62