Passed
Push — master ( 9623d2...497244 )
by Daimona
01:54
created

TaskResult::__toString()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 2
nop 0
dl 0
loc 13
rs 9.9332
c 0
b 0
f 0
1
<?php declare( strict_types=1 );
2
3
namespace BotRiconferme\TaskHelper;
4
5
/**
6
 * Object wrapping the result of the execution of a task.
7
 */
8
class TaskResult {
9
	// Status codes. GOOD = everything fine, NOTHING = nothing to do, ERROR = found non-fatal errors
10
	public const STATUS_NOTHING = 0;
11
	public const STATUS_GOOD = 1;
12
	public const STATUS_ERROR = 3;
13
14
	/** @var string[] */
15
	private $errors;
16
17
	/** @var int */
18
	private $status;
19
20
	/**
21
	 * @param int $status One of the Task::STATUS_* constants
22
	 * @param string[] $errors
23
	 */
24
	public function __construct( int $status, array $errors = [] ) {
25
		$this->status = $status;
26
		$this->errors = $errors;
27
	}
28
29
	/**
30
	 * @return int
31
	 */
32
	public function getStatus() : int {
33
		return $this->status;
34
	}
35
36
	/**
37
	 * @return string[]
38
	 * @suppress PhanUnreferencedPublicMethod
39
	 */
40
	public function getErrors() : array {
41
		return $this->errors;
42
	}
43
44
	/**
45
	 * @param TaskResult $that
46
	 */
47
	public function merge( TaskResult $that ) : void {
48
		$this->status |= $that->status;
49
		$this->errors = array_merge( $this->errors, $that->errors );
50
	}
51
52
	/**
53
	 * @return string
54
	 */
55
	public function __toString() {
56
		if ( $this->isOK() ) {
57
			$stat = 'OK';
58
			$errs = "\tNo errors.";
59
		} else {
60
			$stat = 'ERROR';
61
			$formattedErrs = [];
62
			foreach ( $this->errors as $err ) {
63
				$formattedErrs[] = "\t - $err";
64
			}
65
			$errs = implode( "\n", $formattedErrs );
66
		}
67
		return "=== RESULT ===\n - Status: $stat\n - Errors:\n$errs\n";
68
	}
69
70
	/**
71
	 * Shorthand
72
	 *
73
	 * @return bool
74
	 */
75
	public function isOK() : bool {
76
		return ( $this->status | self::STATUS_GOOD ) === self::STATUS_GOOD;
77
	}
78
}
79