FilterTypeGuesser   A
last analyzed

Complexity

Total Complexity 21

Size/Duplication

Total Lines 125
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
wmc 21
lcom 0
cbo 3
dl 0
loc 125
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
F guessType() 0 122 21
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\DoctrineMongoDBAdminBundle\Guesser;
15
16
use Doctrine\Bundle\MongoDBBundle\Form\Type\DocumentType;
17
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
18
use Doctrine\ODM\MongoDB\Types\Type;
19
use Sonata\AdminBundle\Form\Type\Operator\EqualOperatorType;
20
use Sonata\AdminBundle\Model\ModelManagerInterface;
21
use Sonata\DoctrineMongoDBAdminBundle\Filter\BooleanFilter;
22
use Sonata\DoctrineMongoDBAdminBundle\Filter\DateFilter;
23
use Sonata\DoctrineMongoDBAdminBundle\Filter\DateTimeFilter;
24
use Sonata\DoctrineMongoDBAdminBundle\Filter\ModelFilter;
25
use Sonata\DoctrineMongoDBAdminBundle\Filter\NumberFilter;
26
use Sonata\DoctrineMongoDBAdminBundle\Filter\StringFilter;
27
use Sonata\DoctrineMongoDBAdminBundle\Model\MissingPropertyMetadataException;
28
use Sonata\Form\Type\BooleanType;
29
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
30
use Symfony\Component\Form\Extension\Core\Type\DateType;
31
use Symfony\Component\Form\Extension\Core\Type\NumberType;
32
use Symfony\Component\Form\Extension\Core\Type\TextType;
33
use Symfony\Component\Form\Guess\Guess;
34
use Symfony\Component\Form\Guess\TypeGuess;
35
36
class FilterTypeGuesser extends AbstractTypeGuesser
37
{
38
    public function guessType($class, $property, ModelManagerInterface $modelManager)
39
    {
40
        if (!$ret = $this->getParentMetadataForProperty($class, $property, $modelManager)) {
0 ignored issues
show
Compatibility introduced by
$modelManager of type object<Sonata\AdminBundl...\ModelManagerInterface> is not a sub-type of object<Sonata\DoctrineMo...dle\Model\ModelManager>. It seems like you assume a concrete implementation of the interface Sonata\AdminBundle\Model\ModelManagerInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
41
            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...
42
        }
43
44
        $options = [
45
            'field_type' => null,
46
            'field_options' => [],
47
            'options' => [],
48
        ];
49
50
        [$metadata, $propertyName, $parentAssociationMappings] = $ret;
0 ignored issues
show
Bug introduced by
The variable $metadata does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $propertyName does not exist. Did you mean $property?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
Bug introduced by
The variable $parentAssociationMappings does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
51
52
        $options['parent_association_mappings'] = $parentAssociationMappings;
53
54
        if ($metadata->hasAssociation($propertyName)) {
0 ignored issues
show
Bug introduced by
The variable $propertyName does not exist. Did you mean $property?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
55
            $mapping = $metadata->fieldMappings[$propertyName];
0 ignored issues
show
Bug introduced by
The variable $propertyName does not exist. Did you mean $property?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
56
57
            switch ($mapping['type']) {
58
                case ClassMetadata::ONE:
59
                case ClassMetadata::MANY:
60
                    $options['operator_type'] = EqualOperatorType::class;
61
                    $options['operator_options'] = [];
62
63
                    $options['field_type'] = DocumentType::class;
64
                    $options['field_options'] = [
65
                        'class' => $mapping['targetDocument'],
66
                    ];
67
68
                    $options['field_name'] = $mapping['fieldName'];
69
                    $options['mapping_type'] = $mapping['type'];
70
71
                    return new TypeGuess(ModelFilter::class, $options, Guess::HIGH_CONFIDENCE);
72
            }
73
        }
74
75
        if (!\array_key_exists($propertyName, $metadata->fieldMappings)) {
0 ignored issues
show
Bug introduced by
The variable $propertyName does not exist. Did you mean $property?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
76
            throw new MissingPropertyMetadataException($class, $property);
77
        }
78
79
        $options['field_name'] = $metadata->fieldMappings[$propertyName]['fieldName'];
0 ignored issues
show
Bug introduced by
The variable $propertyName does not exist. Did you mean $property?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
80
81
        switch ($metadata->getTypeOfField($propertyName)) {
0 ignored issues
show
Bug introduced by
The variable $propertyName does not exist. Did you mean $property?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
82
            case Type::BOOL:
83
            case Type::BOOLEAN:
84
                $options['field_type'] = BooleanType::class;
85
                $options['field_options'] = [];
86
87
                return new TypeGuess(BooleanFilter::class, $options, Guess::HIGH_CONFIDENCE);
88
            case 'datetime':
89
                @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
90
                    'The datetime type is deprecated since sonata-project/doctrine-mongodb-admin-bundle 3.x, to be removed in 4.0.'.
91
                    E_USER_DEPRECATED
92
                );
93
94
                $options['field_type'] = DateTimeType::class;
95
96
                return new TypeGuess(DateTimeFilter::class, $options, Guess::HIGH_CONFIDENCE);
97
            case Type::TIMESTAMP:
98
                $options['field_type'] = DateTimeType::class;
99
100
                return new TypeGuess(DateTimeFilter::class, $options, Guess::HIGH_CONFIDENCE);
101
            case Type::DATE:
102
103
            // NEXT_MAJOR: Use only the constant when dropping support for doctrine/mongodb-odm 1.3.
104
            // case Type::DATE_IMMUTABLE:
105
            case 'date_immutable':
106
                $options['field_type'] = DateType::class;
107
108
                return new TypeGuess(DateFilter::class, $options, Guess::HIGH_CONFIDENCE);
109
            case 'decimal':
110
                @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
111
                    'The decimal type is deprecated since sonata-project/doctrine-mongodb-admin-bundle 3.x, to be removed in 4.0.'.
112
                    E_USER_DEPRECATED
113
                );
114
115
                $options['field_type'] = NumberType::class;
116
117
                return new TypeGuess(NumberFilter::class, $options, Guess::MEDIUM_CONFIDENCE);
118
            case 'bigint':
119
                @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
120
                    'The bigint type is deprecated since sonata-project/doctrine-mongodb-admin-bundle 3.x, to be removed in 4.0.'.
121
                    E_USER_DEPRECATED
122
                );
