Passed
Push — master ( 35639c...18326f )
by Daimona
01:42
created

TaskBase::handleError()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 4
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php declare( strict_types=1 );
2
3
namespace BotRiconferme\Task;
4
5
use BotRiconferme\TaskResult;
6
use BotRiconferme\ContextSource;
7
use BotRiconferme\TaskDataProvider;
8
9
/**
10
 * Base framework for all kind of tasks and subtasks
11
 */
12
abstract class TaskBase extends ContextSource {
13
	// Status codes
14
	const STATUS_OK = 0;
15
	const STATUS_ERROR = 1;
16
	/** @var string[] */
17
	protected $errors = [];
18
	/** @var TaskDataProvider */
19
	protected $dataProvider;
20
21
	/**
22
	 * Final to keep calls linear in the TaskManager
23
	 *
24
	 * @param TaskDataProvider $dataProvider
25
	 */
26
	final public function __construct( TaskDataProvider $dataProvider ) {
27
		set_exception_handler( [ $this, 'handleException' ] );
28
		set_error_handler( [ $this, 'handleError' ] );
29
		parent::__construct();
30
		$this->dataProvider = $dataProvider;
31
	}
32
33
	public function __destruct() {
34
		restore_error_handler();
35
		restore_exception_handler();
36
	}
37
38
	/**
39
	 * Main routine
40
	 *
41
	 * @return TaskResult
42
	 */
43
	abstract public function run() : TaskResult;
44
45
	/**
46
	 * Exception handler.
47
	 *
48
	 * @param \Throwable $ex
49
	 * @protected
50
	 */
51
	public function handleException( \Throwable $ex ) {
52
		$this->getLogger()->error(
53
			get_class( $ex ) . ': ' .
54
			$ex->getMessage() . "\nTrace:\n" .
55
			$ex->getTraceAsString()
56
		);
57
	}
58
59
	/**
60
	 * Error handler. As default, always throw
61
	 *
62
	 * @param int $errno
63
	 * @param string $errstr
64
	 * @param string $errfile
65
	 * @param int $errline
66
	 * @protected
67
	 */
68
	public function handleError( $errno, $errstr, $errfile, $errline ) {
69
		throw new \ErrorException( $errstr, 0, $errno, $errfile, $errline );
70
	}
71
72
	/**
73
	 * @return TaskDataProvider
74
	 */
75
	protected function getDataProvider() : TaskDataProvider {
76
		return $this->dataProvider;
77
	}
78
}
79