Passed
Push — master ( e1e446...1b5c12 )
by Fabio
06:00
created

TComponent::attachBehaviors()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 10
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 14
ccs 0
cts 0
cp 0
crap 56
rs 8.8333
1
<?php
2
/**
3
 * TComponent, TPropertyValue classes
4
 *
5
 * @author Qiang Xue <[email protected]>
6
 *
7
 * Global Events, intra-object events, Class behaviors, expanded behaviors
8
 * @author Brad Anderson <[email protected]>
9
 *
10
 * @author Qiang Xue <[email protected]>
11
 * @link https://github.com/pradosoft/prado
12
 * @license https://github.com/pradosoft/prado/blob/master/LICENSE
13
 */
14
15
namespace Prado;
16
17
use Prado\Collections\TPriorityMap;
18
use Prado\Collections\TWeakCallableCollection;
19
use Prado\Exceptions\TApplicationException;
20
use Prado\Exceptions\TInvalidDataTypeException;
21
use Prado\Exceptions\TInvalidDataValueException;
22
use Prado\Exceptions\TInvalidOperationException;
23
use Prado\Util\IBaseBehavior;
24
use Prado\Util\IBehavior;
25
use Prado\Util\TCallChain;
26
use Prado\Util\IClassBehavior;
27
use Prado\Util\IDynamicMethods;
28
use Prado\Util\TClassBehaviorEventParameter;
29
use Prado\Web\Javascripts\TJavaScriptLiteral;
30
use Prado\Web\Javascripts\TJavaScriptString;
31
32
/**
33
 * TComponent class
34
 *
35
 * TComponent is the base class for all PRADO components.
36
 * TComponent implements the protocol of defining, using properties, behaviors,
37
 * events, dynamic events, and global events.
38
 *
39
 * Properties
40
 *
41
 * A property is defined by a getter method, and/or a setter method.
42
 * Properties can be accessed in the way like accessing normal object members.
43
 * Reading or writing a property will cause the invocation of the corresponding
44
 * getter or setter method, e.g.,
45
 * <code>
46
 * $a=$this->Text;     // equivalent to $a=$this->getText();
47
 * $this->Text='abc';  // equivalent to $this->setText('abc');
48
 * </code>
49
 * The signatures of getter and setter methods are as follows,
50
 * <code>
51
 * // getter, defines a readable property 'Text'
52
 * function getText() { ... }
53
 * // setter, defines a writable property 'Text', with $value being the value to be set to the property
54
 * function setText($value) { ... }
55
 * </code>
56
 * Property names are case-insensitive. It is recommended that they are written
57
 * in the format of concatenated words, with the first letter of each word
58
 * capitalized (e.g. DisplayMode, ItemStyle).
59
 *
60
 *
61
 * Javascript Get and Set Properties
62
 *
63
 * Since Prado 3.2 a new class of javascript-friendly properties have been introduced
64
 * to better deal with potential security problems like cross-site scripting issues.
65
 * All the data that gets sent clientside inside a javascript block is now encoded by default.
66
 * Sometimes there's the need to bypass this encoding and be able to send raw javascript code.
67
 * This new class of javascript-friendly properties are identified by their name
68
 * starting with 'js' (case insensitive):
69
 * <code>
70
 * // getter, defines a readable property 'Text'
71
 * function getJsText() { ... }
72
 * // setter, defines a writable property 'Text', with $value being the value to be set to the property
73
 * function setJsText(TJavaScriptLiteral $value) { ... }
74
 * </code>
75
 * Js-friendly properties can be accessed using both their Js-less name and their Js-enabled name:
76
 * <code>
77
 * // set some simple text as property value
78
 * $component->Text = 'text';
79
 * // set some javascript code as property value
80
 * $component->JsText = 'raw javascript';
81
 * </code>
82
 * In the first case, the property value will automatically gets encoded when sent
83
 * clientside inside a javascript block.
84
 * In the second case, the property will be 'marked' as being a safe javascript
85
 * statement and will not be encoded when rendered inside a javascript block.
86
 * This special handling makes use of the {@link TJavaScriptLiteral} class.
87
 *
88
 *
89
 * Object Events
90
 *
91
 * An event is defined by the presence of a method whose name starts with 'on'.
92
 * The event name is the method name and is thus case-insensitive.
93
 * An event can be attached with one or several methods (called event handlers).
94
 * An event can be raised by calling {@link raiseEvent} method, upon which
95
 * the attached event handlers will be invoked automatically in the order they
96
 * are attached to the event. Event handlers must have the following signature,
97
 * <code>
98
 * function eventHandlerFuncName($sender, $param) { ... }
99
 * </code>
100
 * where $sender refers to the object who is responsible for the raising of the event,
101
 * and $param refers to a structure that may contain event-specific information.
102
 * To raise an event (assuming named as 'Click') of a component, use
103
 * <code>
104
 * $component->raiseEvent('OnClick');
105
 * $component->raiseEvent('OnClick', $this, $param);
106
 * </code>
107
 * To attach an event handler to an event, use one of the following ways,
108
 * <code>
109
 * $component->OnClick = $callback;
110
 * $component->OnClick->add($callback);
111
 * $component->attachEventHandler('OnClick', $callback);
112
 * </code>
113
 * The first two ways make use of the fact that $component->OnClick refers to
114
 * the event handler list {@link TWeakCallableCollection} for the 'OnClick' event.
115
 * The variable $callback contains the definition of the event handler that can
116
 * be either:
117
 *
118
 * a string referring to a global function name
119
 * <code>
120
 * $component->OnClick = 'buttonClicked';
121
 * // will cause the following function to be called
122
 * buttonClicked($sender, $param);
123
 * </code>
124
 *
125
 * All types of PHP Callables are supported, such as:
126
 *  - Simple Callback function string, eg. 'my_callback_function'
127
 *  - Static class method call, eg. ['MyClass', 'myCallbackMethod'] and 'MyClass::myCallbackMethod'
128
 *  - Object method call, eg. [$object, 'myCallbackMethod']
129
 *  - Objects implementing __invoke
130
 *  - Closure / anonymous functions
131
 *
132
 * PRADO can accept method names in PRADO namespace as well.
133
 * <code>
134
 * $component->OnClick = [$object, 'buttonClicked'];
135
 * // will cause the following function to be called
136
 * $object->buttonClicked($sender, param);
137
 *
138
 * // the method can also be expressed using the PRADO namespace format
139
 * $component->OnClick = [$object, 'MainContent.SubmitButton.buttonClicked'];
140
 * // will cause the following function to be called
141
 * $object->MainContent->SubmitButton->buttonClicked($sender, $param);
142
 *
143
 * // Closure as an event handler
144
 * $component->OnClick = function ($sender, $param) { ... };
145
 * </code
146
 *
147
 *
148
 * Global and Dynamic Events
149
 *
150
 * With the addition of behaviors, a more expansive event model is needed.  There
151
 * are two new event types (global and dynamic events) as well as a more comprehensive
152
 * behavior model that includes class wide behaviors.
153
 *
154
 * A global event is defined by all events whose name starts with 'fx'.
155
 * The event name is potentially a method name and is thus case-insensitive. All 'fx' events
156
 * are valid as the whole 'fx' event/method space is global in nature. Any object may patch into
157
 * any global event by defining that event as a method. Global events have priorities
158
 * just like 'on' events; so as to be able to order the event execution. Due to the
159
 * nature of all events which start with 'fx' being valid, in effect, every object
160
 * has every 'fx' global event. It is simply an issue of tapping into the desired
161
 * global event.
162
 *
163
 * A global event that starts with 'fx' can be called even if the object does not
164
 * implement the method of the global event.  A call to a non-existing 'fx' method
165
 * will, at minimal, function and return null.  If a method argument list has a first
166
 * parameter, it will be returned instead of null.  This allows filtering and chaining.
167
 * 'fx' methods do not automatically install and uninstall. To install and uninstall an
168
 * object's global event listeners, call the object's {@link listen} and
169
 * {@link unlisten} methods, respectively.  An object may auto-install its global event
170
 * during {@link __construct} by overriding {@link getAutoGlobalListen} and returning true.
171
 *
172
 * As of PHP version 5.3, nulled objects without code references will still continue to persist
173
 * in the global event queue because {@link __destruct} is not automatically called.  In the common
174
 * __destruct method, if an object is listening to global events, then {@link unlisten} is called.
175
 * {@link unlisten} is required to be manually called before an object is
176
 * left without references if it is currently listening to any global events. This includes
177
 * class wide behaviors.  This is corrected in PHP 7.4.0 with WeakReferences and {@link
178
 * TWeakCallableCollection}
179
 *
180
 * An object that contains a method that starts with 'fx' will have those functions
181
 * automatically receive those events of the same name after {@link listen} is called on the object.
182
 *
183
 * An object may listen to a global event without defining an 'fx' method of the same name by
184
 * adding an object method to the global event list.  For example
185
 * <code>
186
 * $component->fxGlobalCheck=$callback;
187
 * $component->fxGlobalCheck->add($callback);
188
 * $component->attachEventHandler('fxGlobalCheck', [$object, 'someMethod']);
189
 * </code>
190
 *
191
 *
192
 * Events between Objects and their behaviors, Dynamic Events
193
 *
194
 * An intra-object/behavior event is defined by methods that start with 'dy'.  Just as with
195
 * 'fx' global events, every object has every dynamic event.  Any call to a method that
196
 * starts with 'dy' will be handled, regardless of whether it is implemented.  These
197
 * events are for communicating with attached behaviors.
198
 *
199
 * Dynamic events can be used in a variety of ways.  They can be used to tell behaviors
200
 * when a non-behavior method is called.  Dynamic events could be used as data filters.
201
 * They could also be used to specify when a piece of code is to be run, eg. should the
202
 * loop process be performed on a particular piece of data.  In this way, some control
203
 * is handed to the behaviors over the process and/or data.
204
 *
205
 * If there are no handlers for an 'fx' or 'dy' event, it will return the first
206
 * parameter of the argument list.  If there are no arguments, these events
207
 * will return null.  If there are handlers an 'fx' method will be called directly
208
 * within the object.  Global 'fx' events are triggered by calling {@link raiseEvent}.
209
 * For dynamic events where there are behaviors that respond to the dynamic events, a
210
 * {@link TCallChain} is developed.  A call chain allows the behavior dynamic event
211
 * implementations to call further implementing behaviors within a chain.
212
 *
213
 * If an object implements {@link IDynamicMethods}, all global and object dynamic
214
 * events will be sent to {@link __dycall}.  In the case of global events, all
215
 * global events will trigger this method.  In the case of behaviors, all undefined
216
 * dynamic events  which are called will be passed through to this method.
217
 *
218
 *
219
 * Behaviors
220
 *
221
 * PRADO TComponent Behaviors is a method to extend a single component or a class
222
 * of components with new properties, methods, features, and fine control over the
223
 * owner object.  Behaviors can be attached to single objects or whole classes
224
 * (or interfaces, parents, and first level traits).
225
 *
226
 * There are two types of behaviors.  There are individual {@link IBehavior} and
227
 * there are class wide {IClassBehavior}.  IBehavior has one owner and IClassBehavior
228
 * can attach to multiple owners at the same time.  IClassBehavior is designed to be
229
 * stateless, like for specific filtering or addition of data.
230
 *
231
 * When a new class implements {@link IClassBehavior} or {@link IBehavior}, or extends
232
 * the PRADO implementations {@link TClassBehavior} and {@link TBehavior}, it may be
233
 * attached to a TComponent by calling the object's {@link attachBehavior}. The
234
 * behaviors associated name can then be used to {@link enableBehavior} or {@link
235
 * disableBehavior} the specific behavior.
236
 *
237
 * All behaviors may be turned on and off via {@link enableBehaviors} and
238
 * {@link disableBehaviors}, respectively.  To check if behaviors are on or off
239
 * a call to {@link getBehaviorsEnabled} will provide the variable.  By default,
240
 * a behavior's event handlers will be removed from events when disabled.
241
 *
242
 * Attaching and detaching whole sets of behaviors is done using
243
 * {@link attachBehaviors} and {@link detachBehaviors}.  {@link clearBehaviors}
244
 * removes all of an object's behaviors.
245
 *
246
 * {@link asa} returns a behavior of a specific name.  {@link isa} is the
247
 * behavior inclusive function that acts as the PHP operator {@link instanceof}.
248
 * A behavior could provide the functionality of a specific class thus causing
249
 * the host object to act similarly to a completely different class.  A behavior
250
 * would then implement {@link IInstanceCheck} to provide the identity of the
251
 * different class.
252
 *
253
 * IClassBehavior are similar to IBehavior except that the class behavior
254
 * attaches to multiple owners, like all the instances of a class.  A class behavior
255
 * will have the object upon which is being called be prepended to the parameter
256
 * list.  This way the object is known across the class behavior implementation.
257
 *
258
 * Class behaviors are attached using {@link attachClassBehavior} and detached
259
 * using {@link detachClassBehavior}.  Class behaviors are important in that
260
 * they will be applied to all new instances of a particular class and all listening
261
 * components as well.  Classes, Class Parents, Interfaces, and first level Traits
262
 * can be attached by class.
263
 * Class behaviors are default behaviors to new instances of a class in and are
264
 * received in {@link __construct}.  Detaching a class behavior will remove the
265
 * behavior from the default set of behaviors created for an object when the object
266
 * is instanced.
267
 *
268
 * Class behaviors are also added to all existing instances via the global 'fx'
269
 * event mechanism.  When a new class behavior is added, the event
270
 * {@link fxAttachClassBehavior} is raised and all existing instances that are
271
 * listening to this global event (primarily after {@link listen} is called)
272
 * will have this new behavior attached.  A similar process is used when
273
 * detaching class behaviors.  Any objects listening to the global 'fx' event
274
 * {@link fxDetachClassBehavior} will have a class behavior removed.
275
 *
276
 *
277
 * Dynamic Intra-Object Behavior Events
278
 *
279
 * Dynamic events start with 'dy'.  This mechanism is used to allow objects
280
 * to communicate with their behaviors directly.  The entire 'dy' event space
281
 * is valid.  All attached, enabled behaviors that implement a dynamic event
282
 * are called when the host object calls the dynamic event.  If there is no
283
 * implementation or behaviors, this returns null when no parameters are
284
 * supplied and will return the first parameter when there is at least one
285
 * parameter in the dynamic event.
286
 * <code>
287
 *	 null == $this->dyBehaviorEvent();
288
 *	 5 == $this->dyBehaviorEvent(5); //when no behaviors implement this dynamic event
289
 * </code>
290
 *
291
 * Dynamic events can be chained together within behaviors to allow for data
292
 * filtering. Dynamic events are implemented within behaviors by defining the
293
 * event as a method.
294
 * <code>
295
 * class TObjectBehavior extends TBehavior {
296
 *     public function dyBehaviorEvent($param1, $callchain) {
297
 *			//Do something, eg:  $param1 += $this->getOwner()->getNumber();
298
 *			return $callchain->dyBehaviorEvent($param1);
299
 *     }
300
 * }
301
 * </code>
302
 * This implementation of a behavior and dynamic event will flow through to the
303
 * next behavior implementing the dynamic event.  The first parameter is always
304
 * return when it is supplied.  Otherwise a dynamic event returns null.
305
 *
306
 * In the case of a class behavior, the object is also prepended to the dynamic
307
 * event.
308
 * <code>
309
 * class TObjectClassBehavior extends TClassBehavior {
310
 *     public function dyBehaviorEvent($hostobject, $param1, $callchain) {
311
 *			//Do something, eg:  $param1 += $hostobject->getNumber();
312
 *			return $callchain->dyBehaviorEvent($param1);
313
 *     }
314
 * }
315
 * </code>
316
 * When calling a dynamic event, only the parameters are passed.  The host object
317
 * and the call chain are built into the framework.
318
 *
319
 *
320
 * Global Event and Dynamic Event Catching
321
 *
322
 * Given that all global 'fx' events and dynamic 'dy' events are valid and
323
 * operational, there is a mechanism for catching events called that are not
324
 * implemented (similar to the built-in PHP method {@link __call}).  When
325
 * a dynamic or global event is called but a behavior does not implement it,
326
 * yet desires to know when an undefined dynamic event is run, the behavior
327
 * implements the interface {@link IDynamicMethods} and method {@link __dycall}.
328
 *
329
 * In the case of dynamic events, {@link __dycall} is supplied with the method
330
 * name and its parameters.  When a global event is raised, via {@link raiseEvent},
331
 * the method is the event name and the parameters are supplied.
332
 *
333
 * When implemented, this catch-all mechanism is called for event global event event
334
 * when implemented outside of a behavior.  Within a behavior, it will also be called
335
 * when the object to which the behavior is attached calls any unimplemented dynamic
336
 * event.  This is the fall-back mechanism for informing a class and/or behavior
337
 * of when an global and/or undefined dynamic event is executed.
338
 *
339
 * @author Qiang Xue <[email protected]>
340
 * @author Brad Anderson <[email protected]>
341
 * @since 3.0
342
 * @method void dyClone()
343
 * @method void dyWakeUp()
344
 * @method void dyListen(array $globalEvents)
345
 * @method void dyUnlisten(array $globalEvents)
346 194
 * @method string dyPreRaiseEvent(string $name, mixed $sender, \Prado\TEventParameter $param, null|numeric $responsetype, null|function $postfunction)
347
 * @method dyIntraRaiseEventTestHandler(callable $handler, mixed $sender, \Prado\TEventParameter $param, string $name)
348 194
 * @method bool dyIntraRaiseEventPostHandler(string $name, mixed $sender, \Prado\TEventParameter $param, callable $handler, $response)
349 38
 * @method array dyPostRaiseEvent(array $responses, string $name, mixed $sender, \Prado\TEventParameter $param, null|numeric $responsetype, null|function $postfunction)
350
 * @method string dyEvaluateExpressionFilter(string $statements)
351
 * @method string dyEvaluateStatementsFilter(string $statements)
352 194
 * @method dyCreatedOnTemplate(\Prado\TComponent $parent)
353 194
 * @method void dyAddParsedObject(\Prado\TComponent|string $object)
354 194
 * @method void dyAttachBehavior(string $name, IBaseBehavior $behavior)
355 194
 * @method void dyDetachBehavior(string $name, IBaseBehavior $behavior)
356
 * @method void dyEnableBehavior(string $name, IBaseBehavior $behavior)
357
 * @method void dyDisableBehavior(string $name, IBaseBehavior $behavior)
358 194
 * @method void dyEnableBehaviors()
359
 * @method void dyDisableBehaviors()
360
 */
