Completed
Push — 3.x ( ca65af...ac0550 )
by Grégoire
03:27
created

GenerateObjectAclCommand::__construct()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.8977
c 0
b 0
f 0
cc 6
nc 3
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\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
 * @final since sonata-project/admin-bundle 3.52
29
 *
30
 * @author Thomas Rabaix <[email protected]>
31
 */
32
class GenerateObjectAclCommand extends QuestionableCommand
33
{
34
    protected static $defaultName = 'sonata:admin:generate-object-acl';
35
36
    /**
37
     * @var string
38
     */
39
    protected $userEntityClass = '';
40
41
    /**
42
     * @var Pool
43
     */
44
    private $pool;
45
46
    /**
47
     * An array of object ACL manipulators indexed by their service ids.
48
     *
49
     * @var ObjectAclManipulatorInterface[]
50
     */
51
    private $aclObjectManipulators = [];
52
53
    /**
54
     * @var RegistryInterface|ManagerRegistry|null
55
     */
56
    private $registry;
57
58
    /**
59
     * @param RegistryInterface|ManagerRegistry|null $registry
60
     */
61
    public function __construct(Pool $pool, array $aclObjectManipulators, $registry = null)
62
    {
63
        $this->pool = $pool;
64
        $this->aclObjectManipulators = $aclObjectManipulators;
65
        if (null !== $registry && (!$registry instanceof RegistryInterface && !$registry instanceof ManagerRegistry)) {
66
            if (!$registry instanceof ManagerRegistry) {
67
                @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...
68
                    "Passing an object that doesn't implement %s as argument 3 to %s() is deprecated since sonata-project/admin-bundle 3.x.",
69
                    ManagerRegistry::class,
70
                    __METHOD__
71
                ), E_USER_DEPRECATED);
72
            }
73
74
            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...
75
                'Argument 3 passed to %s() must be either an instance of %s or %s, %s given.',
76
                __METHOD__,
77
                RegistryInterface::class,
78
                ManagerRegistry::class,
79
                \is_object($registry) ? \get_class($registry) : \gettype($registry)
80
            ));
81
        }
82
        $this->registry = $registry;
83
84
        parent::__construct();
85
    }
86
87
    public function configure()
88
    {
89
        $this
90
            ->setDescription('Install ACL for the objects of the Admin Classes.')
91
            ->addOption('object_owner', null, InputOption::VALUE_OPTIONAL, 'If set, the task will set the object owner for each admin.')
92
            ->addOption('user_entity', 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.')
93
            ->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.')
94
        ;
95
    }
96
97
    public function execute(InputInterface $input, OutputInterface $output)
98
    {
99
        $output->writeln('Welcome to the AdminBundle object ACL generator');
100
        $output->writeln([
101
                '',
102
                'This command helps you to generate ACL entities for the objects handled by the AdminBundle.',
103
                '',
104
                'If the step option is used, you will be asked if you want to generate the object ACL entities for each Admin.',
105
                'You must use the shortcut notation like <comment>AcmeDemoBundle:User</comment> if you want to set an object owner.',
106
                '',
107
        ]);
108
109
        if (!$this->registry) {
110
            $msg = sprintf('The command "%s" has a dependency on a non-existent service "doctrine".', static::$defaultName);
111
112
            throw new ServiceNotFoundException('doctrine', static::class, null, [], $msg);
113
        }
114
115
        if ($input->getOption('user_entity')) {
116
            try {
117
                $this->getUserEntityClass($input, $output);
118
            } catch (\Exception $e) {
119
                $output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
120
121
                return;
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;
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->getUserEntityClass($input, $output));
150
            }
151
            if (!$input->getOption('step') && $input->getOption('object_owner')) {
152
                $securityIdentity = new UserSecurityIdentity($input->getOption('object_owner'), $this->getUserEntityClass($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
172
    /**
173
     * @return string
174
     */
175
    protected function getUserEntityClass(InputInterface $input, OutputInterface $output)
176
    {
177
        if ('' === $this->userEntityClass) {
178
            if ($input->getOption('user_entity')) {
179
                list($userBundle, $userEntity) = Validators::validateEntityName($input->getOption('user_entity'));
180
            } else {
181
                list($userBundle, $userEntity) = $this->askAndValidate($input, $output, 'Please enter the User Entity shortcut name: ', '', 'Sonata\AdminBundle\Command\Validators::validateEntityName');
182
            }
183
            // Entity exists?
184
            if ($this->registry instanceof RegistryInterface) {
185
                $this->userEntityClass = $this->registry->getEntityNamespace($userBundle).'\\'.$userEntity;
186
            } else {
187
                $this->userEntityClass = $this->registry->getAliasNamespace($userBundle).'\\'.$userEntity;
188
            }
189
        }
190
191
        return $this->userEntityClass;
192
    }
193
}
194