ArrayResolver::buildFromConfig()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 1
1
<?php
2
3
namespace T4web\Cron\Resolver;
4
5
use Cron\Job\JobInterface;
6
use Cron\Schedule\CrontabSchedule;
7
use Cron\Resolver\ResolverInterface;
8
use T4web\Cron\Job\ShellJob;
9
use T4web\Cron\Exception\RuntimeException;
10
11
class ArrayResolver implements ResolverInterface
12
{
13
    /**
14
     * @var JobInterface[]
15
     */
16
    protected $jobs = [];
17
18
    /**
19
     * @var string
20
     */
21
    private $phpPath;
22
23
    /**
24
     * @var string
25
     */
26
    private $scriptPath;
27
28
    /**
29
     * @param $phpPath
30
     * @param $scriptPath
31
     */
32
    public function __construct($phpPath, $scriptPath)
33
    {
34
        $this->phpPath = $phpPath;
35
        $this->scriptPath = $scriptPath;
36
    }
37
38
    /**
39
     * @param array $rawJobs
40
     * @return JobInterface[]
41
     * @throws RuntimeException
42
     */
43
    public function buildFromConfig(array $rawJobs)
44
    {
45
        foreach ($rawJobs as $jobArray) {
46
47
            $this->validateJob($jobArray);
48
49
            $job = new ShellJob(
50
                $jobArray['id'],
51
                $this->assembleShellJobString($jobArray['command']),
52
                new CrontabSchedule($jobArray['schedule'])
53
            );
54
55
            $this->jobs[] = $job;
56
        }
57
58
        return $this->jobs;
59
    }
60
61
    /**
62
     * @param array $jobArray
63
     * @throws RuntimeException
64
     */
65
    private function validateJob(array $jobArray)
66
    {
67
        if (!isset($jobArray['id'])) {
68
            throw new RuntimeException(sprintf("Job must contain ID"));
69
        }
70
71
        if (!isset($jobArray['command'])) {
72
            throw new RuntimeException(sprintf("Job %s must contain command", $jobArray['id']));
73
        }
74
75
        if (!isset($jobArray['schedule'])) {
76
            throw new RuntimeException(sprintf("Job %s must contain schedule", $jobArray['id']));
77
        }
78
    }
79
80
    /**
81
     * @param $command
82
     * @return string
83
     */
84
    private function assembleShellJobString($command)
85
    {
86
        return $this->phpPath . ' ' . $this->scriptPath . $command;
87
    }
88
89
    /**
90
     * @return JobInterface[]
91
     */
92
    public function resolve()
93
    {
94
        $jobs = [];
95
        $now = new \DateTime();
96
97
        foreach ($this->jobs as $job) {
98
            if ($job->valid($now)) {
99
                $jobs[] = $job;
100
            }
101
        }
102
103
        return $jobs;
104
    }
105
}
106