1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @author Nurlan Mukhanov <[email protected]> |
4
|
|
|
* @copyright 2022 Nurlan Mukhanov |
5
|
|
|
* @license https://en.wikipedia.org/wiki/MIT_License MIT License |
6
|
|
|
* @link https://github.com/Falseclock/service-layer |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
declare(strict_types=1); |
10
|
|
|
|
11
|
|
|
namespace Falseclock\Service; |
12
|
|
|
|
13
|
|
|
use Falseclock\Service\Validation\ValidatorError; |
14
|
|
|
use Psr\Log\LoggerInterface; |
15
|
|
|
|
16
|
|
|
abstract class Service |
17
|
|
|
{ |
18
|
|
|
/** @var ValidatorError[] */ |
19
|
|
|
public $lastValidationErrors = []; |
20
|
|
|
/** @var LoggerInterface */ |
21
|
|
|
protected $logger; |
22
|
|
|
/** @var ServiceResponse */ |
23
|
|
|
protected $response; |
24
|
|
|
/** @var ServiceError[] */ |
25
|
|
|
protected $serviceErrors = []; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Service constructor. |
29
|
|
|
* |
30
|
|
|
* @param LoggerInterface|null $logger |
31
|
|
|
*/ |
32
|
|
|
public function __construct(?LoggerInterface $logger = null) |
33
|
|
|
{ |
34
|
|
|
$this->logger = $logger; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @return ServiceResponse |
39
|
|
|
*/ |
40
|
|
|
final public function invalidRequestResponse(): ServiceResponse |
41
|
|
|
{ |
42
|
|
|
$this->serviceErrors[] = new ServiceError("Request parameters are invalid", ServiceError::ERROR_INVALID_REQUEST); |
43
|
|
|
|
44
|
|
|
return new ServiceResponse(null, $this->serviceErrors, $this->lastValidationErrors); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param ServiceError $error |
49
|
|
|
* @return $this |
50
|
|
|
*/ |
51
|
|
|
final protected function addError(ServiceError $error): self |
52
|
|
|
{ |
53
|
|
|
$this->serviceErrors[] = $error; |
54
|
|
|
|
55
|
|
|
return $this; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Each service handler has to call request validation to be sure all supplied data is valid |
60
|
|
|
* |
61
|
|
|
* @param RequestImpl $request |
62
|
|
|
* @return bool |
63
|
|
|
*/ |
64
|
|
|
final protected function validateRequest(Request $request): bool |
65
|
|
|
{ |
66
|
|
|
$this->lastValidationErrors = $request->validate(); |
67
|
|
|
|
68
|
|
|
return count($this->lastValidationErrors) == 0; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Just return result to the caller |
73
|
|
|
* |
74
|
|
|
* @param mixed $result |
75
|
|
|
* @param ServiceError ...$errors |
76
|
|
|
* @return ServiceResponse |
77
|
|
|
*/ |
78
|
|
|
final protected function createResponse($result, ?ServiceError ...$errors): ServiceResponse |
79
|
|
|
{ |
80
|
|
|
return new ServiceResponse($result, array_merge($this->serviceErrors, $errors), $this->lastValidationErrors); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|