PluginProbe
Travelpayouts / trunk
Travelpayouts vtrunk
1.1.11 1.1.12 1.1.13 1.1.14 1.1.15 1.1.16 1.1.17 1.1.18 1.1.19 1.1.2 1.1.20 1.1.21 1.1.22 1.1.23 1.1.3 1.1.4 1.1.5 1.1.6 1.1.7 1.1.8 1.1.9 1.2.0 1.2.1 1.2.2 1.2.3 All 56 releases
travelpayouts / src / components / BaseObject.php

BaseObject.php in Travelpayouts trunk, at src/components/BaseObject.php

97 lines 2.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * Created by: Andrey Polyakov (andrey@polyakov.im)
5 */
6
7 namespace Travelpayouts\components;
8
9 use Exception;
10 use Travelpayouts\components\exceptions\InvalidConfigException;
11 use Travelpayouts\traits\GetterSetterTrait;
12
13 class BaseObject
14 {
15 use GetterSetterTrait;
16
17 public function __construct($config = [])
18 {
19 if (!empty($config) && is_array($config)) {
20 self::configure($this, $config);
21 }
22 $this->init();
23 }
24
25 /**
26 * Initializes the object.
27 * This method is invoked at the end of the constructor after the object is initialized with the
28 * given configuration.
29 */
30 public function init()
31 {
32 }
33
34 /**
35 * Configures an object with the initial property values.
36 * @param object $object the object to be configured
37 * @param array $properties the property initial values given in terms of name-value pairs.
38 * @return object the object itself
39 */
40 public static function configure($object, $properties)
41 {
42 foreach ($properties as $name => $value) {
43 $object->$name = $value;
44 }
45
46 return $object;
47 }
48
49 /**
50 * Calls the named method which is not a class method.
51 * Do not call this method directly as it is a PHP magic method that
52 * will be implicitly called when an unknown method is being invoked.
53 * @param string $name the method name
54 * @param array $params method parameters
55 * @return mixed the method return value
56 * @throws Exception when calling unknown method
57 */
58 public function __call($name, $params)
59 {
60 throw new Exception('Calling unknown method: ' . get_class($this) . "::$name()");
61 }
62
63 /**
64 * @param $type
65 * @param array $params
66 * @return mixed
67 * @throws InvalidConfigException
68 */
69 public static function createObject($type, array $params = [])
70 {
71 if (is_string($type)) {
72 return new $type($params);
73 }
74 if (is_callable($type, true)) {
75 return call_user_func_array($type, $params);
76 }
77
78 if (!is_array($type)) {
79 throw new InvalidConfigException('Unsupported configuration type: ' . gettype($type));
80 }
81
82 if (isset($type['__class'])) {
83 $class = $type['__class'];
84 unset($type['__class'], $type['class']);
85 return new $class($type);
86 }
87
88 if (isset($type['class'])) {
89 $class = $type['class'];
90 unset($type['class']);
91 return new $class($type);
92 }
93
94 throw new InvalidConfigException('Object configuration must be an array containing a "class" or "__class" element.');
95 }
96 }
97