ValidatorMiddleware::handle()   B
last analyzed

Complexity

Conditions 5
Paths 12

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.439
c 0
b 0
f 0
cc 5
eloc 14
nc 12
nop 2
1
<?php
2
3
/**
4
 * This file is part of the Cubiche package.
5
 *
6
 * Copyright (c) Cubiche
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Cubiche\Core\Bus\Middlewares\Validator;
13
14
use Cubiche\Core\Bus\Exception\NotFoundException;
15
use Cubiche\Core\Bus\Middlewares\Handler\MessageHandlerMiddleware;
16
use Cubiche\Core\Validator\Validator;
17
18
/**
19
 * ValidatorMiddleware class.
20
 *
21
 * @author Ivannis Suárez Jerez <[email protected]>
22
 */
23
class ValidatorMiddleware extends MessageHandlerMiddleware
24
{
25
    /**
26
     * {@inheritdoc}
27
     */
28
    public function handle($message, callable $next)
29
    {
30
        $this->ensureTypeOfMessage($message);
31
32
        try {
33
            $handler = $this->handlerClassResolver->resolve($message);
34
            $metadata = Validator::getMetadataForClass(get_class($message));
35
            $classMetadata = null;
36
37
            if ($metadata !== null) {
38
                /** @var ClassMetadata $classMetadata */
39
                $classMetadata = $metadata->getRootClassMetadata();
0 ignored issues
show
Bug introduced by
The method getRootClassMetadata does only exist in Metadata\ClassHierarchyMetadata, but not in Metadata\MergeableClassMetadata.

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...
40
            }
41
42
            $handler($message, $classMetadata);
43
        } catch (NotFoundException $e) {
44
            // NotFoundException::handlerMethodNameForObject
45
            // NotFoundException::methodForObject
46
            if ($e->getCode() == 3 || $e->getCode() == 7) {
47
                throw $e;
48
            }
49
        }
50
51
        Validator::assert($message);
52
53
        return $next($message);
54
    }
55
}
56