Entity.php 2.1 KB
Newer Older
LONGMAN's avatar
LONGMAN committed
1
<?php
2

LONGMAN's avatar
LONGMAN committed
3 4 5 6 7 8 9
/*
 * This file is part of the TelegramBot package.
 *
 * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
10
*/
LONGMAN's avatar
LONGMAN committed
11 12 13 14
namespace Longman\TelegramBot\Entities;

class Entity
{
LONGMAN's avatar
LONGMAN committed
15 16 17 18 19 20 21 22 23
    protected $bot_name;


    public function getBotName()
    {

        return $this->bot_name;
    }

24 25 26 27
    public function toJSON()
    {
        $fields = $this->reflect($this);
        $json = json_encode($fields);
LONGMAN's avatar
LONGMAN committed
28

29 30
        return $json;
    }
LONGMAN's avatar
LONGMAN committed
31

32

MBoretto's avatar
MBoretto committed
33
    public function reflect($object = null)
34
    {
MBoretto's avatar
MBoretto committed
35 36 37 38
        if ($object == null) {
            $object = $this;
        }

39
        $reflection = new \ReflectionObject($object);
40
        $properties = $reflection->getProperties();
LONGMAN's avatar
LONGMAN committed
41

42
        $fields = [];
LONGMAN's avatar
LONGMAN committed
43

44 45
        foreach ($properties as $property) {
            $name = $property->getName();
LONGMAN's avatar
LONGMAN committed
46

47 48 49
            if ($name == 'bot_name') {
                continue;
            }
LONGMAN's avatar
LONGMAN committed
50

51
            if (!$property->isPrivate()) {
MBoretto's avatar
MBoretto committed
52 53 54 55 56 57 58 59 60 61 62
                $array_of_obj = false;
                if (is_array($object->$name)) {
                    $array_of_obj = true;
                    foreach ($object->$name as $elm) {
                        if (!is_object($elm)) {
                            $array_of_obj = false;
                            break;
                        }
                    }
                }

63 64
                if (is_object($object->$name)) {
                    $fields[$name] = $this->reflect($object->$name);
MBoretto's avatar
MBoretto committed
65 66 67 68
                } elseif ($array_of_obj) {
                    foreach ($object->$name as $elm) {
                        $fields[$name][] = $this->reflect($elm);
                    }
69 70 71 72 73 74 75 76 77 78 79
                } else {
                    $property->setAccessible(true);
                    $value = $property->getValue($object);
                    if (is_null($value)) {
                        continue;
                    }
                    $fields[$name] = $value;
                }
            }
        }
        return $fields;
80
    }
81

82

83 84 85 86
    public function __toString()
    {
        return $this->toJSON();
    }
LONGMAN's avatar
LONGMAN committed
87
}