AbstractTaskEndpoint.php
2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
namespace WPML\BackgroundTask;
use WPML\BackgroundTask\BackgroundTaskLoader;
use WPML\BackgroundTask\BackgroundTaskViewModel;
use WPML\Collect\Support\Collection;
use WPML\Core\BackgroundTask\Exception\TaskIsNotRunnableException;
use WPML\Core\BackgroundTask\Model\TaskEndpointInterface;
use WPML\Core\BackgroundTask\Service\BackgroundTaskService;
use WPML\Core\BackgroundTask\Command\UpdateBackgroundTask;
use WPML\Core\BackgroundTask\Model\BackgroundTask;
use WPML\FP\Either;
use function WPML\Container\make;
abstract class AbstractTaskEndpoint implements TaskEndpointInterface {
const LOCK_TIME = 2*60;
const MAX_RETRIES = 0;
/** @var UpdateBackgroundTask $updateBackgroundTask */
protected $updateBackgroundTask;
/** @var BackgroundTaskService $backgroundTaskService */
protected $backgroundTaskService;
/**
* @param UpdateBackgroundTask $updateBackgroundTask
* @param BackgroundTaskService $backgroundTaskService
*/
public function __construct( UpdateBackgroundTask $updateBackgroundTask, BackgroundTaskService $backgroundTaskService ) {
$this->updateBackgroundTask = $updateBackgroundTask;
$this->backgroundTaskService = $backgroundTaskService;
}
public function isDisplayed() {
return true;
}
public function getLockTime() {
return static::LOCK_TIME;
}
public function getMaxRetries() {
return static::MAX_RETRIES;
}
public function getType() {
return static::class;
}
/**
* @param BackgroundTask $task
*
* @return BackgroundTask
*/
abstract function runBackgroundTask( BackgroundTask $task );
public function run(
Collection $data
) {
try {
$taskId = $data['taskId'];
$task = $this->backgroundTaskService->startByTaskId( $taskId );
$task = $this->runBackgroundTask( $task );
$this->updateBackgroundTask->runUpdate( $task );
return $this->getResponse( $task );
} catch ( TaskIsNotRunnableException $e ) {
return Either::of( [ 'error' => $e->getMessage() ] );
}
}
/**
* @param BackgroundTask $backgroundTask
*
* @return callable|\WPML\FP\Right
*/
private function getResponse( BackgroundTask $backgroundTask ) {
/** @var \WPML\Utilities\Lock $endpointLock */
$endpointLock = make( 'WPML\Utilities\Lock', [ ':name' => $backgroundTask->getTaskType() ] );
$endpointLock->release();
return Either::of(
BackgroundTaskViewModel::get( $backgroundTask, true )
);
}
}