361
class TComponent
362
{
363
	/**
364
	 * @var array event handler lists
365
	 */
366
	protected $_e = [];
367
368
	/**
369
	 * @var bool if listening is enabled.  Automatically turned on or off in
370
	 * constructor according to {@link getAutoGlobalListen}.  Default false, off
371
	 */
372
	protected $_listeningenabled = false;
373 183
374
	/**
375 183
	 * @var array static registered global event handler lists
376
	 */
377
	private static $_ue = [];
378
379
	/**
380
	 * @var bool if object behaviors are on or off.  default true, on
381
	 */
382
	protected $_behaviorsenabled = true;
383
384
	/**
385
	 * @var TPriorityMap list of object behaviors
386 620
	 */
387
	protected $_m;
388 620
389
	/**
390
	 * @var array static global class behaviors, these behaviors are added upon instantiation of a class
391 620
	 */
392
	private static $_um = [];
393
394
395
	/**
396
	 * @const string the name of the global {@link raiseEvent} listener
397
	 */
398
	public const GLOBAL_RAISE_EVENT_LISTENER = 'fxGlobalListener';
399 38
400
401 38
	/**
402
	 * The common __construct.
403
	 * If desired by the new object, this will auto install and listen to global event functions
404
	 * as defined by the object via 'fx' methods. This also attaches any predefined behaviors.
405
	 * This function installs all class behaviors in a class hierarchy from the deepest subclass
406
	 * through each parent to the top most class, TComponent.
407
	 */
408
	public function __construct()
409
	{
410
		if ($this->getAutoGlobalListen()) {
411 194
			$this->listen();
412
		}
413 194
414 194
		$classes = $this->getClassHierarchy(true);
415 194
		array_pop($classes);
416 192
		foreach ($classes as $class) {
417
			if (isset(self::$_um[$class])) {
418 194
				$this->attachBehaviors(self::$_um[$class], true);
419 194
			}
420
		}
421 1
	}
422
423
	/**
424
	 * The common __clone magic method from PHP's "clone".
425
	 * This reattaches the behaviors to the cloned object.
426
	 * IBehavior objects are cloned, IClassBehaviors are not.
427
	 * Clone object events are scrubbed of the old object behaviors' events.
428
	 * To finalize the behaviors, dyClone is raised.
429
	 * @since 4.2.3
430
	 */
431
	public function __clone()
432
	{
433
		foreach ($this->_e as $event => $handlers) {
434
			$this->_e[$event] = clone $handlers;
435
		}
436
		$behaviorArray = array_values(($this->_m !== null) ? $this->_m->toArray() : []);
437
		if (count($behaviorArray) && count($this->_e)) {
438
			$behaviorArray = array_combine(array_map('spl_object_id', $behaviorArray), $behaviorArray);
439 38
			foreach ($this->_e as $event => $handlers) {
440
				foreach ($handlers->toArray() as $handler) {
441 38
					$a = is_array($handler);
442
					if ($a && array_key_exists(spl_object_id($handler[0]), $behaviorArray) || !$a && array_key_exists(spl_object_id($handler), $behaviorArray)) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($a && array_key_exists(...ndler), $behaviorArray), Probably Intended Meaning: $a && (array_key_exists(...dler), $behaviorArray))
Loading history...
443
						$handlers->remove($handler);
444
					}
445 38
				}
446
			}
447 38
		}
448 38
		if ($this->_m !== null) {
449
			$behaviors = $this->_m;
450
			$this->_m = new TPriorityMap();
451 38
			foreach ($behaviors->getPriorities() as $priority) {
452 3
				foreach ($behaviors->itemsAtPriority($priority) as $name => $behavior) {
453 3
					if ($behavior instanceof IBehavior) {
454
						$behavior = clone $behavior;
455
					}
456 38
					$this->attachBehavior($name, $behavior, $priority);
457
				}
458 38
			}
459
		}
460 38
		$this->callBehaviorsMethod('dyClone', $return);
461
	}
462
463
	/**
464
	 * The common __wakeup magic method from PHP's "unserialize".
465
	 * This reattaches the behaviors to the reconstructed object.
466
	 * Any global class behaviors are used rather than their unserialized copy.
467
	 * Any global behaviors not found in the object will be added.
468
	 * To finalize the behaviors, dyWakeUp is raised.
469
	 * If a TModule needs to add events to an object during unserialization,
470
	 * the module can use a small IClassBehavior [implementing dyWakeUp]
471
	 * (adding the event[s]) attached to the class with {@link
472
	 * attachClassBehavior} prior to unserialization.
473
	 * @since 4.2.3
474
	 */
475
	public function __wakeup()
476 38
	{
477
		$classes = $this->getClassHierarchy(true);
478 38
		array_pop($classes);
479 3
		$classBehaviors = [];
480
		if ($this->_m !== null) {
481
			$behaviors = $this->_m;
482 38
			$this->_m = new TPriorityMap();
483
			foreach ($behaviors->getPriorities() as $priority) {
484 38
				foreach ($behaviors->itemsAtPriority($priority) as $name => $behavior) {
485 38
					if ($behavior instanceof IClassBehavior) {
486
						foreach ($classes as $class) {
487
							if (isset(self::$_um[$class]) && array_key_exists($name, self::$_um[$class])) {
488 38
								$behavior = self::$_um[$class][$name]->getBehavior();
489 3
								break;
490 3
							}
491
						}
492
					}
493 38
					$classBehaviors[$name] = $name;
494
					$this->attachBehavior($name, $behavior, $priority);
495 38
				}
496
			}
497 38
		}
498
		foreach ($classes as $class) {
499
			if (isset(self::$_um[$class])) {
500
				foreach (self::$_um[$class] as $name => $behavior) {
501
					if (!array_key_exists($name, $classBehaviors)) {
502
						$this->attachBehaviors([$name => $behavior], true);
503
					}
504 4
				}
505
			}
506 4
		}
507
		$this->callBehaviorsMethod('dyWakeUp', $return);
508
	}
509
510
511
	/**
512
	 * Tells TComponent whether or not to automatically listen to global events.
513
	 * Defaults to false because PHP variable cleanup is affected if this is true.
514
	 * When unsetting a variable that is listening to global events, {@link unlisten}
515
	 * must explicitly be called when cleaning variables allocation or else the global
516
	 * event registry will contain references to the old object. This is true for PHP 5.4
517
	 *
518
	 * Override this method by a subclass to change the setting.  When set to true, this
519
	 * will enable {@link __construct} to call {@link listen}.
520
	 *
521
	 * @return bool whether or not to auto listen to global events during {@link __construct}, default false
522
	 */
523
	public function getAutoGlobalListen()