123
124
                $options['field_type'] = NumberType::class;
125
126
                return new TypeGuess(NumberFilter::class, $options, Guess::MEDIUM_CONFIDENCE);
127
            case 'smallint':
128
                @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
129
                    'The smallint type is deprecated since sonata-project/doctrine-mongodb-admin-bundle 3.x, to be removed in 4.0.'.
130
                    E_USER_DEPRECATED
131
                );
132
133
                $options['field_type'] = NumberType::class;
134
135
                return new TypeGuess(NumberFilter::class, $options, Guess::MEDIUM_CONFIDENCE);
136
            case Type::FLOAT:
137
            case Type::INT:
138
            case Type::INTEGER:
139
                $options['field_type'] = NumberType::class;
140
141
                return new TypeGuess(NumberFilter::class, $options, Guess::MEDIUM_CONFIDENCE);
142
            case 'text':
143
                @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
144
                    'The text type is deprecated since sonata-project/doctrine-mongodb-admin-bundle 3.x, to be removed in 4.0.'.
145
                    E_USER_DEPRECATED
146
                );
147
148
                $options['field_type'] = TextType::class;
149
150
                return new TypeGuess(StringFilter::class, $options, Guess::MEDIUM_CONFIDENCE);
151
            case Type::ID:
152
            case Type::STRING:
153
                $options['field_type'] = TextType::class;
154
155
                return new TypeGuess(StringFilter::class, $options, Guess::MEDIUM_CONFIDENCE);
156
            default:
157
                return new TypeGuess(StringFilter::class, $options, Guess::LOW_CONFIDENCE);
158
        }
159
    }
160
}
161