aboutsummaryrefslogtreecommitdiffhomepage
path: root/Digitigrade/Job.php
blob: d460b7e381a9f16797c9527e0a542b8db8576775 (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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
namespace Digitigrade;

abstract class Job implements \JsonSerializable {
    private static \JsonMapper $mapper;

    public int $remainingTries;
    public int $doneTries = 0;

    public static function __initStatic() {
        self::$mapper = new \JsonMapper();
        // to parse DateTime(Immutable)s properly
        self::$mapper->bStrictObjectTypeChecking = false;
        self::$mapper->classMap[\DateTimeInterface::class] = \DateTimeImmutable::class;
    }

    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);
            if ($value instanceof \DateTimeInterface) {
                $array[$prop->getName()] = $value->format('c');
            } else {
                $array[$prop->getName()] = $value;
            }
        }
        return $array;
    }

    public static final function fromJson(string $data): ?self {
        $obj = json_decode($data);
        if (!property_exists($obj, 'jobSubtype')) {
            return null;
        }
        return self::$mapper->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);
    }
}

Job::__initStatic();