524
	{
525
		return false;
526
	}
527
528
529
	/**
530
	 * The common __destruct
531
	 * When listening, this unlistens from the global event routines.  It also detaches
532
	 * all the behaviors so they can clean up, eg remove handlers.
533 211
	 *
534
	 * Prior to PHP 7.4, when listening, unlisten must be manually called for objects
535 211
	 * to destruct because circular references will prevent the __destruct process.
536 211
	 */
537 4
	public function __destruct()
538 4
	{
539 4
		if ($this->_listeningenabled) {
540
			$this->unlisten();
541
		}
542
		$this->clearBehaviors();
543
	}
544
545
546
	/**
547
	 * This utility function is a private array filter method.  The array values
548 4
	 * that start with 'fx' are filtered in.
549
	 * @param mixed $name
550
	 */
551
	private function filter_prado_fx($name)
552
	{
553 211
		return strncasecmp($name, 'fx', 2) === 0;
554 27
	}
555 27
556 27
557 24
	/**
558 3
	 * This returns an array of the class name and the names of all its parents.  The base object last,
559 3
	 * {@link TComponent}, and the deepest subclass is first.
560 2
	 * @param bool $lowercase optional should the names be all lowercase true/false
561
	 * @return string[] array of strings being the class hierarchy of $this.
562 24
	 */
563
	public function getClassHierarchy($lowercase = false)
564
	{
565 27
		static $_classhierarchy = [];
566 27
		$class = $this::class;
567
		if (isset($_classhierarchy[$class]) && isset($_classhierarchy[$class][$lowercase ? 1 : 0])) {
568
			return $_classhierarchy[$class][$lowercase ? 1 : 0];
569 8
		}
570 8
		$classes = [array_values(class_implements($class))];
571 8
		do {
572 3
			$classes[] = array_values(class_uses($class));
573
			$classes[] = [$class];
574 8
		} while ($class = get_parent_class($class));
575
		$classes = array_merge(...$classes);
576
		if ($lowercase) {
577
			$classes = array_map('strtolower', $classes);
578
		}
579
		$_classhierarchy[$class] ??= [];
580 211
		$_classhierarchy[$class][$lowercase ? 1 : 0] = $classes;
581 211
582 6
		return $classes;
583
	}
584 211
585
	/**
586
	 * This caches the 'fx' events for classes.
587
	 * @param object $class
588 4
	 * @return string[] fx events from a specific class
589 4
	 */
590
	protected function getClassFxEvents($class)
591
	{
592
		static $_classfx = [];
593
		$className = $class::class;
594
		if (isset($_classfx[$className])) {
595
			return $_classfx[$className];
596
		}
597
		$fx = array_filter(get_class_methods($class), [$this, 'filter_prado_fx']);
598
		$_classfx[$className] = $fx;
599
		return $fx;
600
	}
601
602
	/**
603
	 * This adds an object's fx event handlers into the global broadcaster to listen into any
604
	 * broadcast global events called through {@link raiseEvent}
605
	 *
606
	 * Behaviors may implement the function:
607
	 * <code>
608
	 *	public function dyListen($globalEvents[, ?TCallChain $chain = null]) {
609
	 * 		$this->listen($globalEvents); //eg
610
	 *      if ($chain)
611
	 *          $chain->dyUnlisten($globalEvents);
612
	 * }
613
	 * </code>
614
	 * to be executed when listen is called.  All attached behaviors are notified through dyListen.
615
	 *
616
	 * @return numeric the number of global events that were registered to the global event registry
0 ignored issues
show
Bug introduced by
The type Prado\numeric was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
617 95
	 */
618
	public function listen()
619 95
	{
620
		if ($this->_listeningenabled) {
621 84
			return;
622 25
		}
623
624 2
		$fx = $this->getClassFxEvents($this);
625 23
626
		foreach ($fx as $func) {
627 13
			$this->getEventHandlers($func)->add([$this, $func]);
628 13
		}
629 12
630
		if (is_a($this, IDynamicMethods::class)) {
631 13
			$this->attachEventHandler(TComponent::GLOBAL_RAISE_EVENT_LISTENER, [$this, '__dycall']);
632 14
			array_push($fx, TComponent::GLOBAL_RAISE_EVENT_LISTENER);
633
		}
634 3
635 3
		$this->_listeningenabled = true;
636 1
637
		$this->callBehaviorsMethod('dyListen', $return, $fx);
638 3
639 13
		return count($fx);
0 ignored issues
show
Bug Best Practice introduced by
The expression return count($fx) returns the type integer which is incompatible with the documented return type Prado\numeric.
Loading history...
640
	}
641 13
642 9
	/**
643 7
	 * this removes an object's fx events from the global broadcaster
644 4
	 *
645 4
	 * Behaviors may implement the function:
646 4
	 * <code>
647 4
	 *	public function dyUnlisten($globalEvents[, ?TCallChain $chain = null]) {
648
	 * 		$this->behaviorUnlisten(); //eg
649
	 *      if ($chain)
650
	 *          $chain->dyUnlisten($globalEvents);
651
	 * }
652 4
	 * </code>
653
	 * to be executed when listen is called.  All attached behaviors are notified through dyUnlisten.
654
	 *
655
	 * @return numeric the number of global events that were unregistered from the global event registry
656
	 */
657
	public function unlisten()
658
	{
659
		if (!$this->_listeningenabled) {
660
			return;
661
		}
662
663
		$fx = $this->getClassFxEvents($this);
664
665
		foreach ($fx as $func) {
666
			$this->detachEventHandler($func, [$this, $func]);
667
		}
668
669
		if (is_a($this, IDynamicMethods::class)) {
670 77
			$this->detachEventHandler(TComponent::GLOBAL_RAISE_EVENT_LISTENER, [$this, '__dycall']);
671
			array_push($fx, TComponent::GLOBAL_RAISE_EVENT_LISTENER);
672 77
		}
673 76
674 2
		$this->_listeningenabled = false;
675
676 76
		$this->callBehaviorsMethod('dyUnlisten', $return, $fx);
677 5
678 1
		return count($fx);
0 ignored issues
show
Bug Best Practice introduced by
The expression return count($fx) returns the type integer which is incompatible with the documented return type Prado\numeric.
Loading history...
679 1
	}
680
681 1
	/**
682 4
	 * Gets the state of listening to global events
683 3
	 * @return bool is Listening to global broadcast enabled
684 4
	 */
685 4
	public function getListeningToGlobalEvents()
686 4
	{
687 4
		return $this->_listeningenabled;
688 4
	}
689 4
690 4
691
	/**
692
	 * Calls a method.
693 4
	 * Do not call this method directly. This is a PHP magic method that we override
694 4
	 * to allow behaviors, dynamic events (intra-object/behavior events),
695
	 * undefined dynamic and global events, and
696
	 * to allow using the following syntax to call a property setter or getter.
697
	 * <code>
698 1
	 * $this->getPropertyName($value); // if there's a $this->getjsPropertyName() method
699 1
	 * $this->setPropertyName($value); // if there's a $this->setjsPropertyName() method
700
	 * </code>
701 1
	 *
702
	 * Additional object behaviors override class behaviors.
703
	 * dynamic and global events do not fail even if they aren't implemented.
704
	 * Any intra-object/behavior dynamic events that are not implemented by the behavior
705
	 * return the first function paramater or null when no parameters are specified.
706
	 *
707
	 * @param string $method method name that doesn't exist and is being called on the object
708
	 * @param mixed $args method parameters
709
	 * @throws TInvalidOperationException If the property is not defined or read-only or
710
	 * 		method is undefined
711
	 * @return mixed result of the method call, or false if 'fx' or 'dy' function but
712
	 *		is not found in the class, otherwise it runs
713
	 */
714
	public function __call($method, $args)
715
	{
716
		$getset = substr($method, 0, 3);
717 5
		if (($getset == 'get') || ($getset == 'set')) {
718
			$propname = substr($method, 3);
719 5
			$jsmethod = $getset . 'js' . $propname;
720 5
			if (method_exists($this, $jsmethod)) {
721 3
				if (count($args) > 0) {
722 2
					if ($args[0] && !($args[0] instanceof TJavaScriptString)) {
723 1
						$args[0] = new TJavaScriptString($args[0]);
724 1
					}
725 1
				}
726 1
				return $this->$jsmethod(...$args);
727 1
			}
728 1
729 1
			if (($getset == 'set') && method_exists($this, 'getjs' . $propname)) {
730 1
				throw new TInvalidOperationException('component_property_readonly', $this::class, $method);
731 1
			}
732
		}
733 1
		if ($this->callBehaviorsMethod($method, $return, ...$args)) {
734 1
			return $return;
735 1
		}
736
737
		// don't throw an exception for __magicMethods() or any other weird methods natively implemented by php
738
		if (!method_exists($this, $method)) {
739 1
			throw new TApplicationException('component_method_undefined', $this::class, $method);
740
		}
741
	}
742
743
744
	/**
745
	 * Returns a property value or an event handler list by property or event name.
746
	 * Do not call this method. This is a PHP magic method that we override
747
	 * to allow using the following syntax to read a property:
748
	 * <code>
749
	 * $value = $component->PropertyName;
750
	 * $value = $component->jsPropertyName; // return JavaScript literal
751
	 * </code>
752
	 * and to obtain the event handler list for an event,
753 3
	 * <code>
754
	 * $eventHandlerList = $component->EventName;
755 3
	 * </code>
756 2
	 * This will also return the global event handler list when specifing an 'fx'
757 3
	 * event,
758 1
	 * <code>
759 2
	 * $globalEventHandlerList = $component->fxEventName;
760 2
	 * </code>
761 2
	 * When behaviors are enabled, this will return the behavior of a specific
762 1
	 * name, a property of a behavior, or an object 'on' event defined by the behavior.
763 2
	 * @param string $name the property name or the event name
764 2
	 * @throws TInvalidOperationException if the property/event is not defined.
765 1
	 * @return mixed the property value or the event handler list as {@link TWeakCallableCollection}
766
	 */
767 2
	public function __get($name)
768 2
	{
769 2
		if (method_exists($this, $getter = 'get' . $name)) {
770 2
			// getting a property
771 2
			return $this->$getter();
772
		} elseif (method_exists($this, $jsgetter = 'getjs' . $name)) {
773
			// getting a javascript property
774 2
			return (string) $this->$jsgetter();
775 2
		} elseif (strncasecmp($name, 'on', 2) === 0 && method_exists($this, $name)) {
776
			// getting an event (handler list)
777
			$name = strtolower($name);
778 1
			if (!isset($this->_e[$name])) {
779 1
				$this->_e[$name] = new TWeakCallableCollection();
780
			}
781 3
			return $this->_e[$name];
782
		} elseif (strncasecmp($name, 'fx', 2) === 0) {
783
			// getting a global event (handler list)
784
			$name = strtolower($name);
785
			if (!isset(self::$_ue[$name])) {
786
				self::$_ue[$name] = new TWeakCallableCollection();
787
			}
788
			return self::$_ue[$name];
789
		} elseif ($this->getBehaviorsEnabled()) {
790 1
			// getting a behavior property/event (handler list)
791
			if (isset($this->_m[$name])) {
792 1
				return $this->_m[$name];
793
			} elseif ($this->_m !== null) {
794
				foreach ($this->_m->toArray() as $behavior) {
795
					if ($behavior->getEnabled() && (property_exists($behavior, $name) || $behavior->canGetProperty($name) || $behavior->hasEvent($name))) {
796
						return $behavior->$name;
797
					}
798
				}
799
			}
800
		}
801
		throw new TInvalidOperationException('component_property_undefined', $this::class, $name);
802
	}
803
804 9
	/**
805
	 * Sets value of a component property.
806 9
	 * Do not call this method. This is a PHP magic method that we override
807 6
	 * to allow using the following syntax to set a property or attach an event handler.
808 8
	 * <code>
809 2
	 *    $this->PropertyName = $value;
810 2
	 *    $this->jsPropertyName = $value; // $value will be treated as a JavaScript literal
811 2
	 *    $this->EventName = $handler;
812
	 *    $this->fxEventName = $handler; //global event listener
813
	 *    $this->EventName = function($sender, $param) {...};
814
	 * </code>
815 8
	 * When behaviors are enabled, this will also set a behaviors properties and events.
816
	 * @param string $name the property name or event name
817
	 * @param mixed $value the property value or event handler
818
	 * @throws TInvalidOperationException If the property is not defined or read-only.
819
	 */
820
	public function __set($name, $value)
