Completed
Push — cecil ( 66a45a )
by Arnaud
02:09
created

AbstractCommand::getProgressBar()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
/*
3
 * This file is part of the PHPoole/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 PHPoole\PHPoole;
14
use Symfony\Component\Filesystem\Filesystem;
15
use Symfony\Component\Yaml\Exception\ParseException;
16
use Symfony\Component\Yaml\Yaml;
17
use Zend\Console\Adapter\AdapterInterface as Console;
18
use Zend\Console\ColorInterface as Color;
19
use Zend\Console\Prompt\Confirm;
20
use Zend\ProgressBar\ProgressBar;
21
use ZF\Console\Route;
22
23
abstract class AbstractCommand
24
{
25
    const CONFIG_FILE = 'config.yml';
26
27
    /**
28
     * @var Console
29
     */
30
    protected $console;
31
    /**
32
     * @var Route
33
     */
34
    protected $route;
35
    /**
36
     * @var string
37
     */
38
    protected $path;
39
    /**
40
     * @var PHPoole
41
     */
42
    protected $phpoole;
43
    /**
44
     * @var Filesystem
45
     */
46
    protected $fs;
47
    /**
48
     * @var ProgressBar
49
     */
50
    protected $progressBar = null;
51
    /**
52
     * @var int
53
     */
54
    protected $progressBarMax = 0;
55
    /**
56
     * @var bool
57
     */
58
    protected $verbose = false;
59
    /**
60
     * @var bool
61
     */
62
    protected $quiet = false;
63
64
    /**
65
     * Start command processing.
66
     *
67
     * @param Route   $route
68
     * @param Console $console
69
     *
70
     * @return mixed
71
     */
72
    public function __invoke(Route $route, Console $console)
73
    {
74
        $this->route = $route;
75
        $this->console = $console;
76
        $this->fs = new Filesystem();
77
78
        $this->path = $this->route->getMatchedParam('path', getcwd());
79
80
        if (realpath($this->path) === false) {
81
            if ($this->getRoute()->getName() != 'new') {
82
                throw new \Exception('Invalid <path> provided!');
83
            }
84
            if (!Confirm::prompt('The provided <path> doesn\'t exist. Do you want to create it? [y/n]', 'y', 'n')) {
85
                exit(0);
86
            }
87
            $this->fs->mkdir($this->path);
88
        }
89
        $this->path = realpath($this->path);
90
        $this->path = str_replace(DIRECTORY_SEPARATOR, '/', $this->path);
91
92
        return $this->processCommand();
93
    }
94
95
    /**
96
     * Process the command.
97
     */
98
    abstract public function processCommand();
0 ignored issues
show
Documentation introduced by
For interfaces and abstract methods it is generally a good practice to add a @return annotation even if it is just @return void or @return null, so that implementors know what to do in the overridden method.

For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a @return doc comment to communicate to implementors of these methods what they are expected to return.

Loading history...
99
100
    /**
101
     * @return Console
102
     */
103
    public function getConsole()
104
    {
105
        return $this->console;
106
    }
107
108
    /**
109
     * @return Route
110
     */
111
    public function getRoute()
112
    {
113
        return $this->route;
114
    }
115
116
    /**
117
     * @return string
118
     */
119
    public function getPath()
120
    {
121
        return $this->path;
122
    }
123
124
    /**
125
     * @param int $start
126
     * @param int $max
127
     *
128
     * @return ProgressBar
129
     */
130
    protected function createProgressBar($start, $max)
131
    {
132
        if ($this->progressBar === null || $max != $this->progressBarMax) {
133
            $this->progressBarMax = $max;
134
            $adapter = new \Zend\ProgressBar\Adapter\Console([
135
                'elements' => [
136
                    \Zend\ProgressBar\Adapter\Console::ELEMENT_PERCENT,
137
                    \Zend\ProgressBar\Adapter\Console::ELEMENT_BAR,
138
                    \Zend\ProgressBar\Adapter\Console::ELEMENT_TEXT,
139
                ],
140
                'textWidth' => 30,
141
            ]);
142
            $this->progressBar = new ProgressBar($adapter, $start, $max);
143
        }
144
145
        return $this->progressBar;
146
    }
147
148
    /**
149
     * @return ProgressBar
150
     */
