-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPending_Dispatch.php
More file actions
94 lines (80 loc) · 2.24 KB
/
Copy pathPending_Dispatch.php
File metadata and controls
94 lines (80 loc) · 2.24 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
88
89
90
91
92
93
94
<?php
/**
* Pending_Dispatch class file.
*
* @package Mantle
*/
namespace Mantle\Queue;
use DateTimeInterface;
use Mantle\Container\Container;
use Mantle\Contracts\Queue\Dispatcher;
use Mantle\Contracts\Queue\Job;
use RuntimeException;
/**
* Allow jobs to be added to the queue with ease.
*/
class Pending_Dispatch {
/**
* Flag to run the job after the response is sent.
*/
protected bool $after_response = false;
/**
* Constructor.
*
* @param Job|Closure_Job $job Job instance.
*/
public function __construct( protected Job|Closure_Job $job ) {}
/**
* Add a dispatch to a specific queue.
*
* @throws RuntimeException If the job does not support queueing.
*
* @param string $queue Queue to add to.
*/
public function on_queue( string $queue ): Pending_Dispatch {
if ( ! method_exists( $this->job, 'on_queue' ) ) {
throw new RuntimeException( 'Job does not support queueing.' );
}
$this->job->on_queue( $queue );
return $this;
}
/**
* Set the delay before the job will be run.
*
* @throws RuntimeException If the job does not support queueing.
*
* @param DateTimeInterface|int $delay Delay in seconds or DateTime instance.
*/
public function delay( DateTimeInterface|int $delay ): Pending_Dispatch {
if ( ! method_exists( $this->job, 'delay' ) ) {
throw new RuntimeException( $this->job::class . ' does not support delayed queueing.' );
}
$this->job->delay( $delay );
return $this;
}
/**
* Flag the job to be run after the response is sent.
*
* @param bool $after_response Flag to run the job after the response is sent.
*/
public function after_response( bool $after_response = true ): Pending_Dispatch {
$this->after_response = $after_response;
return $this;
}
/**
* Handle the job and send it to the queue or run it immediately.
*/
public function __destruct() {
// Allow the queue package to be run independent of the application.
if ( ! class_exists( \Mantle\Application\Application::class ) ) {
$dispatcher = Container::get_instance()->make( Dispatcher::class );
} else {
$dispatcher = app( Dispatcher::class );
}
if ( $this->after_response ) {
$dispatcher->dispatch_after_response( $this->job );
} else {
$dispatcher->dispatch( $this->job );
}
}
}