Completed
Pull Request — master (#525)
by
unknown
03:29
created

TaskIO::setLogLevel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
namespace Robo\Common;
3
4
use Robo\Robo;
5
use Robo\TaskInfo;
6
use Consolidation\Log\ConsoleLogLevel;
7
use Psr\Log\LoggerAwareTrait;
8
use Psr\Log\LogLevel;
9
use Robo\Contract\ProgressIndicatorAwareInterface;
10
11
/**
12
 * Task input/output methods.  TaskIO is 'used' in BaseTask, so any
13
 * task that extends this class has access to all of the methods here.
14
 * printTaskInfo, printTaskSuccess, and printTaskError are the three
15
 * primary output methods that tasks are encouraged to use.  Tasks should
16
 * avoid using the IO trait output methods.
17
 */
18
trait TaskIO
19
{
20
    use LoggerAwareTrait;
21
    use ConfigAwareTrait;
22
23
    /**
24
     * @var int
25
     */
26
    protected $logLevel = LogLevel::NOTICE;
27
28
    /**
29
     * @param int $logLevel
30
     */
31
    public function setLogLevel($logLevel)
32
    {
33
        $this->logLevel = $logLevel;
34
    }
35
36
    /**
37
     * @return int
38
     */
39
    public function getLogLevel()
40
    {
41
        return $this->logLevel;
42
    }
43
44
    /**
45
     * @return mixed|null|\Psr\Log\LoggerInterface
46
     */
47
    public function logger()
48
    {
49
        // $this->logger should always be set in Robo core tasks.
50
        if ($this->logger) {
51
            return $this->logger;
52
        }
53
54
        // TODO: Remove call to Robo::logger() once maintaining backwards
55
        // compatibility with legacy external Robo tasks is no longer desired.
56
        if (!Robo::logger()) {
57
            return null;
58
        }
59
60
        static $gaveDeprecationWarning = false;
61
        if (!$gaveDeprecationWarning) {
62
            trigger_error('No logger set for ' . get_class($this) . '. Use $this->task(Foo::class) rather than new Foo() in loadTasks to ensure the builder can initialize task the task, or use $this->collectionBuilder()->taskFoo() if creating one task from within another.', E_USER_DEPRECATED);
63
            $gaveDeprecationWarning = true;
64
        }
65
        return Robo::logger();
66
    }
67
68
    /**
69
     * Print information about a task in progress.
70
     *
71
     * With the Symfony Console logger, NOTICE is displayed at VERBOSITY_VERBOSE
72
     * and INFO is displayed at VERBOSITY_VERY_VERBOSE.
73
     *
74
     * Robo overrides the default such that NOTICE is displayed at
75
     * VERBOSITY_NORMAL and INFO is displayed at VERBOSITY_VERBOSE.
76
     *
77
     * n.b. We should probably have printTaskNotice for our ordinary
78
     * output, and use printTaskInfo for less interesting messages.
79
     *
80
     * @param string $text
81
     * @param null|array $context
82
     */
83
    protected function printTaskInfo($text, $context = null)
84
    {
85
        // The 'note' style is used for both 'notice' and 'info' log levels;
86
        // However, 'notice' is printed at VERBOSITY_NORMAL, whereas 'info'
87
        // is only printed at VERBOSITY_VERBOSE.
88
        $this->printTaskOutput($this->logLevel, $text, $this->getTaskContext($context));
89
    }
90
91
    /**
92
     * Provide notification that some part of the task succeeded.
93
     *
94
     * With the Symfony Console logger, success messages are remapped to NOTICE,
95
     * and displayed in VERBOSITY_VERBOSE. When used with the Robo logger,
96
     * success messages are displayed at VERBOSITY_NORMAL.
97
     *
98
     * @param string $text
99
     * @param null|array $context
100
     */
101
    protected function printTaskSuccess($text, $context = null)
102
    {
103
        // Not all loggers will recognize ConsoleLogLevel::SUCCESS.
104
        // We therefore log as LogLevel::NOTICE, and apply a '_level'
105
        // override in the context so that this message will be
106
        // logged as SUCCESS if that log level is recognized.
107
        $context['_level'] = ConsoleLogLevel::SUCCESS;
108
        $this->printTaskOutput($this->logLevel, $text, $this->getTaskContext($context));
109
    }
110
111
    /**
112
     * Provide notification that there is something wrong, but
113
     * execution can continue.
114
     *
115
     * Warning messages are displayed at VERBOSITY_NORMAL.
116
     *
117
     * @param string $text
118
     * @param null|array $context
119
     */
120
    protected function printTaskWarning($text, $context = null)
121
    {
122
        $this->printTaskOutput(LogLevel::WARNING, $text, $this->getTaskContext($context));
123
    }
124
125
    /**
126
     * Provide notification that some operation in the task failed,
127
     * and the task cannot continue.
128
     *
129
     * Error messages are displayed at VERBOSITY_NORMAL.
130
     *
131
     * @param string $text
132
     * @param null|array $context
133
     */
134
    protected function printTaskError($text, $context = null)
135
    {
136
        $this->printTaskOutput(LogLevel::ERROR, $text, $this->getTaskContext($context));
137
    }
138
139
    /**
140
     * Provide debugging notification.  These messages are only
141
     * displayed if the log level is VERBOSITY_DEBUG.
142
     *
143
     * @param string$text
144
     * @param null|array $context
145
     */
146
    protected function printTaskDebug($text, $context = null)
147
    {
148
        $this->printTaskOutput(LogLevel::DEBUG, $text, $this->getTaskContext($context));
149
    }
150
151
    /**
152
     * @param string $level
153
     *   One of the \Psr\Log\LogLevel constant
154
     * @param string $text
155
     * @param null|array $context
156
     */
157
    protected function printTaskOutput($level, $text, $context)
158
    {
159
        $logger = $this->logger();
160
        if (!$logger) {
161
            return;
162
        }
163
        // Hide the progress indicator, if it is visible.
164
        $inProgress = $this->hideTaskProgress();
165
        $logger->log($level, $text, $this->getTaskContext($context));
166
        // After we have printed our log message, redraw the progress indicator.
167
        $this->showTaskProgress($inProgress);
168
    }
169
170
    /**
171
     * @return bool
172
     */
173
    protected function hideTaskProgress()
174
    {
175
        $inProgress = false;
176
        if ($this instanceof ProgressIndicatorAwareInterface) {
177
            $inProgress = $this->inProgress();
178
        }
179
180
        // If a progress indicator is running on this task, then we mush
181
        // hide it before we print anything, or its display will be overwritten.
182
        if ($inProgress) {
183
            $inProgress = $this->hideProgressIndicator();
0 ignored issues
show
Bug introduced by
It seems like hideProgressIndicator() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
184
        }
185
        return $inProgress;
186
    }
187
188
    /**
189
     * @param $inProgress
190
     */
191
    protected function showTaskProgress($inProgress)
192
    {
193
        if ($inProgress) {
194
            $this->restoreProgressIndicator($inProgress);
0 ignored issues
show
Bug introduced by
It seems like restoreProgressIndicator() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
195
        }
196
    }
197
198
    /**
199
     * Format a quantity of bytes.
200
     *
201
     * @param int $size
202
     * @param int $precision
203
     *
204
     * @return string
205
     */
206
    protected function formatBytes($size, $precision = 2)
207
    {
208
        if ($size === 0) {
209
            return 0;
210
        }
211
        $base = log($size, 1024);
212
        $suffixes = array('', 'k', 'M', 'G', 'T');
213
        return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
214
    }
215
216
    /**
217
     * Get the formatted task name for use in task output.
218
     * This is placed in the task context under 'name', and
219
     * used as the log label by Robo\Common\RoboLogStyle,
220
     * which is inserted at the head of log messages by
221
     * Robo\Common\CustomLogStyle::formatMessage().
222
     *
223
     * @param null|object $task
224
     *
225
     * @return string
226
     */
227
    protected function getPrintedTaskName($task = null)
228
    {
229
        if (!$task) {
230
            $task = $this;
231
        }
232
        return TaskInfo::formatTaskName($task);
0 ignored issues
show
Bug introduced by
It seems like $task can also be of type this<Robo\Common\TaskIO>; however, Robo\TaskInfo::formatTaskName() does only seem to accept object, 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...
233
    }
234
235
    /**
236
     * @param null|array $context
237
     *
238
     * @return array with context information
239
     */
240
    protected function getTaskContext($context = null)
241
    {
242
        if (!$context) {
243
            $context = [];
244
        }
245
        if (!is_array($context)) {
246
            $context = ['task' => $context];
247
        }
248
        if (!array_key_exists('task', $context)) {
249
            $context['task'] = $this;
250
        }
251
252
        return $context + TaskInfo::getTaskContext($context['task']);
253
    }
254
}
255