821
	{
822
		if (method_exists($this, $setter = 'set' . $name)) {
823
			if (strncasecmp($name, 'js', 2) === 0 && $value && !($value instanceof TJavaScriptLiteral)) {
824
				$value = new TJavaScriptLiteral($value);
825
			}
826
			return $this->$setter($value);
827 11
		} elseif (method_exists($this, $jssetter = 'setjs' . $name)) {
828
			if ($value && !($value instanceof TJavaScriptString)) {
829 11
				$value = new TJavaScriptString($value);
830 8
			}
831 7
			return $this->$jssetter($value);
832 2
		} elseif ((strncasecmp($name, 'on', 2) === 0 && method_exists($this, $name)) || strncasecmp($name, 'fx', 2) === 0) {
833 2
			return $this->attachEventHandler($name, $value);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->attachEventHandler($name, $value) targeting Prado\TComponent::attachEventHandler() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

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

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

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

Loading history...
834 2
		} elseif ($this->_m !== null && $this->_m->getCount() > 0 && $this->getBehaviorsEnabled()) {
835
			$sets = 0;
836
			foreach ($this->_m->toArray() as $behavior) {
837
				if ($behavior->getEnabled() && (property_exists($behavior, $name) || $behavior->canSetProperty($name) || $behavior->hasEvent($name))) {
838 7
					$behavior->$name = $value;
839
					$sets++;
840
				}
841
			}
842
			if ($sets) {
843
				return $value;
844
			}
845
		}
846
847
		if (method_exists($this, 'get' . $name) || method_exists($this, 'getjs' . $name)) {
848
			throw new TInvalidOperationException('component_property_readonly', $this::class, $name);
849
		} else {
850
			throw new TInvalidOperationException('component_property_undefined', $this::class, $name);
851 4
		}
852
	}
853 4
854 4
	/**
855 4
	 * Checks if a property value is null, there are no events in the object
856
	 * event list or global event list registered under the name, and, if
857 4
	 * behaviors are enabled,
858
	 * Do not call this method. This is a PHP magic method that we override
859
	 * to allow using isset() to detect if a component property is set or not.
860
	 * This also works for global events.  When behaviors are enabled, it
861
	 * will check for a behavior of the specified name, and also check
862
	 * the behavior for events and properties.
863
	 * @param string $name the property name or the event name
864
	 * @since 3.2.3
865
	 */
866
	public function __isset($name)
867
	{
868
		if (method_exists($this, $getter = 'get' . $name)) {
869
			return $this->$getter() !== null;
870 2
		} elseif (method_exists($this, $jsgetter = 'getjs' . $name)) {
871
			return $this->$jsgetter() !== null;
872 2
		} elseif (strncasecmp($name, 'on', 2) === 0 && method_exists($this, $name)) {
873 2
			$name = strtolower($name);
874 1
			return isset($this->_e[$name]) && $this->_e[$name]->getCount();
875
		} elseif (strncasecmp($name, 'fx', 2) === 0) {
876 2
			$name = strtolower($name);
877 2
			return isset(self::$_ue[$name]) && self::$_ue[$name]->getCount();
878
		} elseif ($this->_m !== null && $this->_m->getCount() > 0 && $this->getBehaviorsEnabled()) {
879 2
			if (isset($this->_m[$name])) {
880 2
				return true;
881
			}
882
			foreach ($this->_m->toArray() as $behavior) {
883
				if ($behavior->getEnabled() && (property_exists($behavior, $name) || $behavior->canGetProperty($name) || $behavior->hasEvent($name))) {
884
					return isset($behavior->$name);
885
				}
886
			}
887
		}
888
		return false;
889
	}
890
891
	/**
892
	 * Sets a component property to be null.  Clears the object or global
893
	 * events. When enabled, loops through all behaviors and unsets the
894 176
	 * property or event.
895
	 * Do not call this method. This is a PHP magic method that we override
896 176
	 * to allow using unset() to set a component property to be null.
897 176
	 * @param string $name the property name or the event name
898 3
	 * @throws TInvalidOperationException if the property is read only.
899 3
	 * @since 3.2.3
900 3
	 */
901 3
	public function __unset($name)
902
	{
903
		if (method_exists($this, $setter = 'set' . $name)) {
904
			$this->$setter(null);
905 3
		} elseif (method_exists($this, $jssetter = 'setjs' . $name)) {
906
			$this->$jssetter(null);
907
		} elseif (strncasecmp($name, 'on', 2) === 0 && method_exists($this, $name)) {
908
			$this->_e[strtolower($name)]->clear();
909
		} elseif (strncasecmp($name, 'fx', 2) === 0) {
910
			$this->getEventHandlers($name)->remove([$this, $name]);
911
		} elseif ($this->_m !== null && $this->_m->getCount() > 0 && $this->getBehaviorsEnabled()) {
912
			if (isset($this->_m[$name])) {
913
				$this->detachBehavior($name);
914
			} else {
915 211
				$unset = 0;
916
				foreach ($this->_m->toArray() as $behavior) {
917 211
					if ($behavior->getEnabled()) {
918 211
						unset($behavior->$name);
919 211
						$unset++;
920
					}
921 178
				}
922 54
				if (!$unset && method_exists($this, 'get' . $name)) {
923 177
					throw new TInvalidOperationException('component_property_readonly', $this::class, $name);
924 3
				}
925 3
			}
926 3
		} elseif (method_exists($this, 'get' . $name)) {
927
			throw new TInvalidOperationException('component_property_readonly', $this::class, $name);
928
		}
929
	}
930
931 176
	/**
932
	 * Determines whether a property is defined.
933
	 * A property is defined if there is a getter or setter method
934
	 * defined in the class. Note, property names are case-insensitive.
935
	 * @param string $name the property name
936
	 * @return bool whether the property is defined
937
	 */
938
	public function hasProperty($name)
939
	{
940
		return $this->canGetProperty($name) || $this->canSetProperty($name);
941 92
	}
942
943 92
	/**
944 63
	 * Determines whether a property can be read.
945 63
	 * A property can be read if the class has a getter method
946 14
	 * for the property name. Note, property name is case-insensitive.
947
	 * This also checks for getjs.  When enabled, it loops through all
948 63
	 * active behaviors for the get property when undefined by the object.
949 38
	 * @param string $name the property name
950 38
	 * @return bool whether the property can be read
951 38
	 */
952 5
	public function canGetProperty($name)
953
	{
954 38
		if (method_exists($this, 'get' . $name) || method_exists($this, 'getjs' . $name)) {
955 6
			return true;
956 6
		} elseif ($this->_m !== null && $this->getBehaviorsEnabled()) {
957 6
			foreach ($this->_m->toArray() as $behavior) {
958 6
				if ($behavior->getEnabled() && $behavior->canGetProperty($name)) {
959
					return true;
960
				}
961
			}
962 4
		}
963
		return false;
964
	}
965
966
	/**
967
	 * Determines whether a property can be set.
968
	 * A property can be written if the class has a setter method
969
	 * for the property name. Note, property name is case-insensitive.
970
	 * This also checks for setjs.  When enabled, it loops through all
971
	 * active behaviors for the set property when undefined by the object.
972
	 * @param string $name the property name
973
	 * @return bool whether the property can be written
974
	 */
975
	public function canSetProperty($name)
976
	{
977
		if (method_exists($this, 'set' . $name) || method_exists($this, 'setjs' . $name)) {
978
			return true;
979
		} elseif ($this->_m !== null && $this->getBehaviorsEnabled()) {
980
			foreach ($this->_m->toArray() as $behavior) {
981
				if ($behavior->getEnabled() && $behavior->canSetProperty($name)) {
982
					return true;
983
				}
984
			}
985
		}
986
		return false;
987
	}
988
989
	/**
990
	 * Evaluates a property path.
991
	 * A property path is a sequence of property names concatenated by '.' character.
992
	 * For example, 'Parent.Page' refers to the 'Page' property of the component's
993
	 * 'Parent' property value (which should be a component also).
994
	 * When a property is not defined by an object, this also loops through all
995
	 * active behaviors of the object.
996
	 * @param string $path property path
997
	 * @return mixed the property path value
998
	 */
999
	public function getSubProperty($path)
1000
	{
1001
		$object = $this;
1002
		foreach (explode('.', $path) as $property) {
1003
			$object = $object->$property;
1004
		}
1005
		return $object;
1006
	}
1007
1008
	/**
1009
	 * Sets a value to a property path.
1010 44
	 * A property path is a sequence of property names concatenated by '.' character.
1011
	 * For example, 'Parent.Page' refers to the 'Page' property of the component's
1012 44
	 * 'Parent' property value (which should be a component also).
1013 44
	 * When a property is not defined by an object, this also loops through all
1014
	 * active behaviors of the object.
1015
	 * @param string $path property path
1016
	 * @param mixed $value the property path value
1017
	 */
1018
	public function setSubProperty($path, $value)
1019
	{
1020
		$object = $this;
1021
		if (($pos = strrpos($path, '.')) === false) {
1022
			$property = $path;
1023
		} else {
1024
			$object = $this->getSubProperty(substr($path, 0, $pos));
1025 38
			$property = substr($path, $pos + 1);
1026
		}
1027 38
		$object->$property = $value;
1028
	}
1029 38
1030 38
	/**
1031 1
	 * Calls a method on a component's behaviors.  When the method is a
1032
	 * dynamic event, it is raised with all the behaviors.  When a class implements
1033
	 * a dynamic event (eg. for patching), the class can customize raising the
1034 2
	 * dynamic event with the classes behaviors using this method.
1035
	 * Dynamic [dy] and global [fx] events call {@link __dycall} when $this
1036
	 * implements IDynamicMethods.  Finally, this catches all unexecuted
1037
	 * Dynamic [dy] and global [fx] events and returns the first $args parameter;
1038
	 * acting as a passthrough (filter) of the first $args parameter. In dy/fx methods,
1039
	 * there can be no $args parameters, the first parameter used as a pass through
1040
	 * filter, or act as a return variable with the first $args parameter being
1041
	 * the default return value.
1042
	 * @param string $method The method being called or dynamic/global event being raised.
1043
	 * @param mixed &$return The return value.
1044
	 * @param array $args The arguments to the method being called.
1045
	 * @return bool Was the method handled.
1046
	 * @since 4.2.3
1047
	 */
1048
	public function callBehaviorsMethod($method, &$return, ...$args): bool
1049
	{
1050
		if ($this->_m !== null && $this->getBehaviorsEnabled()) {
1051
			if (strncasecmp($method, 'dy', 2) === 0) {
1052
				if ($callchain = $this->getCallChain($method, ...$args)) {
1053
					$return = $callchain->call(...$args);
1054
					return true;
1055
				}
1056
			} else {
1057
				foreach ($this->_m->toArray() as $behavior) {
1058
					if ($behavior->getEnabled() && method_exists($behavior, $method)) {
1059
						if ($behavior instanceof IClassBehavior) {
1060
							array_unshift($args, $this);
1061
						}
1062
						$return = $behavior->$method(...$args);
1063
						return true;
1064
					}
1065
				}
1066
			}
1067
		}
1068
		if (strncasecmp($method, 'dy', 2) === 0 || strncasecmp($method, 'fx', 2) === 0) {
1069
			if ($this instanceof IDynamicMethods) {
1070
				$return = $this->__dycall($method, $args);
0 ignored issues
show
Bug introduced by
The method __dycall() does not exist on Prado\TComponent. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1070
				/** @scrutinizer ignore-call */ 
1071
    $return = $this->__dycall($method, $args);
Loading history...
1071
				return true;
1072
			}
1073
			$return = $args[0] ?? null;
1074
			return true;
1075
		}
1076
		return false;
1077
	}
1078
1079
	/**
1080
	 * This gets the chain of methods implemented by attached and enabled behaviors.
1081
	 * This method disregards the {behaviorsEnabled
1082
	 * @param string $method The name of the behaviors method being chained.
1083
	 * @param array $args The arguments to the behaviors method being chained.
1084
	 * @return ?TCallChain The chain of methods implemented by behaviors or null when
1085
	 *   there are no methods to call.
1086
	 */
1087
	protected function getCallChain($method, ...$args): ?TCallChain
1088
	{
1089
		$classArgs = $callchain = null;
1090
		foreach ($this->_m->toArray() as $behavior) {
1091
			if ($behavior->getEnabled() && (method_exists($behavior, $method) || ($behavior instanceof IDynamicMethods))) {
1092
				if ($classArgs === null) {
1093
					$classArgs = $args;
1094
					array_unshift($classArgs, $this);
1095
				}
1096
				if (!$callchain) {
1097
					$callchain = new TCallChain($method);
1098
				}
1099
				$callchain->addCall([$behavior, $method], ($behavior instanceof IClassBehavior) ? $classArgs : $args);
1100
			}
1101
		}
1102
		return $callchain;
1103
	}
