Completed
Pull Request — master (#6210)
by Jordi Sala
02:52
created

GenerateObjectAclCommand::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
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\Component\Console\Input\InputInterface;
21
use Symfony\Component\Console\Input\InputOption;
22
use Symfony\Component\Console\Output\OutputInterface;
23
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
24
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
25
26
/**
27
 * @author Thomas Rabaix <[email protected]>
28
 */
29
final class GenerateObjectAclCommand extends QuestionableCommand
30
{
31
    protected static $defaultName = 'sonata:admin:generate-object-acl';
32
33
    /**
34
     * @var string
35
     */
36
    private $userModelClass = '';
37
38
    /**
39
     * @var Pool
40
     */
41
    private $pool;
42
43
    /**
44
     * An array of object ACL manipulators indexed by their service ids.
45
     *
46
     * @var ObjectAclManipulatorInterface[]
47
     */
48
    private $aclObjectManipulators = [];
49
50
    /**
51
     * @var ManagerRegistry|null
52
     */
53
    private $registry;
54
55
    /**
56
     * @param ManagerRegistry|null $registry
57
     */
58
    public function __construct(Pool $pool, array $aclObjectManipulators, ?ManagerRegistry $registry = null)
59
    {
60
        $this->pool = $pool;
61
        $this->aclObjectManipulators = $aclObjectManipulators;
62
        $this->registry = $registry;
63
64
        parent::__construct();
65
    }
66
67
    public function configure(): void
68
    {
69
        $this
70
            ->setDescription('Install ACL for the objects of the Admin Classes.')
71
            ->addOption('object_owner', null, InputOption::VALUE_OPTIONAL, 'If set, the task will set the object owner for each admin.')
72
            ->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.')
73
            ->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.')
74
        ;
75
    }
76
77
    public function execute(InputInterface $input, OutputInterface $output): int
78
    {
79
        $output->writeln('Welcome to the AdminBundle object ACL generator');
80
        $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...
81
            '',
82
            'This command helps you to generate ACL entities for the objects handled by the AdminBundle.',
83
            '',
84
            'If the step option is used, you will be asked if you want to generate the object ACL entities for each Admin.',
85
            'You must use the shortcut notation like <comment>AcmeDemoBundle:User</comment> if you want to set an object owner.',
86
            '',
87
        ]);
88
89
        if (!$this->registry) {
90
            throw new ServiceNotFoundException('doctrine', static::class, null, [], sprintf(
91
                'The command "%s" has a dependency on a non-existent service "doctrine".',
92
                static::$defaultName
93
            ));
94
        }
95
96
        if ($input->getOption('user_model')) {
97
            try {
98
                $this->getUserModelClass($input, $output);
99
            } catch (\Exception $e) {
100
                $output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
101
102
                return 1;
103
            }
104
        }
105
106
        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...
107
            $output->writeln('No manipulators are implemented : <info>ignoring</info>');
108
109
            return 1;
110
        }
111
112
        foreach ($this->pool->getAdminServiceIds() as $id) {
113
            try {
114
                $admin = $this->pool->getInstance($id);
115
            } catch (\Exception $e) {
116
                $output->writeln('<error>Warning : The admin class cannot be initiated from the command line</error>');
117
                $output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
118
119
                continue;
120
            }
121
122
            if ($input->getOption('step') && !$this->askConfirmation($input, $output, sprintf("<question>Generate ACLs for the object instances handled by \"%s\"?</question>\n", $id), 'no')) {
123
                continue;
124
            }
125
126
            $securityIdentity = null;
127
            if ($input->getOption('step') && $this->askConfirmation($input, $output, "<question>Set an object owner?</question>\n", 'no')) {
128
                $username = $this->askAndValidate($input, $output, 'Please enter the username: ', '', 'Sonata\AdminBundle\Command\Validators::validateUsername');
129
130
                $securityIdentity = new UserSecurityIdentity($username, $this->getUserModelClass($input, $output));
131
            }
132
            if (!$input->getOption('step') && $input->getOption('object_owner')) {
133
                $securityIdentity = new UserSecurityIdentity($input->getOption('object_owner'), $this->getUserModelClass($input, $output));
134
            }
135
136
            $manipulatorId = sprintf('sonata.admin.manipulator.acl.object.%s', $admin->getManagerType());
137
            if (!$manipulator = $this->aclObjectManipulators[$manipulatorId] ?? null) {
138
                $output->writeln('Admin class is using a manager type that has no manipulator implemented : <info>ignoring</info>');
139
140
                continue;
141
            }
142
            if (!$manipulator instanceof ObjectAclManipulatorInterface) {
143
                $output->writeln(sprintf('The interface "ObjectAclManipulatorInterface" is not implemented for %s: <info>ignoring</info>', \get_class($manipulator)));
144
145
                continue;
146
            }
147
148
            \assert($admin instanceof AdminInterface);
149
            $manipulator->batchConfigureAcls($output, $admin, $securityIdentity);
150
        }
151
152
        return 0;
153
    }
154
155
    protected function initialize(InputInterface $input, OutputInterface $output)
156
    {
157
        parent::initialize($input, $output);
158
    }
159
160
    private function getUserModelClass(InputInterface $input, OutputInterface $output): string
161
    {
162
        if ('' === $this->userModelClass) {
163
            if ($input->getOption('user_model')) {
164
                [$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...
165
            } else {
166
                [$userBundle, $userModel] = $this->askAndValidate(
167
                    $input,
168
                    $output,
169
                    'Please enter the User Entity shortcut name: ',
170
                    '',
171
                    'Sonata\AdminBundle\Command\Validators::validateEntityName'
172
                );
173
            }
174
175
            $namespace = $this->registry->getAliasNamespace($userBundle);
176
177
            $this->userModelClass = sprintf('%s\%s', $namespace, $userModel);
178
        }
179
180
        return $this->userModelClass;
181
    }
182
}
183