Test Failed
Pull Request — master (#4)
by Alex
03:18
created

IsMemberOf::resolveFieldName()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 19
c 0
b 0
f 0
nc 5
nop 3
dl 0
loc 29
rs 9.6333
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Arp\DoctrineQueryFilter\Filter;
6
7
use Arp\DoctrineQueryFilter\Filter\Exception\InvalidArgumentException;
8
use Arp\DoctrineQueryFilter\Metadata\MetadataInterface;
9
use Doctrine\ORM\Mapping\ClassMetadata;
10
use Doctrine\ORM\Query\Expr;
11
12
/**
13
 * @author  Alex Patterson <[email protected]>
14
 * @package Arp\DoctrineQueryFilter\Filter
15
 */
16
final class IsMemberOf extends AbstractExpression
17
{
18
    /**
19
     * @param Expr   $expr
20
     * @param string $fieldName
21
     * @param string $parameterName
22
     * @param string $alias
23
     *
24
     * @return string
25
     */
26
    protected function createExpression(Expr $expr, string $fieldName, string $parameterName, string $alias): string
27
    {
28
        return (string)$expr->isMemberOf(':' . $parameterName, $alias . '.' . $fieldName);
29
    }
30
31
    /**
32
     * @param MetadataInterface $metadata
33
     * @param array             $criteria
34
     * @param string            $key
35
     *
36
     * @return string
37
     *
38
     * @throws InvalidArgumentException
39
     */
40
    protected function resolveFieldName(MetadataInterface $metadata, array $criteria, string $key = 'field'): string
41
    {
42
        $fieldName = parent::resolveFieldName($metadata, $criteria, $key);
43
44
        if ($metadata->hasAssociation($fieldName)) {
45
            $associationType = $metadata->getAssociationMapping($fieldName)['type'];
46
47
            $isCollection = ($associationType & ClassMetadata::TO_ONE) ? false : true;
48
            if ($isCollection) {
49
                return $fieldName;
50
            }
51
52
            throw new InvalidArgumentException(
53
                sprintf(
54
                    'Unable to apply query filter \'%s\': '
55
                    . 'The field \'%s\' is not a collection valued association',
56
                    static::class,
57
                    $fieldName
58
                )
59
            );
60
        }
61
62
        throw new InvalidArgumentException(
63
            sprintf(
64
                'Unable to apply query filter \'%s\': '
65
                . 'The entity class \'%s\' has no association named \'%s\'',
66
                static::class,
67
                $metadata->getName(),
68
                $fieldName
69
            )
70
        );
71
    }
72
}
73