Completed
Branch dev (20d83f)
by Arina
01:20
created

Transformer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace ArinaSystems\JsonResponse\Transformers;
4
5
use Exception;
6
7
abstract class Transformer
8
{
9
    /**
10
     * @var object
11
     */
12
    protected $item;
13
14
    /**
15
     * Create a new instance.
16
     *
17
     * @param object $item
18
     */
19
    public function __construct($item)
20
    {
21
        throw_if(!$this->validate($item), new Exception("Expected argument of type \"" . get_class($item) . "\" \"" . get_class($item) . "\" given."));
22
        $this->item = $item;
23
    }
24
25
    /**
26
     * Convert the object instance to an array.
27
     *
28
     * @return array
29
     */
30
    abstract public function toArray(): array;
31
32
    /**
33
     * Determine which class of object should be transform.
34
     *
35
     * @return string
36
     */
37
    abstract public function objectClass(): string;
38
39
    /**
40
     * Check if the given object item is an instance of the determined class.
41
     *
42
     * @param $item
43
     * @return bool
44
     */
45
    protected function validate($item)
46
    {
47
        return (bool) is_a($item, $this->objectClass());
48
    }
49
}
50