1104
1105
	/**
1106
	 * Determines whether a method is defined. When behaviors are enabled, this
1107
	 * will loop through all enabled behaviors checking for the method as well.
1108
	 * Nested behaviors within behaviors are not supported but the nested behavior can
1109 182
	 * affect the primary behavior like any behavior affects their owner.
1110
	 * Note, method name are case-insensitive.
1111 182
	 * @param string $name the method name
1112 182
	 * @return bool
1113 1
	 * @since 4.2.2
1114 1
	 */
1115
	public function hasMethod($name)
1116
	{
1117 182
		if (method_exists($this, $name) || strncasecmp($name, 'fx', 2) === 0 || strncasecmp($name, 'dy', 2) === 0) {
1118 181
			return true;
1119
		} elseif ($this->_m !== null && $this->getBehaviorsEnabled()) {
1120
			foreach ($this->_m->toArray() as $behavior) {
1121 182
				//method_exists($behavior, $name) rather than $behavior->hasMethod($name) b/c only one layer is supported, @4.2.2
1122 182
				if ($behavior->getEnabled() && method_exists($behavior, $name)) {
1123
					return true;
1124 182
				}
1125
			}
1126 182
		}
1127 60
		return false;
1128 60
	}
1129 60
1130 1
	/**
1131 1
	 * Determines whether an event is defined.
1132
	 * An event is defined if the class has a method whose name is the event name
1133 60
	 * prefixed with 'on', 'fx', or 'dy'.
1134 60
	 * Every object responds to every 'fx' and 'dy' event as they are in a universally
1135 59
	 * accepted event space.  'on' event must be declared by the object.
1136
	 * When enabled, this will loop through all active behaviors for 'on' events
1137
	 * defined by the behavior.
1138
	 * Note, event name is case-insensitive.
1139 59
	 * @param string $name the event name
1140
	 * @return bool
1141
	 */
1142
	public function hasEvent($name)
1143
	{
1144
		if ((strncasecmp($name, 'on', 2) === 0 && method_exists($this, $name)) || strncasecmp($name, 'fx', 2) === 0 || strncasecmp($name, 'dy', 2) === 0) {
1145
			return true;
1146
		} elseif ($this->_m !== null && $this->getBehaviorsEnabled()) {
1147
			foreach ($this->_m->toArray() as $behavior) {
1148
				if ($behavior->getEnabled() && $behavior->hasEvent($name)) {
1149
					return true;
1150
				}
1151
			}
1152
		}
1153
		return false;
1154
	}
1155 59
1156 59
	/**
1157 59
	 * Checks if an event has any handlers.  This function also checks through all
1158
	 * the behaviors for 'on' events when behaviors are enabled.
1159
	 * 'dy' dynamic events are not handled by this function.
1160 59
	 * @param string $name the event name
1161 1
	 * @return bool whether an event has been attached one or several handlers
1162 1
	 */
1163
	public function hasEventHandler($name)
1164 59
	{
1165 59
		$name = strtolower($name);
1166 1
		if (strncasecmp($name, 'fx', 2) === 0) {
1167
			return isset(self::$_ue[$name]) && self::$_ue[$name]->getCount() > 0;
1168 59
		} else {
1169
			if (isset($this->_e[$name]) && $this->_e[$name]->getCount() > 0) {
1170
				return true;
1171 59
			} elseif ($this->_m !== null && $this->getBehaviorsEnabled()) {
1172
				foreach ($this->_m->toArray() as $behavior) {
1173
					if ($behavior->getEnabled() && $behavior->hasEventHandler($name)) {
1174
						return true;
1175
					}
1176
				}
1177
			}
1178 59
		}
1179
		return false;
1180 59
	}
1181 1
1182
	/**
1183
	 * Returns the list of attached event handlers for an 'on' or 'fx' event.   This function also
1184 59
	 * checks through all the behaviors for 'on' event lists when behaviors are enabled.
1185 2
	 * @param mixed $name
1186
	 * @throws TInvalidOperationException if the event is not defined
1187 58
	 * @return TWeakCallableCollection list of attached event handlers for an event
1188
	 */
1189
	public function getEventHandlers($name)
1190 59
	{
1191 60
		if (strncasecmp($name, 'on', 2) === 0 && method_exists($this, $name)) {
1192
			$name = strtolower($name);
1193
			if (!isset($this->_e[$name])) {
1194 173
				$this->_e[$name] = new TWeakCallableCollection();
1195 1
			}
1196
			return $this->_e[$name];
1197
		} elseif (strncasecmp($name, 'fx', 2) === 0) {
1198 182
			$name = strtolower($name);
1199 181
			if (!isset(self::$_ue[$name])) {
1200
				self::$_ue[$name] = new TWeakCallableCollection();
1201
			}
1202 182
			return self::$_ue[$name];
1203
		} elseif ($this->_m !== null && $this->getBehaviorsEnabled()) {
1204 182
			foreach ($this->_m->toArray() as $behavior) {
1205
				if ($behavior->getEnabled() && $behavior->hasEvent($name)) {
1206
					return $behavior->getEventHandlers($name);
1207
				}
1208
			}
1209
		}
1210
		throw new TInvalidOperationException('component_event_undefined', $this::class, $name);
1211
	}
1212
1213
	/**
1214
	 * Attaches an event handler to an event.
1215
	 *
1216
	 * The handler must be a valid PHP callback, i.e., a string referring to
1217
	 * a global function name, or an array containing two elements with
1218
	 * the first element being an object and the second element a method name
1219
	 * of the object. In Prado, you can also use method path to refer to
1220
	 * an event handler. For example, array($object,'Parent.buttonClicked')
1221
	 * uses a method path that refers to the method $object->Parent->buttonClicked(...).
1222
	 *
1223
	 * The event handler must be of the following signature,
1224 2
	 * <code>
1225
	 * function handlerName($sender, $param) {}
1226 2
	 * function handlerName($sender, $param, $name) {}
1227
	 * </code>
1228 2
	 * where $sender represents the object that raises the event,
1229
	 * and $param is the event parameter. $name refers to the event name
1230
	 * being handled.
1231 2
	 *
1232 1
	 * This is a convenient method to add an event handler.
1233 1
	 * It is equivalent to {@link getEventHandlers}($name)->add($handler).
1234
	 * For complete management of event handlers, use {@link getEventHandlers}
1235
	 * to get the event handler list first, and then do various
1236
	 * {@link TWeakCallableCollection} operations to append, insert or remove
1237
	 * event handlers. You may also do these operations like
1238
	 * getting and setting properties, e.g.,
1239
	 * <code>
1240
	 *    $component->OnClick[] = array($object,'buttonClicked');
1241
	 *    $component->OnClick->insertAt(0,array($object,'buttonClicked'));
1242
	 *    $component->OnClick[] = function ($sender, $param) { ... };
1243
	 * </code>
1244
	 * which are equivalent to the following
1245
	 * <code>
1246
	 *    $component->getEventHandlers('OnClick')->add(array($object,'buttonClicked'));
1247
	 *    $component->getEventHandlers('OnClick')->insertAt(0,array($object,'buttonClicked'));
1248
	 * </code>
1249
	 *
1250
	 * Due to the nature of {@link getEventHandlers}, any active behaviors defining
1251
	 * new 'on' events, this method will pass through to the behavior transparently.
1252
	 *
1253
	 * @param string $name the event name
1254 2
	 * @param callable $handler the event handler
1255
	 * @param null|numeric $priority the priority of the handler, defaults to null which translates into the
1256 2
	 * default priority of 10.0 within {@link TWeakCallableCollection}
1257
	 * @throws TInvalidOperationException if the event does not exist
1258 2
	 */
1259 2
	public function attachEventHandler($name, $handler, $priority = null)
1260
	{
1261
		$this->getEventHandlers($name)->add($handler, $priority);
1262 2
	}
1263 2
1264 2
	/**
1265 1
	 * Detaches an existing event handler.
1266 1
	 * This method is the opposite of {@link attachEventHandler}.  It will detach
1267
	 * any 'on' events defined by an objects active behaviors as well.
1268
	 * @param string $name event name
1269
	 * @param callable $handler the event handler to be removed
1270
	 * @param null|false|numeric $priority the priority of the handler, defaults to false which translates
1271
	 * to an item of any priority within {@link TWeakCallableCollection}; null means the default priority
1272
	 * @return bool if the removal is successful
1273
	 */
1274
	public function detachEventHandler($name, $handler, $priority = false)
1275
	{
1276
		if ($this->hasEventHandler($name)) {
1277
			try {
1278
				$this->getEventHandlers($name)->remove($handler, $priority);
0 ignored issues
show
Bug introduced by
It seems like $priority can also be of type Prado\numeric; however, parameter $priority of Prado\Collections\TWeakC...bleCollection::remove() does only seem to accept boolean|double|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1278
				$this->getEventHandlers($name)->remove($handler, /** @scrutinizer ignore-type */ $priority);
Loading history...
1279
				return true;
1280
			} catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
1281
			}
1282
		}
1283
		return false;
1284
	}
1285
1286
	/**
1287
	 * Raises an event.  This raises both inter-object 'on' events and global 'fx' events.
1288
	 * This method represents the happening of an event and will
1289 1
	 * invoke all attached event handlers for the event in {@link TWeakCallableCollection} order.
1290
	 * This method does not handle intra-object/behavior dynamic 'dy' events.
1291 1
	 *
1292 1
	 * There are ways to handle event responses.  By default {@link EVENT_RESULT_FILTER},
1293 1
	 * all event responses are stored in an array, filtered for null responses, and returned.
1294
	 * If {@link EVENT_RESULT_ALL} is specified, all returned results will be stored along
1295
	 * with the sender and param in an array
1296
	 * <code>
1297
	 * 		$result[] = array('sender'=>$sender,'param'=>$param,'response'=>$response);
1298
	 * </code>
1299
	 *
1300
	 * If {@link EVENT_RESULT_FEED_FORWARD} is specified, then each handler result is then
1301
	 * fed forward as the parameters for the next event.  This allows for events to filter data
1302
	 * directly by affecting the event parameters
1303
	 *
1304
	 * If a callable function is set in the response type or the post function filter is specified then the
1305
	 * result of each called event handler is post processed by the callable function.  Used in
1306
	 * combination with {@link EVENT_RESULT_FEED_FORWARD}, any event (and its result) can be chained.
1307
	 *
1308
	 * When raising a global 'fx' event, registered handlers in the global event list for
1309
	 * {@link GLOBAL_RAISE_EVENT_LISTENER} are always added into the set of event handlers.  In this way,
1310
	 * these global events are always raised for every global 'fx' event.  The registered handlers for global
1311
	 * raiseEvent events have priorities.  Any registered global raiseEvent event handlers with a priority less than zero
1312 1
	 * are added before the main event handlers being raised and any registered global raiseEvent event handlers
1313
	 * with a priority equal or greater than zero are added after the main event handlers being raised.  In this way
1314 1
	 * all {@link GLOBAL_RAISE_EVENT_LISTENER} handlers are always called for every raised 'fx' event.
1315 1
	 *
1316
	 * Behaviors may implement the following functions with TBehaviors:
1317
	 * <code>
1318
	 *	public function dyPreRaiseEvent($name, $sender, $param, $responsetype, $postfunction[, TCallChain $chain) {
1319
	 *      ....  //  Your logic
1320
	 *  	return $chain->dyPreRaiseEvent($name, $sender, $param, $responsetype, $postfunction); //eg, the event name may be filtered/changed
1321
	 *  }
1322
	 *	public function dyIntraRaiseEventTestHandler($handler, $sender, $param, $name, TCallChain $chain) {
1323
	 *      ....  //  Your logic
1324
	 *  	return $chain->dyIntraRaiseEventTestHandler($handler, $sender, $param, $name); //should this particular handler be executed?  true/false
1325
	 *  }
1326 6
	 *  public function dyIntraRaiseEventPostHandler($name, $sender, $param, $handler, $response, TCallChain $chain) {
1327
	 *      ....  //  Your logic
1328 6
	 *		return $chain->dyIntraRaiseEventPostHandler($name, $sender, $param, $handler, $response); //contains the per handler response
1329 6
	 *  }
1330
	 *  public function dyPostRaiseEvent($responses, $name, $sender, $param,$ responsetype, $postfunction, TCallChain $chain) {
1331 1
	 *      ....  //  Your logic
1332
	 *		return $chain->dyPostRaiseEvent($responses, $name, $sender, $param,$ responsetype, $postfunction);
1333
	 *  }
1334
	 * </code>
1335
	 * to be executed when raiseEvent is called.  The 'intra' dynamic events are called per handler in
1336
	 * the handler loop.  TClassBehaviors prepend the object being raised.
1337
	 *
1338
	 * dyPreRaiseEvent has the effect of being able to change the event being raised.  This intra
1339
	 * object/behavior event returns the name of the desired event to be raised.  It will pass through
1340
	 * if no dynamic event is specified, or if the original event name is returned.
1341
	 * dyIntraRaiseEventTestHandler returns true or false as to whether a specific handler should be
1342 6
	 * called for a specific raised event (and associated event arguments)
1343
	 * dyIntraRaiseEventPostHandler does not return anything.  This allows behaviors to access the results
1344 6
	 * of an event handler in the per handler loop.
1345 6
	 * dyPostRaiseEvent returns the responses.  This allows for any post processing of the event
1346
	 * results from the sum of all event handlers
1347 1
	 *
1348
	 * When handling a catch-all {@link __dycall}, the method name is the name of the event
1349
	 * and the parameters are the sender, the param, and then the name of the event.
1350
	 *
1351
	 * @param string $name the event name
1352
	 * @param mixed $sender the event sender object
1353
	 * @param \Prado\TEventParameter $param the event parameter
1354
	 * @param null|numeric $responsetype how the results of the event are tabulated.  default: {@link EVENT_RESULT_FILTER}  The default filters out
1355
	 *		null responses. optional
1356
	 * @param null|callable $postfunction any per handler filtering of the response result needed is passed through
1357
	 *		this if not null. default: null.  optional
1358
	 * @throws TInvalidOperationException if the event is undefined
1359
	 * @throws TInvalidDataValueException If an event handler is invalid
1360
	 * @return mixed the results of the event
1361
	 */
