Completed
Pull Request — master (#395)
by
unknown
02:26
created

ListBuilder::fixFieldDescription()   D

Complexity

Conditions 13
Paths 234

Size

Total Lines 62
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 2 Features 1
Metric Value
c 4
b 2
f 1
dl 0
loc 62
rs 4.8995
cc 13
eloc 31
nc 234
nop 2

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
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sonata\DoctrinePHPCRAdminBundle\Builder;
13
14
use Sonata\AdminBundle\Admin\AdminInterface;
15
use Sonata\AdminBundle\Admin\FieldDescriptionCollection;
16
use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
17
use Sonata\AdminBundle\Builder\ListBuilderInterface;
18
use Sonata\AdminBundle\Guesser\TypeGuesserInterface;
19
20
class ListBuilder implements ListBuilderInterface
21
{
22
    /**
23
     * @var TypeGuesserInterface
24
     */
25
    protected $guesser;
26
27
    /**
28
     * @var array
29
     */
30
    protected $templates;
31
32
    /**
33
     * @param TypeGuesserInterface $guesser
34
     * @param array                $templates
35
     */
36
    public function __construct(TypeGuesserInterface $guesser, array $templates = array())
37
    {
38
        $this->guesser = $guesser;
39
        $this->templates = $templates;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function getBaseList(array $options = array())
46
    {
47
        return new FieldDescriptionCollection();
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function buildField($type, FieldDescriptionInterface $fieldDescription, AdminInterface $admin)
54
    {
55
        if ($type == null) {
56
            $guessType = $this->guesser->guessType($admin->getClass(), $fieldDescription->getName(), $admin->getModelManager());
57
            $fieldDescription->setType($guessType->getType());
58
        } else {
59
            $fieldDescription->setType($type);
60
        }
61
62
        $this->fixFieldDescription($admin, $fieldDescription);
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public function addField(FieldDescriptionCollection $list, $type, FieldDescriptionInterface $fieldDescription, AdminInterface $admin)
69
    {
70
        $this->buildField($type, $fieldDescription, $admin);
71
        $admin->addListFieldDescription($fieldDescription->getName(), $fieldDescription);
72
73
        $list->add($fieldDescription);
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     *
79
     * @throws \RuntimeException if the $fieldDescription does not have a type.
80
     */
81
    public function fixFieldDescription(AdminInterface $admin, FieldDescriptionInterface $fieldDescription)
82
    {
83
        if ($fieldDescription->getName() == '_action') {
84
            $this->buildActionFieldDescription($fieldDescription);
85
        }
86
87
        $fieldDescription->setAdmin($admin);
88
89
        if ($admin->getModelManager()->hasMetadata($admin->getClass())) {
90
            $metadata = $admin->getModelManager()->getMetadata($admin->getClass());
91
92
            // TODO sort on parent associations or node name
93
            $defaultSortable = true;
94
            if ($metadata->hasAssociation($fieldDescription->getName())
95
                || $metadata->nodename === $fieldDescription->getName()
96
            ) {
97
                $defaultSortable = false;
98
            }
99
100
            // TODO get and set parent association mappings, see
101
            // https://github.com/sonata-project/SonataDoctrinePhpcrAdminBundle/issues/106
102
            //$fieldDescription->setParentAssociationMappings($parentAssociationMappings);
103
104
            // set the default field mapping
105
            if (isset($metadata->mappings[$fieldDescription->getName()])) {
106
                $fieldDescription->setFieldMapping($metadata->mappings[$fieldDescription->getName()]);
107
                if ($fieldDescription->getOption('sortable') !== false) {
108
                    $fieldDescription->setOption('sortable', $fieldDescription->getOption('sortable', $defaultSortable));
109
                    $fieldDescription->setOption('sort_parent_association_mappings', $fieldDescription->getOption('sort_parent_association_mappings', $fieldDescription->getParentAssociationMappings()));
110
                    $fieldDescription->setOption('sort_field_mapping', $fieldDescription->getOption('sort_field_mapping', $fieldDescription->getFieldMapping()));
111
                }
112
            }
113
114
            // set the default association mapping
115
            if (isset($metadata->associationMappings[$fieldDescription->getName()])) {
116
                $fieldDescription->setAssociationMapping($metadata->associationMappings[$fieldDescription->getName()]);
117
            }
118
119
            $fieldDescription->setOption('_sort_order', $fieldDescription->getOption('_sort_order', 'ASC'));
120
        }
121
122
        if (!$fieldDescription->getType()) {
123
            throw new \RuntimeException(sprintf('Please define a type for field `%s` in `%s`', $fieldDescription->getName(), get_class($admin)));
124
        }
125
126
        $fieldDescription->setOption('code', $fieldDescription->getOption('code', $fieldDescription->getName()));
127
        $fieldDescription->setOption('label', $fieldDescription->getOption('label', $fieldDescription->getName()));
128
129
        if (!$fieldDescription->getTemplate()) {
130
            $fieldDescription->setTemplate($this->getTemplate($fieldDescription->getType()));
131
132
            if ($fieldDescription->describesSingleValuedAssociation()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Sonata\AdminBundle\Admin\FieldDescriptionInterface as the method describesSingleValuedAssociation() does only exist in the following implementations of said interface: Sonata\DoctrinePHPCRAdmi...\Admin\FieldDescription.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
133
                $fieldDescription->setTemplate('SonataAdminBundle:CRUD/Association:list_single.html.twig');
134
            } elseif ($fieldDescription->describesCollectionValuedAssociation()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Sonata\AdminBundle\Admin\FieldDescriptionInterface as the method describesCollectionValuedAssociation() does only exist in the following implementations of said interface: Sonata\DoctrinePHPCRAdmi...\Admin\FieldDescription.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
135
                $fieldDescription->setTemplate('SonataAdminBundle:CRUD/Association:list_collection.html.twig');
136
            }
137
        }
138
139
        if ($fieldDescription->describesAssociation()) {
0 ignored issues
show
Bug introduced by
The method describesAssociation() does not seem to exist on object<Sonata\AdminBundl...ldDescriptionInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
140
            $admin->attachAdminClass($fieldDescription);
141
        }
142
    }
143
144
    /**
145
     * @param FieldDescriptionInterface $fieldDescription
146
     *
147
     * @return FieldDescriptionInterface
148
     */
149
    public function buildActionFieldDescription(FieldDescriptionInterface $fieldDescription)
150
    {
151
        if (null === $fieldDescription->getTemplate()) {
152
            $fieldDescription->setTemplate('SonataAdminBundle:CRUD:list__action.html.twig');
153
        }
154
155
        if (null === $fieldDescription->getType()) {
156
            $fieldDescription->setType('action');
157
        }
158
159
        if (null === $fieldDescription->getOption('name')) {
160
            $fieldDescription->setOption('name', 'Action');
161
        }
162
163
        if (null === $fieldDescription->getOption('code')) {
164
            $fieldDescription->setOption('code', 'Action');
165
        }
166
167
        if (null !== $fieldDescription->getOption('actions')) {
168
            $actions = $fieldDescription->getOption('actions');
169
            foreach ($actions as $k => $action) {
170
                if (!isset($action['template'])) {
171
                    $actions[$k]['template'] = sprintf('SonataAdminBundle:CRUD:list__action_%s.html.twig', $k);
172
                }
173
            }
174
175
            $fieldDescription->setOption('actions', $actions);
176
        }
177
178
        return $fieldDescription;
179
    }
180
181
    /**
182
     * @param string $type
183
     *
184
     * @return string
185
     */
186
    private function getTemplate($type)
187
    {
188
        if (!isset($this->templates[$type])) {
189
            return;
190
        }
191
192
        return $this->templates[$type];
193
    }
194
}
195