Completed
Push — master ( 4a8d0f...5fbf19 )
by Konstantinos
04:38
created

UniqueAliasValidator::validate()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 31
rs 8.439
c 1
b 0
f 1
cc 5
eloc 19
nc 5
nop 2
1
<?php
2
/**
3
 * This file contains a validator constraint that makes sure aliases are unique
4
 *
5
 * @license    https://github.com/allejo/bzion/blob/master/LICENSE.md GNU General Public License Version 3
6
 */
7
8
namespace BZIon\Form\Constraint;
9
10
use Symfony\Component\Validator\Constraint;
11
use Symfony\Component\Validator\ConstraintValidator;
12
13
/**
14
 * Unique alias validator for models
15
 */
16
class UniqueAliasValidator extends ConstraintValidator
17
{
18
    /**
19
     * {@inheritdoc}
20
     */
21
    public function validate($value, Constraint $constraint)
22
    {
23
        if (empty($value)) {
24
            // No need to run any checks if no alias is provided
25
            return;
26
        }
27
28
        $database = \Database::getInstance();
29
        $type = $constraint->type;
30
        $table = $type::TABLE;
31
32
        if ($constraint->model && $constraint->model->isValid()) {
33
            // A model is being edited, make sure we don't show an error because
34
            // its alias is found in the database
35
            $results = $database->query(
36
                "SELECT EXISTS(SELECT 1 FROM $table WHERE alias = ? AND id != ?) AS 'exists'",
37
                'si',
38
                array($value, $constraint->model->getId())
39
            );
40
        } else {
41
            $results = $database->query(
42
                "SELECT EXISTS(SELECT 1 FROM $table WHERE alias = ?) AS 'exists'",
43
                's',
44
                $value);
45
        }
46
47
        if ($results[0]['exists']) {
48
            $this->context->buildViolation($constraint->message)
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Valida...ecutionContextInterface as the method buildViolation() does only exist in the following implementations of said interface: Symfony\Component\Valida...ontext\ExecutionContext, Symfony\Component\Valida...\LegacyExecutionContext.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
49
                ->addViolation();
50
        }
51
    }
52
}
53