CreateOrganizationCommand   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 127
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 8

Importance

Changes 0
Metric Value
wmc 15
lcom 2
cbo 8
dl 0
loc 127
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 16 1
A execute() 0 23 3
A sendOutput() 0 11 2
A interact() 0 7 2
A askAndValidateInteract() 0 19 3
A createOrganization() 0 16 2
A getObjectManager() 0 4 1
A getOrganizationRepository() 0 4 1
1
<?php
2
3
/*
4
 * This file is part of the Superdesk Web Publisher MultiTenancyBundle.
5
 *
6
 * Copyright 2016 Sourcefabric z.ú. 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\Repository\OrganizationRepositoryInterface;
20
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
21
use Symfony\Component\Console\Input\InputArgument;
22
use Symfony\Component\Console\Input\InputInterface;
23
use Symfony\Component\Console\Input\InputOption;
24
use Symfony\Component\Console\Output\OutputInterface;
25
use Symfony\Component\Console\Question\Question;
26
27
/**
28
 * Class CreateOrganizationCommand.
29
 */
30
class CreateOrganizationCommand extends ContainerAwareCommand
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Bundle\Framework...d\ContainerAwareCommand has been deprecated with message: since Symfony 4.2, use {@see Command} instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
31
{
32
    protected static $defaultName = 'swp:organization:create';
33
34
    /**
35
     * {@inheritdoc}
36
     */
37
    protected function configure()
38
    {
39
        $this
40
            ->setName('swp:organization:create')
41
            ->setDescription('Creates a new organization.')
42
            ->setDefinition([
43
                new InputArgument('name', InputArgument::OPTIONAL, 'Organization name'),
44
                new InputOption('disabled', null, InputOption::VALUE_NONE, 'Set the organization as a disabled'),
45
                new InputOption('default', null, InputOption::VALUE_NONE, 'Creates the default organization'),
46
            ])
47
            ->setHelp(
48
                <<<'EOT'
49
                The <info>%command.name%</info> command creates a new organization.
50
EOT
51
            );
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57
    protected function execute(InputInterface $input, OutputInterface $output)
58
    {
59
        $name = $input->getArgument('name');
60
        $default = $input->getOption('default');
61
        $code = null;
62
        if ($default) {
63
            $name = OrganizationInterface::DEFAULT_NAME;
64
            $code = OrganizationInterface::DEFAULT_CODE;
65
        }
66
67
        $organization = $this->getOrganizationRepository()->findOneByName($name);
68
69
        if (null !== $organization) {
70
            throw new \InvalidArgumentException(sprintf('"%s" organization already exists!', $name));
71
        }
72
73
        $organization = $this->createOrganization($name, $input, $code);
74
75
        $this->getObjectManager()->persist($organization);
76
        $this->getObjectManager()->flush();
77
78
        $this->sendOutput($output, $organization);
79
    }
80
81
    protected function sendOutput(OutputInterface $output, OrganizationInterface $organization)
82
    {
83
        $output->writeln(
84
            sprintf(
85
                'Organization <info>%s</info> (code: <info>%s</info>) has been created and <info>%s</info>!',
86
                $organization->getName(),
87
                $organization->getCode(),
88
                $organization->isEnabled() ? 'enabled' : 'disabled'
89
            )
90
        );
91
    }
92
93
    protected function interact(InputInterface $input, OutputInterface $output)
94
    {
95
        $default = $input->getOption('default');
96
        if (!$default) {
97
            $this->askAndValidateInteract($input, $output, 'name');
98
        }
99
    }
100
101
    /**
102
     * @param string $name
103
     */
104
    protected function askAndValidateInteract(InputInterface $input, OutputInterface $output, $name)
105
    {
106
        if (!$input->getArgument($name)) {
107
            $question = new Question(sprintf('<question>Please enter %s:</question>', $name));
108
            $question->setValidator(function ($argument) use ($name) {
109
                if (empty($argument)) {
110
                    throw new \RuntimeException(sprintf('The %s can not be empty', $name));
111
                }
112
113
                return $argument;
114
            });
115
116
            $question->setMaxAttempts(3);
117
118
            $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: 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...
119
120
            $input->setArgument($name, $argument);
121
        }
122
    }
123
124
    protected function createOrganization(string $name, InputInterface $input, string $code = null): OrganizationInterface
125
    {
126
        $organizationFactory = $this->getContainer()->get('swp.factory.organization');
127
        /* @var OrganizationInterface $organization */
128
        if (null !== $code) {
129
            $organization = $organizationFactory->create();
130
            $organization->setCode($code);
131
        } else {
132
            $organization = $organizationFactory->createWithCode();
133
        }
134
135
        $organization->setName($name);
136
        $organization->setEnabled(!$input->getOption('disabled'));
137
138
        return $organization;
139
    }
140
141
    /**
142
     * @return ObjectManager
143
     */
144
    protected function getObjectManager()
145
    {
146
        return $this->getContainer()->get('swp.object_manager.organization');
147
    }
148
149
    /**
150
     * @return OrganizationRepositoryInterface
151
     */
152
    protected function getOrganizationRepository()
153
    {
154
        return $this->getContainer()->get('swp.repository.organization');
155
    }
156
}
157