Passed
Push — develop ( a93deb...c2cf51 )
by Ludwig
04:39
created

EntityType::parameterToArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/*
3
 * This file is part of cwdFancyGridBundle
4
 *
5
 * (c)2017 cwd.at GmbH <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
declare(strict_types=1);
11
namespace Cwd\FancyGridBundle\Column;
12
13
use Doctrine\Common\Persistence\ObjectManager;
14
use Symfony\Bridge\Doctrine\Form\ChoiceList\DoctrineChoiceLoader;
15
use Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader;
16
use Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader;
17
use Symfony\Bridge\Doctrine\ManagerRegistry;
18
use Symfony\Component\Form\ChoiceList\Factory\CachingFactoryDecorator;
19
use Symfony\Component\Form\ChoiceList\Factory\DefaultChoiceListFactory;
20
use Symfony\Component\Form\ChoiceList\View\ChoiceView;
21
use Symfony\Component\OptionsResolver\Options;
22
use Symfony\Component\OptionsResolver\OptionsResolver;
23
24
/**
25
 * Class EntityType
26
 * @package Cwd\FancyGridBundle\Column
27
 * @author Ludwig Ruderstaler <[email protected]>
28
 */
29
class EntityType extends AbstractColumn
30
{
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function configureOptions(OptionsResolver $resolver)
35
    {
36
        parent::configureOptions($resolver);
37
38
        $choiceLoader = function (Options $options) {
39
            // Unless the choices are given explicitly, load them on demand
40
            if (null === $options['data']) {
41
                $hash = null;
0 ignored issues
show
Unused Code introduced by
$hash is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
42
                $qbParts = null;
0 ignored issues
show
Unused Code introduced by
$qbParts is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
43
44
                if (null !== $options['query_builder']) {
45
                    $entityLoader = $this->getLoader($options['em'], $options['query_builder'], $options['class']);
46
                } else {
47
                    $queryBuilder = $options['em']->getRepository($options['class'])->createQueryBuilder('e');
48
                    $entityLoader = $this->getLoader($options['em'], $queryBuilder, $options['class']);
49
                }
50
51
                $doctrineChoiceLoader = new DoctrineChoiceLoader(
52
                    $options['em'],
53
                    $options['class'],
54
                    $options['id_reader'],
55
                    $entityLoader
56
                );
57
58
                return $doctrineChoiceLoader;
59
            }
60
        };
61
62
        $emNormalizer = function (Options $options, $em) {
63
            /* @var ManagerRegistry $registry */
64
            if (null !== $em) {
65
                if ($em instanceof ObjectManager) {
66
                    return $em;
67
                }
68
69
                return $this->getOb->getManager($em);
0 ignored issues
show
Bug introduced by
The property getOb does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
70
            }
71
72
            $em = $this->registry->getManagerForClass($options['class']);
0 ignored issues
show
Bug introduced by
The property registry does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
73
74
            if (null === $em) {
75
                throw new \RuntimeException(sprintf(
76
                    'Class "%s" seems not to be a managed Doctrine entity. '.
77
                    'Did you forget to map it?',
78
                    $options['class']
79
                ));
80
            }
81
82
            return $em;
83
        };
84
85
        // Invoke the query builder closure so that we can cache choice lists
86
        // for equal query builders
87
        $queryBuilderNormalizer = function (Options $options, $queryBuilder) {
88
            if (is_callable($queryBuilder)) {
89
                $queryBuilder = call_user_func($queryBuilder, $options['em']->getRepository($options['class']));
90
            }
91
92
            return $queryBuilder;
93
        };
94
95
        // Set the "id_reader" option via the normalizer. This option is not
96
        // supposed to be set by the user.
97
        $idReaderNormalizer = function (Options $options) {
98
            $classMetadata = $options['em']->getClassMetadata($options['class']);
99
            return new IdReader($options['em'], $classMetadata);
100
        };
101
102
        $resolver->setDefaults(array(
103
            'align' => 'left',
104
            'cellAlign' => 'left',
105
            'type' => 'combo',
106
            'data' => null,
107
            'class' => null,
108
            'query_builder' => null,
109
            'choice_loader' => $choiceLoader,
110
            'choice_label'  => null,
111
            'id_reader' => null,
112
            'em' => null,
113
        ));
114
        $resolver->setRequired(['class']);
115
116
        $resolver->setNormalizer('em', $emNormalizer);
117
        $resolver->setNormalizer('query_builder', $queryBuilderNormalizer);
118
        $resolver->setNormalizer('id_reader', $idReaderNormalizer);
119
120
        $resolver->setAllowedTypes('attr', 'array');
121
        $resolver->setAllowedTypes('data', ['array', 'null']);
122
    }
123
124
125
    public function buildColumnOptions() : array
126
    {
127
        $printOptions = parent::buildColumnOptions();
128
129
        if (is_array($this->getOption('data')) && count($this->getOption('data')) > 0) {
130
            return $printOptions;
131
        }
132
133
        //new ArrayChoiceList(call_user_func($this->callback), $value)
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
134
135
        $list = $this->getOption('choice_loader');
136
        $viewFactory = new DefaultChoiceListFactory();
137
        $views = $viewFactory->createView($list->loadChoiceList(), null, $this->getOption('choice_label'));
1 ignored issue
show
Bug introduced by
The method loadChoiceList cannot be called on $list (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
138
139
        $printOptions['data'] = [];
140
        $printOptions['displayKey'] = 'label';
141
        $printOptions['valueKey'] = 'name';
142
143
        foreach ($views->choices as $view) {
144
            $printOptions['data'][] = [
145
                'id' => $view->value,
146
                'label' => $view->label,
147
                'name' => $view->data->getName()
148
            ];
149
        }
150
151
        return $printOptions;
152
    }
153
154
155
    /**
156
     * We consider two query builders with an equal SQL string and
157
     * equal parameters to be equal.
158
     *
159
     * @param QueryBuilder $queryBuilder
160
     *
161
     * @return array
162
     *
163
     * @internal This method is public to be usable as callback. It should not
164
     *           be used in user code.
165
     */
166
    public function getQueryBuilderPartsForCachingHash($queryBuilder)
167
    {
168
        return array(
169
            $queryBuilder->getQuery()->getSQL(),
170
            array_map(array($this, 'parameterToArray'), $queryBuilder->getParameters()->toArray()),
171
        );
172
    }
173
174
    /**
175
     * Converts a query parameter to an array.
176
     *
177
     * @return array The array representation of the parameter
178
     */
179
    private function parameterToArray(Parameter $parameter)
180
    {
181
        return array($parameter->getName(), $parameter->getType(), $parameter->getValue());
182
    }
183
184
    /**
185
     * Return the default loader object.
186
     *
187
     * @param ObjectManager $manager
188
     * @param QueryBuilder  $queryBuilder
189
     * @param string        $class
190
     *
191
     * @return ORMQueryBuilderLoader
192
     */
193
    public function getLoader(ObjectManager $manager, $queryBuilder, $class)
2 ignored issues
show
Unused Code introduced by
The parameter $manager is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $class is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
194
    {
195
        return new ORMQueryBuilderLoader($queryBuilder);
196
    }
197
}
198