FilterTypeGuesser::guessType()   C
last analyzed

Complexity

Conditions 13
Paths 29

Size

Total Lines 67

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 67
rs 6.0133
c 0
b 0
f 0
cc 13
nc 29
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\DoctrinePHPCRAdminBundle\Guesser;
15
16
use Doctrine\Bundle\PHPCRBundle\Form\Type\DocumentType;
17
use Doctrine\Bundle\PHPCRBundle\ManagerRegistry;
18
use Doctrine\ODM\PHPCR\Mapping\ClassMetadata;
19
use Doctrine\ODM\PHPCR\Mapping\MappingException;
20
use Sonata\AdminBundle\Guesser\TypeGuesserInterface;
21
use Sonata\AdminBundle\Model\ModelManagerInterface;
22
use Sonata\DoctrinePHPCRAdminBundle\Filter\BooleanFilter;
23
use Sonata\DoctrinePHPCRAdminBundle\Filter\DateFilter;
24
use Sonata\DoctrinePHPCRAdminBundle\Filter\NumberFilter;
25
use Sonata\DoctrinePHPCRAdminBundle\Filter\StringFilter;
26
use Sonata\Form\Type\BooleanType;
27
use Symfony\Component\Form\Extension\Core\Type\NumberType;
28
use Symfony\Component\Form\Extension\Core\Type\TextType;
29
use Symfony\Component\Form\Guess\Guess;
30
use Symfony\Component\Form\Guess\TypeGuess;
31
32
class FilterTypeGuesser implements TypeGuesserInterface
33
{
34
    /**
35
     * @var ManagerRegistry
36
     */
37
    protected $registry;
38
39
    /**
40
     * @var array
41
     */
42
    private $cache;
43
44
    public function __construct(ManagerRegistry $registry)
45
    {
46
        $this->registry = $registry;
47
        $this->cache = [];
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function guessType($class, $property, ModelManagerInterface $modelManager)
54
    {
55
        if (!$metadata = $this->getMetadata($class)) {
56
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type declared by the interface Sonata\AdminBundle\Guess...serInterface::guessType of type Symfony\Component\Form\Guess\Guess|null.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
57
        }
58
59
        $options = [
60
            'field_type' => TextType::class,
61
            'field_options' => [],
62
            'options' => [],
63
        ];
64
65
        if ($metadata->hasAssociation($property)) {
66
            // TODO add support for children, child, referrers and parentDocument associations
67
            $mapping = $metadata->mappings[$property];
68
69
            $options['operator_type'] = BooleanType::class;
70
            $options['operator_options'] = [];
71
72
            $options['field_type'] = DocumentType::class;
73
            if (!empty($mapping['targetDocument'])) {
74
                $options['field_options'] = [
75
                    'class' => $mapping['targetDocument'],
76
                ];
77
            }
78
            $options['field_name'] = $mapping['fieldName'];
79
            $options['mapping_type'] = $mapping['type'];
80
81
            switch ($mapping['type']) {
82
                case ClassMetadata::MANY_TO_MANY:
83
                    return new TypeGuess('doctrine_phpcr_many_to_many', $options, Guess::HIGH_CONFIDENCE);
84
85
                case ClassMetadata::MANY_TO_ONE:
86
                    return new TypeGuess('doctrine_phpcr_many_to_one', $options, Guess::HIGH_CONFIDENCE);
87
            }
88
        }
89
90
        // TODO add support for node, nodename, version created, version name
91
92
        $options['field_name'] = $property;
93
        switch ($metadata->getTypeOfField($property)) {
94
            case 'boolean':
95
                $options['field_type'] = BooleanType::class;
96
                $options['field_options'] = [];
97
98
                return new TypeGuess(BooleanFilter::class, $options, Guess::HIGH_CONFIDENCE);
99
            case 'date':
100
                return new TypeGuess(DateFilter::class, $options, Guess::HIGH_CONFIDENCE);
101
            case 'decimal':
102
            case 'float':
103
                return new TypeGuess(NumberFilter::class, $options, Guess::HIGH_CONFIDENCE);
104
            case 'integer':
105
                $options['field_type'] = NumberType::class;
106
                $options['field_options'] = [
107
                    'csrf_protection' => false,
108
                ];
109
110
                return new TypeGuess(NumberFilter::class, $options, Guess::HIGH_CONFIDENCE);
111
            case 'text':
112
            case 'string':
113
                $options['field_type'] = TextType::class;
114
115
                return new TypeGuess(StringFilter::class, $options, Guess::HIGH_CONFIDENCE);
116
        }
117
118
        return new TypeGuess(StringFilter::class, $options, Guess::LOW_CONFIDENCE);
119
    }
120
121
    /**
122
     * @param string $class
123
     *
124
     * @return mixed
125
     */
126
    protected function getMetadata($class)
127
    {
128
        if (\array_key_exists($class, $this->cache)) {
129
            return $this->cache[$class];
130
        }
131
132
        $this->cache[$class] = null;
133
        foreach ($this->registry->getManagers() as $dm) {
134
            try {
135
                return $this->cache[$class] = $dm->getClassMetadata($class);
136
            } catch (MappingException $e) {
137
                // not an entity or mapped super class
138
            }
139
        }
140
    }
141
}
142