Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
PayloadTrait
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
4 / 4
5
100.00% covered (success)
100.00%
1 / 1
 getPayload
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setPayload
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 setPayloadTester
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getPayloadTester
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3/**
4 * @author: Doug Wilbourne (dougwilbourne@gmail.com)
5 */
6
7declare(strict_types=1);
8
9namespace pvc\struct\payload;
10
11use pvc\interfaces\validator\ValTesterInterface;
12use pvc\struct\tree\err\InvalidValueException;
13
14/**
15 * Class PayloadTrait
16 * @template PayloadType
17 *
18 * this implementation allows payloads to be nullable only if the payloadtester is set, and it allows null values.
19 * Another way to say that is that the default payload tester returns true if the payload is not null.
20 */
21trait PayloadTrait
22{
23    /**
24     * @var PayloadType|null
25     */
26    protected mixed $payload;
27
28    /**
29     * @var ValTesterInterface<PayloadType>
30     */
31    protected ValTesterInterface $tester;
32
33    /**
34     * getPayload
35     * @return PayloadType|null
36     */
37    public function getPayload()
38    {
39        return $this->payload ?? null;
40    }
41
42    /**
43     * setPayload
44     * @param PayloadType $payload
45     * @throws InvalidValueException
46     */
47    public function setPayload(mixed $payload): void
48    {
49        if (!$this->getPayloadTester()->testValue($payload)) {
50            throw new InvalidValueException();
51        }
52        $this->payload = $payload;
53    }
54
55    /**
56     * setPayloadTester
57     * @param ValTesterInterface<PayloadType> $tester
58     */
59    public function setPayloadTester(ValTesterInterface $tester): void
60    {
61        $this->tester = $tester;
62    }
63
64    /**
65     * getPayloadTester
66     * @return ValTesterInterface<PayloadType>
67     */
68    public function getPayloadTester(): ValTesterInterface
69    {
70        $alwaysTrue = new class implements ValTesterInterface {
71            public function testValue(mixed $value): bool
72            {
73                return true;
74            }
75        };
76        return $this->tester ?? $alwaysTrue;
77    }
78}