diff --git a/Chain/ChainHelper.php b/Chain/ChainHelper.php index 131ccea..9e16181 100644 --- a/Chain/ChainHelper.php +++ b/Chain/ChainHelper.php @@ -7,7 +7,7 @@ * and send events to them. * * @package Stoic\Chain - * @version 1.0.0 + * @version 1.0.1 */ class ChainHelper { /** @@ -15,7 +15,7 @@ class ChainHelper { * * @var array */ - protected $_nodes = array(); + protected $_nodes = []; /** * Whether or not instance is an event-chain. * @@ -43,9 +43,8 @@ class ChainHelper { * * @param boolean $isEvent Toggle for event-chain. * @param boolean $doDebug Toggle for sending debug messages. - * @return void */ - public function __construct($isEvent = false, $doDebug = false) { + public function __construct(bool $isEvent = false, bool $doDebug = false) { $this->_isEvent = $isEvent; $this->toggleDebug($doDebug); @@ -55,10 +54,10 @@ public function __construct($isEvent = false, $doDebug = false) { /** * Toggles the use of debug messages by this instance. * - * @param bool $doDebug Toggle for sending debug messages. + * @param boolean $doDebug Toggle for sending debug messages. * @return ChainHelper */ - public function toggleDebug($doDebug) { + public function toggleDebug(bool $doDebug) : ChainHelper { $this->_doDebug = ($doDebug) ? true : false; return $this; @@ -67,7 +66,7 @@ public function toggleDebug($doDebug) { /** * Returns the full list of nodes linked to the chain. * - * @return array[] + * @return array */ public function getNodeList() { $ret = array(); @@ -88,12 +87,12 @@ public function getNodeList() { * should accept a single string argument. * * @param callable $callback Callable method/function that receives messages. - * @return boolean + * @return void */ - public function hookLogger(callable $callback) { + public function hookLogger(callable $callback) : void { $this->_logger = $callback; - return true; + return; } /** @@ -102,7 +101,7 @@ public function hookLogger(callable $callback) { * * @return boolean */ - public function isEvent() { + public function isEvent() : bool { return $this->_isEvent; } @@ -114,7 +113,7 @@ public function isEvent() { * @param NodeBase $node NodeBase object to register with chain. * @return ChainHelper */ - public function linkNode(NodeBase $node) { + public function linkNode(NodeBase $node) : ChainHelper { if (!$node->isValid()) { if ($this->_doDebug) { $this->log("Attempted to add invalid node: " . $node); @@ -151,7 +150,7 @@ public function linkNode(NodeBase $node) { * @param mixed $sender Optional sender data to pass to linked nodes. * @return boolean */ - public function traverse(DispatchBase &$dispatch, $sender = null) { + public function traverse(DispatchBase &$dispatch, $sender = null) : bool { if (count($this->_nodes) < 1) { if ($this->_doDebug) { $this->log("Attempted to traverse chain with no nodes"); @@ -218,7 +217,7 @@ public function traverse(DispatchBase &$dispatch, $sender = null) { * @param string $message Message to send to callback. * @return void */ - protected function log($message) { + protected function log(string $message) : void { if ($this->_logger !== null) { call_user_func($this->_logger, $message); } diff --git a/Chain/DispatchBase.php b/Chain/DispatchBase.php index f7ff8eb..f7d3006 100644 --- a/Chain/DispatchBase.php +++ b/Chain/DispatchBase.php @@ -8,7 +8,7 @@ * chain system. * * @package Stoic\Chain - * @version 1.0.0 + * @version 1.0.1 */ abstract class DispatchBase { /** @@ -32,9 +32,9 @@ abstract class DispatchBase { /** * Collection of results from nodes. * - * @var array + * @var mixed[] */ - private $_results = array(); + private $_results = []; /** * Whether or not the dispatch is valid for processing. * @@ -44,12 +44,17 @@ abstract class DispatchBase { /** * Date and time the dispatch was made valid. * - * @var \DateTime + * @var \DateTimeInterface */ private $_calledDateTime = null; - public function __toString() { + /** + * Serializes the DispatchBase class to a string. + * + * @return string + */ + public function __toString() : string { $calledDateTime = ($this->_calledDateTime instanceof \DateTimeInterface) ? $this->_calledDateTime->format("Y-m-d G:i:s") : 'N/A'; return static::class . "{ \"calledDateTime\": \"" . $calledDateTime . "\", " . @@ -66,7 +71,7 @@ public function __toString() { * * @return boolean */ - public function consume() { + public function consume() : bool { if ($this->_isConsumable && !$this->_isConsumed) { $this->_isConsumed = true; @@ -79,9 +84,9 @@ public function consume() { /** * Returns time the dispatch was marked valid. * - * @return \DateTime + * @return \DateTimeInterface */ - public function getCalledDateTime() { + public function getCalledDateTime() : \DateTimeInterface { return $this->_calledDateTime; } @@ -90,7 +95,7 @@ public function getCalledDateTime() { * is stateful, this can be multiple results, otherwise * it will be null or a single result. * - * @return array|null + * @return mixed[]|mixed|null */ public function getResults() { if (count($this->_results) < 1) { @@ -116,7 +121,7 @@ abstract public function initialize($input); * * @return boolean */ - public function isConsumable() { + public function isConsumable() : bool { return $this->_isConsumable; } @@ -127,7 +132,7 @@ public function isConsumable() { * * @return boolean */ - public function isConsumed() { + public function isConsumed() : bool { return $this->_isConsumed; } @@ -137,7 +142,7 @@ public function isConsumed() { * * @return boolean */ - public function isStateful() { + public function isStateful() : bool { return $this->_isStateful; } @@ -147,7 +152,7 @@ public function isStateful() { * * @return boolean */ - public function isValid() { + public function isValid() : bool { return $this->_isValid; } @@ -156,7 +161,7 @@ public function isValid() { * * @return DispatchBase */ - protected function makeConsumable() { + protected function makeConsumable() : DispatchBase { $this->_isConsumable = true; return $this; @@ -167,7 +172,7 @@ protected function makeConsumable() { * * @return DispatchBase */ - protected function makeStateful() { + protected function makeStateful() : DispatchBase { $this->_isStateful = true; return $this; @@ -179,8 +184,8 @@ protected function makeStateful() { * * @return DispatchBase */ - protected function makeValid() { - $this->_calledDateTime = new \DateTime('now', new \DateTimeZone('UTC')); + protected function makeValid() : DispatchBase { + $this->_calledDateTime = new \DateTimeImmutable('now', new \DateTimeZone('UTC')); $this->_isValid = true; return $this; @@ -191,7 +196,7 @@ protected function makeValid() { * * @return integer */ - public function numResults() { + public function numResults() : int { return count($this->_results); } @@ -203,7 +208,7 @@ public function numResults() { * @param mixed $result Result data to store in dispatch. * @return DispatchBase */ - public function setResult($result) { + public function setResult($result) : DispatchBase { if (!$this->_isStateful) { $this->_results = array($result); } else { diff --git a/Chain/NodeBase.php b/Chain/NodeBase.php index 31376a1..c9dea82 100644 --- a/Chain/NodeBase.php +++ b/Chain/NodeBase.php @@ -8,7 +8,7 @@ * system. * * @package Stoic\Chain - * @version 1.0.0 + * @version 1.0.1 */ abstract class NodeBase { /** @@ -25,7 +25,12 @@ abstract class NodeBase { protected $_version = null; - public function __toString() { + /** + * Serializes object as a string. + * + * @return string + */ + public function __toString() : string { return static::class . "{ \"key\": \"{$this->_key}\", \"version\": \"{$this->_version}\" }"; } @@ -34,7 +39,7 @@ public function __toString() { * * @return string */ - public function getKey() { + public function getKey() : string { return $this->_key; } @@ -43,7 +48,7 @@ public function getKey() { * * @return string */ - public function getVersion() { + public function getVersion() : string { return $this->_version; } @@ -55,7 +60,7 @@ public function getVersion() { * * @return boolean */ - public function isValid() { + public function isValid() : bool { return !empty($this->_key) && !empty($this->_version); } @@ -74,7 +79,7 @@ abstract public function process($sender, DispatchBase &$dispatch); * @param string $key Value to use for node key. * @return NodeBase */ - protected function setKey($key) { + protected function setKey(string $key) : NodeBase { $this->_key = $key; return $this; @@ -86,7 +91,7 @@ protected function setKey($key) { * @param string $version Value to use for node version. * @return NodeBase */ - protected function setVersion($version) { + protected function setVersion(string $version) : NodeBase { $this->_version = $version; return $this; diff --git a/Docs/Chains/chainhelper.md b/Docs/Chains/chainhelper.md deleted file mode 100644 index e789417..0000000 --- a/Docs/Chains/chainhelper.md +++ /dev/null @@ -1,34 +0,0 @@ -## ChainHelper Class -The `ChainHelper` class provides the basic functionality -associated with the Stoic chain system, specifically linking -nodes together and traversing that 'chain' using a dispatch -that implements the [DispatchBase](dispatches.md#dispatchbase) -abstract class. - -### Events vs Chains -The `ChainHelper` class was built to operate with multiple linked -nodes at any given time, but this design also easily lends itself -to use as an event dispatcher. By telling a `ChainHelper` instance -to be an event, the instance will only allow a single node to be -linked at any given time. Additional nodes that are linked will -simply overwrite the previously linked node and take its place -as the event callback. - -### Properties -- [protected:array] `$_nodes` -> Internal collection of linked nodes -- [protected:boolean] `$_isEvent` -> Whether or not instance is an event-chain -- [protected:boolean] `$_doDebug` -> Whether or not instance should record debug messages -- [protected:callback] `$_logger` -> Optional callback that receives debug messages (if enabled) - -### Methods -- [public] `__construct($isEvent, $doDebug)` -> Constructor with ability to override event and debug toggles -- [public] `toggleDebug($doDebug)` -> Toggles use of debug messages by instance -- [public] `getNodeList()` -> Returns full list of nodes linked to the chain -- [public] `hookLogger(callable $callback)` -> Attaches the given callback to the chain for receive debug messages -- [public] `isEvent()` Returns whether or not the instance is setup as an event chain -- [public] `linkNode(NodeBase $node)` -> Registers a valid node which implements `NodeBase` into the chain -- [public] `traverse(DispatchBase &$dispatch, $sender)` -> Begins distributing the given dispatch to any linked nodes, optional sender parameter -- [protected] `log($message)` -> Conditionally sends debug message to registered logger callback - -### Examples -For examples, please see the 'ChainHelper' section of the [Examples](examples.md) page. \ No newline at end of file diff --git a/Docs/Chains/dispatches.md b/Docs/Chains/dispatches.md deleted file mode 100644 index 8da6594..0000000 --- a/Docs/Chains/dispatches.md +++ /dev/null @@ -1,65 +0,0 @@ -## Dispatches -Dispatches in the Stoic chain system are data. Any information -that should be carried along a chain should be stored within the -dispatch. This makes the data available to any node which -receives the dispatch during chain traversal, and allows it to -serve as a container for results returned by any nodes that -record them. - -### Concepts -Dispatches by default have three 'states' that can be queries. -Each defaults to `false` and must be set by any dispatch during -initialization. The states are as follows: - -- Consumable -- Stateful -- Valid - -#### Consumable -When a dispatch marks itself as consumable, it tells the [ChainHelper](chainhelper.md) -to stop traversing a chain if the dispatch is consumed by a node. -This can be helpful in chains that resemble the "chain-of-responsibility" -pattern. - -#### Stateful -All nodes are given the ability to store results in dispatches, -and the dispatch's stateful setting will determine if only one -result is allowed or multiple are kept. Regardless of this -setting, results are always returned as `null` or an array. - -#### Valid -In order for the [ChainHelper](chainhelper.md) to traverse a chain -it must have both nodes and a valid dispatch. This gives developers -the ability to enforce custom restrictions on data validity at -initialization in order to stop chain traversal. - -### DispatchBase -All dispatches must implement the `DispatchBase` abstract class. -This provides some minimum functionality and requires developers -to implement an `initialize()` method. The following are the -properties and methods defined in `DispatchBase`: - -#### Properties -- [protected:boolean] `$_isConsumable` -> Whether or not the dispatch is 'consumable' -- [protected:boolean] `$_isStateful` -> Whether or not the dispatch should retain results -- [protected:boolean] `$_isConsumed` -> Whether or not the dispatch has been consumed by a node -- [protected:array] `$_results` -> Collection of results (state) from nodes -- [protected:boolean] `$_isValid` -> Whether or not the dispatch is valid for processing - -#### Methods -- [public] `consume()` -> Marks dispatch as having been consumed -- [public] `getCalledDateTime()` -> Returns time dispatch was marked valid -- [public] `getResults()` -> Returns any results stored in dispatch -- [abstract public] `initialize($input)` -> Abstract method for handling initialization -- [public] `isConsumable()` -> Returns whether or not dispatch can be consumed -- [public] `isConsumed()` -> Returns whether or not dispatch has been consumed -- [public] `isStateful()` -> Returns whether or not dispatch is stateful -- [public] `isValid()` -> Returns whether or not dispatch is marked as valid -- [protected] `makeConsumable()` -> Sets dispatch as consumable -- [protected] `makeStateful()` -> Sets dispatch as stateful -- [protected] `makeValid()` -> Sets dispatch as valid -- [public] `numResults()` -> Returns number of results stored in dispatch -- [public] `setResult($result)` -> Sets a result in dispatch, overwrites any existing result if dispatch not stateful - -### Examples -For examples, please see the 'Dispatch' section of the [Examples](examples.md) page. \ No newline at end of file diff --git a/Docs/Chains/examples.md b/Docs/Chains/examples.md deleted file mode 100644 index 5e3edb5..0000000 --- a/Docs/Chains/examples.md +++ /dev/null @@ -1,227 +0,0 @@ -## Examples -- [Dispatch Examples](#dispatch-examples) - - [Consumable Dispatch](#consumable-dispatch) - - [Stateful Dispatch](#stateful-dispatch) - - [An Increment Dispatch](#an-increment-dispatch) -- [Node Examples](#node-examples) - - [Incrementer Node](#an-incrementer-node) - - [Consumer Node](#a-consumer-node) - - [Chatty Node](#a-chatty-node) -- [Chain Examples](#chain-examples) - -### Dispatch Examples -The following dispatches will be used for examples later on. - -#### Consumable Dispatch -```php -use Stoic\Chain\DispatchBase; - -// A simple dispatch that can be consumed -class ConsumableDispatch extends DispatchBase { - // Implement the abstract method with no real use of $input - public function initialize($input) { - // Mark the dispatch as consumable, this way chain traversal - // can be stopped by a node - $this->makeConsumable(); - - // Exclude this if you have something about your $input that - // isn't valid for this dispatch's type - $this->makeValid(); - - return; - } -} -``` - -#### Stateful Dispatch -```php -use Stoic\Chain\DispatchBase; - -// A simple dispatch that is stateful -class StatefulDispatch extends DispatchBase { - // Implement the abstract method with no real use of $input - public function initialize($input) { - // Mark the dispatch as stateful so multiple results can be - // stored in the dispatch by a node (or nodes) - $this->makeStateful(); - - // Exclude this if you have something about your $input that - // isn't valid for this dispatch's type - $this->makeValid(); - - return; - } -} -``` - -#### An Increment Dispatch -```php -use Stoic\Chain\DispatchBase; - -// A simple dispatch that can be consumed -class IncrementDispatch extends DispatchBase { - // Private integer for our increment - private $counter = 0; - - // Implement abstract with override for increment number - public function initialize($input) { - // Mark the dispatch as consumable - $this->makeConsumable(); - - // if we have input, check if it's valid - if ($input !== null) { - if (is_int($input) === true) { - // it's valid, so set it and prepare for traversal - $this->counter = $input; - $this->makeValid(); - } - } else { - // we aren't modifying our counter, so prepare for traversal - $this->makeValid(); - } - - return; - } - - // So we can see what our counter is at currently - public function getCounterValue() { - return $this->counter; - } - - // A public method to let a node trigger incrementing the counter - public function incrementCount() { - $this->counter++; - - return; - } -} -``` - -### Node Examples -The following nodes will be used for examples later on. - -#### An Incrementer Node -```php -use Stoic\Chain\DispatchBase; -use Stoic\Chain\NodeBase; - -// A node that only calls an increment method on the dispatch -class IncrementerNode extends NodeBase { - // Need to instantiate with key/version info to be valid - public function __construct() { - $this->setKey('incrementerNode'); - $this->setVersion('0.0.1'); - - return; - } - - // Implement this to actually perform processing in a chain - public function process($sender, DispatchBase &$dispatch) { - if (!($dispatch instanceof IncrementDispatch)) { - return; - } - - // Now we're sure it's the dispatch we want, so increment - // and simply return so the next node in the chain can do - // its job - $dispatch->incrementCount(); - - return; - } -} -``` - -#### A Consumer Node -```php -use Stoic\Chain\DispatchBase; -use Stoic\Chain\NodeBase; - -// A node that simply attempts to consume a dispatch -class ConsumerNode extends NodeBase { - // Need to instantiate with key/version info to be valid - public function __construct() { - $this->setKey('consumerNode'); - $this->setVersion('0.0.1'); - - return; - } - - // Implement this to actually perform processing in a chain - public function process($sender, DispatchBase &$dispatch) { - // Since we don't care what kind of dispatch (all should - // have the consume method), just consume and return - $dispatch->consume(); - - return; - } -} -``` - -#### A Chatty Node -```php -use Stoic\Chain\DispatchBase; -use Stoic\Chain\NodeBase; - -// An IncrementerNode that yells out what it's doing -class ChattyNode extends IncrementerNode { - public function __construct() { - $this->setKey('chattyNode'); - $this->setVersion('0.0.1'); - - return; - } - - public function process($sender, DispatchBase &$dispatch) { - if (!($dispatch instanceof IncrementDispatch)) { - return; - } - - // Call the IncrementerNode process so it does its job - parent::process($sender, $dispatch); - - // Echo the current counter value after incrementing - echo($dispatch->getCounterValue() . " "); - - return; - } -} -``` - -### Chain Examples -```php -use Stoic\Chain\ChainHelper; - -// A plain IncrementDispatch -$rawDispatch = new IncrementDispatch(); -$rawDispatch->initialize(null); - -// An IncrementDispatch that starts at 10 -$offsetDispatch = new IncrementDispatch(); -$offsetDispatch->initialize(10); - -// First chain to execute a few chatty nodes and continue -$simpleChain = new ChainHelper(); -$simpleChain->linkNode(new ChattyNode()); -$simpleChain->linkNode(new ChattyNode()); -$simpleChain->linkNode(new ChattyNode()); - -// Traverse plain dispatch in loop -for ($i = 0; $i < 3; ++$i) { - $simpleChain->traverse($rawDispatch); -} - -// Should output: -// 1 2 3 4 5 6 7 8 9 - -// Second chain to execute chatty nodes and a consumer -$stopChain = new ChainHelper(); -$stopChain->linkNode(new ChattyNode()); -$stopChain->linkNode(new ChattyNode()); -$stopChain->linkNode(new ConsumerNode()); -$stopChain->linkNode(new ChattyNode()); - -$stopChain->traverse($offsetDispatch); - -// Should output: -// 11 12 -``` \ No newline at end of file diff --git a/Docs/Chains/index.md b/Docs/Chains/index.md deleted file mode 100644 index bda13f0..0000000 --- a/Docs/Chains/index.md +++ /dev/null @@ -1,75 +0,0 @@ -# Stoic Core Chains -An execution system inspired by the chain-of-responsibility design pattern. - -## Concept -Similar to the chain-of-responsibility design pattern, chains are groups of -processing objects, or nodes, which receive data in order as it is passed -to the chain. - -The entire system revolves around a simple - but effective - `ChainHelper` -class. This class facilitates the linking of processing nodes together, -all derived from the `NodeBase` abstract class, and sending along data -to the nodes in the form of a class deriving from the `DispatchBase` -abstract class. - -## End-to-End Example -Before going any further, here is a fully functional (albeit simple) example -of the chain system in use: - -```php -makeValid(); - - return; - } - - public function increment($number) { - return ++$number; - } - } - - class IncrementNode extends NodeBase { - public function __construct() { - $this->setKey('incrementNode'); - $this->setVersion('1.0.0'); - - return; - } - - public function process($sender, DispatchBase &$dispatch) { - if (!($dispatch instanceof IncrementDispatch)) { - return; - } - - $dispatch->setResult($dispatch->increment(1)); - - return; - } - } - - $chain = new ChainHelper(); - $chain->linkNode(new IncrementNode()); - - $dispatch = new IncrementDispatch(); - $dispatch->initialize(null); - - $success = $chain->traverse($dispatch); - $results = $dispatch->getResults(); - - print_r($results); -``` - -## Further Reading -To find out more about the system, check out the following pages: - -* [Dispatches](dispatches.md) -* [Nodes](nodes.md) -* [ChainHelper](chainhelper.md) -* [All Examples](examples.md) \ No newline at end of file diff --git a/Docs/Chains/nodes.md b/Docs/Chains/nodes.md deleted file mode 100644 index 986ec7e..0000000 --- a/Docs/Chains/nodes.md +++ /dev/null @@ -1,28 +0,0 @@ -## Nodes -Nodes in the Stoic chain system exist to process data (dispatches). -They are connected to each other via a [ChainHelper](chainhelper.md) -instance and receive a [Dispatch](dispatches.md) when they are asked -by the `ChainHelper` to execute their `process()` method. - -### NodeBase -All nodes used by the provided [ChainHelper](chainhelper.md) must -implement the `NodeBase` abstract class. This provides meta -information for the node and requires developers to implement a -`process()` method. The following are the properties and methods -defined in `NodeBase`: - -#### Properties -- [protected:string] `$_key` -> String that identifies the node -- [protected:string] `$_version` -> String that provides the node's version number - -#### Methods -- [public] `getKey()` -> Returns the node's key value -- [public] `getVersion()` -> Returns the node's version value -- [public] `isValid()` -> Returns whether or not both key and version values are set for node -- [abstract public] `process($sender, DispatchBase &$dispatch)` -> Abstract method for processing dispatch; Only called if node is valid -- [protected] `setKey($key)` -> Sets the node key value -- [protected] `setVersion($version)` -> Sets the node version value - -### Examples -For examples, please see the 'Node' section of the [Examples](examples.md) -page. \ No newline at end of file diff --git a/Docs/Logging/appenders.md b/Docs/Logging/appenders.md deleted file mode 100644 index 391e650..0000000 --- a/Docs/Logging/appenders.md +++ /dev/null @@ -1,16 +0,0 @@ -## Appenders -Appenders in Stoic's logging system are nothing more than `NodeBase` classes that process the [MessageDispatch](message-dispatch.md) class. -This means that all rules from the [Chain](../Chains/index.md) system apply, simplifying the process of setting up new appenders. - -### AppenderBase -The `AppenderBase` abstract class simply extends the [NodeBase](../Chains/nodes.md#nodebase) abstract class. This is done simply to force -some differentiation when implementing logging appenders vs other types of nodes. - -### MessageDispatch -All `AppenderBase` nodes will receive the `MessageDispatch` dispatch. For full details, please see the [MessageDispatch](message-dispatch.md) page. - -### NullAppender -The only appender which is included with the default Stoic distribution is the `NullAppender`, which serves as a null-sink for any log messages it is passed. - -### Examples -For examples, please see the 'Appenders' section of the [Examples](examples.md) page. \ No newline at end of file diff --git a/Docs/Logging/examples.md b/Docs/Logging/examples.md deleted file mode 100644 index cb8fdd9..0000000 --- a/Docs/Logging/examples.md +++ /dev/null @@ -1,185 +0,0 @@ -## Examples -- [Logger Examples](#logger-examples) - - [Basic Logger Usage](#basic-logger-usage) - - [Logger Usage With Level](#logger-usage-with-level) - - [Logger Context Interpolation](#logger-context-interpolation) -- [Appender Examples](#appender-examples) - - [Basic Appender](#basic-appender) - - [Adding Appenders](#adding-appenders) - -### Logger Examples -#### Basic Logger Usage -```php - use Stoic\Log\Logger; - - $log = new Logger(); - $log->emergency("Testing emergency logging"); - $log->alert("Testing alert logging"); - $log->critical("Testing critical logging"); - $log->error("Testing error logging"); - $log->warning("Testing warning logging"); - $log->notice("Testing notice logging"); - $log->info("Testing info logging"); - $log->debug("Testing debug logging"); - -/* - -Logger now produces this message collection, from memory: - [ - 0 => Stoic\Log\Message { "level": "EMERGENCY", "message": "Testing emergency logging", "timestamp": "2018-09-25 17:10:40.518600" }, - 1 => Stoic\Log\Message { "level": "ALERT", "message": "Testing alert logging", "timestamp": "2018-09-25 17:10:40.518900" }, - 2 => Stoic\Log\Message { "level": "CRITICAL", "message": "Testing critical logging", "timestamp": "2018-09-25 17:10:40.519000" }, - 3 => Stoic\Log\Message { "level": "ERROR", "message": "Testing error logging", "timestamp": "2018-09-25 17:10:40.519000" }, - 4 => Stoic\Log\Message { "level": "WARNING", "message": "Testing warning logging", "timestamp": "2018-09-25 17:10:40.519100" }, - 5 => Stoic\Log\Message { "level": "NOTICE", "message": "Testing notice logging", "timestamp": "2018-09-25 17:10:40.519100" }, - 6 => Stoic\Log\Message { "level": "INFO", "message": "Testing info logging", "timestamp": "2018-09-25 17:10:40.519200" }, - 7 => Stoic\Log\Message { "level": "DEBUG", "message": "Testing debug logging", "timestamp": "2018-09-25 17:10:40.519200" } - ] - -*/ -``` - -#### Logger Usage With Level -```php - use Stoic\Log\Logger; - - $log = new Logger(\Psr\Log\LogLevel::WARNING); - $log->emergency("Testing emergency logging"); - $log->alert("Testing alert logging"); - $log->critical("Testing critical logging"); - $log->error("Testing error logging"); - $log->warning("Testing warning logging"); - $log->notice("Testing notice logging"); - $log->info("Testing info logging"); - $log->debug("Testing debug logging"); - -/* - -Logger now produces this message collection, from memory (notice we're missing anything less severe than a warning): - [ - 0 => Stoic\Log\Message { "level": "EMERGENCY", "message": "Testing emergency logging", "timestamp": "2018-09-25 17:17:28.449400" } - 1 => Stoic\Log\Message { "level": "ALERT", "message": "Testing alert logging", "timestamp": "2018-09-25 17:17:28.449600" } - 2 => Stoic\Log\Message { "level": "CRITICAL", "message": "Testing critical logging", "timestamp": "2018-09-25 17:17:28.449600" } - 3 => Stoic\Log\Message { "level": "ERROR", "message": "Testing error logging", "timestamp": "2018-09-25 17:17:28.449700" } - 4 => Stoic\Log\Message { "level": "WARNING", "message": "Testing warning logging", "timestamp": "2018-09-25 17:17:28.449700" } - ] - -*/ -``` - -#### Logger Context Interpolation -```php - use Stoic\Log\Logger; - - class DummyClass { - public $variable = 'value'; - } - - class LessDummyClass { - public $variable = 'value'; - - public function __toString() { - return "[object LessDummyClass: variable={$this->variable}]"; - } - } - - $log = new Logger(); - $log->info("This is an exception: {exception}", array('exception' => new Exception("Test exception"))); - $log->info("This is a {something}", array('something' => 'message')); - $log->info("This is an object: {obj}", array('obj' => new DummyClass())); - $log->info("This is a smarter object: {obj}", array('obj' => new LessDummyClass())); - $log->info("And this is a datetime object: {obj}", array('obj' => new DateTime())); - -/* - -Logger now produces this message collection, from memory (notice we're missing anything less severe than a warning): - [ - 0 => Stoic\Log\Message { "level": "INFO", "message": "This is an exception: [exception Exception] - Message: Test exception - Stack Trace: #0 {main}", "timestamp": "2018-09-25 17:24:11.228700" } - 1 => Stoic\Log\Message { "level": "INFO", "message": "This is a message", "timestamp": "2018-09-25 17:24:11.228900" } - 2 => Stoic\Log\Message { "level": "INFO", "message": "This is an object: [object DummyClass]", "timestamp": "2018-09-25 17:24:11.228900" } - 3 => Stoic\Log\Message { "level": "INFO", "message": "This is a smarter object: [object LessDummyClass: variable=value]", "timestamp": "2018-09-25 17:24:11.229000" } - 4 => Stoic\Log\Message { "level": "INFO", "message": "And this is a datetime object: 2018-09-25T17:24:11-04:00", "timestamp": "2018-09-25 17:24:11.229000" } - ] - -*/ -``` - -### Appender Examples -#### Basic Appender -These appenders will be used in the following examples. - -```php - use Stoic\Chain\DispatchBase; - use Stoic\Log\AppenderBase; - use Stoic\Log\MessageDispatch; - - class EchoAppender extends AppenderBase { - public function __construct() { - $this->setKey('EchoAppender'); - $this->setVersion('1.0.0'); - - return; - } - - public function process($sender, DispatchBase &$dispatch) { - if (!($dispatch instanceof MessageDispatch)) { - return; - } - - foreach (array_values($dispatch->messages) as $message) { - echo("{$message}\n"); - } - - return; - } - } - - class JsonAppender extends AppenderBase { - public function __construct() { - $this->setKey('JsonAppender'); - $this->setVersion('1.0.0'); - - return; - } - - public function process($sender, DispatchBase &$dispatch) { - if (!($dispatch instanceof MessageDispatch)) { - return; - } - - foreach (array_values($dispatch->messages) as $message) { - echo("{$message->__toJson()}\n"); - } - - return; - } - } -``` - -#### Adding Appenders -```php - use Psr\Log\LogLevel; - use Stoic\Log\Logger; - - // Add appenders using constructor - $log = new Logger(LogLevel::DEBUG, array(new EchoAppender(), new JsonAppender())); - $log->info("Testing info logging"); - $log->output(); - - // Add appenders using addAppender() method - $log = new Logger(); - $log->addAppender(new EchoAppender()); - $log->addAppender(new JsonAppender()); - $log->info("Testing info logging"); - $log->output(); - -/* - -Both instances produce the same results (excluding different timestamps, of course): - - 2018-09-25 17:59:19.599100 INFO Testing info logging - { "level": "INFO", "message": "Testing info logging", "timestamp": "2018-09-25 17:59:19.599100" } - -*/ \ No newline at end of file diff --git a/Docs/Logging/index.md b/Docs/Logging/index.md deleted file mode 100644 index 2e21372..0000000 --- a/Docs/Logging/index.md +++ /dev/null @@ -1,59 +0,0 @@ -# Stoic Core Logging -A logging system that is PSR-3 complient but better suited to configured output. - -## Concept -Building on top of the [Chain](../Chains/index.md) system built into Stoic, the Logger retains PSR-3 compatibility by implementing -all appropriate interfaces, but is built in a way that considers output as simply a configurable option on each `Logger` instance. - -Since the system IS PSR-3 compatible, we'll focus here on our usage of logging 'appenders' and how they provide easy configurability -to your systems. For information on PSR-3 logging, please refer for the [PHP FIG website](https://www.php-fig.org/psr/psr-3/). - -## End-to-End Example -A fully-functional (and very simplistic) example of a new appender: - -```php - use Stoic\Chain\DispatchBase; - use Stoic\Log\AppenderBase; - use Stoic\Log\Logger; - use Stoic\Log\MessageDispatch; - - class EchoAppender extends AppenderBase { - public function __construct() { - $this->setKey('EchoAppender'); - $this->setVersion('1.0.0'); - - return; - } - - public function process($sender, DispatchBase &$dispatch) { - if (!($dispatch instanceof MessageDispatch)) { - return; - } - - if (count($dispatch->messages) > 0) { - foreach (array_values($dispatch->messages) as $message) { - echo("{$message}\n"); - } - } - - return; - } - } - - $log = new Logger(); - $log->addAppender(new EchoAppender()); - - $log->info("Testing log info output."); - $log->critical("Testing log critical output."); - - $log->output(); - -``` - -## Further Reading -To find out more about the system, check out the following pages: - -* [Logger](logger.md) -* [Appenders](appenders.md) -* [Messages](messages.md) -* [All Examples](examples.md) \ No newline at end of file diff --git a/Docs/Logging/logger.md b/Docs/Logging/logger.md deleted file mode 100644 index fb6fd4b..0000000 --- a/Docs/Logging/logger.md +++ /dev/null @@ -1,34 +0,0 @@ -## Logger Class -The `Logger` class provides the basic functionality set by PSR-3 and guaranteed by the `Psr\Log\AbstractLogger` class. Additionally -it provides a mechanism to attach one or more [appenders](appenders.md) that implement the `AppenderBase` abstract class and are used -during log output. - -### PSR-3 Note -This class, by implementing the `\Psr\Log\AbstractLogger` abstract class, guarantees the existence of the following methods: - -- [public] `emergency($message, array $context)` -- [public] `alert($message, array $context)` -- [public] `critical($message, array $context)` -- [public] `error($message, array $context)` -- [public] `warning($message, array $context)` -- [public] `notice($message, array $context)` -- [public] `info($message, array $context)` -- [public] `debug($message, array $context)` - -Since these are well documented on the [PHP FIG website](https://www.php-fig.org/psr/psr-3/), we won't go into the details here. - -### Properties -- [private:Stoic\Chain\ChainHelper] `$appenders` -> Internal instance of a `Stoic\Chain\ChainHelper` instance to manage appenders for this logger instance -- [private:Message[]] `$messages` -> Collection of log messages encapsulated by the `Message` class -- [protected:static:string[]] `$levels` -> Numerically indexed collection of log levels for 'minimum level' comparisons - -### Methods -- [public] `__construct($minimumLevel, array $appenders)` -> Constructor with optional arguments to set minimum log level and provide collection of `AppenderBase` appenders to add immediately -- [public] `addAppender(AppenderBase $appender)` -> Attempts to add (link) an [appender](appenders.md) to the internal `ChainHelper` for output appenders -- [protected] `interpolate($message, array $context)` -> Interpolates context values into a log message -- [public] `log($level, $message, array $context)` -> Stores an arbitrary message & log level into the internal collection as a `Message` -- [protected] `meetsMinimumLevel($level)` -> Determines whether or not a given level is at least as 'high' in importance as the minimum level set at instantiation -- [public] `output()` -> Triggers a dump of all log messages in memory to any configured appenders; Additionally clears internal message collection - -### Examples -For examples, please see the 'Logger' section of the [Examples](examples.md) page. \ No newline at end of file diff --git a/Docs/Logging/message-dispatch.md b/Docs/Logging/message-dispatch.md deleted file mode 100644 index 4d41559..0000000 --- a/Docs/Logging/message-dispatch.md +++ /dev/null @@ -1,9 +0,0 @@ -## MessageDispatch Class -The `MessageDispatch` class is used to provide collections of [Message](messages.md) objects for consumption -by [appenders](appenders.md). - -### Properties -- [public:Message[]] `$messages` -> Collection of any messages returned by the `Logger` instance (possibly filtered by minimum level) - -### Methods -- [public] `initialize($input)` -> Initializes the dispatch with message values before being used for chain traversal \ No newline at end of file diff --git a/Docs/Logging/messages.md b/Docs/Logging/messages.md deleted file mode 100644 index ebf6489..0000000 --- a/Docs/Logging/messages.md +++ /dev/null @@ -1,17 +0,0 @@ -## Message Class -The `Message` class provides some structure and immutable time storage for log messages. Any message -stored inside a `Message` object should have already been passed through context interpolation, thus -rendering the message text in a 'final' state. - -### Properties -- [public:string] `$level` -> String value of message's log level -- [public:string] `$message` -> Finalized string value of log message -- [private:\DateTimeImmutable] `$timestamp` -> Immutable DateTime value for time message object was generated (includes microseconds) -- [private:static:array] `$validLevels` -> Collection of valid level values for making sure good information is provided at instantiation - -### Methods -- [public] `__construct($level, $message)` -> Instantiates a new Message object, validating the log level and creating a `\DateTimeImmutable` -- [public] `getTimestamp()` -> Returns the immutable timestamp value so it can't be overwritten -- [public] `__toArray()` -> Returns the object information as a simplified array: `['level' => '', 'message' => '', 'timestamp' => '']` -- [public] `__toJson()` -> Returns the object information as a simplified JSON string: `{ 'level': '', 'message': '', 'timestamp': '' }` -- [public] `__toString()` -> Returns the object information as a simplified string \ No newline at end of file diff --git a/Docs/Utilities/enum-helper.md b/Docs/Utilities/enum-helper.md deleted file mode 100644 index 8ae3d1f..0000000 --- a/Docs/Utilities/enum-helper.md +++ /dev/null @@ -1,55 +0,0 @@ -## EnumBase Class -The `EnumBase` abstract class provides some general functionality -for creating enumerated classes/values within PHP. - -### A Quick Example -Creating and using a class of enumerated values is easy: - -```php -is(Numbers::TWO)) { - echo("This is number 2"); - } else { - echo("The number is: {$num}"); - } -``` - -Since enumerated values aren't supported in PHP, using a -class with constants allows for type-checking. Usage is -simple and both string and JSON serialization are automatically -implemented. - -### Static Properties -- [protected:array] `$constCache` -> Static internal cache of const lookups - -### Properties -- [protected:string] `$name` -> Internal storage for name -- [protected:integer] `$value` -> Internal storage for value -- [protected:boolean] `$serializeAsName` -> Determines whether or not to serialize as name, defaults to true - -### Static Methods -- [public] `fromString($string, $serializeAsName)` -> Returns a new Enum object using the name instead of the value for initialization -- [public] `getConstList()` -> Returns the const lookup for the called class -- [public] `tryGetEnum($value, $className)` -> Returns an EnumBase object of the type `$className`, either using an existing instance given to `$value` or using a valid integer given to `$value` -- [public] `validName($name)` -> Validates a name against the const lookup values for the called class -- [public] `validValue($value)` -> Validates a value against the const lookup values for the called class - -### Methods -- [public] `__construct($value, $serializeAsName)` -> Instantiates a new Enum object with an optional value -- [public] `__toString()` -> Serializes the object to its string representation -- [public] `getName()` -> Retrieves the set name for the object -- [public] `getValue()` -> Retrieves the set value for the object -- [public] `is($value)` -> Determines if the set value for the object is the same as the supplied value -- [public] `isIn(...$values)` -> Determines if the current value is equal to any of the supplied values -- [public] `jsonSerialize()` -> Serializes the object to its string representation \ No newline at end of file diff --git a/Docs/Utilities/index.md b/Docs/Utilities/index.md deleted file mode 100644 index ddf62a7..0000000 --- a/Docs/Utilities/index.md +++ /dev/null @@ -1 +0,0 @@ -# Stoic Utilities \ No newline at end of file diff --git a/Docs/Utilities/return-helper.md b/Docs/Utilities/return-helper.md deleted file mode 100644 index 6ad66e2..0000000 --- a/Docs/Utilities/return-helper.md +++ /dev/null @@ -1,93 +0,0 @@ -## ReturnHelper Class -The `ReturnHelper` class provides a mechanism for creating -methods and functions that returns more information than -a simple scalar value to indicate success. - -### The Problem -Given the following function: - -```php -makeBad(); - $ret->addMessage("myTest() received a null valuie"); - - return $ret; - } - - if ($inputA < $inputB) { - $ret->makeBad(); - $ret->addMessage("inputA is less than inputB"); - - return $ret; - } - - $ret->makeGood(); - - return $ret; - } - - $ret = myTest($varA, $varB); - - if ($ret->isBad()) { - // deal with false & messages here - } -``` - -### Properties -- [protected:array] `$_messages` -> Collection of messages for this return -- [protected:array] `$_results` -> Collection of results for this return -- [protected:integer] `$_status` -> Integer value of return's current status - -### Constants -- [integer] `STATUS_BAD` -> Internal status for 'Bad' returns -- [integer] `STATUS_GOOD` -> Internal status for 'Good' returns - -### Methods -- [public] `__construct()` -> Constructor that creates a new `ReturnHelper` set as 'Bad' -- [public] `addMessage($message)` -> Adds a message to the return -- [public] `addMessages(array $messages)` -> Adds an array of messages to the return -- [public] `addResult($result)` -> Adds a result value to the return -- [public] `addResults(array $results)` -> Adds an array of results to the return -- [public] `isBad()` -> Returns true if the return's status is 'Bad' -- [public] `isGood()` -> Returns true if the return's status is 'Good' -- [public] `getMessages()` -> Returns the collection of messages for the return -- [public] `getResults()` -> Returns the collection of results for the return -- [public] `hasMessages()` -> Returns true if there are messages in the return's collection -- [public] `hasResults()` -> Returns true if there are results in the return's collection -- [public] `makeBad()` -> Sets the return's status as 'Bad' -- [public] `makeGood()` -> Sets the return's status as 'Good' \ No newline at end of file diff --git a/Docs/components.md b/Docs/components.md deleted file mode 100644 index c46fa45..0000000 --- a/Docs/components.md +++ /dev/null @@ -1 +0,0 @@ -# Stoic Core Components \ No newline at end of file diff --git a/Docs/getting-started.md b/Docs/getting-started.md deleted file mode 100644 index f04671d..0000000 --- a/Docs/getting-started.md +++ /dev/null @@ -1 +0,0 @@ -# Getting Started w/ Stoic PHP \ No newline at end of file diff --git a/Docs/index.md b/Docs/index.md index 02fb52b..c9881eb 100644 --- a/Docs/index.md +++ b/Docs/index.md @@ -1,14 +1,2 @@ -# Stoic Framework -Collection of PHP components crafted via years of a very pedantic approach to building websites. - -## Authors -* Andrew Male ([@AndyM84](https://github.com/AndyM84)) -* Chris Butcher ([@c-butcher](https://github.com/c-butcher)) - -## Contents -* [Getting Started](getting-started.md) -* [Main Components](components.md) - * [Chains](Chains/index.md) - * [Logging](Logging/index.md) - * [ReturnHelper](Utilities/return-helper.md) - * [EnumBase](Utilities/enum-helper.md) \ No newline at end of file +# Documentation +Our documentation has moved to our website: [https://stoic-framework.com](https://stoic-framework.com) \ No newline at end of file diff --git a/Log/AppenderBase.php b/Log/AppenderBase.php index a5c0109..a0c3993 100644 --- a/Log/AppenderBase.php +++ b/Log/AppenderBase.php @@ -9,6 +9,6 @@ * do many-splendored things with log messages. * * @package Stoic\Log - * @version 1.0.0 + * @version 1.0.1 */ abstract class AppenderBase extends NodeBase { } diff --git a/Log/Logger.php b/Log/Logger.php index eb50366..9913667 100644 --- a/Log/Logger.php +++ b/Log/Logger.php @@ -11,7 +11,7 @@ * multiple appenders for output/handling. * * @package Stoic\Log - * @version 1.0.0 + * @version 1.0.1 */ class Logger extends AbstractLogger { /** @@ -25,7 +25,7 @@ class Logger extends AbstractLogger { * * @var Message[] */ - private $messages = array(); + private $messages = []; /** * The minimum log level to push to appennders. * @@ -38,7 +38,7 @@ class Logger extends AbstractLogger { * * @var string[] */ - protected static $levels = array( + protected static $levels = [ LogLevel::DEBUG, LogLevel::INFO, LogLevel::NOTICE, @@ -47,7 +47,7 @@ class Logger extends AbstractLogger { LogLevel::CRITICAL, LogLevel::ALERT, LogLevel::EMERGENCY - ); + ]; /** @@ -62,7 +62,7 @@ class Logger extends AbstractLogger { * @param null|string $minimumLevel Optional minimum log level for output; Default is LogLevel::DEBUG * @param null|AppenderBase[] $appenders Optional collection of LogAppenderBase objects to assign. */ - public function __construct($minimumLevel = null, array $appenders = null) { + public function __construct(?string $minimumLevel = null, ?array $appenders = null) { $this->appenders = new ChainHelper(); if ($minimumLevel !== null) { @@ -90,7 +90,7 @@ public function __construct($minimumLevel = null, array $appenders = null) { * @param AppenderBase $appender Appender which extends the AppenderBase abstract class. * @throws \Psr\Log\InvalidArgumentException Thrown if invalid appender argument provided. */ - public function addAppender(AppenderBase $appender) { + public function addAppender(AppenderBase $appender) : void { $this->appenders->linkNode($appender); return; @@ -103,7 +103,7 @@ public function addAppender(AppenderBase $appender) { * @param array $context Array of context values to interpolate with placeholers. * @return string */ - protected function interpolate($message, array $context) { + protected function interpolate(string $message, array $context) : string { if (strpos($message, '{') === false || strpos($message, '}') === false) { return $message; } @@ -159,7 +159,7 @@ public function log($level, $message, array $context = array()) { * @param string $level String value of level to check against minimum. * @return boolean */ - protected function meetsMinimumLevel($level) { + protected function meetsMinimumLevel(string $level) : bool { return array_search($level, self::$levels) >= array_search($this->minLevel, self::$levels); } @@ -168,7 +168,7 @@ protected function meetsMinimumLevel($level) { * messages to output and traverses them through * the appender stack. */ - public function output() { + public function output() : void { $messages = array(); foreach (array_values($this->messages) as $message) { diff --git a/Log/Message.php b/Log/Message.php index a7abf8a..b902f81 100644 --- a/Log/Message.php +++ b/Log/Message.php @@ -9,7 +9,7 @@ * Represents a log message. * * @package Stoic\Log - * @version 1.0.0 + * @version 1.0.1 */ class Message implements \JsonSerializable { /** @@ -28,7 +28,7 @@ class Message implements \JsonSerializable { * Immutable timestamp for log * message creation time. * - * @var \DateTimeImmutable + * @var \DateTimeInterface */ private $timestamp; /** @@ -57,7 +57,7 @@ class Message implements \JsonSerializable { * @param string $message String value of log message. * @throws \InvalidArgumentException Thrown if invalid log level provided. */ - public function __construct($level, $message) { + public function __construct(string $level, string $message) { if (array_key_exists($level, self::$validLevels) === false) { throw new \InvalidArgumentException("Invalid log level provided to Stoic\Log\LogMessage: {$level}"); } @@ -75,9 +75,9 @@ public function __construct($level, $message) { * Returns the immutable timestamp marking * message creation. * - * @return \DateTimeImmutable + * @return \DateTimeInterface */ - public function getTimestamp() { + public function getTimestamp() : \DateTimeInterface { return $this->timestamp; } @@ -101,7 +101,7 @@ public function __toArray() { * * @return string */ - public function __toJson() { + public function __toJson() : string { return json_encode($this); } @@ -125,7 +125,7 @@ public function jsonSerialize() { * * @return string */ - public function __toString() { + public function __toString() : string { return sprintf("%s %' -9s %s", $this->timestamp->format('Y-m-d G:i:s.u'), strtoupper($this->level), diff --git a/Log/MessageDispatch.php b/Log/MessageDispatch.php index 41c8c05..b64aa2f 100644 --- a/Log/MessageDispatch.php +++ b/Log/MessageDispatch.php @@ -9,7 +9,7 @@ * will be passed to log appenders. * * @package Stoic\Log - * @version 1.0.0 + * @version 1.0.1 */ class MessageDispatch extends DispatchBase { /** @@ -17,7 +17,7 @@ class MessageDispatch extends DispatchBase { * * @var Message[] */ - public $messages = array(); + public $messages = []; /** @@ -25,7 +25,7 @@ class MessageDispatch extends DispatchBase { * * @param Message[] $messages Collection of Message objects to handle. */ - public function initialize($input) { + public function initialize($input) : void { if (!is_array($input) && (!is_object($input) || !($input instanceof Message))) { return; } diff --git a/Log/NullAppender.php b/Log/NullAppender.php index 36c529a..4c8936d 100644 --- a/Log/NullAppender.php +++ b/Log/NullAppender.php @@ -8,7 +8,7 @@ * Null-sink/noop log appender. * * @package Stoic\Log - * @version 1.0.0 + * @version 1.0.1 */ class NullAppender extends AppenderBase { /** @@ -31,7 +31,7 @@ public function __construct() { * @param DispatchBase $dispatch Collection of Message objects to handle. * @codeCoverageIgnore */ - public function process($sender, DispatchBase &$dispatch) { + public function process($sender, DispatchBase &$dispatch) : void { return; } } diff --git a/README.md b/README.md index 6c1258b..dd3ce9b 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,11 @@ # stoic-php-core -PHP version of Stoic Framework. +Core component for the PHP Stoic Framework. For more information, visit our website at [stoic-framework.com](https://stoic-framework.com) -## Installation -In order to install, simply make use of composer (eventually). +# Installation +Typical composer installation is supported, simply run the following command: -## Documentation -Documentation is available in the [Docs](Docs/index.md) directory. \ No newline at end of file +``` +composer require stoic-php-core +``` + +Alternatively, downloads are available via the releases page here on GitHub. \ No newline at end of file diff --git a/Tests/Chain/LoggingTest.php b/Tests/Chain/LoggingTest.php index 9b070f7..fd1baed 100644 --- a/Tests/Chain/LoggingTest.php +++ b/Tests/Chain/LoggingTest.php @@ -70,10 +70,10 @@ public function test_logMessageCount() { $ch_norm = new ChainHelper(); $ch_consume = new ChainHelper(false, true); - self::assertTrue($ch_nonevent->hookLogger(array($lg_nonevent, "receiveLog"))); - self::assertTrue($ch_event->hookLogger(array($lg_event, "receiveLog"))); - self::assertTrue($ch_norm->hookLogger(array($lg_norm, "receiveLog"))); - self::assertTrue($ch_consume->hookLogger(array($lg_consume, "receiveLog"))); + $ch_nonevent->hookLogger(array($lg_nonevent, "receiveLog")); + $ch_event->hookLogger(array($lg_event, "receiveLog")); + $ch_norm->hookLogger(array($lg_norm, "receiveLog")); + $ch_consume->hookLogger(array($lg_consume, "receiveLog")); $ch_nonevent->linkNode(new NonConsumeTestNode()); $ch_nonevent->linkNode(new ConsumeTestNode()); diff --git a/Utilities/EnumBase.php b/Utilities/EnumBase.php index 865d498..51c865d 100644 --- a/Utilities/EnumBase.php +++ b/Utilities/EnumBase.php @@ -7,7 +7,7 @@ * functionality. * * @package Stoic\Utilities - * @version 1.0.0 + * @version 1.0.1 */ abstract class EnumBase implements \JsonSerializable { /** @@ -47,7 +47,7 @@ abstract class EnumBase implements \JsonSerializable { * @param boolean $serializeAsName Causes object to serialize into the name of the set value, defaults to true. * @return object */ - public static function fromString($string, $serializeAsName = true) { + public static function fromString(string $string, bool $serializeAsName = true) { $class = get_called_class(); if ($string === null || empty($string) || !static::validName($string)) { @@ -128,7 +128,7 @@ public static function tryGetEnum($value, $className) { * @param string $name String to use as name. * @return boolean */ - public static function validName($name) { + public static function validName(string $name) : bool { $consts = static::getConstList(); return array_key_exists($name, $consts['name']) !== false; @@ -141,7 +141,7 @@ public static function validName($name) { * @param integer $value Integer to use as value. * @return boolean */ - public static function validValue($value) { + public static function validValue(int $value) : bool { $consts = static::getConstList(); return array_key_exists($value, $consts['value']) !== false; @@ -152,9 +152,9 @@ public static function validValue($value) { * Instantiates a new Enum object. * * @param null|integer $value Integer to use as value, defaults to null. - * @param mixed $serializeAsName Causes object to serialize into the name of the set value, defaults to true. + * @param boolean $serializeAsName Causes object to serialize into the name of the set value, defaults to true. */ - public function __construct($value = null, $serializeAsName = true) { + public function __construct(?int $value = null, bool $serializeAsName = true) { $this->serializeAsName = $serializeAsName; if ($value !== null && static::validValue($value)) { @@ -172,7 +172,7 @@ public function __construct($value = null, $serializeAsName = true) { * * @return string */ - public function __toString() { + public function __toString() : string { if ($this->serializeAsName) { return $this->name ?? ''; } @@ -186,7 +186,7 @@ public function __toString() { * * @return null|string */ - public function getName() { + public function getName() : ?string { return $this->name; } @@ -196,7 +196,7 @@ public function getName() { * * @return null|integer */ - public function getValue() { + public function getValue() : ?int { return $this->value; } @@ -207,7 +207,7 @@ public function getValue() { * @param integer $value Integer to test against current value. * @return boolean */ - public function is($value) { + public function is(int $value) : bool { if ($this->value === null || $this->value !== $value) { return false; } @@ -222,7 +222,7 @@ public function is($value) { * @param integer[] $values Array of integer values to compare against current value. * @return boolean */ - public function isIn(int ...$values) { + public function isIn(int ...$values) : bool { if ($this->value === null) { return false; } @@ -241,7 +241,7 @@ public function isIn(int ...$values) { * * @return string */ - public function jsonSerialize() { + public function jsonSerialize() : string { return $this->__toString(); } } diff --git a/Utilities/ReturnHelper.php b/Utilities/ReturnHelper.php index e3ca929..2b9e1c7 100644 --- a/Utilities/ReturnHelper.php +++ b/Utilities/ReturnHelper.php @@ -7,7 +7,7 @@ * method/function returns. * * @package Stoic\Utilities - * @version 1.0.0 + * @version 1.0.1 */ class ReturnHelper { /** @@ -39,8 +39,8 @@ class ReturnHelper { * status is STATUS_BAD. */ public function __construct() { - $this->_messages = array(); - $this->_results = array(); + $this->_messages = []; + $this->_results = []; $this->_status = self::STATUS_BAD; return; @@ -51,7 +51,7 @@ public function __construct() { * * @param string $message String value of message to add to collection. */ - public function addMessage($message) { + public function addMessage(string $message) : void { $this->_messages[] = $message; return; @@ -64,7 +64,7 @@ public function addMessage($message) { * @param string[] $messages Array of strings to add to collection. * @throws \InvalidArgumentException Thrown if null or empty array provided. */ - public function addMessages(array $messages) { + public function addMessages(array $messages) : void { if ($messages === null || count($messages) < 1) { throw new \InvalidArgumentException("Messages array to ReturnHelper::addMessages() must be array with elements"); } @@ -81,7 +81,7 @@ public function addMessages(array $messages) { * * @param mixed $result Result value to add to collection. */ - public function addResult($result) { + public function addResult($result) : void { $this->_results[] = $result; return; @@ -94,7 +94,7 @@ public function addResult($result) { * @param mixed[] $results Array of results to add to collection. * @throws \InvalidArgumentException Thrown if null or empty array provided. */ - public function addResults(array $results) { + public function addResults(array $results) : void { if ($results === null || count($results) < 1) { throw new \InvalidArgumentException("Results array to ReturnHelper::addResults() must be array with elements"); } @@ -112,7 +112,7 @@ public function addResults(array $results) { * * @return boolean */ - public function isBad() { + public function isBad() : bool { return $this->_status === self::STATUS_BAD; } @@ -122,7 +122,7 @@ public function isBad() { * * @return boolean */ - public function isGood() { + public function isGood() : bool { return $this->_status === self::STATUS_GOOD; } @@ -150,7 +150,7 @@ public function getResults() { * * @return boolean */ - public function hasMessages() { + public function hasMessages() : bool { return count($this->_messages) > 0; } @@ -160,14 +160,14 @@ public function hasMessages() { * * @return boolean */ - public function hasResults() { + public function hasResults() : bool { return count($this->_results) > 0; } /** * Sets the internal status as STATUS_BAD. */ - public function makeBad() { + public function makeBad() : void { $this->_status = self::STATUS_BAD; return; @@ -176,7 +176,7 @@ public function makeBad() { /** * Sets the internal status as STATUS_GOOD. */ - public function makeGood() { + public function makeGood() : void { $this->_status = self::STATUS_GOOD; return; diff --git a/composer.json b/composer.json index 911dd40..697c928 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "stoic/stoic", "description": "Stoic framework Core component", - "version": "1.0.0", + "version": "1.0.1", "homepage": "https://stoic-framework.com", "autoload": { "psr-0": { @@ -15,7 +15,7 @@ "Stoic\\Utilities\\": "./Utilities" }, "exclude-from-classmap": [ - "/Tests/" + "./Tests/" ] }, "require": {