aboutsummaryrefslogtreecommitdiffstats
path: root/Zotlabs/Lib/BaseObject.php
blob: 7125d34cb060269033ef84a1612c6439b23377f1 (plain) (blame)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php

namespace Zotlabs\Lib;

use Zotlabs\ActivityStreams\UnhandledElementException;

class BaseObject
{

    public $string;
    public $ldContext;

    /**
     * @param $input
     * @param $strict
     * @throws UnhandledElementException if $strict
     */

    public function __construct($input = null, $strict = false)
    {
        if (isset($input)) {
            if (is_string($input)) {
                $this->string = $input;
            }
            elseif(is_array($input)) {
                foreach ($input as $key => $value) {
                    $key = ($key === '@context') ? 'ldContext' : $key;
                    if ($strict && !property_exists($this, $key)) {
                        throw new UnhandledElementException("Unhandled element: $key");
                    }
                    $this->{$key} = $value;
                }
            }
        }
        return $this;
    }

    public function getDataType($element, $object = null)
    {
        $object = $object ?? $this;
        $type = gettype($object[$element]);
        if ($type === 'array' && array_is_list($object[$element])) {
            return 'list';
        }
        return $type;
    }

    public function toArray()
    {
        if ($this->string) {
            return $this->string;
        }
        $returnValue = [];
        foreach ((array) $this as $key => $value) {
            if (isset($value)) {
                $key = ($key === 'ldContext') ? '@context' : $key;
                $returnValue[$key] = (($value instanceof BaseObject) ? $value->toArray() : $value);
            }
        }
        return $returnValue;
    }

    /**
     * @return mixed
     */
    public function getLdContext()
    {
        return $this->ldContext;
    }

    /**
     * @param mixed $ldContext
     * @return BaseObject
     */
    public function setLdContext($ldContext)
    {
        $this->ldContext = $ldContext;
        return $this;
    }
}