Completed
Push — 3.x ( 3e834f...38b337 )
by Grégoire
03:36
created

src/Show/ShowMapper.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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\AdminBundle\Show;
15
16
use Sonata\AdminBundle\Admin\AdminInterface;
17
use Sonata\AdminBundle\Admin\FieldDescriptionCollection;
18
use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
19
use Sonata\AdminBundle\Builder\ShowBuilderInterface;
20
use Sonata\AdminBundle\Mapper\BaseGroupedMapper;
21
22
/**
23
 * This class is used to simulate the Form API.
24
 *
25
 * @final since sonata-project/admin-bundle 3.52
26
 *
27
 * @author Thomas Rabaix <[email protected]>
28
 */
29
class ShowMapper extends BaseGroupedMapper
30
{
31
    protected $list;
32
33
    public function __construct(
34
        ShowBuilderInterface $showBuilder,
35
        FieldDescriptionCollection $list,
36
        AdminInterface $admin
37
    ) {
38
        parent::__construct($showBuilder, $admin);
39
        $this->list = $list;
40
    }
41
42
    /**
43
     * @param FieldDescriptionInterface|string $name
44
     * @param string|null                      $type
45
     *
46
     * @throws \LogicException
47
     *
48
     * @return $this
49
     */
50
    public function add($name, $type = null, array $fieldDescriptionOptions = [])
51
    {
52
        if (!$this->shouldApply()) {
53
            return $this;
54
        }
55
56
        $fieldKey = ($name instanceof FieldDescriptionInterface) ? $name->getName() : $name;
57
58
        $this->addFieldToCurrentGroup($fieldKey);
59
60
        if ($name instanceof FieldDescriptionInterface) {
61
            $fieldDescription = $name;
62
            $fieldDescription->mergeOptions($fieldDescriptionOptions);
63
        } elseif (\is_string($name)) {
64
            if (!$this->admin->hasShowFieldDescription($name)) {
65
                $fieldDescription = $this->admin->getModelManager()->getNewFieldDescriptionInstance(
66
                    $this->admin->getClass(),
67
                    $name,
68
                    $fieldDescriptionOptions
69
                );
70
            } else {
71
                throw new \LogicException(sprintf('Duplicate field name "%s" in show mapper. Names should be unique.', $name));
72
            }
73
        } else {
74
            throw new \TypeError(
75
                'Unknown field name in show mapper. '
76
                .'Field name should be either of FieldDescriptionInterface interface or string.'
77
            );
78
        }
79
80
        // NEXT_MAJOR: Remove the argument "sonata_deprecation_mute" in the following call.
81
        if (null === $fieldDescription->getLabel('sonata_deprecation_mute')) {
82
            $fieldDescription->setOption('label', $this->admin->getLabelTranslatorStrategy()->getLabel($fieldDescription->getName(), 'show', 'label'));
83
        }
84
85
        $fieldDescription->setOption('safe', $fieldDescription->getOption('safe', false));
86
87
        if (!isset($fieldDescriptionOptions['role']) || $this->admin->isGranted($fieldDescriptionOptions['role'])) {
88
            // add the field with the FormBuilder
89
            $this->builder->addField($this->list, $type, $fieldDescription, $this->admin);
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Sonata\AdminBundle\Builder\BuilderInterface as the method addField() does only exist in the following implementations of said interface: Sonata\AdminBundle\Tests\App\Builder\ListBuilder, Sonata\AdminBundle\Tests\App\Builder\ShowBuilder.

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...
90
        }
91
92
        return $this;
93
    }
94
95
    public function get($name)
96
    {
97
        return $this->list->get($name);
98
    }
99
100
    public function has($key)
101
    {
102
        return $this->list->has($key);
103
    }
104
105
    public function remove($key)
106
    {
107
        $this->admin->removeShowFieldDescription($key);
108
        $this->list->remove($key);
109
110
        return $this;
111
    }
112
113
    /**
114
     * Removes a group.
115
     *
116
     * @param string $group          The group to delete
117
     * @param string $tab            The tab the group belongs to, defaults to 'default'
118
     * @param bool   $deleteEmptyTab Whether or not the parent Tab should be deleted too,
119
     *                               when the deleted group leaves the tab empty after deletion
120
     *
121
     * @return $this
122
     */
123
    public function removeGroup($group, $tab = 'default', $deleteEmptyTab = false)
124
    {
125
        $groups = $this->getGroups();
126
127
        // When the default tab is used, the tabname is not prepended to the index in the group array
128
        if ('default' !== $tab) {
129
            $group = $tab.'.'.$group;
130
        }
131
132
        if (isset($groups[$group])) {
133
            foreach ($groups[$group]['fields'] as $field) {
134
                $this->remove($field);
135
            }
136
        }
137
        unset($groups[$group]);
138
139
        $tabs = $this->getTabs();
140
        $key = array_search($group, $tabs[$tab]['groups'], true);
141
142
        if (false !== $key) {
143
            unset($tabs[$tab]['groups'][$key]);
144
        }
145
        if ($deleteEmptyTab && 0 === \count($tabs[$tab]['groups'])) {
146
            unset($tabs[$tab]);
147
        }
148
149
        $this->setTabs($tabs);
150
        $this->setGroups($groups);
151
152
        return $this;
153
    }
154
155
    final public function keys()
156
    {
157
        return array_keys($this->list->getElements());
158
    }
159
160
    public function reorder(array $keys)
161
    {
162
        $this->admin->reorderShowGroup($this->getCurrentGroupName(), $keys);
163
164
        return $this;
165
    }
166
167
    protected function getGroups()
168
    {
169
        // NEXT_MAJOR: Remove the argument "sonata_deprecation_mute" in the following call.
170
171
        return $this->admin->getShowGroups('sonata_deprecation_mute');
172
    }
173
174
    protected function setGroups(array $groups)
175
    {
176
        $this->admin->setShowGroups($groups);
177
    }
178
179
    protected function getTabs()
180
    {
181
        // NEXT_MAJOR: Remove the argument "sonata_deprecation_mute" in the following call.
182
183
        return $this->admin->getShowTabs('sonata_deprecation_mute');
184
    }
185
186
    protected function setTabs(array $tabs)
187
    {
188
        $this->admin->setShowTabs($tabs);
189
    }
190
191
    protected function getName()
192
    {
193
        return 'show';
194
    }
195
}
196