Completed
Push — not-exists ( 0b7a0f )
by Sullivan
05:13 queued 02:01
created

AbstractIsoCodesConstraintValidator::validate()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 19
rs 8.2222
cc 7
eloc 11
nc 6
nop 2
1
<?php
2
3
namespace SLLH\IsoCodesValidator;
4
5
use SLLH\IsoCodesValidator\Constraints\IsoCodesGeneric;
6
use SLLH\IsoCodesValidator\Constraints\IsoCodesGenericValidator;
7
use SLLH\IsoCodesValidator\Exception\ValidatorNotExistsException;
8
use Symfony\Component\Validator\Constraint;
9
use Symfony\Component\Validator\ConstraintValidator;
10
use Symfony\Component\Validator\Context\ExecutionContext;
11
use Symfony\Component\Validator\Context\ExecutionContextInterface;
12
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
13
14
/**
15
 * @author Sullivan Senechal <[email protected]>
16
 */
17
abstract class AbstractIsoCodesConstraintValidator extends ConstraintValidator
18
{
19
    /**
20
     * Override PHP doc block to get IDE completion.
21
     * Can be removed when `buildViolation` would be added on ExecutionContextInterface.
22
     * Should probably done in Symfony 3.0.
23
     *
24
     * @var ExecutionContextInterface|ExecutionContext
25
     */
26
    protected $context;
27
28
    /**
29
     * {@inheritdoc}
30
     */
31
    public function validate($value, Constraint $constraint)
32
    {
33
        $validatorClass = get_class($this);
34
        if (IsoCodesGenericValidator::class === $validatorClass
35
            && !($constraint instanceof AbstractIsoCodesGenericConstraint || $constraint instanceof IsoCodesGeneric)
36
        ) {
37
            throw new UnexpectedTypeException($constraint, AbstractIsoCodesGenericConstraint::class);
38
        } elseif (IsoCodesGenericValidator::class !== $validatorClass) {
39
            $constraintClass = preg_replace('/Validator$/', '', $validatorClass);
40
41
            if (!$constraint instanceof $constraintClass) {
42
                throw new UnexpectedTypeException($constraint, $constraintClass);
43
            }
44
        }
45
46
        if (!class_exists($constraint->getIsoCodesClass())) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Validator\Constraint as the method getIsoCodesClass() does only exist in the following sub-classes of Symfony\Component\Validator\Constraint: SLLH\IsoCodesValidator\AbstractConstraint, SLLH\IsoCodesValidator\A...oCodesGenericConstraint, SLLH\IsoCodesValidator\Constraints\Bban, SLLH\IsoCodesValidator\Constraints\Cif, SLLH\IsoCodesValidator\Constraints\CreditCard, SLLH\IsoCodesValidator\Constraints\Ean13, SLLH\IsoCodesValidator\Constraints\Ean8, SLLH\IsoCodesValidator\Constraints\Iban, SLLH\IsoCodesValidator\Constraints\Insee, SLLH\IsoCodesValidator\Constraints\Ip, SLLH\IsoCodesValidator\Constraints\Isbn, SLLH\IsoCodesValidator\Constraints\Nif, SLLH\IsoCodesValidator\Constraints\Siren, SLLH\IsoCodesValidator\Constraints\Siret, SLLH\IsoCodesValidator\Constraints\Ssn, SLLH\IsoCodesValidator\C...StructuredCommunication, SLLH\IsoCodesValidator\Constraints\SwiftBic, SLLH\IsoCodesValidator\Constraints\Uknin, SLLH\IsoCodesValidator\Constraints\Vat, SLLH\IsoCodesValidator\Constraints\ZipCode. 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...
47
            throw new ValidatorNotExistsException($constraint);
0 ignored issues
show
Documentation introduced by
$constraint is of type object<Symfony\Component\Validator\Constraint>, but the function expects a object<SLLH\IsoCodesVali...or\ConstraintInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
48
        }
49
    }
50
51
    /**
52
     * Makes and adds a Constraint violation.
53
     *
54
     * @param string $message
55
     */
56
    protected function createViolation($message)
57
    {
58
        $this->context->buildViolation($message)
59
            ->addViolation();
60
    }
61
}
62