1362
	public function raiseEvent($name, $sender, $param, $responsetype = null, $postfunction = null)
1363
	{
1364
		$p = $param;
0 ignored issues
show
Unused Code introduced by
The assignment to $p is dead and can be removed.
Loading history...
1365
		if (is_callable($responsetype)) {
1366
			$postfunction = $responsetype;
1367
			$responsetype = null;
1368 6
		}
1369
1370 6
		if ($responsetype === null) {
1371 5
			$responsetype = TEventResults::EVENT_RESULT_FILTER;
1372
		}
1373 6
1374
		$name = strtolower($name);
1375
		$responses = [];
1376
1377 6
		$this->callBehaviorsMethod('dyPreRaiseEvent', $name, $name, $sender, $param, $responsetype, $postfunction);
1378
1379
		if ($this->hasEventHandler($name) || $this->hasEventHandler(TComponent::GLOBAL_RAISE_EVENT_LISTENER)) {
1380 6
			$handlers = $this->getEventHandlers($name);
1381 6
			$handlerArray = $handlers->toArray();
1382 1
			if (strncasecmp($name, 'fx', 2) === 0 && $this->hasEventHandler(TComponent::GLOBAL_RAISE_EVENT_LISTENER)) {
1383
				$globalhandlers = $this->getEventHandlers(TComponent::GLOBAL_RAISE_EVENT_LISTENER);
1384 6
				$handlerArray = array_merge($globalhandlers->toArrayBelowPriority(0), $handlerArray, $globalhandlers->toArrayAbovePriority(0));
0 ignored issues
show
Bug introduced by
0 of type integer is incompatible with the type Prado\Collections\numeric expected by parameter $priority of Prado\Collections\TWeakC...:toArrayAbovePriority(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1384
				$handlerArray = array_merge($globalhandlers->toArrayBelowPriority(0), $handlerArray, $globalhandlers->toArrayAbovePriority(/** @scrutinizer ignore-type */ 0));
Loading history...
Bug introduced by
0 of type integer is incompatible with the type Prado\Collections\numeric expected by parameter $priority of Prado\Collections\TWeakC...:toArrayBelowPriority(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1384
				$handlerArray = array_merge($globalhandlers->toArrayBelowPriority(/** @scrutinizer ignore-type */ 0), $handlerArray, $globalhandlers->toArrayAbovePriority(0));
Loading history...
1385 6
			}
1386
			$response = null;
1387 6
			foreach ($handlerArray as $handler) {
1388 1
				$this->callBehaviorsMethod('dyIntraRaiseEventTestHandler', $return, $handler, $sender, $param, $name);
1389
				if ($return === false) {
1390 6
					continue;
1391 6
				}
1392 6
1393 6
				if (is_string($handler)) {
1394
					if (($pos = strrpos($handler, '.')) !== false) {
1395
						$object = $this->getSubProperty(substr($handler, 0, $pos));
1396
						$method = substr($handler, $pos + 1);
1397
						if (method_exists($object, $method) || strncasecmp($method, 'dy', 2) === 0 || strncasecmp($method, 'fx', 2) === 0) {
1398
							if ($method == '__dycall') {
1399
								$response = $object->__dycall($name, [$sender, $param, $name]);
1400
							} else {
1401
								$response = $object->$method($sender, $param, $name);
1402
							}
1403
						} else {
1404
							throw new TInvalidDataValueException('component_eventhandler_invalid', $this::class, $name, $handler);
1405
						}
1406
					} else {
1407
						$response = call_user_func($handler, $sender, $param, $name);
1408
					}
1409 6
				} elseif (is_callable($handler, true)) {
1410
					[$object, $method] = $handler;
1411 6
					if (is_string($object)) {
1412 5
						$response = call_user_func($handler, $sender, $param, $name);
1413
					} else {
1414 6
						if (($pos = strrpos($method, '.')) !== false) {
1415
							$object = $object->getSubProperty(substr($method, 0, $pos));
1416
							$method = substr($method, $pos + 1);
1417
						}
1418 6
						if (method_exists($object, $method) || strncasecmp($method, 'dy', 2) === 0 || strncasecmp($method, 'fx', 2) === 0) {
1419 6
							if ($method == '__dycall') {
1420
								$response = $object->__dycall($name, [$sender, $param, $name]);
1421
							} else {
1422 6
								$response = $object->$method($sender, $param, $name);
1423
							}
1424
						} else {
1425 6
							throw new TInvalidDataValueException('component_eventhandler_invalid', $this::class, $name, $handler[1]);
1426 6
						}
1427 6
					}
1428 6
				} else {
1429 6
					throw new TInvalidDataValueException('component_eventhandler_invalid', $this::class, $name, gettype($handler));
1430
				}
1431
1432
				$this->callBehaviorsMethod('dyIntraRaiseEventPostHandler', $return, $name, $sender, $param, $handler, $response);
1433
1434
				if ($postfunction) {
1435
					$response = call_user_func_array($postfunction, [$sender, $param, $this, $response]);
1436
				}
1437
1438
				if ($responsetype & TEventResults::EVENT_RESULT_ALL) {
1439 8
					$responses[] = ['sender' => $sender, 'param' => $param, 'response' => $response];
1440
				} else {
1441 8
					$responses[] = $response;
1442
				}
1443
1444
				if ($response !== null && ($responsetype & TEventResults::EVENT_RESULT_FEED_FORWARD)) {
1445
					$param = $response;
1446
				}
1447
			}
1448
		} elseif (strncasecmp($name, 'on', 2) === 0 && !$this->hasEvent($name)) {
1449
			throw new TInvalidOperationException('component_event_undefined', $this::class, $name);
1450
		}
1451
1452
		if ($responsetype & TEventResults::EVENT_RESULT_FILTER) {
1453
			$responses = array_filter($responses);
1454
		}
1455
1456
		$this->callBehaviorsMethod('dyPostRaiseEvent', $responses, $responses, $name, $sender, $param, $responsetype, $postfunction);
1457
1458
		return $responses;
1459
	}
1460
1461
	/**
1462
	 * Evaluates a PHP expression in the context of this control.
1463 6
	 *
1464
	 * Behaviors may implement the function:
1465 6
	 * <code>
1466 6
	 *	public function dyEvaluateExpressionFilter($expression, TCallChain $chain) {
1467
	 * 		return $chain->dyEvaluateExpressionFilter(str_replace('foo', 'bar', $expression)); //example
1468 6
	 * }
1469 6
	 * </code>
1470 6
	 * to be executed when evaluateExpression is called.  All attached behaviors are notified through
1471 2
	 * dyEvaluateExpressionFilter.  The chaining is important in this function due to the filtering
1472
	 * pass-through effect.
1473
	 *
1474 6
	 * @param string $expression PHP expression
1475 6
	 * @throws TInvalidOperationException if the expression is invalid
1476 1
	 * @return mixed the expression result
1477
	 */
1478 6
	public function evaluateExpression($expression)
1479 6
	{
1480
		$this->callBehaviorsMethod('dyEvaluateExpressionFilter', $expression, $expression);
1481
		try {
1482
			return eval("return $expression;");
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
1483 6
		} catch (\Exception $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Exception $e) is not 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...
1484
			throw new TInvalidOperationException('component_expression_invalid', $this::class, $expression, $e->getMessage());
1485
		}
1486
	}
1487
1488
	/**
1489
	 * Evaluates a list of PHP statements.
1490
	 *
1491
	 * Behaviors may implement the function:
1492
	 * <code>
1493
	 *	public function dyEvaluateStatementsFilter($statements, TCallChain $chain) {
1494 37
	 * 		return $chain->dyEvaluateStatementsFilter(str_replace('foo', 'bar', $statements)); //example
1495
	 * }
1496 37
	 * </code>
1497 6
	 * to be executed when evaluateStatements is called.  All attached behaviors are notified through
1498 4
	 * dyEvaluateStatementsFilter.  The chaining is important in this function due to the filtering
1499
	 * pass-through effect.
1500 6
	 *
1501
	 * @param string $statements PHP statements
1502
	 * @throws TInvalidOperationException if the statements are invalid
1503 37
	 * @return string content echoed or printed by the PHP statements
1504
	 */
1505
	public function evaluateStatements($statements)
1506
	{
1507
		$this->callBehaviorsMethod('dyEvaluateStatementsFilter', $statements, $statements);
1508
		try {
1509
			ob_start();
1510
			if (eval($statements) === false) {
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
1511
				throw new \Exception('');
1512
			}
1513 1
			$content = ob_get_contents();
1514
			ob_end_clean();
1515 1
			return $content;
1516 1
		} catch (\Exception $e) {
1517 1
			throw new TInvalidOperationException('component_statements_invalid', $this::class, $statements, $e->getMessage());
1518
		}
1519
	}
1520 1
1521
	/**
1522
	 * This method is invoked after the component is instantiated by a template.
1523
	 * When this method is invoked, the component's properties have been initialized.
1524 1
	 * The default implementation of this method will invoke
1525
	 * the potential parent component's {@link addParsedObject}.
1526
	 * This method can be overridden.
1527
	 *
1528
	 * Behaviors may implement the function:
1529
	 * <code>
1530 1
	 *	public function dyCreatedOnTemplate($parent, TCallChain $chain) {
1531
	 * 		return $chain->dyCreatedOnTemplate($parent); //example
1532 1
	 *  }
1533 1
	 * </code>
1534 1
	 * to be executed when createdOnTemplate is called.  All attached behaviors are notified through
1535
	 * dyCreatedOnTemplate.
1536 1
	 *
1537
	 * @param \Prado\TComponent $parent potential parent of this control
1538 1
	 * @see addParsedObject
1539
	 */
1540
	public function createdOnTemplate($parent)
1541
	{
1542
		$this->callBehaviorsMethod('dyCreatedOnTemplate', $parent, $parent);
1543
		$parent->addParsedObject($this);
1544
	}
1545
1546
	/**
1547
	 * Processes an object that is created during parsing template.
1548
	 * The object can be either a component or a static text string.
1549
	 * This method can be overridden to customize the handling of newly created objects in template.
1550
	 * Only framework developers and control developers should use this method.
1551
	 *
1552
	 * Behaviors may implement the function:
1553
	 * <code>
1554
	 *	public function dyAddParsedObject($object, TCallChain $chain) {
1555
	 *      return $chain-> dyAddParsedObject($object);
1556
	 *  }
1557
	 * </code>
1558
	 * to be executed when addParsedObject is called.  All attached behaviors are notified through
1559
	 * dyAddParsedObject.
1560
	 *
1561 27
	 * @param \Prado\TComponent|string $object text string or component parsed and instantiated in template
1562
	 * @see createdOnTemplate
1563 27
	 */
1564 3
	public function addParsedObject($object)
1565
	{
1566 27
		$this->callBehaviorsMethod('dyAddParsedObject', $return, $object);
1567 1
	}
1568
1569 27
	/**
1570 26
	 *This is the method registered for all instanced objects should a class behavior be added after
1571
	 * the class is instanced.  Only when the class to which the behavior is being added is in this
1572 27
	 * object's class hierarchy, via {@link getClassHierarchy}, is the behavior added to this instance.
1573 27
	 * @param mixed $sender the application
1574
	 * @param TClassBehaviorEventParameter $param
1575 27
	 * @since 3.2.3
1576 27
	 */
1577 27
	public function fxAttachClassBehavior($sender, $param)
1578 27
	{
1579
		if ($this->isa($param->getClass())) {
1580
			if (($behavior = $param->getBehavior()) instanceof IBehavior) {
1581
				$behavior = clone $behavior;
1582
			}
1583
			return $this->attachBehavior($param->getName(), $behavior, $param->getPriority());
1584
		}
1585
	}
1586
1587
	/**
1588
	 *	This is the method registered for all instanced objects should a class behavior be removed after
1589
	 * the class is instanced.  Only when the class to which the behavior is being added is in this
1590
	 * object's class hierarchy, via {@link getClassHierarchy}, is the behavior removed from this instance.
1591
	 * @param mixed $sender the application
1592
	 * @param TClassBehaviorEventParameter $param
1593
	 * @since 3.2.3
1594
	 */
1595
	public function fxDetachClassBehavior($sender, $param)
1596
	{
1597
		if ($this->isa($param->getClass())) {
1598 18
			return $this->detachBehavior($param->getName(), $param->getPriority());
1599
		}
1600 18
	}
1601 18
1602 18
	/**
1603 18
	 * instanceBehavior is an internal method that takes a Behavior Object, a class name, or array of
1604 18
	 * ['class' => 'MyBehavior', 'property1' => 'Value1'...] and creates a Behavior in return. eg.
1605 18
	 * <code>
1606
	 *		$b = $this->instanceBehavior('MyBehavior');
1607
	 * 		$b = $this->instanceBehavior(['class' => 'MyBehavior', 'property1' => 'Value1']);
1608
	 * 		$b = $this->instanceBehavior(new MyBehavior);
1609
	 * </code>
1610
	 * If the behavior is an array, the key IBaseBehavior::CONFIG_KEY is stripped and used to initialize
1611
	 * the behavior.
1612
	 *
1613
	 * @param array|IBaseBehavior|string $behavior string, Behavior, or array of ['class' => 'MyBehavior', 'property1' => 'Value1' ...].
1614
	 * @throws TInvalidDataTypeException if the behavior is not an {@link IBaseBehavior}
1615
	 * @return IBaseBehavior&TComponent an instance of $behavior or $behavior itself
1616
	 * @since 4.2.0
1617
	 */
1618
	protected static function instanceBehavior($behavior)
1619
	{
1620
		$config = null;
1621 8
		$isArray = false;
1622
		$init = false;
1623 8
		if (is_string($behavior) || (($isArray = is_array($behavior)) && isset($behavior['class']))) {
1624 8
			if ($isArray && array_key_exists(IBaseBehavior::CONFIG_KEY, $behavior)) {
0 ignored issues
show
Bug introduced by
It seems like $behavior can also be of type string; however, parameter $array of array_key_exists() does only seem to accept ArrayObject|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1624
			if ($isArray && array_key_exists(IBaseBehavior::CONFIG_KEY, /** @scrutinizer ignore-type */ $behavior)) {
Loading history...
1625 8
				$config = $behavior[IBaseBehavior::CONFIG_KEY];
1626
				unset($behavior[IBaseBehavior::CONFIG_KEY]);
1627 8
			}
1628
			$behavior = Prado::createComponent($behavior);
1629
			$init = true;
1630
		}
1631
		if (!($behavior instanceof IBaseBehavior)) {
1632
			throw new TInvalidDataTypeException('component_not_a_behavior', $behavior::class);
1633
		}
1634
		if ($init) {
1635
			$behavior->init($config);
1636
		}
1637
		return $behavior;
1638
	}
1639
1640
1641 8
	/**
1642
	 *	This will add a class behavior to all classes instanced (that are listening) and future newly instanced objects.
1643 8
	 * This registers the behavior for future instances and pushes the changes to all the instances that are listening as well.
1644 8
	 * The universal class behaviors are stored in an inverted stack with the latest class behavior being at the first position in the array.
1645 8
	 * This is done so class behaviors are added last first.
1646
	 * @param string $name name the key of the class behavior
1647 8
	 * @param object|string $behavior class behavior or name of the object behavior per instance
1648
	 * @param null|array|IBaseBehavior|string $class string of class or class on which to attach this behavior.  Defaults to null which will error
1649
	 *	but more important, if this is on PHP 5.3 it will use Late Static Binding to derive the class
1650
	 * it should extend.
1651
	 * <code>
1652
	 *   TPanel::attachClassBehavior('javascripts', new TJsPanelClassBehavior());
1653
	 *   TApplication::attachClassBehavior('jpegize', \Prado\Util\Behaviors\TJPEGizeAssetBehavior::class, \Prado\Web\TFileAsset::class);
1654
	 * </code>
1655
	 * An array is used to initialize values of the behavior. eg. ['class' => '\\MyBehavior', 'property' => 'value'].
1656
	 * @param null|numeric $priority priority of behavior, default: null the default
1657
	 *  priority of the {@link TWeakCallableCollection}  Optional.
1658
	 * @throws TInvalidOperationException if the class behavior is being added to a
1659
	 *  {@link TComponent}; due to recursion.
1660
	 * @throws TInvalidOperationException if the class behavior is already defined
1661
	 * @return array|object the behavior if its an IClassBehavior and an array of all
1662
	 * behaviors that have been attached from 'fxAttachClassBehavior' when the Class
1663
	 * Behavior being attached is a per instance IBaseBehavior.
1664
	 * @since 3.2.3
1665
	 */
1666
	public static function attachClassBehavior($name, $behavior, $class = null, $priority = null)
1667
	{
1668
		if (!$class) {
1669
			$class = get_called_class();
1670
		}
1671
		if (!$class) {
1672
			throw new TInvalidOperationException('component_no_class_provided_nor_late_binding');
1673
		}
1674
1675
		if (!is_string($name)) {
0 ignored issues
show
introduced by
The condition is_string($name) is always true.
Loading history...
1676 16
			$name = $name::class;
1677
		}
1678 16
		$class = strtolower($class);
1679 16
		if ($class === strtolower(TComponent::class)) {
1680 16
			throw new TInvalidOperationException('component_no_tcomponent_class_behaviors');
1681 16
		}
1682 16
		if (empty(self::$_um[$class])) {
1683
			self::$_um[$class] = [];
1684 1
		}
1685
		if (isset(self::$_um[$class][$name])) {
1686 2
			throw new TInvalidOperationException('component_class_behavior_defined', $class, $name);
1687
		}
1688
		$behaviorObject = self::instanceBehavior($behavior);
1689
		$behaviorObject->setName($name);
1690
		$isClassBehavior = $behaviorObject instanceof \Prado\Util\IClassBehavior;
1691
		$param = new TClassBehaviorEventParameter($class, $name, $isClassBehavior ? $behaviorObject : $behavior, $priority);
0 ignored issues
show
Bug introduced by
It seems like $isClassBehavior ? $behaviorObject : $behavior can also be of type string; however, parameter $behavior of Prado\Util\TClassBehavio...arameter::__construct() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1691
		$param = new TClassBehaviorEventParameter($class, $name, /** @scrutinizer ignore-type */ $isClassBehavior ? $behaviorObject : $behavior, $priority);
Loading history...
1692
		self::$_um[$class] = [$name => $param] + self::$_um[$class];
1693
		$results = $behaviorObject->raiseEvent('fxAttachClassBehavior', null, $param);
0 ignored issues
show
Bug introduced by
The method raiseEvent() does not exist on Prado\Util\IBaseBehavior. It seems like you code against a sub-type of said class. However, the method does not exist in Prado\Util\IBehavior or Prado\Util\IClassBehavior. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1693
		/** @scrutinizer ignore-call */ 
1694
  $results = $behaviorObject->raiseEvent('fxAttachClassBehavior', null, $param);
Loading history...
1694
		return $isClassBehavior ? $behaviorObject : $results;
1695
	}
1696
1697
	/**
1698
	 *	This will remove a behavior from a class.  It unregisters it from future instances and
1699
	 * pulls the changes from all the instances that are listening as well.
1700
	 * PHP 5.3 uses Late Static Binding to derive the static class upon which this method is called.
1701
	 * @param string $name the key of the class behavior
1702
	 * @param string $class class on which to attach this behavior.  Defaults to null.
1703
	 * @param null|false|numeric $priority priority: false is any priority, null is default
1704 16
	 *		{@link TWeakCallableCollection} priority, and numeric is a specific priority.
1705
	 * @throws TInvalidOperationException if the the class cannot be derived from Late Static Binding and is not
1706 16
	 * not supplied as a parameter.
1707 16
	 * @return null|array|object the behavior if its an IClassBehavior and an array of all behaviors
1708 16
	 * that have been detached from 'fxDetachClassBehavior' when the Class Behavior being
1709 16
	 * attached is a per instance IBehavior.  Null if no behavior of $name to detach.
1710 16
	 * @since 3.2.3
1711
	 */
1712 1
	public static function detachClassBehavior($name, $class = null, $priority = false)
1713
	{
1714 2
		if (!$class) {
1715
			$class = get_called_class();
1716
		}
1717
		if (!$class) {
1718
			throw new TInvalidOperationException('component_no_class_provided_nor_late_binding');
1719
		}
1720
1721
		$class = strtolower($class);
1722 5
		if (!is_string($name)) {
0 ignored issues
show
introduced by
The condition is_string($name) is always true.
Loading history...
1723
			$name = $name::class;
1724 5
		}
1725 5
		if (empty(self::$_um[$class]) || !isset(self::$_um[$class][$name])) {
1726 5
			return null;
1727 5
		}
1728 5
		$param = self::$_um[$class][$name];
1729
		$behavior = $param->getBehavior();
1730
		$behaviorObject = self::instanceBehavior($behavior);
1731
		$behaviorObject->setName($name);
1732
		$isClassBehavior = $behaviorObject instanceof IClassBehavior;
1733
		unset(self::$_um[$class][$name]);
1734
		$results = $behaviorObject->raiseEvent('fxDetachClassBehavior', null, $param);
1735
		return $isClassBehavior ? $behaviorObject : $results;
1736
	}
1737
1738 5
	/**
1739
	 * Returns the named behavior object.
1740 5
	 * The name 'asa' stands for 'as a'.
1741 5
	 * @param string $behaviorname the behavior name
1742
	 * @return object the behavior object, or null if the behavior does not exist
1743 5
	 * @since 3.2.3
1744 5
	 */
1745
	public function asa($behaviorname)
1746 5
	{
1747 5
		return $this->_m[$behaviorname] ?? null;
1748
	}
1749 5
1750 5
	/**
1751
	 * Returns whether or not the object or any of the behaviors are of a particular class.
1752 5
	 * The name 'isa' stands for 'is a'.  This first checks if $this is an instanceof the class.
1753
	 * It then checks each Behavior.  If a behavior implements {@link IInstanceCheck},
1754
	 * then the behavior can determine what it is an instanceof.  If this behavior function returns true,
1755
	 * then this method returns true.  If the behavior instance checking function returns false,
1756
	 * then no further checking is performed as it is assumed to be correct.
1757
	 *
1758
	 * If the behavior instance check function returns nothing or null or the behavior
1759
	 * doesn't implement the {@link IInstanceCheck} interface, then the default instanceof occurs.
1760
	 * The default isa behavior is to check if the behavior is an instanceof the class.
1761
	 *
1762
	 * The behavior {@link IInstanceCheck} is to allow a behavior to have the host object
1763
	 * act as a completely different object.
1764
	 *
1765
	 * @param mixed|string $class class or string
1766
	 * @return bool whether or not the object or a behavior is an instance of a particular class
1767
	 * @since 3.2.3
1768
	 */
1769
	public function isa($class)
1770
	{
1771
		if ($this instanceof $class) {
1772
			return true;
1773
		}
1774
		if ($this->_m !== null && $this->getBehaviorsEnabled()) {
1775
			foreach ($this->_m->toArray() as $behavior) {
1776
				if (!$behavior->getEnabled()) {
1777
					continue;
1778
				}
1779
1780
				$check = null;
1781
				if (($behavior->isa(\Prado\Util\IInstanceCheck::class)) && $check = $behavior->isinstanceof($class, $this)) {
1782
					return true;
1783
				}
1784
				if ($check === null && ($behavior->isa($class))) {
1785
					return true;
1786
				}
1787
			}
1788
		}
1789
		return false;
1790
	}
1791
1792
	/**
1793
	 * Returns all the behaviors attached to the TComponent.  IBaseBehavior[s] may
1794
	 * be attached but not {@link IBaseBehavior::getEnabled Enabled}.
1795
	 *
1796
	 * @return array all the behaviors attached to the TComponent
1797
	 * @since 4.2.2
1798
	 */
1799
	public function getBehaviors()
1800
	{
1801
		return isset($this->_m) ? $this->_m->toArray() : [];
1802
	}
1803
1804
	/**
1805
	 * Attaches a list of behaviors to the component.
1806
	 * Each behavior is indexed by its name and should be an instance of
1807
	 * {@link IBaseBehavior}, a string specifying the behavior class, or a
1808
	 * {@link TClassBehaviorEventParameter}.
1809
	 * @param array $behaviors list of behaviors to be attached to the component
1810
	 * @param bool $cloneIBehavior Should IBehavior be cloned before attaching.
1811
	 *   Default is false.
1812
	 * @since 3.2.3
1813
	 */
1814
	public function attachBehaviors($behaviors, bool $cloneIBehavior = false)
1815
	{
1816
		foreach ($behaviors as $name => $behavior) {
1817
			if ($behavior instanceof TClassBehaviorEventParameter) {
1818
				$paramBehavior = $behavior->getBehavior();
1819
				if ($cloneIBehavior && ($paramBehavior instanceof IBehavior)) {
1820
					$paramBehavior = clone $paramBehavior;
1821
				}
1822
				$this->attachBehavior($behavior->getName(), $paramBehavior, $behavior->getPriority());
1823
			} else {
1824
				if ($cloneIBehavior && ($behavior instanceof IBehavior)) {
1825
					$behavior = clone $behavior;
1826
				}
1827
				$this->attachBehavior($name, $behavior);
1828
			}
1829
		}
1830
	}
1831
1832
	/**
1833
	 * Detaches select behaviors from the component.
1834
	 * Each behavior is indexed by its name and should be an instance of
1835
	 * {@link IBaseBehavior}, a string specifying the behavior class, or a
1836
	 * {@link TClassBehaviorEventParameter}.
1837
	 * @param array $behaviors list of behaviors to be detached from the component
1838
	 * @since 3.2.3
1839
	 */
1840
	public function detachBehaviors($behaviors)
1841
	{
1842
		if ($this->_m !== null) {
1843
			foreach ($behaviors as $name => $behavior) {
1844
				if ($behavior instanceof TClassBehaviorEventParameter) {
1845
					$this->detachBehavior($behavior->getName(), $behavior->getPriority());
1846
				} else {
1847
					$this->detachBehavior(is_string($behavior) ? $behavior : $name);
1848
				}
1849
			}
1850
		}
1851
	}
1852
1853
	/**
1854
	 * Detaches all behaviors from the component.
1855
	 * @since 3.2.3
1856
	 */
1857
	public function clearBehaviors()
1858
	{
1859
		if ($this->_m !== null) {
1860
			foreach ($this->_m->getKeys() as $name) {
1861
				$this->detachBehavior($name);
1862
			}
1863
			$this->_m = null;
1864
		}
1865
	}
1866
1867
	/**
1868
	 * Attaches a behavior to this component.
1869
	 * This method will create the behavior object based on the given
1870
	 * configuration. After that, the behavior object will be initialized
1871
	 * by calling its {@link IBaseBehavior::attach} method.
1872
	 *
1873
	 * Already attached behaviors may implement the function:
1874
	 * <code>
1875
	 *	public function dyAttachBehavior($name,$behavior[, ?TCallChain $chain = null]) {
1876
	 *      if ($chain)
1877
	 *          return $chain->dyDetachBehavior($name, $behavior);
1878
	 *  }
1879
	 * </code>
1880
	 * to be executed when attachBehavior is called.  All attached behaviors are notified through
1881
	 * dyAttachBehavior.
1882
	 *
1883
	 * @param string $name the behavior's name. It should uniquely identify this behavior.
1884
	 * @param array|IBaseBehavior|string $behavior the behavior configuration. This is the name of the Behavior Class
1885
	 * instanced by {@link PradoBase::createComponent}, or is a Behavior, or is an array of
1886
	 * ['class'=>'TBehavior' property1='value 1' property2='value2'...] with the class and properties
1887
	 * with values.
1888
	 * @param null|numeric $priority
1889
	 * @return IBaseBehavior the behavior object
1890
	 * @since 3.2.3
1891
	 */
1892
	public function attachBehavior($name, $behavior, $priority = null)
1893
	{
1894
		if ($this->_m && isset($this->_m[$name])) {
1895
			$this->detachBehavior($name);
1896
		}
1897
		$behavior = self::instanceBehavior($behavior);
1898
		if ($this->_m === null) {
1899
			$this->_m = new TPriorityMap();
1900
		}
1901
		$this->_m->add($name, $behavior, $priority);
1902
		$behavior->setName($name);
1903
		$behavior->attach($this);
1904
		$this->callBehaviorsMethod('dyAttachBehavior', $return, $name, $behavior);
1905
		return $behavior;
1906
	}
1907
1908
	/**
1909
	 * Detaches a behavior from the component.
1910
	 * The behavior's {@link IBaseBehavior::detach} method will be invoked.
1911
	 *
1912
	 * Behaviors may implement the function:
1913
	 * <code>
1914
	 *	public function dyDetachBehavior($name, $behavior[, ?TCallChain $chain = null]) {
1915
	 *      if ($chain)
1916
	 *          return $chain->dyDetachBehavior($name, $behavior);
1917
	 *  }
1918
	 * </code>
1919
	 * to be executed when detachBehavior is called.  All attached behaviors are notified through
1920
	 * dyDetachBehavior.
1921
	 *
1922
	 * @param string $name the behavior's name. It uniquely identifies the behavior.
1923
	 * @param false|numeric $priority the behavior's priority. This defaults to false, which is any priority.
1924
	 * @return null|IBaseBehavior the detached behavior. Null if the behavior does not exist.
1925
	 * @since 3.2.3
1926
	 */
1927
	public function detachBehavior($name, $priority = false)
1928
	{
1929
		if ($this->_m != null && ($behavior = $this->_m->itemAt($name, $priority))) {
1930
			$this->callBehaviorsMethod('dyDetachBehavior', $return, $name, $behavior);
1931
			$behavior->detach($this);
1932
			$this->_m->remove($name, $priority);
1933
			return $behavior;
1934
		}
1935
		return null;
1936
	}
1937
1938
	/**
1939
	 * Enables all behaviors attached to this component independent of the behaviors
1940
	 *
1941
	 * Behaviors may implement the function:
1942
	 * <code>
1943
	 *	public function dyEnableBehaviors([?TCallChain $chain = null]) {
1944
	 *      if ($chain)
1945
	 *          return $chain->dyEnableBehaviors();
1946
	 *  }
1947
	 * </code>
1948
	 * to be executed when enableBehaviors is called.  All attached behaviors are notified through
1949
	 * dyEnableBehaviors.
1950
	 * @since 3.2.3
1951
	 */
1952
	public function enableBehaviors()
1953
	{
1954
		if (!$this->_behaviorsenabled) {
1955
			$this->_behaviorsenabled = true;
1956
			$this->callBehaviorsMethod('dyEnableBehaviors', $return);
1957
		}
1958
	}
1959
1960
	/**
1961
	 * Disables all behaviors attached to this component independent of the behaviors
1962
	 *
1963
	 * Behaviors may implement the function:
1964
	 * <code>
1965
	 *	public function dyDisableBehaviors([?TCallChain $chain = null]) {
1966
	 *      if ($chain)
1967
	 *          return $chain->dyDisableBehaviors();
1968
	 *  }
1969
	 * </code>
1970
	 * to be executed when disableBehaviors is called.  All attached behaviors are notified through
1971
	 * dyDisableBehaviors.
1972
	 * @since 3.2.3
1973
	 */
1974
	public function disableBehaviors()
1975
	{
1976
		if ($this->_behaviorsenabled) {
1977
			$callchain = $this->getCallChain('dyDisableBehaviors');
1978
			$this->_behaviorsenabled = false;
1979
			if ($callchain) { // normal dynamic events won't work because behaviors are disabled.
1980
				$callchain->call();
1981
			}
1982
		}
1983
	}
1984
1985
1986
	/**
1987
	 * Returns if all the behaviors are turned on or off for the object.
1988
	 * @return bool whether or not all behaviors are enabled (true) or not (false)
1989
	 * @since 3.2.3
1990
	 */
1991
	public function getBehaviorsEnabled()
1992
	{
1993
		return $this->_behaviorsenabled;
1994
	}
1995
1996
	/**
1997
	 * Enables an attached object behavior.  This cannot enable or disable whole class behaviors.
1998
	 * A behavior is only effective when it is enabled.
1999
	 * A behavior is enabled when first attached.
2000
	 *
2001
	 * Behaviors may implement the function:
2002
	 * <code>
2003
	 *	public function dyEnableBehavior($name, $behavior[, ?TCallChain $chain = null]) {
2004
	 *      if ($chain)
2005
	 *          return $chain->dyEnableBehavior($name, $behavior);
2006
	 *  }
2007
	 * </code>
2008
	 * to be executed when enableBehavior is called.  All attached behaviors are notified through
2009
	 * dyEnableBehavior.
2010
	 *
2011
	 * @param string $name the behavior's name. It uniquely identifies the behavior.
2012
	 * @return bool Was the behavior found and enabled.
2013
	 * @since 3.2.3
2014
	 */
2015
	public function enableBehavior($name): bool
2016
	{
2017
		if ($this->_m != null && isset($this->_m[$name])) {
2018
			$behavior = $this->_m[$name];
2019
			if ($behavior->getEnabled() === false) {
2020
				$behavior->setEnabled(true);
2021
				$this->callBehaviorsMethod('dyEnableBehavior', $return, $name, $behavior);
2022
			}
2023
			return true;
2024
		}
2025
		return false;
2026
	}
2027
2028
	/**
2029
	 * Disables an attached behavior.  This cannot enable or disable whole class behaviors.
2030
	 * A behavior is only effective when it is enabled.
2031
	 *
2032
	 * Behaviors may implement the function:
2033
	 * <code>
2034
	 *	public function dyDisableBehavior($name, $behavior[, ?TCallChain $chain = null]) {
2035
	 *      if ($chain)
2036
	 *          return $chain->dyDisableBehavior($name, $behavior);
2037
	 *  }
2038
	 * </code>
2039
	 * to be executed when disableBehavior is called.  All attached behaviors are notified through
2040
	 * dyDisableBehavior.
2041
	 *
2042
	 * @param string $name the behavior's name. It uniquely identifies the behavior.
2043
	 * @return bool Was the behavior found and disabled.
2044
	 * @since 3.2.3
2045
	 */
2046
	public function disableBehavior($name): bool
2047
	{
2048
		if ($this->_m != null && isset($this->_m[$name])) {
2049
			$behavior = $this->_m[$name];
2050
			if ($behavior->getEnabled() === true) {
2051
				$behavior->setEnabled(false);
2052
				$this->callBehaviorsMethod('dyDisableBehavior', $return, $name, $behavior);
2053
			}
2054
			return true;
2055
		}
2056
		return false;
2057
	}
2058
2059
	/**
2060
	 * Returns an array with the names of all variables of that object that should be serialized.
2061
	 * Do not call this method. This is a PHP magic method that will be called automatically
2062
	 * prior to any serialization.
2063
	 */
2064
	public function __sleep()
2065
	{
2066
		$a = (array) $this;
2067
		$a = array_keys($a);
2068
		$exprops = [];
2069
		$this->_getZappableSleepProps($exprops);
2070
		return array_diff($a, $exprops);
2071
	}
2072
2073
	/**
2074
	 * Returns an array with the names of all variables of this object that should NOT be serialized
2075
	 * because their value is the default one or useless to be cached for the next page loads.
2076
	 * Reimplement in derived classes to add new variables, but remember to  also to call the parent
2077
	 * implementation first.
2078
	 * @param array $exprops by reference
2079
	 */
2080
	protected function _getZappableSleepProps(&$exprops)
2081
	{
2082
		if ($this->_listeningenabled === false) {
2083
			$exprops[] = "\0*\0_listeningenabled";
2084
		}
2085
		if ($this->_behaviorsenabled === true) {
2086
			$exprops[] = "\0*\0_behaviorsenabled";
2087
		}
2088
		$exprops[] = "\0*\0_e";
2089
		if ($this->_m === null) {
2090
			$exprops[] = "\0*\0_m";
2091
		}
2092
	}
2093
}
2094