Completed
Push — master ( caf135...d947d8 )
by Auke
63:25
created

Prototype::jsonSerialize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
/*
3
 * This file is part of the Ariadne Component Library.
4
 *
5
 * (c) Muze <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace arc\prototype;
11
12
/**
13
 * Implements a class of objects with prototypical inheritance, getters/setters, and observable changes
14
 * very similar to EcmaScript objects
15
 * @property \arc\prototype\Prototype $prototype The prototype for this object
16
 * @property array $properties
17
 */
18
final class Prototype implements \JsonSerializable
19
{
20
    /**
21
     * @var array cache for prototype properties
22
     */
23
    private static $properties = [];
24
25
    /**
26
     * @var array store for all properties of this instance. Must be private to always trigger __set and observers
27
     */
28
    private $_ownProperties = [];
29
30
    /**
31
     * @var array contains a list of local methods that have a static scope, such methods must be prefixed with a ':' when defined.
32
     */
33
    private $_staticMethods = [];
34
35
    /**
36
    * @var Prototype prototype Readonly reference to a prototype object. Can only be set in the constructor.
37
    */
38
    private $prototype = null;
39
40
    /**
41
     * @param array $properties
42
     */
43
    public function __construct($properties = [])
44
    {
45
        foreach ($properties as $property => $value) {
46
            if ( !is_numeric( $property ) && $property!='properties' ) {
47
                 if ( $property[0] == ':' ) {
48
                    $property = substr($property, 1);
49
                    $this->_staticMethods[$property] = true;
50
                    $this->_ownProperties[$property] = $value;
51
                } else if ($property == 'prototype') {
52
                    $this->prototype = $value;
53
                } else {
54
                    $this->_ownProperties[$property] = $this->_bind( $value );
55
                }
56
            }
57
        }
58
    }
59
60
    /**
61
     * @param $name
62
     * @param $args
63
     * @return mixed
64
     * @throws \BadMethodCallException
65
     */
66
    public function __call($name, $args)
67
    {
68
        if (array_key_exists( $name, $this->_ownProperties ) && is_callable( $this->_ownProperties[$name] )) {
69
            if ( array_key_exists($name, $this->_staticMethods) ) {
70
                array_unshift($args, $this);
71
            }
72
            return call_user_func_array( $this->_ownProperties[$name], $args );
73
        } elseif (is_object( $this->prototype)) {
74
            $method = $this->_getPrototypeProperty( $name );
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $method is correct as $this->_getPrototypeProperty($name) (which targets arc\prototype\Prototype::_getPrototypeProperty()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
75
            if (is_callable( $method )) {
76
                if ( array_key_exists($name, $this->_staticMethods) ) {
77
                    array_unshift($args, $this);
78
                }
79
                return call_user_func_array( $method, $args );
80
            }
81
        }
82
        throw new \BadMethodCallException( $name.' is not a method on this Object');
83
    }
84
85
    /**
86
     * @param $name
87
     * @return array|null|Prototype
88
     */
89
    public function __get($name)
90
    {
91
        switch ($name) {
92
            case 'prototype':
93
                return $this->prototype;
94
            break;
95
            case 'properties':
96
                return $this->_getPublicProperties();
97
            break;
98
            default:
99
                if ( array_key_exists($name, $this->_ownProperties) ) {
100
                    $property = $this->_ownProperties[$name];
101
                    if ( is_array($property) ) {
102
                        if ( isset($property['get']) && is_callable($property['get']) ) {
103
                            $getter = \Closure::bind( $property['get'], $this, $this );
104
                            return $getter();
105
                        } else if ( isset($property[':get']) && is_callable($property[':get']) ) {
106
                            return $property[':get']($this);
107
                        } else if ( (isset($property['set']) && is_callable($property['set']) )
108
                            || ( isset($property[':set']) && is_callable($property[':set']) ) ) {
109
                            return null;
110
                        }
111
                    }
112
                    return $property;
113
                }
114
                return $this->_getPrototypeProperty( $name );
115
            break;
116
        }
117
    }
118
119
    private function _isGetterOrSetter($property) {
120
        return (
121
            isset($property)
122
            && is_array($property)
123
            && (
124
                 ( isset($property['get']) && is_callable($property['get']) )
125
                || ( isset($property[':get']) && is_callable($property[':get']) )
126
                || ( isset($property['set']) && is_callable($property['set']) )
127
                || ( isset($property[':set']) && is_callable($property[':set']) )
128
            )
129
        );
130
    }
131
132
    /**
133
     * @param $name
134
     * @param $value
135
     * @throws \LogicException
136
     */
137
    public function __set($name, $value)
138
    {
139
        if (in_array( $name, [ 'prototype', 'properties' ] )) {
140
            throw new \LogicException('Property "'.$name.'" is read only.');
141
            return;
0 ignored issues
show
Unused Code introduced by
return; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
142
        }
143
        if ( !isset($this->_ownProperties[$name]) && !\arc\prototype::isExtensible($this) ) {
144
            throw new \LogicException('Object is not extensible.');
145
            return;
0 ignored issues
show
Unused Code introduced by
return; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
146
        }
147
        $valueIsSetterOrGetter = $this->_isGetterOrSetter($value);
148
        $propertyIsSetterOrGetter = (isset($this->_ownProperties[$name])
149
            ? $this->_isGetterOrSetter($this->_ownProperties[$name])
150
            : false
151
        );
152
        if ( \arc\prototype::isSealed($this) && $valueIsSetterOrGetter!=$propertyIsSetterOrGetter ) {
153
            throw new \LogicException('Object is sealed.');
154
            return;
0 ignored issues
show
Unused Code introduced by
return; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
155
        }
156
        $changes = [];
157
        $changes['name'] = $name;
158
        $changes['object'] = $this;
159
        if ( array_key_exists($name, $this->_ownProperties) ) {
160
            $changes['type'] = 'update';
161
            $changes['oldValue'] = $this->_ownProperties[$name];
162
        } else {
163
            $changes['type'] = 'add';
164
        }
165
166
        $clearcache = false;
167
        // get current value for $name, to check if it has a getter and/or a setter
168 View Code Duplication
        if ( array_key_exists($name, $this->_ownProperties) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
169
            $current = $this->_ownProperties[$name];
170
        } else {
171
            $current = $this->_getPrototypeProperty($name);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $current is correct as $this->_getPrototypeProperty($name) (which targets arc\prototype\Prototype::_getPrototypeProperty()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
172
        }
173
        if ( $valueIsSetterOrGetter ) {
174
            // reconfigure current property
175
            $clearcache = true;
176
            $this->_ownProperties[$name] = $value;
177
            unset($this->_staticMethods[$name]);
178
        } else if (
179
            isset($current)
180
            && (is_array($current) || $current instanceof \ArrayAccess) 
181
            && isset($current['set']) 
182
            && is_callable($current['set'])
183
        ) {
184
            // bindable setter found, use it, no need to set anything in _ownProperties
185
            $setter = \Closure::bind($current['set'], $this, $this);
186
            $setter($value);
187
        } else if (
188
            isset($current) 
189
            && (is_array($current) || $current instanceof \ArrayAccess) 
190
            && isset($current[':set']) 
191
            && is_callable($current[':set'])
192
        ) {
193
            // nonbindable setter found
194
            $current[':set']($this, $value);
195
        } else if (
196
            isset($current) 
197
            && (is_array($current) || $current instanceof \ArrayAccess) 
198
            && ( 
199
                (isset($current['get']) && is_callable($current['get']) )
200
                || (isset($current[':get']) && is_callable($current[':get']) )
201
            )
202
        ) {
203
            // there is only a getter, no setter, so ignore setting this property, its readonly.
204
            throw new \LogicException('Property "'.$name.'" is readonly.');
205
            return null;
0 ignored issues
show
Unused Code introduced by
return null; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
206
        } else if (!array_key_exists($name, $this->_staticMethods)) {
207
            // bindable value, update _ownProperties, so clearcache as well
208
            $clearcache = true;
209
            $this->_ownProperties[$name] = $this->_bind( $value );
210
        } else {
211
            // non bindable value, update _ownProperties, so clearcache as well
212
            $clearcache = true;
213
            $this->_ownProperties[$name] = $value;
214
        }
215
        if ( $clearcache ) {
216
            // purge prototype cache for this property - this will clear too much but cache will be filled again
217
            // clearing exactly the right entries from the cache will generally cost more performance than this
218
            unset( self::$properties[ $name ] );
219
            $observers = \arc\prototype::getObservers($this);
220
            if ( isset($observers[$changes['type']]) ) {
221
                foreach($observers[$changes['type']] as $observer) {
222
                    $observer($changes);
223
                }
224
            }
225
        }
226
    }
227
228
    /**
229
     * Returns a list of publically accessible properties of this object and its prototypes.
230
     * @return array
231
     */
232
    private function _getPublicProperties()
233
    {
234
        // get public properties only, so use closure to escape local scope.
235
        // the anonymous function / closure is needed to make sure that get_object_vars
236
        // only returns public properties.
237
        return ( is_object( $this->prototype )
238
            ? array_merge( $this->prototype->properties, $this->_getLocalProperties() )
239
            : $this->_getLocalProperties() );
240
    }
241
242
    /**
243
     * Returns a list of publically accessible properties of this object only, disregarding its prototypes.
244
     * @return array
245
     */
246
    private function _getLocalProperties()
247
    {
248
        return [ 'prototype' => $this->prototype ] + $this->_ownProperties;
249
    }
250
251
    /**
252
     * Get a property from the prototype chain and caches it.
253
     * @param $name
254
     * @return null
255
     */
256
    private function _getPrototypeProperty($name)
257
    {
258
        if (is_object( $this->prototype )) {
259
            // cache prototype access per property - allows fast but partial cache purging
260
            if (!array_key_exists( $name, self::$properties )) {
261
                self::$properties[ $name ] = new \SplObjectStorage();
262
            }
263
            if (!self::$properties[$name]->contains( $this->prototype )) {
264
                $property = $this->prototype->{$name};
265
                if ( $property instanceof \Closure ) {
266
                    if ( !array_key_exists($name, $this->prototype->_staticMethods)) {
267
                        $property = $this->_bind( $property );
268
                    } else {
269
                        $this->_staticMethods[$name] = true;
270
                    }
271
                }
272
                self::$properties[$name][ $this->prototype ] = $property;
273
            }
274
            return self::$properties[$name][ $this->prototype ];
275
        } else {
276
            return null;
277
        }
278
    }
279
280
281
    /**
282
     * @param $name
283
     * @return bool
284
     */
285
    public function __isset($name)
286
    {
287 View Code Duplication
        if ( array_key_exists($name, $this->_ownProperties) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
288
            return isset($this->_ownProperties[$name]);
289
        } else {
290
            $val = $this->_getPrototypeProperty( $name );
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $val is correct as $this->_getPrototypeProperty($name) (which targets arc\prototype\Prototype::_getPrototypeProperty()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
291
            return isset( $val );
292
        }
293
    }
294
295
    /**
296
     * @param $name
297
     * @throws \LogicException
298
     */
299
    public function __unset($name) {
300
        if (!in_array( $name, [ 'prototype', 'properties' ] )) {
301
            if ( !\arc\prototype::isSealed($this) ) {
302
                $oldValue = $this->_ownProperties[$name];
303
                if (array_key_exists($name, $this->_staticMethods)) {
304
                    unset($this->_staticMethods[$name]);
305
                }
306
                unset($this->_ownProperties[$name]);
307
                // purge prototype cache for this property - this will clear too much but cache will be filled again
308
                // clearing exactly the right entries from the cache will generally cost more performance than this
309
                unset( self::$properties[ $name ] );
310
                $observers = \arc\prototype::getObservers($this);
311
                $changes = [
312
                    'type' => 'delete',
313
                    'name' => $name,
314
                    'object' => $this,
315
                    'oldValue' => $oldValue
316
                ];
317
                foreach ($observers['delete'] as $observer) {
318
                    $observer($changes);
319
                }
320
            } else {
321
                throw new \LogicException('Object is sealed.');
322
            }
323
        } else {
324
            throw new \LogicException('Property "'.$name.'" is protected.');
325
        }
326
    }
327
328
    /**
329
     *
330
     */
331
    public function __destruct()
332
    {
333
    	\arc\prototype::_destroy($this);
334
        return $this->_tryToCall( '__destruct' );
335
    }
336
337
    /**
338
     * @return mixed
339
     */
340
    public function __toString()
341
    {
342
        return (string) $this->_tryToCall( '__toString' );
343
    }
344
345
    /**
346
     * @return mixed
347
     * @throws \BadMethodCallException
348
     */
349
    public function __invoke()
350
    {
351
        if (is_callable( $this->__invoke )) {
352
            return call_user_func_array( $this->__invoke, func_get_args() );
353
        } else {
354
            throw new \BadMethodCallException( 'No __invoke method found in this Object' );
355
        }
356
    }
357
358
    /**
359
     *
360
     */
361
    public function __clone()
362
    {
363
        // make sure all methods are bound to $this - the new clone.
364
        foreach ($this->_ownProperties as $name => $property) {
365
            if ( $property instanceof \Closure && !$this->_staticMethods[$name] ) {
366
                $this->{$name} = $this->_bind( $property );
367
            }
368
        }
369
        $this->_tryToCall( '__clone' );
370
    }
371
372
    public function jsonSerialize() {
373
        $result = $this->_tryToCall( '__toJSON' );
374
        if (!$result) {
375
            return \arc\prototype::entries($this);
376
        } else {
377
            return $result;
378
        }
379
    }
380
381
    /**
382
     * Binds the property to this object
383
     * @param $property
384
     * @return mixed
385
     */
386
    private function _bind($property)
387
    {
388
        if ($property instanceof \Closure ) {
389
            // make sure any internal $this references point to this object and not the prototype or undefined
390
            return \Closure::bind( $property, $this );
391
        }
392
393
        return $property;
394
    }
395
396
    /**
397
     * Only call $f if it is a callable.
398
     * @param $f
399
     * @param array $args
400
     * @return mixed
401
     */
402
    private function _tryToCall($name, $args = [])
403
    {
404
        if ( isset($this->{$name}) && is_callable( $this->{$name} )) {
405
            if ( array_key_exists($name, $this->_staticMethods) ) {
406
                array_unshift($args, $this);
407
            }
408
            return call_user_func_array( $this->{$name}, $args );
409
        }
410
    }
411
}
412
413
/**
414
 * Class dummy
415
 * This class is needed because in PHP7 you can no longer bind to \stdClass
416
 * And anonymous classes are syntax errors in PHP5.6, so there.
417
 * @package arc\lambda
418
 */
419
class dummy {
420
}
421