IsMemberOf::resolveFieldName()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
c 0
b 0
f 0
nc 3
nop 2
dl 0
loc 18
rs 9.9
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\Exception\MetadataException;
9
use Arp\DoctrineQueryFilter\Metadata\MetadataInterface;
10
use Doctrine\ORM\Mapping\ClassMetadataInfo;
11
use Doctrine\ORM\Query\Expr;
12
13
final class IsMemberOf extends AbstractExpression
14
{
15
    protected function createExpression(Expr $expr, string $fieldName, string $parameterName, string $alias): string
16
    {
17
        return (string) $expr->isMemberOf(':' . $parameterName, $alias . '.' . $fieldName);
18
    }
19
20
    /**
21
     * @throws InvalidArgumentException
22
     * @throws MetadataException
23
     */
24
    protected function resolveFieldName(MetadataInterface $metadata, array $criteria): string
25
    {
26
        $fieldName = parent::resolveFieldName($metadata, $criteria);
27
28
        if ($metadata->hasAssociation($fieldName)) {
29
            $associationType = $metadata->getAssociationMapping($fieldName)['type'] ?? null;
30
31
            if (null !== $associationType && !($associationType & ClassMetadataInfo::TO_ONE)) {
32
                return $fieldName;
33
            }
34
        }
35
36
        throw new InvalidArgumentException(
37
            sprintf(
38
                'Unable to apply query filter \'%s\': '
39
                . 'The field \'%s\' is not a valid collection valued association',
40
                self::class,
41
                $fieldName,
42
            ),
43
        );
44
    }
45
}
46