Completed
Push — master ( 692aa1...25e5a7 )
by Paweł
60:22
created

CreateTenantCommand::createTenant()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
ccs 5
cts 5
cp 1
cc 1
eloc 9
nc 1
nop 5
crap 1
1
<?php
2
3
/*
4
 * This file is part of the Superdesk Web Publisher MultiTenancyBundle.
5
 *
6
 * Copyright 2016 Sourcefabric z.u. and contributors.
7
 *
8
 * For the full copyright and license information, please see the
9
 * AUTHORS and LICENSE files distributed with this source code.
10
 *
11
 * @copyright 2016 Sourcefabric z.ú
12
 * @license http://www.superdesk.org/license
13
 */
14
15
namespace SWP\Bundle\MultiTenancyBundle\Command;
16
17
use Doctrine\Common\Persistence\ObjectManager;
18
use SWP\Component\MultiTenancy\Model\OrganizationInterface;
19
use SWP\Component\MultiTenancy\Model\TenantInterface;
20
use SWP\Component\MultiTenancy\Repository\OrganizationRepositoryInterface;
21
use SWP\Component\MultiTenancy\Repository\TenantRepositoryInterface;
22
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
23
use Symfony\Component\Console\Input\InputArgument;
24
use Symfony\Component\Console\Input\InputInterface;
25
use Symfony\Component\Console\Input\InputOption;
26
use Symfony\Component\Console\Output\OutputInterface;
27
use Symfony\Component\Console\Question\Question;
28
29
/**
30
 * Class CreateTenantCommand.
31
 */
32
class CreateTenantCommand extends ContainerAwareCommand
33
{
34
    /**
35
     * @var array
36
     */
37
    protected $arguments = ['domain', 'subdomain', 'name', 'organization'];
38
39
    /**
40
     * {@inheritdoc}
41
     */
42 107
    protected function configure()
43
    {
44
        $this
45 107
            ->setName('swp:tenant:create')
46 107
            ->setDescription('Creates a new tenant.')
47 107
            ->setDefinition([
48 107
                new InputArgument($this->arguments[3], InputArgument::OPTIONAL, 'Organization code'),
49 107
                new InputArgument($this->arguments[0], InputArgument::OPTIONAL, 'Domain name'),
50 107
                new InputArgument($this->arguments[2], InputArgument::OPTIONAL, 'Tenant name'),
51 107
                new InputArgument($this->arguments[1], InputArgument::OPTIONAL, 'Subdomain name', null),
52 107
                new InputOption('disabled', null, InputOption::VALUE_NONE, 'Set the tenant as a disabled'),
53
                new InputOption('default', null, InputOption::VALUE_NONE, 'Creates the default tenant'),
54 107
            ])
55
            ->setHelp(
56 107
                <<<'EOT'
57
                The <info>%command.name%</info> command creates a new tenant.
58
EOT
59 107
            );
60
    }
61
62
    /**
63
     * {@inheritdoc}
64 11
     */
65
    protected function execute(InputInterface $input, OutputInterface $output)
66 11
    {
67 11
        $domain = $input->getArgument($this->arguments[0]);
68 11
        $subdomain = $input->getArgument($this->arguments[1]);
69 11
        $name = $input->getArgument($this->arguments[2]);
70 11
        $organizationCode = $input->getArgument($this->arguments[3]);
71
        $default = $input->getOption('default');
72 11
        $disabled = $input->getOption('disabled');
73 9
74 9
        if ($default) {
75 9
            $name = TenantInterface::DEFAULT_TENANT_NAME;
76 9
            $domain = $this->getContainer()->getParameter('domain');
77 9
            $organization = $this->getOrganizationRepository()->findOneByName(OrganizationInterface::DEFAULT_NAME);
78
            if (null === $organization) {
79
                throw new \InvalidArgumentException('Default organization doesn\'t exist!');
80 2
            }
81
        } else {
82 2
            $organization = $this->getOrganizationRepository()->findOneByCode($organizationCode);
83
84
            if (null === $organization) {
85
                throw new \InvalidArgumentException(sprintf('Organization with "%s" code doesn\'t exist!', $organizationCode));
86
            }
87 9
        }
88 9
89 6 View Code Duplication
        if (null !== $subdomain) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
90
            $tenant = $this->getTenantRepository()->findOneBySubdomainAndDomain($subdomain, $domain);
91
        } else {
92 3
            $tenant = $this->getTenantRepository()->findOneByDomain($domain);
93
        }
94 3
95 3
        if (null !== $tenant) {
96
            throw new \InvalidArgumentException(sprintf('Tenant with domain %s and subdomain "%s" already exists!', $domain, $subdomain));
97 3
        }
98
99 3
        $tenant = $this->createTenant($domain, $subdomain, $name, $disabled, $organization);
100
101 3
        $this->getObjectManager()->persist($tenant);
102 3
        $this->getObjectManager()->flush();
103
104
        $output->writeln(
105 3
            sprintf(
106
                'Tenant <info>%s</info> (code: <info>%s</info>) has been created and <info>%s</info>!',
107
                $name,
108
                $tenant->getCode(),
109
                $tenant->isEnabled() ? 'enabled' : 'disabled'
110 5
            )
111
        );
112 5
    }
