Completed
Push — open-in-editor ( 699198 )
by Arnaud
02:43
created

NewPage::hasEditor()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
/*
3
 * This file is part of the Cecil/Cecil package.
4
 *
5
 * Copyright (c) Arnaud Ligny <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Cecil\Command;
12
13
use Cecil\Util\Plateform;
14
use Symfony\Component\Process\Process;
15
use Zend\Console\Prompt\Confirm;
16
17
/**
18
 * Class NewPage.
19
 */
20
class NewPage extends AbstractCommand
21
{
22
    /**
23
     * @var string
24
     */
25
    protected $name;
26
    /**
27
     * @var bool
28
     */
29
    protected $force;
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function processCommand()
35
    {
36
        $this->name = $this->getRoute()->getMatchedParam('name');
37
        $this->force = $this->getRoute()->getMatchedParam('force', false);
38
        $this->open = $this->getRoute()->getMatchedParam('open', false);
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...
39
40
        try {
41
            // file name (without extension)
42
            if (false !== $extPos = strripos($this->name, '.md')) {
43
                $this->name = substr($this->name, 0, $extPos);
44
            }
45
            // path
46
            $fileRelativePath = $this->getBuilder()->getConfig()->get('content.dir').'/'.$this->name.'.md';
47
            $filePath = $this->getPath().'/'.$fileRelativePath;
48
49
            // file already exists?
50
            if ($this->fs->exists($filePath) && !$this->force) {
51
                if (!Confirm::prompt('This page already exists. Do you want to override it? [y/n]', 'y', 'n')) {
52
                    exit(0);
53
                }
54
            }
55
56
            // create new file
57
            $title = $this->name;
58
            if (false !== strrchr($this->name, '/')) {
59
                $title = substr(strrchr($this->name, '/'), 1);
60
            }
61
            $date = date('Y-m-d');
62
            $fileContent = str_replace(['%title%', '%date%'], [$title, $date], $this->findModel($this->name));
63
            $this->fs->dumpFile($filePath, $fileContent);
64
65
            $this->wlDone(sprintf('File "%s" created!', $fileRelativePath));
66
67
            // open editor?
68
            if ($this->open) {
69
                if (!$this->hasEditor()) {
70
                    $this->wlAlert('No editor configured!');
71
                }
72
                $this->openEditor($filePath);
73
            }
74
        } catch (\Exception $e) {
75
            throw new \Exception(sprintf($e->getMessage()));
76
        }
77
    }
78
79
    /**
80
     * Find the page model and return its content.
81
     *
82
     * @param string $name
83
     *
84
     * @return string
85
     */
86
    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...
87
    {
88
        $section = strstr($this->name, '/', true);
89
        if ($section && file_exists($model = sprintf('%s/models/%s.md', $this->getPath(), $section))) {
90
            return file_get_contents($model);
91
        }
92
        if (file_exists($model = sprintf('%s/models/default.md', $this->getPath()))) {
93
            return file_get_contents($model);
94
        }
95
96
        return <<<'EOT'
97
---
98
title: '%title%'
99
date: '%date%'
100
draft: true
101
---
102
103
_[Your content here]_
104
EOT;
105
    }
106
107
    /**
108
     * Editor is configured?
109
     *
110
     * @return bool
111
     */
112
    protected function hasEditor()
113
    {
114
        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...
115
            return true;
116
        }
117
118
        return false;
119
    }
120
121
    /**
122
     * Open new file in editor (if configured).
123
     *
124
     * @param string $filePath
125
     *
126
     * @return void
127
     */
128
    protected function openEditor($filePath)
129
    {
130
        if ($editor = $this->builder->getConfig()->get('editor')) {
131
            switch ($editor) {
132
                case 'typora':
133
                    if (Plateform::getOS() == Plateform::OS_OSX) {
134
                        $command = sprintf('open -a typora %s', $filePath);
135
                    }
136
                    break;
137
                default:
138
                    $command = sprintf('%s %s', $editor, $filePath);
139
                    break;
140
            }
141
            $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...
142
            $process->run();
143
            if (!$process->isSuccessful()) {
144
                throw new \Exception(sprintf('Can\'t open "%s" editor.', $editor));
145
            }
146
        }
147
    }
148
}
149