InitCommand::initialize()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 2
1
<?php
2
/**
3
 * For the full copyright and license information, please view the LICENSE.md
4
 * file that was distributed with this source code.
5
 */
6
7
namespace Notamedia\ConsoleJedi\Application\Command;
8
9
use Symfony\Component\Console\Helper\QuestionHelper;
10
use Symfony\Component\Console\Input\InputInterface;
11
use Symfony\Component\Console\Input\InputOption;
12
use Symfony\Component\Console\Output\OutputInterface;
13
use Symfony\Component\Console\Question\ConfirmationQuestion;
14
use Symfony\Component\Console\Question\Question;
15
use Symfony\Component\Filesystem\Filesystem;
16
17
/**
18
 * Command application initialization.
19
 *
20
 * @author Nik Samokhvalov <[email protected]>
21
 */
22
class InitCommand extends Command
23
{
24
    const COMPLETED_LOGO = '
25
                      ____
26
                 _.\' :  `._
27
             .-.\'`.  ;   .\'`.-.
28
    __      / : ___\ ;  /___ ; \      __
29
  ,\'_ ""--.:__;".-.";: :".-.":__;.--"" _`,
30
  :\' `.t""--.. \'<@.`;_  \',@>` ..--""j.\' `;
31
       `:-.._J \'-.-\'L__ `-- \' L_..-;\'
32
         "-.__ ;  .-"  "-.  : __.-"
33
             L \' /.------.\ \' J
34
              "-.   "--"   .-"
35
             __.l"-:_JL_;-";.__
36
          .-j/\'.;  ;""""  / .\'\"-.
37
        .\' /:`. "-.:     .-" .\';  `.
38
     .-"  / ;  "-. "-..-" .-"  :    "-.
39
  .+"-.  : :      "-.__.-"      ;-._   \
40
  ; \  `.; ;                    : : "+. ;
41
  :  ;   ; ;                    : ;  : \:
42
 : `."-; ;  ;                  :  ;   ,/;
43
  ;    -: ;  :                ;  : .-"\'  :
44
  :\     \  : ;             : \.-"      :
45
   ;`.    \  ; :            ;.\'_..--  / ;
46
   :  "-.  "-:  ;          :/."      .\'  :
47
     \       .-`.\        /t-""  ":-+.   :
48
      `.  .-"    `l    __/ /`. :  ; ; \  ;
49
        \   .-" .-"-.-"  .\' .\'j \  /   ;/
50
         \ / .-"   /.     .\'.\' ;_:\'    ;
51
          :-""-.`./-.\'     /    `.___.\'
52
                \ `t  ._  /  bug :F_P:
53
                 "-.t-._:\'
54
                 
55
          Installation is completed.
56
          May the Force be with you.
57
     ';
58
59
    /**
60
     * @var string Path to directory with templates of the application files.
61
     */
62
    protected $tmplDir;
63
    /**
64
     * @var string Default name of directory with environments settings.
65
     */
66
    protected $envDir = 'environments';
67
    /**
68
     * @var QuestionHelper $question
69
     */
70
    protected $questionHelper;
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    protected function configure()
76
    {
77
        $this->setName('init')
78
            ->setDescription('Initialize the Console Jedi')
79
            ->addOption('force', 'f', InputOption::VALUE_NONE, 'Override an existing files');
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85
    protected function initialize(InputInterface $input, OutputInterface $output)
86
    {
87
        $this->tmplDir = __DIR__ . '/../../../tmpl';
88
        $this->questionHelper = $this->getHelper('question');
89
90
        parent::initialize($input, $output);
91
    }
92
93
    /**
94
     * {@inheritdoc}
95
     */
96
    protected function execute(InputInterface $input, OutputInterface $output)
97
    {
98
        $output->writeln('<info>Install Console Jedi application</info>');
99
100
        $this->createEnvironmentsDir($input, $output);
101
        $this->createConfiguration($input, $output);
102
103
        $output->writeln('<info>' . static::COMPLETED_LOGO . '</info>');
104
    }
105
106
    /**
107
     * Creates directory with environments settings.
108
     *
109
     * @param InputInterface $input
110
     * @param OutputInterface $output
111
     */
112
    protected function createEnvironmentsDir(InputInterface $input, OutputInterface $output)
113
    {
114
        $targetDir = getcwd() . '/' . $this->envDir;
115
        $tmplDir = $this->tmplDir . '/environments';
116
117
        $output->writeln('  - Environment settings');
118
119 View Code Duplication
        if (file_exists($targetDir)) {
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...
120
            $question = new ConfirmationQuestion(
121
                '    <error>Directory ' . $targetDir . ' already exists</error>' . PHP_EOL
122
                . '    <info>Overwrite? [Y/n]</info> ',
123
                true,
124
                '/^(y|j)/i'
125
            );
126
127
            if (!$this->questionHelper->ask($input, $output, $question)) {
128
                return;
129
            }
130
        }
131
132
        $fs = new Filesystem();
133
        $tmplIterator = new \RecursiveDirectoryIterator($tmplDir, \RecursiveDirectoryIterator::SKIP_DOTS);
134
        $iterator = new \RecursiveIteratorIterator($tmplIterator, \RecursiveIteratorIterator::SELF_FIRST);
135
136
        foreach ($iterator as $item) {
137
            $itemPath = $targetDir . '/' . $iterator->getSubPathName();
138
139
            if ($item->isDir()) {
140
                $fs->mkdir($itemPath);
141
            } else {
142
                $fs->copy($item, $itemPath, true);
143
            }
144
        }
145
146
        $output->writeln('    Created directory settings of environments: <comment>' . $targetDir . '</comment>');
147
    }
148
149
    /**
150
     * Creates configuration file of application.
151
     *
152
     * @param InputInterface $input
153
     * @param OutputInterface $output
154
     */
155
    protected function createConfiguration(InputInterface $input, OutputInterface $output)
156
    {
157
        $path = $this->getApplication()->getRoot() . '/.jedi.php';
158
159
        $output->writeln('  - Configuration');
160
161 View Code Duplication
        if (file_exists($path)) {
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...
162
            $question = new ConfirmationQuestion(
163
                '    <error>Configuration file ' . $path . ' already exists</error>' . PHP_EOL
164
                . '    <info>Overwrite? [Y/n]</info> ',
165
                true,
166
                '/^(y|j)/i'
167
            );
168
169
            if (!$this->questionHelper->ask($input, $output, $question)) {
170
                return;
171
            }
172
        }
173
174
        $fs = new Filesystem();
175
176
        $question = new Question('    <info>Enter path to web directory relative to '
177
            . $this->getApplication()->getRoot() . ':</info> ' . PHP_EOL
178
            . '    (or do not specify if you are already in the web directory)' . PHP_EOL);
179
180
        $question->setValidator(function ($answer) use ($fs) {
181
            $path = $answer;
182
183
            if ($answer === null) {
184
                $path = $this->getApplication()->getRoot();
185
            } elseif (!$fs->isAbsolutePath($answer)) {
186
                $path = $this->getApplication()->getRoot() . '/' . $answer;
187
            }
188
189
            if (!is_dir($path)) {
190
                throw new \RuntimeException('Directory "' . $path . '" is missing');
191
            }
192
193
            return $answer;
194
        });
195
196
        $webDir = $this->questionHelper->ask($input, $output, $question);
197
198
        $content = file_get_contents($this->tmplDir . '/.jedi.php');
199
        $content = str_replace(
200
            ['%web-dir%', '%env-dir%'],
201
            [addslashes($webDir), addslashes($this->envDir)],
202
            $content
203
        );
204
        $fs->dumpFile($path, $content);
205
206
        $output->writeln('    Created configuration file of application <comment>' . $path . '</comment>');
207
    }
208
}