Completed
Push — phonenumber ( dc108a...0fb569 )
by Sullivan
12:22 queued 09:32
created

AbstractIsoCodesConstraintValidator   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
c 1
b 0
f 0
lcom 1
cbo 3
dl 0
loc 45
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B validate() 0 19 7
A createViolation() 0 5 1
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)
0 ignored issues
show
Bug introduced by
The class SLLH\IsoCodesValidator\Constraints\IsoCodesGeneric does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
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\Mac, 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