Completed
Push — symfony-console ( 505007...6e7652 )
by Arnaud
02:41 queued 10s
created

NewPage::execute()   B

Complexity

Conditions 9
Paths 112

Size

Total Lines 48

Duplication

Lines 7
Ratio 14.58 %

Importance

Changes 0
Metric Value
dl 7
loc 48
rs 7.4989
c 0
b 0
f 0
cc 9
nc 112
nop 2
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, 'If specified, 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
        $this->name = $input->getArgument('name');
0 ignored issues
show
Bug introduced by
The property name cannot be accessed from this context as it is declared private in class Symfony\Component\Console\Command\Command.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
47
        $this->force = $input->getOption('force');
0 ignored issues
show
Bug introduced by
The property force does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
48
        $this->open = $input->getOption('open');
0 ignored issues
show
Bug introduced by
The property open does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
49
50
        try {
51
            // file name (without extension)
52
            if (false !== $extPos = strripos($this->name, '.md')) {
0 ignored issues
show
Bug introduced by
The property name cannot be accessed from this context as it is declared private in class Symfony\Component\Console\Command\Command.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
53
                $this->name = substr($this->name, 0, $extPos);
0 ignored issues
show
Bug introduced by
The property name cannot be accessed from this context as it is declared private in class Symfony\Component\Console\Command\Command.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
54
            }
55
            // path
56
            $fileRelativePath = $this->getBuilder($output)->getConfig()->get('content.dir').'/'.$this->name.'.md';
0 ignored issues
show
Bug introduced by
The property name cannot be accessed from this context as it is declared private in class Symfony\Component\Console\Command\Command.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
57
            $filePath = $this->getPath().'/'.$fileRelativePath;
58
59
            // file already exists?
60 View Code Duplication
            if ($this->fs->exists($filePath) && !$this->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...
61
                $helper = $this->getHelper('question');
62
                $question = new ConfirmationQuestion(sprintf('This page already exists. Do you want to override it? [y/n]', $this->getpath()), false);
63
                if (!$helper->ask($input, $output, $question)) {
64
                    return;
65
                }
66
            }
67
68
            // create new file
69
            $title = $this->name;
0 ignored issues
show
Bug introduced by
The property name cannot be accessed from this context as it is declared private in class Symfony\Component\Console\Command\Command.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
70
            if (false !== strrchr($this->name, '/')) {
0 ignored issues
show
Bug introduced by
The property name cannot be accessed from this context as it is declared private in class Symfony\Component\Console\Command\Command.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
71
                $title = substr(strrchr($this->name, '/'), 1);
0 ignored issues
show
Bug introduced by
The property name cannot be accessed from this context as it is declared private in class Symfony\Component\Console\Command\Command.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
72
            }
73
            $date = date('Y-m-d');
74
            $fileContent = str_replace(['%title%', '%date%'], [$title, $date], $this->findModel($this->name));
0 ignored issues
show
Bug introduced by
The property name cannot be accessed from this context as it is declared private in class Symfony\Component\Console\Command\Command.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
Bug introduced by
It seems like $this->name can also be of type array<integer,string> or null; however, Cecil\Command\NewPage::findModel() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
75
            $this->fs->dumpFile($filePath, $fileContent);
76
77
            $output->writeln(sprintf('File "%s" created.', $fileRelativePath));
78
79
            // open editor?
80
            if ($this->open) {
81
                if (!$this->hasEditor()) {
82
                    $output->writeln('<comment>No editor configured.</comment>');
83
                }
84
                $this->openEditor($filePath);
85
            }
86
        } catch (\Exception $e) {
87
            throw new \Exception(sprintf($e->getMessage()));
88
        }
89
90
        return 0;
91
    }
92
93
    /**
94
     * Find the page model and return its content.
95
     *
96
     * @param string $name
97
     *
98
     * @return string
99
     */
100
    protected function findModel($name)
0 ignored issues
show
Unused Code introduced by
The parameter $name is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
101
    {
102
        $section = strstr($this->name, '/', true);
0 ignored issues
show
Bug introduced by
The property name cannot be accessed from this context as it is declared private in class Symfony\Component\Console\Command\Command.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
103
        if ($section && file_exists($model = sprintf('%s/models/%s.md', $this->getPath(), $section))) {
104
            return file_get_contents($model);
105
        }
106
        if (file_exists($model = sprintf('%s/models/default.md', $this->getPath()))) {
107
            return file_get_contents($model);
108
        }
109
110
        return <<<'EOT'
111
---
112
title: '%title%'
113
date: '%date%'
114
draft: true
115
---
116
117
_[Your content here]_
118
EOT;
119
    }
120
121
    /**
122
     * Editor is configured?
123
     *
124
     * @return bool
125
     */
126
    protected function hasEditor()
127
    {
128
        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...
129
            return true;
130
        }
131
132
        return false;
133
    }
134
135
    /**
136
     * Open new file in editor (if configured).
137
     *
138
     * @param string $filePath
139
     *
140
     * @return void
141
     */
142
    protected function openEditor($filePath)
143
    {
144
        if ($editor = $this->builder->getConfig()->get('editor')) {
145
            switch ($editor) {
146
                case 'typora':
147
                    if (Plateform::getOS() == Plateform::OS_OSX) {
148
                        $command = sprintf('open -a typora "%s"', $filePath);
149
                    }
150
                    break;
151
                default:
152
                    $command = sprintf('%s "%s"', $editor, $filePath);
153
                    break;
154
            }
155
            $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...
156
            $process->run();
157
            if (!$process->isSuccessful()) {
158
                throw new \Exception(sprintf('Can\'t run "%s".', $command));
159
            }
160
        }
161
    }
162
}
163