aboutsummaryrefslogtreecommitdiffhomepage
path: root/Digitigrade/Job.php
blob: 146e4b2376adc3a540ced247fea480e86d039c3a (plain)
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
<?php
namespace Digitigrade;

abstract class Job implements \JsonSerializable {
    public int $remainingTries;
    public int $doneTries = 0;

    public function jsonSerialize(): array {
        $array = ['jobSubtype' => static::class];
        foreach ((new \ReflectionObject($this))->getProperties() as $prop) {
            assert($prop instanceof \ReflectionProperty); // for intellisense
            $value = $prop->getValue($this);
            $array[$prop->getName()] = is_object($value) ? json_encode($value) : $value;
        }
        return $array;
    }

    public static final function fromJson(string $data): ?self {
        $obj = json_decode($data);
        if (!property_exists($obj, 'jobSubtype')) {
            return null;
        }
        return (new \JsonMapper())->map($obj, $obj->jobSubtype);
    }

    /**
     * Runs the job. Returns nothing on success, or throws some error/exception.
     * @return void
     */
    public abstract function run();

    /**
     * Submits the job to the global job queue with appropriate options.
     * @return void
     */
    public function submit() {
        JobQueue::getInstance()->submitNormal($this);
    }
}