Completed
Push — symfony-console ( 439ffc...7a5fb0 )
by Arnaud
02:08
created

NewPage::findModel()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
cc 4
nc 3
nop 1
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(
67
                    sprintf('This page already exists. Do you want to override it? [y/n]', $this->getpath()),
68
                    false
69
                );
70
                if (!$helper->ask($input, $output, $question)) {
71
                    return;
72
                }
73
            }
74
75
            // create new file
76
            $title = $name;
77
            if (false !== strrchr($name, '/')) {
78
                $title = substr(strrchr($name, '/'), 1);
79
            }
80
            $date = date('Y-m-d');
81
            $fileContent = str_replace(['%title%', '%date%'], [$title, $date], $this->findModel($name));
82
            $this->fs->dumpFile($filePath, $fileContent);
83
84
            $output->writeln(sprintf('File "%s" created.', $fileRelativePath));
85
86
            // open editor?
87
            if ($open) {
88
                if (!$this->hasEditor()) {
89
                    $output->writeln('<comment>No editor configured.</comment>');
90
                }
91
                $this->openEditor($filePath);
92
            }
93
        } catch (\Exception $e) {
94
            throw new \Exception(sprintf($e->getMessage()));
95
        }
96
97
        return 0;
98
    }
99
100
    /**
101
     * Find the page model and return its content.
102
     *
103
     * @param string $name
104
     *
105
     * @return string
106
     */
107
    protected function findModel(string $name): string
108
    {
109
        $section = strstr($name, '/', true);
110
        if ($section && file_exists($model = sprintf('%s/models/%s.md', $this->getPath(), $section))) {
111
            return file_get_contents($model);
112
        }
113
        if (file_exists($model = sprintf('%s/models/default.md', $this->getPath()))) {
114
            return file_get_contents($model);
115
        }
116
117
        return <<<'EOT'
118
---
119
title: '%title%'
120
date: '%date%'
121
draft: true
122
---
123
124
_[Your content here]_
125
EOT;
126
    }
127
128
    /**
129
     * Editor is configured?
130
     *
131
     * @return bool
132
     */
133
    protected function hasEditor(): bool
134
    {
135
        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...
136
            return true;
137
        }
138
139
        return false;
140
    }
141
142
    /**
143
     * Open new file in editor (if configured).
144
     *
145
     * @param string $filePath
146
     *
147
     * @return void
148
     */
149
    protected function openEditor(string $filePath)
150
    {
151
        if ($editor = $this->builder->getConfig()->get('editor')) {
152
            switch ($editor) {
153
                case 'typora':
154
                    if (Plateform::getOS() == Plateform::OS_OSX) {
155
                        $command = sprintf('open -a typora "%s"', $filePath);
156
                    }
157
                    break;
158
                default:
159
                    $command = sprintf('%s "%s"', $editor, $filePath);
160
                    break;
161
            }
162
            $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...
163
            $process->run();
164
            if (!$process->isSuccessful()) {
165
                throw new \Exception(sprintf('Can\'t run "%s".', $command));
166
            }
167
        }
168
    }
169
}
170