EntityCheckerTest::testIsUnique()   B
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 36
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 36
rs 8.8571
c 1
b 0
f 0
cc 1
eloc 17
nc 1
nop 0
1
<?php
2
3
namespace Vvval\Spiral\Validation\Tests\Checkers;
4
5
use TestApplication\Database\Sources\TestSource;
6
use TestApplication\Database\TestRecord;
7
use Vvval\Spiral\Validation\Tests\BaseTest;
8
9
class EntityCheckerTest extends BaseTest
10
{
11
    public function testIsUnique()
12
    {
13
        $rules = [
14
            'field' => [
15
                ['entity::isUnique', TestSource::class, 'field']
16
            ],
17
        ];
18
        $validator = $this->createValidator($rules);
19
        $validator->setData(['field' => 'value']);
20
21
        //nothing in db
22
        $this->assertTrue($validator->isValid(), 'Validation FAILED');
23
24
        /**
25
         * @var TestSource $source
26
         * @var TestRecord $record
27
         */
28
        $source = $this->container->get(TestSource::class);
29
        $entity = $source->create();
30
31
        //nothing in db (entity not saved)
32
        $validator->setContext($entity);
33
        $this->assertTrue($validator->isValid(), 'Validation FAILED');
34
35
        //nothing in db (entity not saved)
36
        $entity->field = 'value';
37
        $this->assertTrue($validator->isValid(), 'Validation FAILED');
38
39
        //entity in db, but it is passed as context, no conflicts with another entities
40
        $entity->save();
0 ignored issues
show
Bug introduced by
The method save does only exist in Spiral\ORM\Record, but not in Spiral\Models\EntityInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
41
        $this->assertTrue($validator->isValid(), 'Validation FAILED');
42
43
        //entity in db and it isn't passed as context, fail with conflict
44
        $validator->setContext(null);
45
        $this->assertFalse($validator->isValid(), 'Validation PASSED');
46
    }
47
}