151
    protected function getProgressBar()
152
    {
153
        return $this->progressBar;
154
    }
155
156
    /**
157
     * Print progress bar.
158
     *
159
     * @param int    $itemsCount
160
     * @param int    $itemsMax
161
     * @param string $message
162
     */
163
    protected function printProgressBar($itemsCount, $itemsMax, $message)
164
    {
165
        $this->createProgressBar(0, $itemsMax);
166
        $this->getProgressBar()->update($itemsCount, "$message");
167
        if ($itemsCount == $itemsMax) {
168
            $this->getProgressBar()->update($itemsCount, "[$itemsCount/$itemsMax]");
169
            $this->getProgressBar()->finish();
170
        }
171
    }
172
173
    /**
174
     * @param array $config
175
     * @param array $options
176
     *
177
     * @return PHPoole
178
     */
179
    public function getPHPoole(
180
        array $config = ['debug' => false],
181
        array $options = ['verbosity' => PHPoole::VERBOSITY_NORMAL])
182
    {
183
        if (!file_exists($this->getPath().'/'.self::CONFIG_FILE)) {
184
            throw new \Exception(sprintf('Config file not found in "%s"!', $this->getPath()));
185
        }
186
        // verbosity: verbose
187
        if ($options['verbosity'] == PHPoole::VERBOSITY_VERBOSE) {
188
            $this->verbose = true;
189
        }
190
        // verbosity: quiet
191
        if ($options['verbosity'] == PHPoole::VERBOSITY_QUIET) {
192
            $this->quiet = true;
193
        }
194
195
        try {
196
            $configFile = Yaml::parse(file_get_contents($this->getPath().'/'.self::CONFIG_FILE));
197
            $config = array_replace_recursive($configFile, $config);
198
            $this->phpoole = (new PHPoole($config, $this->messageCallback()))
199
                ->setSourceDir($this->getPath())
200
                ->setDestinationDir($this->getPath());
201
        } catch (ParseException $e) {
202
            throw new \Exception(sprintf('Config file parse error: %s', $e->getMessage()));
203
        } catch (\Exception $e) {
204
            throw new \Exception(sprintf($e->getMessage()));
205
        }
206
207
        return $this->phpoole;
208
    }
209
210
    /**
211
     * Custom message callback function.
212
     */
213
    public function messageCallback()
214
    {
215
        return function ($code, $message = '', $itemsCount = 0, $itemsMax = 0) {
216
            if ($this->quiet) {
217
                return;
218
            } else {
219
                if (strpos($code, '_PROGRESS') !== false) {
220
                    if ($this->verbose) {
221
                        if ($itemsCount > 0) {
222
                            $this->wlDone(sprintf('(%u/%u) %s', $itemsCount, $itemsMax, $message));
223
224
                            return;
225
                        }
226
                        $this->wlDone("$message");
227
                    } else {
228
                        if (isset($itemsCount) && $itemsMax > 0) {
229
                            $this->printProgressBar($itemsCount, $itemsMax, $message);
230
                        } else {
231
                            $this->wl($message);
232
                        }
233
                    }
234
                } elseif (strpos($code, '_ERROR') !== false) {
235
                    $this->wlError($message);
236
                } elseif ($code == 'TIME') {
237
                    $this->wl($message);
238
                } else {
239
                    $this->wlAnnonce($message);
240
                }
241
            }
242
        };
243
    }
244
245
    /**
246
     * @param string $text
247
     */
248
    public function wl($text)
249
    {
250
        $this->console->writeLine($text);
251
    }
252
253
    /**
254
     * @param string $text
255
     */
256
    public function wlAnnonce($text)
257
    {
258
        $this->console->writeLine($text, Color::WHITE);
259
    }
260
261
    /**
262
     * @param string $text
263
     */
264
    public function wlDone($text)
265
    {
266
        $this->console->writeLine($text, Color::GREEN);
267
    }
268
269
    /**
270
     * @param string $text
271
     */
272
    public function wlAlert($text)
273
    {
274
        $this->console->writeLine($text, Color::YELLOW);
275
    }
276
277
    /**
278
     * @param string $text
279
     */
280
    public function wlError($text)
281
    {
282
        $this->console->writeLine($text, Color::RED);
283
    }
284
}
285