Completed
Pull Request — master (#6210)
by Jordi Sala
02:51 queued 10s
created

GenerateObjectAclCommand::getUserEntityClass()   A

Complexity

Conditions 5
Paths 10

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 36
rs 9.0328
c 0
b 0
f 0
cc 5
nc 10
nop 2
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\Command;
15
16
use Doctrine\Common\Persistence\ManagerRegistry;
17
use Sonata\AdminBundle\Admin\AdminInterface;
18
use Sonata\AdminBundle\Admin\Pool;
19
use Sonata\AdminBundle\Util\ObjectAclManipulatorInterface;
20
use Symfony\Bridge\Doctrine\RegistryInterface;
21
use Symfony\Component\Console\Input\InputInterface;
22
use Symfony\Component\Console\Input\InputOption;
23
use Symfony\Component\Console\Output\OutputInterface;
24
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
25
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
26
27
/**
28
 * @author Thomas Rabaix <[email protected]>
29
 */
30
final class GenerateObjectAclCommand extends QuestionableCommand
31
{
32
    protected static $defaultName = 'sonata:admin:generate-object-acl';
33
34
    /**
35
     * @var string
36
     */
37
    private $userModelClass = '';
38
39
    /**
40
     * @var Pool
41
     */
42
    private $pool;
43
44
    /**
45
     * An array of object ACL manipulators indexed by their service ids.
46
     *
47
     * @var ObjectAclManipulatorInterface[]
48
     */
49
    private $aclObjectManipulators = [];
50
51
    /**
52
     * @var RegistryInterface|ManagerRegistry|null
53
     */
54
    private $registry;
55
56
    /**
57
     * @param RegistryInterface|ManagerRegistry|null $registry
58
     */
59
    public function __construct(Pool $pool, array $aclObjectManipulators, $registry = null)
60
    {
61
        $this->pool = $pool;
62
        $this->aclObjectManipulators = $aclObjectManipulators;
63
        if (null !== $registry && (!$registry instanceof RegistryInterface && !$registry instanceof ManagerRegistry)) {
64
            if (!$registry instanceof ManagerRegistry) {
65
                @trigger_error(sprintf(
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...
66
                    'Passing an object that doesn\'t implement %s as argument 3 to %s() is deprecated since'
67
                    .' sonata-project/admin-bundle 3.56.',
68
                    ManagerRegistry::class,
69
                    __METHOD__
70
                ), E_USER_DEPRECATED);
71
            }
72
73
            throw new \TypeError(sprintf(
0 ignored issues
show
Unused Code introduced by
The call to TypeError::__construct() has too many arguments starting with sprintf('Argument 3 pass... : \gettype($registry)).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
74
                'Argument 3 passed to %s() must be either an instance of %s or %s, %s given.',
75
                __METHOD__,
76
                RegistryInterface::class,
77
                ManagerRegistry::class,
78
                \is_object($registry) ? \get_class($registry) : \gettype($registry)
79
            ));
80
        }
81
        $this->registry = $registry;
82
83
        parent::__construct();
84
    }
85
86
    public function configure(): void
87
    {
88
        $this
89
            ->setDescription('Install ACL for the objects of the Admin Classes.')
90
            ->addOption('object_owner', null, InputOption::VALUE_OPTIONAL, 'If set, the task will set the object owner for each admin.')
91
            ->addOption('user_model', null, InputOption::VALUE_OPTIONAL, 'Shortcut notation like <comment>AcmeDemoBundle:User</comment>. If not set, it will be asked the first time an object owner is set.')
92
            ->addOption('step', null, InputOption::VALUE_NONE, 'If set, the task will ask for each admin if the ACLs need to be generated and what object owner to set, if any.')
93
        ;
94
    }
95
96
    public function execute(InputInterface $input, OutputInterface $output): int
97
    {
98
        $output->writeln('Welcome to the AdminBundle object ACL generator');
99
        $output->writeln([
0 ignored issues
show
Documentation introduced by
array('', 'This command ... an object owner.', '') is of type array<integer,string,{"0..."string","5":"string"}>, but the function expects a string|object<Symfony\Co...onsole\Output\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
100
            '',
101
            'This command helps you to generate ACL entities for the objects handled by the AdminBundle.',
102
            '',
103
            'If the step option is used, you will be asked if you want to generate the object ACL entities for each Admin.',
104
            'You must use the shortcut notation like <comment>AcmeDemoBundle:User</comment> if you want to set an object owner.',
105
            '',
106
        ]);
107
108
        if (!$this->registry) {
109
            throw new ServiceNotFoundException('doctrine', static::class, null, [], sprintf(
110
                'The command "%s" has a dependency on a non-existent service "doctrine".',
111
                static::$defaultName
112
            ));
113
        }
114
115
        if ($input->getOption('user_model')) {
116
            try {
117
                $this->getUserModelClass($input, $output);
118
            } catch (\Exception $e) {
119
                $output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
120
121
                return 1;
122
            }
123
        }
124
125
        if (!$this->aclObjectManipulators) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->aclObjectManipulators of type Sonata\AdminBundle\Util\...lManipulatorInterface[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
126
            $output->writeln('No manipulators are implemented : <info>ignoring</info>');
127
128
            return 1;
129
        }
130
131
        foreach ($this->pool->getAdminServiceIds() as $id) {
132
            try {
133
                $admin = $this->pool->getInstance($id);
134
            } catch (\Exception $e) {
135
                $output->writeln('<error>Warning : The admin class cannot be initiated from the command line</error>');
136
                $output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
137
138
                continue;
139
            }
140
141
            if ($input->getOption('step') && !$this->askConfirmation($input, $output, sprintf("<question>Generate ACLs for the object instances handled by \"%s\"?</question>\n", $id), 'no')) {
142
                continue;
143
            }
144
145
            $securityIdentity = null;
146
            if ($input->getOption('step') && $this->askConfirmation($input, $output, "<question>Set an object owner?</question>\n", 'no')) {
147
                $username = $this->askAndValidate($input, $output, 'Please enter the username: ', '', 'Sonata\AdminBundle\Command\Validators::validateUsername');
148
149
                $securityIdentity = new UserSecurityIdentity($username, $this->getUserModelClass($input, $output));
150
            }
151
            if (!$input->getOption('step') && $input->getOption('object_owner')) {
152
                $securityIdentity = new UserSecurityIdentity($input->getOption('object_owner'), $this->getUserModelClass($input, $output));
153
            }
154
155
            $manipulatorId = sprintf('sonata.admin.manipulator.acl.object.%s', $admin->getManagerType());
156
            if (!$manipulator = $this->aclObjectManipulators[$manipulatorId] ?? null) {
157
                $output->writeln('Admin class is using a manager type that has no manipulator implemented : <info>ignoring</info>');
158
159
                continue;
160
            }
161
            if (!$manipulator instanceof ObjectAclManipulatorInterface) {
162
                $output->writeln(sprintf('The interface "ObjectAclManipulatorInterface" is not implemented for %s: <info>ignoring</info>', \get_class($manipulator)));
163
164
                continue;
165
            }
166
167
            \assert($admin instanceof AdminInterface);
168
            $manipulator->batchConfigureAcls($output, $admin, $securityIdentity);
169
        }
170
171
        return 0;
172
    }
173
174
    protected function initialize(InputInterface $input, OutputInterface $output)
175
    {
176
        parent::initialize($input, $output);
177
    }
178
179
    private function getUserModelClass(InputInterface $input, OutputInterface $output): string
180
    {
181
        if ('' === $this->userModelClass) {
182
            if ($input->getOption('user_model')) {
183
                [$userBundle, $userModel] = Validators::validateEntityName($input->getOption('user_model'));
0 ignored issues
show
Bug introduced by
The variable $userBundle 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 $userModel 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...
184
            } else {
185
                [$userBundle, $userModel] = $this->askAndValidate(
186
                    $input,
187
                    $output,
188
                    'Please enter the User Entity shortcut name: ',
189
                    '',
190
                    'Sonata\AdminBundle\Command\Validators::validateEntityName'
191
                );
192
            }
193
194
            // Entity exists?
195
            if ($this->registry instanceof RegistryInterface) {
196
                $namespace = $this->registry->getEntityNamespace($userBundle);
197
            } else {
198
                $namespace = $this->registry->getAliasNamespace($userBundle);
199
            }
200
201
            $this->userModelClass = sprintf('%s\%s', $namespace, $userModel);
202
        }
203
204
        return $this->userModelClass;
205
    }
206
}
207