Completed
Push — symfony-console ( f34f7f...439ffc )
by Arnaud
03:15
created

NewPage::execute()   C

Complexity

Conditions 10
Paths 114

Size

Total Lines 56

Duplication

Lines 7
Ratio 12.5 %

Importance

Changes 0
Metric Value
dl 7
loc 56
rs 6.9999
c 0
b 0
f 0
cc 10
nc 114
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/*
3
 * Copyright (c) Arnaud Ligny <[email protected]>
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Cecil\Command;
10
11
use Cecil\Util\Plateform;
12
use Symfony\Component\Console\Input\InputArgument;
13
use Symfony\Component\Console\Input\InputDefinition;
14
use Symfony\Component\Console\Input\InputInterface;
15
use Symfony\Component\Console\Input\InputOption;
16
use Symfony\Component\Console\Output\OutputInterface;
17
use Symfony\Component\Console\Question\ConfirmationQuestion;
18
use Symfony\Component\Process\Process;
19
20
class NewPage extends Command
21
{
22
    /**
23
     * {@inheritdoc}
24
     */
25
    protected function configure()
26
    {
27
        $this
28
            ->setName('new:page')
29
            ->setDescription('Create a new page')
30
            ->setDefinition(
31
                new InputDefinition([
32
                    new InputArgument('name', InputArgument::REQUIRED, 'New page name'),
33
                    new InputArgument('path', InputArgument::OPTIONAL, 'Use the given path as working directory'),
34
                    new InputOption('force', 'f', InputOption::VALUE_NONE, 'Override the file if already exist'),
35
                    new InputOption('open', 'o', InputOption::VALUE_NONE, 'Open editor automatically'),
36
                ])
37
            )
38
            ->setHelp('Create a new page file (with a default title and the current date).');
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    protected function execute(InputInterface $input, OutputInterface $output)
45
    {
46
        $name = (string) $input->getArgument('name');
47
        $force = $input->getOption('force');
48
        $open = $input->getOption('open');
49
50
        try {
51
            // file name (without extension)
52
            if (false !== $extPos = strripos($name, '.md')) {
53
                $name = substr($name, 0, $extPos);
54
            }
55
            if (null === $name) {
56
                throw new \Exception('New page\'s name can\'t be empty');
57
            }
58
59
            // path
60
            $fileRelativePath = $this->getBuilder($output)->getConfig()->get('content.dir').'/'.$name.'.md';
61
            $filePath = $this->getPath().'/'.$fileRelativePath;
62
63
            // file already exists?
64 View Code Duplication
            if ($this->fs->exists($filePath) && !$force) {
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...
65
                $helper = $this->getHelper('question');
66
                $question = new ConfirmationQuestion(sprintf(
67
                    'This page already exists. Do you want to override it? [y/n]',
68
                    $this->getpath()),
69
                    false
70
                );
71
                if (!$helper->ask($input, $output, $question)) {
72
                    return;
73
                }
74
            }
75
76
            // create new file
77
            $title = $name;
78
            if (false !== strrchr($name, '/')) {
79
                $title = substr(strrchr($name, '/'), 1);
80
            }
81
            $date = date('Y-m-d');
82
            $fileContent = str_replace(['%title%', '%date%'], [$title, $date], $this->findModel($name));
83
            $this->fs->dumpFile($filePath, $fileContent);
84
85
            $output->writeln(sprintf('File "%s" created.', $fileRelativePath));
86
87
            // open editor?
88
            if ($open) {
89
                if (!$this->hasEditor()) {
90
                    $output->writeln('<comment>No editor configured.</comment>');
91
                }
92
                $this->openEditor($filePath);
93
            }
94
        } catch (\Exception $e) {
95
            throw new \Exception(sprintf($e->getMessage()));
96
        }
97
98
        return 0;
99
    }
100
101
    /**
102
     * Find the page model and return its content.
103
     *
104
     * @param string $name
105
     *
106
     * @return string
107
     */
108
    protected function findModel(string $name): string
109
    {
110
        $section = strstr($name, '/', true);
111
        if ($section && file_exists($model = sprintf('%s/models/%s.md', $this->getPath(), $section))) {
112
            return file_get_contents($model);
113
        }
114
        if (file_exists($model = sprintf('%s/models/default.md', $this->getPath()))) {
115
            return file_get_contents($model);
116
        }
117
118
        return <<<'EOT'
119
---
120
title: '%title%'
121
date: '%date%'
122
draft: true
123
---
124
125
_[Your content here]_
126
EOT;
127
    }
128
129
    /**
130
     * Editor is configured?
131
     *
132
     * @return bool
133
     */
134
    protected function hasEditor(): bool
135
    {
136
        if ($this->builder->getConfig()->get('editor')) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return (bool) $this->bui...onfig()->get('editor');.
Loading history...
137
            return true;
138
        }
139
140
        return false;
141
    }
142
143
    /**
144
     * Open new file in editor (if configured).
145
     *
146
     * @param string $filePath
147
     *
148
     * @return void
149
     */
150
    protected function openEditor(string $filePath)
151
    {
152
        if ($editor = $this->builder->getConfig()->get('editor')) {
153
            switch ($editor) {
154
                case 'typora':
155
                    if (Plateform::getOS() == Plateform::OS_OSX) {
156
                        $command = sprintf('open -a typora "%s"', $filePath);
157
                    }
158
                    break;
159
                default:
160
                    $command = sprintf('%s "%s"', $editor, $filePath);
161
                    break;
162
            }
163
            $process = new Process($command);
0 ignored issues
show
Bug introduced by
The variable $command does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Documentation introduced by
$command is of type string, but the function expects a array.

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...
164
            $process->run();
165
            if (!$process->isSuccessful()) {
166
                throw new \Exception(sprintf('Can\'t run "%s".', $command));
167
            }
168
        }
169
    }
170
}
171