113 5
114
    /**
115 5
     * {@inheritdoc}
116
     */
117
    protected function interact(InputInterface $input, OutputInterface $output)
118
    {
119
        foreach ($this->arguments as $value) {
120
            $this->askAndValidateInteract($input, $output, $value);
121
        }
122 5
    }
123
124 5
    /**
125 5
     * @param InputInterface  $input
126 2
     * @param OutputInterface $output
127 2
     * @param string          $name
128 2
     */
129 View Code Duplication
    protected function askAndValidateInteract(InputInterface $input, OutputInterface $output, $name)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
130
    {
131
        $default = $input->getOption('default');
132 2
        if (!$input->getArgument($name) && !$default && $name !== $this->arguments[1]) {
133 2
            $question = new Question(sprintf('<question>Please enter %s:</question>', $name));
134
            $question->setValidator(function ($argument) use ($name) {
135 2
                if (empty($argument)) {
136
                    throw new \RuntimeException(sprintf('The %s can not be empty', $name));
137 2
                }
138
139 2
                return $argument;
140
            });
141 5
142
            $question->setMaxAttempts(3);
143
144
            $argument = $this->getHelper('question')->ask($input, $output, $question);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method ask() does only exist in the following implementations of said interface: Sensio\Bundle\GeneratorB...d\Helper\QuestionHelper, Symfony\Component\Console\Helper\QuestionHelper, Symfony\Component\Consol...r\SymfonyQuestionHelper.

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...
145
146
            $input->setArgument($name, $argument);
147
        }
148
    }
149
150
    /**
151
     * Creates a new tenant.
152
     *
153 3
     * @param $subdomain
154
     * @param $name
155 3
     * @param $disabled
156
     * @param $organization
157 3
     *
158 3
     * @return TenantInterface
159 3
     */
160 3
    protected function createTenant($domain, $subdomain, $name, $disabled, $organization)
161 3
    {
162
        $tenantFactory = $this->getContainer()->get('swp.factory.tenant');
163 3
        /** @var TenantInterface $tenant */
164
        $tenant = $tenantFactory->create();
165
        $tenant->setSubdomain($subdomain);
166
        $tenant->setDomainName($domain);
167
        $tenant->setName($name);
168
        $tenant->setEnabled(!$disabled);
169 3
        $tenant->setOrganization($organization);
170
171 3
        return $tenant;
172
    }
173
174
    /**
175
     * @return ObjectManager
176
     */
177 9
    protected function getObjectManager()
178
    {
179 9
        return $this->getContainer()->get('swp.object_manager.tenant');
180
    }
181
182
    /**
183
     * @return TenantRepositoryInterface
184
     */
185 11
    protected function getTenantRepository()
186
    {
187 11
        return $this->getContainer()->get('swp.repository.tenant');
188
    }
189
190
    /**
191
     * @return OrganizationRepositoryInterface
192
     */
193
    protected function getOrganizationRepository()
194
    {
195
        return $this->getContainer()->get('swp.repository.organization');
196
    }
197
}
198