Completed
Push — master ( d3a073...5737c8 )
by Greg
02:21
created

src/Task/File/Replace.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
namespace Robo\Task\File;
3
4
use Robo\Result;
5
use Robo\Task\BaseTask;
6
7
/**
8
 * Performs search and replace inside a files.
9
 *
10
 * ``` php
11
 * <?php
12
 * $this->taskReplaceInFile('VERSION')
13
 *  ->from('0.2.0')
14
 *  ->to('0.3.0')
15
 *  ->run();
16
 *
17
 * $this->taskReplaceInFile('README.md')
18
 *  ->from(date('Y')-1)
19
 *  ->to(date('Y'))
20
 *  ->run();
21
 *
22
 * $this->taskReplaceInFile('config.yml')
23
 *  ->regex('~^service:~')
24
 *  ->to('services:')
25
 *  ->run();
26
 *
27
 * $this->taskReplaceInFile('box/robo.txt')
28
 *  ->from(array('##dbname##', '##dbhost##'))
29
 *  ->to(array('robo', 'localhost'))
30
 *  ->run();
31
 * ?>
32
 * ```
33
 */
34
class Replace extends BaseTask
35
{
36
    /**
37
     * @var string
38
     */
39
    protected $filename;
40
41
    /**
42
     * @var string|string[]
43
     */
44
    protected $from;
45
46
    /**
47
     * @var string|string[]
48
     */
49
    protected $to;
50
51
    /**
52
     * @var string
53
     */
54
    protected $regex;
55
56
    /**
57
     * @param string $filename
58
     */
59
    public function __construct($filename)
60
    {
61
        $this->filename = $filename;
62
    }
63
64
    /**
65
     * @param string $filename
66
     *
67
     * @return $this
68
     */
69
    public function filename($filename)
70
    {
71
        $this->filename = $filename;
72
        return $this;
73
    }
74
75
    /**
76
     * String(s) to be replaced.
77
     *
78
     * @param string|string[] $from
79
     *
80
     * @return $this
81
     */
82
    public function from($from)
83
    {
84
        $this->from = $from;
85
        return $this;
86
    }
87
88
    /**
89
     * Value(s) to be set as a replacement.
90
     *
91
     * @param string|string[] $to
92
     *
93
     * @return $this
94
     */
95
    public function to($to)
96
    {
97
        $this->to = $to;
98
        return $this;
99
    }
100
101
    /**
102
     * Regex to match string to be replaced.
103
     *
104
     * @param string $regex
105
     *
106
     * @return $this
107
     */
108
    public function regex($regex)
109
    {
110
        $this->regex = $regex;
111
        return $this;
112
    }
113
114
    /**
115
     * {@inheritdoc}
116
     */
117
    public function run()
118
    {
119 View Code Duplication
        if (!file_exists($this->filename)) {
0 ignored issues
show
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
            $this->printTaskError('File {filename} does not exist', ['filename' => $this->filename]);
121
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type declared by the interface Robo\Contract\TaskInterface::run of type Robo\Result.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
122
        }
123
124
        $text = file_get_contents($this->filename);
125
        if ($this->regex) {
126
            $text = preg_replace($this->regex, $this->to, $text, -1, $count);
127
        } else {
128
            $text = str_replace($this->from, $this->to, $text, $count);
129
        }
130
        if ($count > 0) {
131
            $res = file_put_contents($this->filename, $text);
132
            if ($res === false) {
133
                return Result::error($this, "Error writing to file {filename}.", ['filename' => $this->filename]);
134
            }
135
            $this->printTaskSuccess("{filename} updated. {count} items replaced", ['filename' => $this->filename, 'count' => $count]);
136
        } else {
137
            $this->printTaskInfo("{filename} unchanged. {count} items replaced", ['filename' => $this->filename, 'count' => $count]);
138
        }
139
        return Result::success($this, '', ['replaced' => $count]);
140
    }
141
}
142