From e8ebc8e7d57cdf9a5720785220b274e4fe5c493c Mon Sep 17 00:00:00 2001 From: =?utf8?q?Roland=20H=C3=A4der?= Date: Fri, 6 Nov 2020 16:14:06 +0100 Subject: [PATCH] Rewrites: - Added type-hints: string, int, bool an other primitive types - updated core framework MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Roland Häder --- .../apt-proxy/class_BaseNodeAptProxy.php | 4 +- .../hub/classes/chat/class_BaseNodeChat.php | 4 +- .../socket/class_SocketContainer.php | 112 ++++++++++-------- .../classes/crawler/class_BaseNodeCrawler.php | 4 +- .../cruncher/class_BaseHubCruncher.php | 4 +- ...odeDistributedHashTableDatabaseWrapper.php | 15 ++- .../class_PeerStateLookupDatabaseWrapper.php | 2 +- .../classes/dht/node/class_NodeDhtFacade.php | 10 +- .../socket/class_PackageSocketDiscovery.php | 7 +- .../factories/socket/class_SocketFactory.php | 15 ++- .../package/class_NetworkPackageHandler.php | 96 ++++++++------- .../connection/class_BaseConnectionHelper.php | 76 +++++------- .../info/connection/class_ConnectionInfo.php | 18 ++- .../classes/listener/class_BaseListener.php | 41 +++---- .../hub/classes/miner/class_BaseHubMiner.php | 4 +- .../hub/classes/nodes/class_BaseHubNode.php | 8 +- .../pools/peer/class_DefaultPeerPool.php | 35 ++++-- .../template/class_BaseXmlTemplateEngine.php | 12 +- .../interfaces/apt-proxy/class_AptProxy.php | 5 +- .../hub/interfaces/chat/class_Chatter.php | 5 +- .../container/socket/class_StorableSocket.php | 8 +- .../hub/interfaces/crawler/class_Crawler.php | 5 +- .../cruncher/class_CruncherHelper.php | 5 +- .../frontend/class_NodeDhtWrapper.php | 2 +- .../socket/class_DiscoverableSocket.php | 2 +- .../distributable/class_Distributable.php | 2 +- .../interfaces/miner/class_MinerHelper.php | 2 +- .../pool/peer/class_PoolablePeer.php | 4 +- .../hub/interfaces/socket/class_SocketTag.php | 2 +- core | 2 +- 30 files changed, 284 insertions(+), 227 deletions(-) diff --git a/application/hub/classes/apt-proxy/class_BaseNodeAptProxy.php b/application/hub/classes/apt-proxy/class_BaseNodeAptProxy.php index 377d5dc4c..b549e0cce 100644 --- a/application/hub/classes/apt-proxy/class_BaseNodeAptProxy.php +++ b/application/hub/classes/apt-proxy/class_BaseNodeAptProxy.php @@ -50,8 +50,8 @@ abstract class BaseNodeAptProxy extends BaseHubSystem { * @param $version Version number of this apt-proxy * @return void */ - public final function enableIsActive ($isActive = TRUE) { - $this->isActive = (bool) $isActive; + public final function enableIsActive (bool $isActive = TRUE) { + $this->isActive = $isActive; } /** diff --git a/application/hub/classes/chat/class_BaseNodeChat.php b/application/hub/classes/chat/class_BaseNodeChat.php index 09c68ef06..bbe184dc6 100644 --- a/application/hub/classes/chat/class_BaseNodeChat.php +++ b/application/hub/classes/chat/class_BaseNodeChat.php @@ -50,8 +50,8 @@ abstract class BaseNodeChat extends BaseHubSystem { * @param $version Version number of this chatter * @return void */ - public final function enableIsActive ($isActive = TRUE) { - $this->isActive = (bool) $isActive; + public final function enableIsActive (bool $isActive = TRUE) { + $this->isActive = $isActive; } /** diff --git a/application/hub/classes/container/socket/class_SocketContainer.php b/application/hub/classes/container/socket/class_SocketContainer.php index c45ebf4ef..8c4de84a6 100644 --- a/application/hub/classes/container/socket/class_SocketContainer.php +++ b/application/hub/classes/container/socket/class_SocketContainer.php @@ -140,19 +140,27 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita * @param $socketProtocol Socket protocol (TCP, UDP, file) * @param $packageInstance An instance of a DeliverablePackage class * @param $socketType Socket type (incoming, outgoing, server, file, ...) - * @return $socketInstance An instance of this Container class - * @throws InvalidArgumentException If socket type is not set in $packageData array + * @return $socketInstance An instance of a StorableSocket class + * @throws InvalidArgumentException If a parameter is not valid */ - public static final function createSocketContainer ($socketResource, $socketProtocol, DeliverablePackage $packageInstance, $socketType) { - // Trace message + public static final function createSocketContainer ($socketResource, string $socketProtocol, DeliverablePackage $packageInstance, string $socketType) { + // Validate parameter /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('SOCKET-CONTAINER: socketResource[%s]=%s,socketProtocol=%s,packageInstance[]=%s,socketType=%s - CALLED!', gettype($socketResource), $socketResource, $socketProtocol, gettype($packageInstance), $socketType)); - //* DEBUG-PRINT: */ printf('[%s:%d]: packageInstance=%s', __METHOD__, __LINE__, print_r($packageInstance, TRUE)); + if (!is_resource($socketResource)) { + // Throw exception + throw new InvalidArgumentException(sprintf('socketResource[]=%s is not valid', $socketResource)); + } elseif (empty($socketProtocol)) { + // Throw again + throw new InvalidArgumentException('socketProtocol is empty'); + } elseif (empty($socketType)) { + // Throw again + throw new InvalidArgumentException('socketType is empty'); + } // Get a new instance $socketInstance = new SocketContainer(); // Set all values - /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('SOCKET-CONTAINER: socketResource=%s,socketProtocol=%s', $socketResource, $socketProtocol)); $socketInstance->setSocketProtocol($socketProtocol); $socketInstance->setSocketResource($socketResource); $socketInstance->setPackageDataInstance($packageInstance); @@ -168,10 +176,17 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita * * @param $unl A Universal Node Locator * @return $matches Whether $address matches with the one from package data - */ - public function ifAddressMatches ($unl) { + * @throws InvalidArgumentException If a parameter is not valid + */ + public function ifAddressMatches (string $unl) { + // Is parameter valid? + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-SOCKET: unl=%s - CALLED!', strtoupper($this->getSocketProtocol()), $unl)); + if (empty($unl)) { + // Throw again + throw new InvalidArgumentException('unl is empty'); + } + // Get current package data - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-SOCKET: unl=%s - CALLED!', strtoupper($this->getSocketProtocol()), $unl)); $packageInstance = $this->getPackageDataInstance(); // So, does both match? @@ -268,13 +283,13 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita * @return $result Result from asking for peer address * @throws InvalidSocketException If socket is invalid */ - public function determineSocketPeerName (&$peerAddress, &$peerPort) { + public function determineSocketPeerName (string &$peerAddress, int &$peerPort) { // Should be valid socket /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-SOCKET: peerAddress[%s]=%s,peerPort[%s]=%d - CALLED!', strtoupper($this->getSocketProtocol()), gettype($peerAddress), $peerAddress, gettype($peerPort), $peerPort)); if (!$this->isValidSocket()) { // Throw exception throw new InvalidSocketException(array($this), self::EXCEPTION_INVALID_SOCKET); - } // END - if + } // Init result $result = FALSE; @@ -320,7 +335,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita if (!$this->isValidSocket()) { // Throw exception throw new InvalidSocketException(array($this), self::EXCEPTION_INVALID_SOCKET); - } // END - if + } // Get package data $packageInstance = $this->getPackageDataInstance(); @@ -342,7 +357,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita if (!$this->isValidSocket()) { // Throw exception throw new InvalidSocketException(array($this), self::EXCEPTION_INVALID_SOCKET); - } // END - if + } // Get recipient $recipient = $this->getSocketRecipient(); @@ -370,7 +385,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita if (!$this->isValidSocket()) { // Throw exception throw new InvalidSocketException(array($this), self::EXCEPTION_INVALID_SOCKET); - } // END - if + } // Get recipient $recipient = $this->getSocketRecipient(); @@ -417,7 +432,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita if (!$this->isValidSocket()) { // Throw exception throw new InvalidSocketException(array($this), self::EXCEPTION_INVALID_SOCKET); - } // END - if + } // Get it from stored socket resource $socketResource = $this->getSocketResource(); @@ -442,7 +457,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita if (!$this->isValidSocket()) { // Throw exception throw new InvalidSocketException(array($this), self::EXCEPTION_INVALID_SOCKET); - } // END - if + } // Get it from stored socket resource $socketResource = $this->getSocketResource(); @@ -547,7 +562,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita if (!$this->isValidSocket()) { // Throw exception throw new InvalidSocketException(array($this), self::EXCEPTION_INVALID_SOCKET); - } // END - if + } // Try to listen on socket $result = socket_listen($this->getSocketResource()); @@ -569,7 +584,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita if (!$this->isValidSocket()) { // Throw exception throw new InvalidSocketException(array($this), self::EXCEPTION_INVALID_SOCKET); - } // END - if + } // Try to set non-blocking I/O $result = socket_set_nonblock($this->getSocketResource()); @@ -591,7 +606,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita if (!$this->isValidSocket()) { // Throw exception throw new InvalidSocketException(array($this), self::EXCEPTION_INVALID_SOCKET); - } // END - if + } // Tries to set option $result = $this->setSocketOption(SOL_SOCKET, SO_REUSEADDR, 1); @@ -613,7 +628,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita if (!$this->isValidSocket()) { // Throw exception throw new InvalidSocketException(array($this), self::EXCEPTION_INVALID_SOCKET); - } // END - if + } // Get recipient UNL $unlRecipient = $this->getSocketRecipient(); @@ -646,7 +661,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita if (!$this->isValidSocket()) { // Throw exception throw new BadMethodCallException(sprintf('[%s:%d]: Shutdown on invalid socket. Maybe called already?', __METHOD__, __LINE__), self::EXCEPTION_INVALID_SOCKET); - } // END - if + } // Debug message self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($this->getSocketProtocol()) . '-SOCKET: Shutting down socket ' . $this->getSocketResource()); @@ -662,8 +677,8 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita if (socket_last_error($this->getSocketResource()) != 107) { // Something bad happened while we shutdown a socket throw new SocketShutdownException($this, self::EXCEPTION_INVALID_SOCKET); - } // END - if - } // END - if + } + } // Try to make blocking I/O for socket_close() socket_set_block($this->getSocketResource()); @@ -686,18 +701,21 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita * * @param $connectionType Type of connection, can be 'incoming', 'outgoing' or 'server' * @return $isValid Whether the provided connection type is valid + * @throws InvalidArgumentException If $connectionType is empty */ - public function isValidConnectionType ($connectionType) { - // Trace message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-SOCKET: connectionType=%d - CALLED!', strtoupper($this->getSocketProtocol()), $connectionType)); + public function isValidConnectionType (string $connectionType) { + // Validate parameter + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-SOCKET: connectionType=%d - CALLED!', strtoupper($this->getSocketProtocol()), $connectionType)); + if (empty($connectionType)) { + // Throw exception + throw new InvalidArgumentException('connectionType is empty'); + } // Is it valid? $isValid = in_array($connectionType, $this->connectionTypes, TRUE); - // Trace message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-SOCKET: isValid=%d - EXIT!', strtoupper($this->getSocketProtocol()), intval($isValid))); - // Return result + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-SOCKET: isValid=%d - EXIT!', strtoupper($this->getSocketProtocol()), intval($isValid))); return $isValid; } @@ -713,7 +731,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita if (!$this->isValidSocket()) { // Throw exception throw new InvalidSocketException(array($this), self::EXCEPTION_INVALID_SOCKET); - } // END - if + } // Init all arrays, at least readers /* EXTREME-NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-SOCKET: this->socketResource=%s', strtoupper($this->getSocketProtocol()), $this->getSocketResource())); @@ -773,7 +791,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita if (!$this->isValidSocket()) { // Throw exception throw new InvalidSocketException(array($this), self::EXCEPTION_INVALID_SOCKET); - } // END - if + } /* * Read raw data from socket. If you change PHP_BINARY_READ to @@ -797,7 +815,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita // Init peer address (IP)/port /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getSocketResource())); $peerAddress = '0.0.0.0'; - $peerPort = '0'; + $peerPort = 0; // Call other method $result = $this->determineSocketPeerName($peerAddress, $peerPort); @@ -808,7 +826,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita // Set both $this->setPeerAddress($peerAddress); $this->setPeerPort($peerPort); - } // END - if + } // Return result /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-SOCKET: result[%s]=%d - EXIT!', strtoupper($this->getSocketProtocol()), gettype($result), intval($result))); @@ -997,13 +1015,13 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita * @throws InvalidSocketException If the stored socket resource is no socket resource * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back */ - public function handleSocketError ($method, $line) { + public function handleSocketError (string $method, int $line) { // This method handles only socket resources //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HUB-SYSTEM: Handling socket errorCode=%d - CALLED!', $this->getLastSocketErrorCode())); if (!$this->isValidSocket()) { // No resource, abort here throw new InvalidSocketException(array($this), self::EXCEPTION_INVALID_SOCKET); - } // END - if + } // Get error code for first validation (0 is not an error) $errorCode = $this->getLastSocketErrorCode(); @@ -1012,7 +1030,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita if ($errorCode == 0) { // No error detected (or previously cleared outside this method) throw new NoSocketErrorDetectedException(array($this), BaseListener::EXCEPTION_NO_SOCKET_ERROR); - } // END - if + } // Get handler (method) name $handlerName = $this->getSocketErrorHandlerFromCode($errorCode); @@ -1035,7 +1053,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita * @return $handlerName Call-back method name for the error handler * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented */ - protected function getSocketErrorHandlerFromCode ($errorCode) { + protected function getSocketErrorHandlerFromCode (int $errorCode) { // Create a name from translated error code //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-SOCKET: errorCode=%d - CALLED!', strtoupper($this->getSocketProtocol()), $errorCode)); $handlerName = 'handleSocketError' . self::convertToClassName($this->translateSocketErrorCodeToName($errorCode)); @@ -1044,7 +1062,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita if (!method_exists($this, $handlerName)) { // Please implement this throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), BaseConnectionHelper::EXCEPTION_UNSUPPORTED_ERROR_HANDLER); - } // END - if + } // Return it //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-SOCKET: handlerName=%d - EXIT!', strtoupper($this->getSocketProtocol()), $handlerName)); @@ -1254,7 +1272,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita * @param $errorCode The error code from socket_last_error() to be translated * @return $errorName The translated name (all lower-case, with underlines) */ - private function translateSocketErrorCodeToName ($errorCode) { + private function translateSocketErrorCodeToName (int $errorCode) { // Unknown error code by default //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-SOCKET: errorCode=%d - CALLED!', strtoupper($this->getSocketProtocol()), $errorCode)); $errorName = StorableSocket::SOCKET_ERROR_UNKNOWN; @@ -1315,7 +1333,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita // Unhandled error code detected, so first debug it because we may want to handle it like the others self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf(strtoupper($this->getSocketProtocol()) . '-SOCKET: Unsupported errorCode=%d,message=%s', $errorCode, socket_strerror($errorCode))); break; - } // END - switch + } // Return translated name //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-SOCKET: errorName=%d - EXIT!', strtoupper($this->getSocketProtocol()), $errorName)); @@ -1337,7 +1355,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita if (!$this->isValidSocket()) { // Throw exception throw new InvalidSocketException(array($this), self::EXCEPTION_INVALID_SOCKET); - } // END - if + } // Set it $result = socket_set_option($this->getSocketResource(), $level, $optionName, $optionValue); @@ -1353,7 +1371,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita * @param $socketProtocol Socket protocol * @return void */ - private function setSocketProtocol ($socketProtocol) { + private function setSocketProtocol (string $socketProtocol) { $this->socketProtocol = $socketProtocol; } @@ -1410,7 +1428,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita * @param $socketType Socket type * @return void */ - protected function setSocketType ($socketType) { + protected function setSocketType (string $socketType) { $this->socketType = $socketType; } @@ -1429,7 +1447,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita * @param $peerAddress Peer address * @return void */ - public function setPeerAddress ($peerAddress) { + public function setPeerAddress (string $peerAddress) { $this->peerAddress = $peerAddress; } @@ -1448,7 +1466,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita * @param $peerPort Peer port * @return void */ - public function setPeerPort ($peerPort) { + public function setPeerPort (int $peerPort) { $this->peerPort = $peerPort; } @@ -1467,7 +1485,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita * @param $senderAddress Sender address * @return void */ - public function setSenderAddress ($senderAddress) { + public function setSenderAddress (string $senderAddress) { $this->senderAddress = $senderAddress; } @@ -1486,7 +1504,7 @@ class SocketContainer extends BaseHubContainer implements StorableSocket, Visita * @param $senderPort Sender port * @return void */ - public function setSenderPort ($senderPort) { + public function setSenderPort (int $senderPort) { $this->senderPort = $senderPort; } diff --git a/application/hub/classes/crawler/class_BaseNodeCrawler.php b/application/hub/classes/crawler/class_BaseNodeCrawler.php index 4df7bf66d..ac2d34719 100644 --- a/application/hub/classes/crawler/class_BaseNodeCrawler.php +++ b/application/hub/classes/crawler/class_BaseNodeCrawler.php @@ -83,8 +83,8 @@ abstract class BaseNodeCrawler extends BaseHubSystem { * @param $version Version number of this crawler * @return void */ - public final function enableIsActive ($isActive = TRUE) { - $this->isActive = (bool) $isActive; + public final function enableIsActive (bool $isActive = TRUE) { + $this->isActive = $isActive; } /** diff --git a/application/hub/classes/cruncher/class_BaseHubCruncher.php b/application/hub/classes/cruncher/class_BaseHubCruncher.php index 15771d133..59c348f05 100644 --- a/application/hub/classes/cruncher/class_BaseHubCruncher.php +++ b/application/hub/classes/cruncher/class_BaseHubCruncher.php @@ -146,8 +146,8 @@ abstract class BaseHubCruncher extends BaseHubSystem implements Updateable { * @param $version Version number of this cruncher * @return void */ - public final function enableIsActive ($isActive = TRUE) { - $this->isActive = (bool) $isActive; + public final function enableIsActive (bool $isActive = TRUE) { + $this->isActive = $isActive; } /** diff --git a/application/hub/classes/database/frontend/node/class_NodeDistributedHashTableDatabaseWrapper.php b/application/hub/classes/database/frontend/node/class_NodeDistributedHashTableDatabaseWrapper.php index e2f7ceb01..aec61b504 100644 --- a/application/hub/classes/database/frontend/node/class_NodeDistributedHashTableDatabaseWrapper.php +++ b/application/hub/classes/database/frontend/node/class_NodeDistributedHashTableDatabaseWrapper.php @@ -671,10 +671,15 @@ class NodeDistributedHashTableDatabaseWrapper extends BaseHubDatabaseWrapper imp * @param $key Key to look for * @param $value Value to compare if key matches * @return $recipients An indexed array with DHT recipients + * @throws InvalidArgumentException If $key is empty */ - public function getResultFromKeyValue ($key, $value) { - // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: CALLED!'); + public function getResultFromKeyValue (string $key, $value) { + // Is key parameter valid? + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-WRAPPER: key=%s,value[%s]=%s - CALLED!', $key, gettype($value), $value)); + if (empty($key)) { + // Throw exception + throw new InvalidArgumentException('Parameter key is empty'); + } // Get max recipients $maxRecipients = $this->getConfigInstance()->getConfigEntry('max_dht_recipients'); @@ -688,10 +693,8 @@ class NodeDistributedHashTableDatabaseWrapper extends BaseHubDatabaseWrapper imp // Get a result instance back from DHT database wrapper. $resultInstance = $this->doSelectByCriteria($searchInstance); - // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-WRAPPER: EXIT!'); - // Return result instance + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-WRAPPER: resultInstance=%s - EXIT!', $resultInstance->__toString())); return $resultInstance; } diff --git a/application/hub/classes/database/frontend/states/class_PeerStateLookupDatabaseWrapper.php b/application/hub/classes/database/frontend/states/class_PeerStateLookupDatabaseWrapper.php index 90d47ab2e..594de0a5f 100644 --- a/application/hub/classes/database/frontend/states/class_PeerStateLookupDatabaseWrapper.php +++ b/application/hub/classes/database/frontend/states/class_PeerStateLookupDatabaseWrapper.php @@ -157,7 +157,7 @@ class PeerStateLookupDatabaseWrapper extends BaseHubDatabaseWrapper implements L // Init peer address/port $peerAddress = '0.0.0.0'; - $peerPort = '0'; + $peerPort = 0; // Get peer name if (!$socketInstance->determineSocketPeerName($peerAddress, $peerPort)) { diff --git a/application/hub/classes/dht/node/class_NodeDhtFacade.php b/application/hub/classes/dht/node/class_NodeDhtFacade.php index c2e992f3b..0eb971241 100644 --- a/application/hub/classes/dht/node/class_NodeDhtFacade.php +++ b/application/hub/classes/dht/node/class_NodeDhtFacade.php @@ -428,8 +428,16 @@ class NodeDhtFacade extends BaseDht implements DistributableNode, Registerable { * @param $key Key to search for * @param $value Value to check on found key * @return $recipiens Array with DHT recipients from given key/value pair + * @throws InvalidArgumentException If $key is empty */ - public function findRecipientsByKey ($key, $value) { + public function findRecipientsByKey (string $key, $value) { + // Is key parameter valid? + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('NODE-DHT-FACADE: key=%s,value[%s]=%s - CALLED!', $key, gettype($value), $value)); + if (empty($key)) { + // Throw exception + throw new InvalidArgumentException('Parameter key is empty'); + } + // Look for all suitable nodes $resultInstance = $this->getWrapperInstance()->getResultFromKeyValue($key, $value); diff --git a/application/hub/classes/discovery/recipient/socket/class_PackageSocketDiscovery.php b/application/hub/classes/discovery/recipient/socket/class_PackageSocketDiscovery.php index fc0a24148..a631ca43d 100644 --- a/application/hub/classes/discovery/recipient/socket/class_PackageSocketDiscovery.php +++ b/application/hub/classes/discovery/recipient/socket/class_PackageSocketDiscovery.php @@ -148,11 +148,14 @@ class PackageSocketDiscovery extends BaseRecipientDiscovery implements Discovera * @throws InvalidArgumentException If one of the parameters are not valid * @throws LogicException If the discovered listener instance has no pool set */ - public function discoverSocket (DeliverablePackage $packageInstance, $connectionType) { + public function discoverSocket (DeliverablePackage $packageInstance, string $connectionType) { // Make sure all parameters are valid /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('PACKAGE-SOCKET-DISOVERY: packageInstance=%s,connectionType=%s - CALLED!', $packageInstance->__toString(), $connectionType)); //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('PACKAGE-SOCKET-DISOVERY: packageInstance=' . print_r($packageInstance, TRUE)); - if (($connectionType != StorableSocket::CONNECTION_TYPE_INCOMING) && ($connectionType != StorableSocket::CONNECTION_TYPE_OUTGOING)) { + if (empty($connectionType)) { + // Throw exception + throw new InvalidArgumentException('Parameter connectionType is empty'); + } elseif (($connectionType != StorableSocket::CONNECTION_TYPE_INCOMING) && ($connectionType != StorableSocket::CONNECTION_TYPE_OUTGOING)) { // Abort here throw new InvalidArgumentException(sprintf('connectionType=%s is whether "%s" nor "%s".', $connectionType, diff --git a/application/hub/classes/factories/socket/class_SocketFactory.php b/application/hub/classes/factories/socket/class_SocketFactory.php index b00926d4d..3219a1877 100644 --- a/application/hub/classes/factories/socket/class_SocketFactory.php +++ b/application/hub/classes/factories/socket/class_SocketFactory.php @@ -17,6 +17,7 @@ use Org\Mxchange\CoreFramework\Registry\GenericRegistry; use Org\Mxchange\CoreFramework\Socket\InvalidSocketException; // Import SPL stuff +use \InvalidArgumentException; use \LogicException; use \SplFileInfo; @@ -475,10 +476,20 @@ class SocketFactory extends ObjectFactory { * @param $socketResource Valid socket resource from calling socket_accept() * @param $socketProtocol Protcol of socket (e.g. 'tcp', 'udp', see StorableSocket interface for valid values * @return $socketInstance An instance of a StorableSocket class + * @throws InvalidArgumentException If a parameter is not valid */ - public static final function createIncomingSocketInstance ($socketResource, $socketProtocol) { - // Create package instance + public static final function createIncomingSocketInstance ($socketResource, string $socketProtocol) { + // Validate parameter /* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('SOCKET-FACTORY: socketResource[%s]=%s,socketProtocol=%s - CALLED!', gettype($socketResource), $socketResource, $socketProtocol)); + if (!is_resource($socketResource)) { + // Throw exception + throw new InvalidArgumentException(sprintf('socketResource[]=%s is not valid', gettype($socketResource))); + } elseif (empty($socketProtocol)) { + // Throw it again + throw new InvalidArgumentException('socketProtocol is empty'); + } + + // Create package instance $packageInstance = ObjectFactory::createObjectByConfiguredName('package_data_class'); // Create socket instance diff --git a/application/hub/classes/handler/package/class_NetworkPackageHandler.php b/application/hub/classes/handler/package/class_NetworkPackageHandler.php index 53a5a8427..ab25ee015 100644 --- a/application/hub/classes/handler/package/class_NetworkPackageHandler.php +++ b/application/hub/classes/handler/package/class_NetworkPackageHandler.php @@ -46,6 +46,7 @@ use Org\Mxchange\CoreFramework\Visitor\Visitor; use \BadMethodCallException; use \InvalidArgumentException; use \Iterator; +use \UnexpectedValueException; /** * A NetworkPackageHandler class. This class implements Deliverable and Receivable @@ -514,10 +515,17 @@ class NetworkPackageHandler extends BaseHubHandler implements Deliverable, Recei * * @param $packageInstance An instance of a DeliverablePackage class in an array * @return $hash Hash for given package content + * @throws InvalidArgumentException If $packageInstance has no sessionId set */ public function getHashFromPackageSessionId (DeliverablePackage $packageInstance) { - // Create the hash + // Is session id set? /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('NETWORK-PACKAGE-HANDLER: packageInstance=%s - CALLED!', $packageInstance->__toString())); + if (empty($packageInstance->getSessionId())) { + // Throw exception + throw new InvalidArgumentException('packageInstance has no sessionId set.'); + } + + // Create the hash // @TODO md5() is very weak, but it needs to be fast $hash = md5(sprintf(self::CONTENT_CHECKSUM_MASK, $packageInstance->getContentMessage(), @@ -547,7 +555,7 @@ class NetworkPackageHandler extends BaseHubHandler implements Deliverable, Recei * target because it causes an overload on the network and may be * abused for attacking the network with large packages. */ - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('NETWORK-PACKAGE-HANDLER: packageInstance=%s - CALLED!', $packageInstance->__toString())); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('NETWORK-PACKAGE-HANDLER: packageInstance=%s - CALLED!', $packageInstance->__toString())); $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance(); // Discover all recipients, this may throw an exception @@ -586,6 +594,9 @@ class NetworkPackageHandler extends BaseHubHandler implements Deliverable, Recei */ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: Calling discoveryInstance->clearRecipients() ...'); $discoveryInstance->clearRecipients(); + + // Trace message + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: EXIT!'); } /** @@ -610,33 +621,28 @@ class NetworkPackageHandler extends BaseHubHandler implements Deliverable, Recei * which (configurable!) protocol should be used for that type of * package. */ - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('NETWORK-PACKAGE-HANDLER: packageInstance=%s - CALLED!', $packageInstance->__toString())); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('NETWORK-PACKAGE-HANDLER: packageInstance=%s - CALLED!', $packageInstance->__toString())); $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance(); // Now discover the right socket instance from given package data $socketInstance = $discoveryInstance->discoverSocket($packageInstance, StorableSocket::CONNECTION_TYPE_OUTGOING); // Get the connection helper from registry - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: Reached line ' . __LINE__ . ' after discoverSocket() has been called.'); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: Reached line ' . __LINE__ . ' after discoverSocket() has been called.'); $helperInstance = GenericRegistry::getRegistry()->getInstance('connection'); - // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: stateInstance=' . $helperInstance->getStateInstance()); - - // And make sure it is valid - assert($helperInstance instanceof ConnectionHelper); - // Get connection info class + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('NETWORK-PACKAGE-HANDLER: stateInstance=%s', $helperInstance->getStateInstance())); $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($helperInstance->getProtocolName(), 'helper'); // Will the info instance with connection helper data $infoInstance->fillWithConnectionHelperInformation($helperInstance); // Is it not there? - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.'); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.'); if (($socketInstance->isValidSocket()) && (!$this->getRegistryInstance()->isSocketRegistered($infoInstance, $socketInstance))) { // Then register it - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: Registering socket ' . $socketInstance . ' ...'); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('NETWORK-PACKAGE-HANDLER: Registering socket %s ...', $socketInstance)); $this->getRegistryInstance()->registerSocketInstance($infoInstance, $socketInstance); } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) { // Is not connected, then we cannot send @@ -647,15 +653,15 @@ class NetworkPackageHandler extends BaseHubHandler implements Deliverable, Recei } // Make sure the connection is up - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.'); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.'); $helperInstance->getStateInstance()->validatePeerStateConnected(); // Enqueue it again on the out-going queue, the connection is up and working at this point - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.'); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.'); $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageInstance); // Trace message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: Reached line ' . __LINE__ . ' after pushNamed() has been called.'); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: Reached line ' . __LINE__ . ' after pushNamed() has been called.'); } /** @@ -665,10 +671,8 @@ class NetworkPackageHandler extends BaseHubHandler implements Deliverable, Recei * @return void */ private function sendOutgoingRawPackageData (DeliverablePackage $packageInstance) { - // Trace message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('NETWORK-PACKAGE-HANDLER: packageInstance=%s - CALLED!', $packageInstance->__toString())); - // Init sent bytes + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('NETWORK-PACKAGE-HANDLER: packageInstance=%s - CALLED!', $packageInstance->__toString())); $sentBytes = 0; // Get the right connection instance @@ -680,12 +684,8 @@ class NetworkPackageHandler extends BaseHubHandler implements Deliverable, Recei // Get helper instance $helperInstance = $infoInstance->getHelperInstance(); - // Some sanity-checks on the object - //* DEBUG-DIE: */ die(': p1=' . $infoInstance->getProtocolName() . ',p2=' . $helperInstance->getProtocolName() . ',infoInstance=' . print_r($infoInstance, TRUE)); - assert($helperInstance instanceof ConnectionHelper); - assert($infoInstance->getProtocolName() == $helperInstance->getProtocolName()); - // Is this connection still alive? + //* DEBUG-DIE: */ die(': p1=' . $infoInstance->getProtocolName() . ',p2=' . $helperInstance->getProtocolName() . ',infoInstance=' . print_r($infoInstance, TRUE)); if ($helperInstance->isShuttedDown()) { // This connection is shutting down // @TODO We may want to do somthing more here? @@ -696,7 +696,7 @@ class NetworkPackageHandler extends BaseHubHandler implements Deliverable, Recei $helperInstance->sendRawPackageData($packageInstance); // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: EXIT!'); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: EXIT!'); } /** @@ -707,10 +707,8 @@ class NetworkPackageHandler extends BaseHubHandler implements Deliverable, Recei * @return $hash Hash as hex-encoded string */ private function generatePackageHash ($content, $senderId) { - // Debug message - /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: content()=' . strlen($content) . ',senderId=' . $senderId . ' - CALLED!'); - // Assert on variables + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: content()=' . strlen($content) . ',senderId=' . $senderId . ' - CALLED!'); assert(!empty($content)); assert(!empty($senderId)); @@ -783,14 +781,19 @@ class NetworkPackageHandler extends BaseHubHandler implements Deliverable, Recei * * @param $helperInstance An instance of a HubHelper class * @return void + * @throws UnexpectedValueException If the helper instance contains now raw template data */ public function enqueueRawDataFromTemplate (HubHelper $helperInstance) { - // Debug message - /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: helperInstance=' . $helperInstance->__toString() . ' - CALLED!'); - // Get the raw content ... + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: helperInstance=' . $helperInstance->__toString() . ' - CALLED!'); $content = $helperInstance->getTemplateInstance()->getRawTemplateData(); - /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('content(' . strlen($content) . ')=' . $content); + + // Should not be empty + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('NETWORK-PACKAGE-HANDLER: content(%d)=%s', strlen($content), $content)); + if (empty($content)) { + // Abort here + throw new UnexpectedValueException('content cannot be empty.'); + } // ... and compress it $compressed = $this->getCompressorInstance()->compressStream($content); @@ -813,12 +816,8 @@ class NetworkPackageHandler extends BaseHubHandler implements Deliverable, Recei $this->getHashFromContent($compressed) ); - // Make sure required data is there - /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: Enqueueing package for recipientType=' . $helperInstance->getRecipientType() . ' ...'); - assert(!empty($content)); - assert($this->getNodeInstance()->getSessionId() != ''); - // Init package instance + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: Enqueueing package for recipientType=' . $helperInstance->getRecipientType() . ' ...'); $packageInstance = ObjectFactory::createObjectByConfiguredName('package_data_class'); // Set all data @@ -884,7 +883,13 @@ class NetworkPackageHandler extends BaseHubHandler implements Deliverable, Recei public function isPackageWaitingForDelivery () { // Check whether the stacker is not empty //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: CALLED!'); - $isWaitingDelivery = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING))); + $isWaitingDelivery = ( + ( + $this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING) + ) && ( + !$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING) + ) + ); // Return the result //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('NETWORK-PACKAGE-HANDLER: isWaitingDelivery=%d - EXIT!', intval($isWaitingDelivery))); @@ -899,7 +904,13 @@ class NetworkPackageHandler extends BaseHubHandler implements Deliverable, Recei public function isEncodedDataPending () { // Check whether the stacker is not empty //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: CALLED!'); - $isPending = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING_STREAM)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING_STREAM))); + $isPending = ( + ( + $this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING_STREAM) + ) && ( + !$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING_STREAM) + ) + ); // Return the result //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('NETWORK-PACKAGE-HANDLER: isPending=%d - EXIT!', intval($isPending))); @@ -917,10 +928,8 @@ class NetworkPackageHandler extends BaseHubHandler implements Deliverable, Recei * @throws NoTargetException If no target can't be determined */ public function declareEnqueuedPackage () { - // Debug message - /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: CALLED!'); - // Make sure this method isn't working if there is no package enqueued + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: CALLED!'); if (!$this->isPackageEnqueued()) { // This is not fatal but should be avoided self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: No raw package data waiting declaration, but ' . __METHOD__ . ' has been called!'); @@ -1028,7 +1037,7 @@ class NetworkPackageHandler extends BaseHubHandler implements Deliverable, Recei } // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: EXIT!'); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: EXIT!'); } /** @@ -1497,7 +1506,8 @@ class NetworkPackageHandler extends BaseHubHandler implements Deliverable, Recei $packageInstance = $this->getStackInstance()->popNamed(self::STACKER_NAME_NEW_MESSAGE); // Generate the hash of comparing it - /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NETWORK-PACKAGE-HANDLER: packageInstance=%s,senderId=%s,senderPrivateKeyHash=%s', $packageInstance->__toString(), $packageInstance->getSenderId(), $packageInstance->getSenderPrivateKeyHash())); + /* DEBUG-DIE: */ die(sprintf('[%s:%d]: packageInstance=%s', __METHOD__, __LINE__, print_r($packageInstance, TRUE))); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('NETWORK-PACKAGE-HANDLER: packageInstance=%s,senderId=%s,senderPrivateKeyHash=%s', $packageInstance->__toString(), $packageInstance->getSenderId(), $packageInstance->getSenderPrivateKeyHash())); if (empty($packageInstance->getSenderId())) { // Invalid $packageInstance throw new InvalidArgumentException('packageInstance does not contain senderId'); diff --git a/application/hub/classes/helper/connection/class_BaseConnectionHelper.php b/application/hub/classes/helper/connection/class_BaseConnectionHelper.php index 9c2c87c72..4a9d49df8 100644 --- a/application/hub/classes/helper/connection/class_BaseConnectionHelper.php +++ b/application/hub/classes/helper/connection/class_BaseConnectionHelper.php @@ -126,13 +126,20 @@ abstract class BaseConnectionHelper extends BaseHubSystemHelper implements Visit */ private function getConnectionClassNameFromSocket () { // Get recipient address/port + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: CALLED!'); $recipientAddress = $this->getSocketInstance()->getSocketRecipientAddress(); $recipientPort = $this->getSocketInstance()->getSocketRecipientPort(); // Construct it - $class = sprintf('%s:%d:%s', $recipientAddress, $recipientPort, parent::__toString()); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: recipientAddress=%s,recipientPort=%d', $recipientAddress, $recipientPort)); + $class = sprintf('%s:%d:%s', + $recipientAddress, + $recipientPort, + parent::__toString() + ); // ... and return it + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: class=%s - EXIT!', $class)); return $class; } @@ -143,7 +150,11 @@ abstract class BaseConnectionHelper extends BaseHubSystemHelper implements Visit */ private function initState() { // Get the state factory and create the initial state. + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: CALLED!'); PeerStateFactory::createPeerStateInstanceByName('init', $this); + + // Trace message + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: EXIT!'); } /** @@ -160,19 +171,15 @@ abstract class BaseConnectionHelper extends BaseHubSystemHelper implements Visit * @return $chunkData Raw data chunk */ private function getRawDataFromPackageArray (DeliverablePackage $packageInstance) { - // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: currentFinalHash=' . $this->currentFinalHash); - // Make sure the final hash is set + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: currentFinalHash=' . $this->currentFinalHash); assert((is_string($this->currentFinalHash)) && (!empty($this->currentFinalHash))); // Get the next raw data chunk from the fragmenter $rawDataChunk = $this->getFragmenterInstance()->getNextRawDataChunk($this->currentFinalHash); - // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: rawDataChunk=' . print_r($rawDataChunk, TRUE)); - // Get chunk hashes and chunk data + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: rawDataChunk=' . print_r($rawDataChunk, TRUE)); $chunkHashes = array_keys($rawDataChunk); $chunkData = array_values($rawDataChunk); @@ -180,21 +187,19 @@ abstract class BaseConnectionHelper extends BaseHubSystemHelper implements Visit $rawData = ''; // Is the required data there? - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: chunkHashes[]=' . count($chunkHashes) . ',chunkData[]=' . count($chunkData)); - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('chunkData='.print_r($chunkData, TRUE)); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: chunkHashes()=' . count($chunkHashes) . ',chunkData()=' . count($chunkData)); + //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('chunkData='.print_r($chunkData, TRUE)); if ((isset($chunkHashes[0])) && (isset($chunkData[0]))) { // Remember this chunk as queued $this->queuedChunks[$chunkHashes[0]] = $chunkData[0]; // Return the raw data - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: rawData()=' . strlen($chunkData[0]) . ' bytes.'); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: rawData()=' . strlen($chunkData[0]) . ' bytes.'); $rawData = $chunkData[0]; } // END - if - // Trace message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: rawData()=%d - EXIT!', strlen($rawData))); - // Return raw data + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: rawData(%d)=%s - EXIT!', strlen($rawData), $rawData)); return $rawData; } @@ -204,7 +209,7 @@ abstract class BaseConnectionHelper extends BaseHubSystemHelper implements Visit * @param $isInitialized Name of used protocol in this connection * @return void */ - protected final function setIsInitialized ($isInitialized) { + protected final function setIsInitialized (bool $isInitialized) { $this->isInitialized = $isInitialized; } @@ -242,7 +247,7 @@ abstract class BaseConnectionHelper extends BaseHubSystemHelper implements Visit */ public function sendRawPackageData (DeliverablePackage $packageInstance) { // Trace message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: packageInstance=%s - CALLED!', $packageInstance->__toString())); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: packageInstance=%s - CALLED!', $packageInstance->__toString())); // The helper's state must be 'connected' $this->getStateInstance()->validatePeerStateConnected(); @@ -250,15 +255,11 @@ abstract class BaseConnectionHelper extends BaseHubSystemHelper implements Visit // Implode the package data array and fragement the resulting string, returns the final hash $finalHash = $this->getFragmenterInstance()->fragmentPackageArray($packageInstance, $this); - // Trace message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: finalHash[%s]=%s', gettype($finalHash), $finalHash)); - // Is the final hash set? + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: finalHash[%s]=%s', gettype($finalHash), $finalHash)); if ($finalHash !== TRUE) { - // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: Setting finalHash=' . $finalHash . ',currentFinalHash[' . gettype($this->currentFinalHash) . ']=' . $this->currentFinalHash); - // Set final hash + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: Setting finalHash=%s,currentFinalHash[%s]=%s', $finalHash, gettype($this->currentFinalHash), $this->currentFinalHash)); $this->currentFinalHash = $finalHash; } // END - if @@ -271,50 +272,33 @@ abstract class BaseConnectionHelper extends BaseHubSystemHelper implements Visit // Fill sending buffer with data while (TRUE) { - // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: dataStream()=%d - BEFORE!', strlen($dataStream))); - // Convert the package data array to a raw data stream + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: dataStream()=%d - BEFORE!', strlen($dataStream))); $dataStream = $this->getRawDataFromPackageArray($packageInstance); - // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: dataStream()=%d - AFTER!', strlen($dataStream))); - // Is it empty? + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: dataStream()=%d - AFTER!', strlen($dataStream))); if (strlen($dataStream) == 0) { - // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: dataStream is now empty, exiting loop ...'); - // Abort here + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: dataStream is now empty, exiting loop ...'); break; } // END - if - // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: Adding ' . strlen($dataStream) . ' bytes to the sending buffer ...'); - // Add raw data + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: Adding %d bytes to the sending buffer ...', strlen($dataStream))); $rawData .= $dataStream; } // END - while - // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: rawData()=%d - after loop ...', strlen($rawData))); - - // Nothing to sent is bad news, so assert on it - assert(strlen($rawData) > 0); - // Calculate buffer size + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: rawData()=%d - after loop ...', strlen($rawData))); $bufferSize = $this->getConfigInstance()->getConfigEntry($this->getProtocolName() . '_buffer_length'); - // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: bufferSize=%d', $bufferSize)); - // Encode the raw data with our output-stream + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: bufferSize=%d', $bufferSize)); $encodedData = $this->getOutputStreamInstance()->streamData($rawData); - // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: socketResource[%s]=%s', gettype($this->getSocketInstance()->getSocketResource()), $this->getSocketInstance()->getSocketResource())); - // Init array + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-HELPER: socketResource[%s]=%s', gettype($this->getSocketInstance()->getSocketResource()), $this->getSocketInstance()->getSocketResource())); $encodedDataArray = array( NetworkPackageHandler::RAW_INDEX_FINAL_HASH => $this->currentFinalHash, NetworkPackageHandler::RAW_INDEX_ENCODED_DATA => $encodedData, @@ -328,7 +312,7 @@ abstract class BaseConnectionHelper extends BaseHubSystemHelper implements Visit $this->getPackageHandlerInstance()->getStackInstance()->pushNamed(NetworkPackageHandler::STACKER_NAME_OUTGOING_STREAM, $encodedDataArray); // Trace message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: EXIT!'); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONNECTION-HELPER: EXIT!'); } /** diff --git a/application/hub/classes/info/connection/class_ConnectionInfo.php b/application/hub/classes/info/connection/class_ConnectionInfo.php index 87ab06435..47c62820c 100644 --- a/application/hub/classes/info/connection/class_ConnectionInfo.php +++ b/application/hub/classes/info/connection/class_ConnectionInfo.php @@ -14,6 +14,9 @@ use Org\Shipsimu\Hub\Locator\Node\LocateableNode; use Org\Mxchange\CoreFramework\Registry\Registerable; use Org\Mxchange\CoreFramework\Socket\InvalidSocketException; +// Import SPL stuff +use \InvalidArgumentException; + /** * A Connection information class * @@ -57,10 +60,17 @@ class ConnectionInfo extends BaseInfo implements ShareableInfo, Registerable { * * @param $connectionType Connection type (valid: 'incoming', 'outgoing', 'server') * @return $infoInstance An instance of a ShareableInfo class + * @throws InvalidArgumentException If $connectionType is empty */ - public final static function createConnectionInfo ($connectionType) { - // Get new instance + public final static function createConnectionInfo (string $connectionType) { + // Validate parameter /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-INFO: connectionType=%s - CALLED!', $connectionType)); + if (empty($connectionType)) { + // Throw exception + throw new InvalidArgumentException('connectionType is empty'); + } + + // Get new instance $infoInstance = new ConnectionInfo(); // Set connection type here @@ -77,7 +87,7 @@ class ConnectionInfo extends BaseInfo implements ShareableInfo, Registerable { * @param $connectionType Connection type * @return void */ - private function setConnectionType ($connectionType) { + private function setConnectionType (string $connectionType) { $this->connectionType = $connectionType; } @@ -141,7 +151,7 @@ class ConnectionInfo extends BaseInfo implements ShareableInfo, Registerable { // Init variables /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-INFO: socketInstance=%s - CALLED!', $socketInstance->__toString())); $socketAddress = '0.0.0.0'; - $socketPort = '0'; + $socketPort = 0; // Get peer name if (!$socketInstance->determineSocketPeerName($socketAddress, $socketPort)) { diff --git a/application/hub/classes/listener/class_BaseListener.php b/application/hub/classes/listener/class_BaseListener.php index cf91676fd..be43cdbcb 100644 --- a/application/hub/classes/listener/class_BaseListener.php +++ b/application/hub/classes/listener/class_BaseListener.php @@ -25,6 +25,7 @@ use Org\Mxchange\CoreFramework\Visitor\Visitable; use Org\Mxchange\CoreFramework\Visitor\Visitor; // Import SPL stuff +use \InvalidArgumentException; use \LogicException; /** @@ -113,8 +114,8 @@ abstract class BaseListener extends BaseHubSystem implements Visitable { * @param $listenAddress The address this listener should listen on * @return void */ - protected final function setListenAddress ($listenAddress) { - $this->listenAddress = (string) $listenAddress; + protected final function setListenAddress (string $listenAddress) { + $this->listenAddress = $listenAddress; } /** @@ -132,8 +133,8 @@ abstract class BaseListener extends BaseHubSystem implements Visitable { * @param $listenPort The port this listener should listen on * @return void */ - protected final function setListenPort ($listenPort) { - $this->listenPort = (int) $listenPort; + protected final function setListenPort (int $listenPort) { + $this->listenPort = $listenPort; } /** @@ -151,7 +152,7 @@ abstract class BaseListener extends BaseHubSystem implements Visitable { * @param $configEntry The configuration entry holding our listen address * @return void */ - public final function setListenAddressByConfiguration ($configEntry) { + public final function setListenAddressByConfiguration (string $configEntry) { $this->setListenAddress($this->getConfigInstance()->getConfigEntry($configEntry)); } @@ -161,7 +162,7 @@ abstract class BaseListener extends BaseHubSystem implements Visitable { * @param $configEntry The configuration entry holding our listen port * @return void */ - public final function setListenPortByConfiguration ($configEntry) { + public final function setListenPortByConfiguration (string $configEntry) { $this->setListenPort($this->getConfigInstance()->getConfigEntry($configEntry)); } @@ -348,13 +349,19 @@ abstract class BaseListener extends BaseHubSystem implements Visitable { * * @param $peerSuffix Suffix for peer name (e.g. :0 for TCP(/UDP?) connections) * @return void + * @throws InvalidArgumentException If $peerSuffix is empty * @throws LogicException If no info instance can be created */ - protected function doListenSocketSelect ($peerSuffix) { - // Check on all instances + protected function doListenSocketSelect (string $peerSuffix) { + // Validate parameter and socket instance /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-LISTENER: peerSuffix=%s - CALLED!', strtoupper($this->getProtocolName()), $peerSuffix)); - assert($this->getPoolInstance() instanceof Poolable); - assert($this->getSocketInstance()->isValidSocket()); + if (empty($peerSuffix)) { + // Throw exception + throw new InvalidArgumentException('peerSuffix is empty'); + } elseif(!$this->getSocketInstance()->isValidSocket()) { + // Invalid socket + throw new LogicException(sprintf('this->socketInstance->socketResource=%s is not valid', $this->getSocketInstance()->getSocketResource())); + } // Get next socket instance from pool over the factory $socketInstance = SocketFactory::createNextAcceptedSocketFromPool($this->getPoolInstance(), $this->getSocketInstance()); @@ -382,7 +389,7 @@ abstract class BaseListener extends BaseHubSystem implements Visitable { // Init peer address/port $peerAddress = '0.0.0.0'; - $peerPort = '0'; + $peerPort = 0; // Get peer name if (!$socketInstance->determineSocketPeerName($peerAddress, $peerPort)) { @@ -412,10 +419,8 @@ abstract class BaseListener extends BaseHubSystem implements Visitable { * @return $accepts Whether this listener does accept */ public function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance) { - // Trace message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-LISTENER: packageInstance=%s - CALLED!', strtoupper($this->getProtocolName()), $packageInstance)); - // Check if same socket protocol + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-LISTENER: packageInstance=%s - CALLED!', strtoupper($this->getProtocolName()), $packageInstance)); $socketProtocol = $this->getSocketInstance()->getSocketProtocol(); // Get UNL instance @@ -424,16 +429,12 @@ abstract class BaseListener extends BaseHubSystem implements Visitable { // Get protocol from it $unlProtocol = $locatorInstance->getUnlProtocol(); - // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-LISTENER: locatorInstance->unlProtocol=%s,socketProtocol=%s', strtoupper($this->getProtocolName()), $unlProtocol, $socketProtocol)); - // Is same protocol? + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-LISTENER: locatorInstance->unlProtocol=%s,socketProtocol=%s', strtoupper($this->getProtocolName()), $unlProtocol, $socketProtocol)); $accepts = ($unlProtocol == $socketProtocol); - // Trace message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-LISTENER: accepts=%d - EXIT!', strtoupper($this->getProtocolName()), $accepts)); - // Return the result + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-LISTENER: accepts=%d - EXIT!', strtoupper($this->getProtocolName()), $accepts)); return $accepts; } diff --git a/application/hub/classes/miner/class_BaseHubMiner.php b/application/hub/classes/miner/class_BaseHubMiner.php index 32a8d2809..c44f4387b 100644 --- a/application/hub/classes/miner/class_BaseHubMiner.php +++ b/application/hub/classes/miner/class_BaseHubMiner.php @@ -158,8 +158,8 @@ abstract class BaseHubMiner extends BaseHubSystem implements Updateable { * @param $version Version number of this miner * @return void */ - public final function enableIsActive ($isActive = TRUE) { - $this->isActive = (bool) $isActive; + public final function enableIsActive (bool $isActive = TRUE) { + $this->isActive = $isActive; } /** diff --git a/application/hub/classes/nodes/class_BaseHubNode.php b/application/hub/classes/nodes/class_BaseHubNode.php index 88a432b1f..4d1501a4a 100644 --- a/application/hub/classes/nodes/class_BaseHubNode.php +++ b/application/hub/classes/nodes/class_BaseHubNode.php @@ -654,8 +654,8 @@ abstract class BaseHubNode extends BaseHubSystem implements Updateable, AddableC * @param $isActive Whether the hub is active * @return void */ - public final function enableIsActive ($isActive = TRUE) { - $this->isActive = (bool) $isActive; + public final function enableIsActive (bool $isActive = TRUE) { + $this->isActive = $isActive; } /** @@ -730,7 +730,7 @@ abstract class BaseHubNode extends BaseHubSystem implements Updateable, AddableC * @param $acceptAnnouncements Whether this node accepts announcements (default: TRUE) * @return void */ - protected final function enableAcceptingAnnouncements ($acceptAnnouncements = TRUE) { + protected final function enableAcceptingAnnouncements (bool $acceptAnnouncements = TRUE) { $this->acceptAnnouncements = $acceptAnnouncements; } @@ -740,7 +740,7 @@ abstract class BaseHubNode extends BaseHubSystem implements Updateable, AddableC * @param $acceptDhtBootstrap Whether this node accepts DHT bootstrap requests (default: TRUE) * @return void */ - public final function enableAcceptDhtBootstrap ($acceptDhtBootstrap = TRUE) { + public final function enableAcceptDhtBootstrap (bool $acceptDhtBootstrap = TRUE) { //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NODE: Enabling DHT bootstrap requests ...'); $this->acceptDhtBootstrap = $acceptDhtBootstrap; } diff --git a/application/hub/classes/pools/peer/class_DefaultPeerPool.php b/application/hub/classes/pools/peer/class_DefaultPeerPool.php index 9bdd7cfde..7f57e148f 100644 --- a/application/hub/classes/pools/peer/class_DefaultPeerPool.php +++ b/application/hub/classes/pools/peer/class_DefaultPeerPool.php @@ -17,6 +17,7 @@ use Org\Shipsimu\Hub\Pool\Peer\PoolablePeer; use Org\Mxchange\CoreFramework\Socket\InvalidSocketException; // Import SPL stuff +use \InvalidArgumentException; use \LogicException; /** @@ -102,11 +103,16 @@ class DefaultPeerPool extends BasePool implements PoolablePeer { * @param $socketInstance An instance of a StorableSocket class * @param $connectionType Type of connection, can only be 'incoming', 'outgoing' or 'server' * @return void + * @throws InvalidArgumentException If $connectionType is empty * @throws InvalidConnectionTypeException If the provided connection type is not valid */ - public function addPeer (StorableSocket $socketInstance, $connectionType) { - // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DEFAULT-PEER-POOL: socketResource[' . gettype($socketInstance->getSocketResource()) . ']=' . $socketInstance->getSocketResource() . ',connectionType=' . $connectionType . ' - CALLED!'); + public function addPeer (StorableSocket $socketInstance, string $connectionType) { + // Validate parameter + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DEFAULT-PEER-POOL: socketResource[%s]=%s,connectionType=%s - CALLED!', gettype($socketInstance->getSocketResource()), $socketInstance->getSocketResource(), $connectionType)); + if (empty($connectionType)) { + // Throw exception + throw new InvalidArgumentException('connectionType is empty'); + } // Validate the socket $this->validateSocket($socketInstance); @@ -115,14 +121,11 @@ class DefaultPeerPool extends BasePool implements PoolablePeer { if (!$socketInstance->isValidConnectionType($connectionType)) { // Is not a valid connection type! throw new InvalidConnectionTypeException(array($this, $connectionType), self::EXCEPTION_INVALID_CONNECTION_TYPE); - } // END - if + } // Default is this peer's IP $peerAddress = '0.0.0.0'; - $peerPort = '0'; - - // Trace message - //* NOSY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DEFAULT-PEER-POOL: Calling this->getListenerInstance() ...'); + $peerPort = 0; // The socket resource should not match server socket if (!$this->getListenerInstance()->getSocketInstance()->equals($socketInstance)) { @@ -190,8 +193,16 @@ class DefaultPeerPool extends BasePool implements PoolablePeer { * @param $connectionType Type of connection, can only be 'incoming', 'outgoing' or 'server' * @return $sockets An array with sockets of given type * @throws InvalidConnectionTypeException If the found connection type is not valid + * @throws InvalidArgumentException If $connectionType is empty */ - public function getSocketsByConnectionType ($connectionType) { + public function getSocketsByConnectionType (string $connectionType) { + // Validate parameter + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DEFAULT-PEER-POOL: connectionType=%s - CALLED!', $connectionType)); + if (empty($connectionType)) { + // Throw exception + throw new InvalidArgumentException('connectionType is empty'); + } + // Get the array list $socketArrays = $this->getArrayFromList('pool'); @@ -226,9 +237,9 @@ class DefaultPeerPool extends BasePool implements PoolablePeer { * @throws InvalidConnectionTypeException If the provided connection type is not valid * @throws LogicException If an expected array element is missing */ - public function getSocketFromPackageInstance (DeliverablePackage $packageInstance, $connectionType = NULL) { + public function getSocketFromPackageInstance (DeliverablePackage $packageInstance, string $connectionType = NULL) { // Default is no socket - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DEFAULT-PEER-POOL:packageInstance=%s,connectionType[%s]=%s - CALLED!', $packageInstance->__toString(), gettype($connectionType), $connectionType)); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DEFAULT-PEER-POOL: packageInstance=%s,connectionType[%s]=%s - CALLED!', $packageInstance->__toString(), gettype($connectionType), $connectionType)); $socketInstance = NULL; // Resolve recipient (UNL) into a handler instance @@ -263,7 +274,7 @@ class DefaultPeerPool extends BasePool implements PoolablePeer { // Init peer address/port $peerAddress = '0.0.0.0'; - $peerPort = '0'; + $peerPort = 0; // Try to get the "peer"'s name /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DEFAULT-PEER-POOL: socketInstance->socketResource=%s,socketInstance->socketProtocol=%s,socketArray[%s]=%s', $socketArray[Poolable::SOCKET_ARRAY_INSTANCE]->getSocketResource(), $socketArray[Poolable::SOCKET_ARRAY_INSTANCE]->getSocketProtocol(), Poolable::SOCKET_ARRAY_CONN_TYPE, $socketArray[Poolable::SOCKET_ARRAY_CONN_TYPE])); diff --git a/application/hub/classes/template/class_BaseXmlTemplateEngine.php b/application/hub/classes/template/class_BaseXmlTemplateEngine.php index fba4658f6..b86515537 100644 --- a/application/hub/classes/template/class_BaseXmlTemplateEngine.php +++ b/application/hub/classes/template/class_BaseXmlTemplateEngine.php @@ -9,6 +9,9 @@ use Org\Mxchange\CoreFramework\Factory\Template\XmlTemplateEngineFactory; use Org\Mxchange\CoreFramework\Registry\GenericRegistry; use Org\Mxchange\CoreFramework\Template\Engine\BaseTemplateEngine; +// Import SPL stuff +use \InvalidArgumentException; + /** * A generic XML template engine class * @@ -230,7 +233,14 @@ abstract class BaseXmlTemplateEngine extends BaseTemplateEngine { * @param $key Key to read from * @return $value Value from variable */ - public function readXmlData ($key) { + public function readXmlData (string $key) { + // Is key parameter valid? + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-XML-TEMPLATE-ENGINE: key=%s - CALLED!', $key)); + if (empty($key)) { + // Throw exception + throw new InvalidArgumentException('Parameter key is empty'); + } + // Read the variable $value = parent::readVariable($key, 'general'); diff --git a/application/hub/interfaces/apt-proxy/class_AptProxy.php b/application/hub/interfaces/apt-proxy/class_AptProxy.php index 38ff9351b..cced7559d 100644 --- a/application/hub/interfaces/apt-proxy/class_AptProxy.php +++ b/application/hub/interfaces/apt-proxy/class_AptProxy.php @@ -65,7 +65,7 @@ interface AptProxy extends HubInterface { * @param $version Version number of this apt-proxy * @return void */ - function enableIsActive ($isActive = TRUE); + function enableIsActive (bool $isActive = TRUE); /** * Determines whether the apt-proxy is active @@ -74,6 +74,3 @@ interface AptProxy extends HubInterface { */ function isActive (); } - -// [EOF] -?> diff --git a/application/hub/interfaces/chat/class_Chatter.php b/application/hub/interfaces/chat/class_Chatter.php index a8b44e355..5fd84af77 100644 --- a/application/hub/interfaces/chat/class_Chatter.php +++ b/application/hub/interfaces/chat/class_Chatter.php @@ -65,7 +65,7 @@ interface Chatter extends HubInterface { * @param $version Version number of this chatter * @return void */ - function enableIsActive ($isActive = TRUE); + function enableIsActive (bool $isActive = TRUE); /** * Determines whether the chatter is active @@ -74,6 +74,3 @@ interface Chatter extends HubInterface { */ function isActive (); } - -// [EOF] -?> diff --git a/application/hub/interfaces/container/socket/class_StorableSocket.php b/application/hub/interfaces/container/socket/class_StorableSocket.php index b6bec8e9a..f87dd245a 100644 --- a/application/hub/interfaces/container/socket/class_StorableSocket.php +++ b/application/hub/interfaces/container/socket/class_StorableSocket.php @@ -124,7 +124,7 @@ interface StorableSocket extends FrameworkInterface { * @return $result Result from asking for peer address * @throws InvalidSocketException If stored socket is invalid */ - function determineSocketPeerName (&$peerAddress, &$peerPort); + function determineSocketPeerName (string &$peerAddress, int &$peerPort); /** * Calls socket_select() on stored socket resource @@ -216,7 +216,7 @@ interface StorableSocket extends FrameworkInterface { * @param $unl A Universal Node Locator * @return $matches Whether $address matches with the one from package data */ - function ifAddressMatches ($unl); + function ifAddressMatches (string $unl); /** * Checks whether the given socket matches with stored @@ -284,7 +284,7 @@ interface StorableSocket extends FrameworkInterface { * @throws InvalidSocketException If the stored socket resource is no socket resource * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back */ - function handleSocketError ($method, $line); + function handleSocketError (string $method, int $line); /** * Do the shutdown sequence for this connection helper @@ -301,7 +301,7 @@ interface StorableSocket extends FrameworkInterface { * @param $connectionType Type of connection, can be 'incoming', 'outgoing' or 'server' * @return $isValid Whether the provided connection type is valid */ - function isValidConnectionType ($connectionType); + function isValidConnectionType (string $connectionType); /** * Clears last socket error diff --git a/application/hub/interfaces/crawler/class_Crawler.php b/application/hub/interfaces/crawler/class_Crawler.php index c43d9bdaa..3a57461aa 100644 --- a/application/hub/interfaces/crawler/class_Crawler.php +++ b/application/hub/interfaces/crawler/class_Crawler.php @@ -66,7 +66,7 @@ interface Crawler extends HubInterface { * @param $version Version number of this crawler * @return void */ - function enableIsActive ($isActive = TRUE); + function enableIsActive (bool $isActive = TRUE); /** * Determines whether the crawler is active @@ -83,6 +83,3 @@ interface Crawler extends HubInterface { */ function initCrawler (Stateable $stateInstance); } - -// [EOF] -?> diff --git a/application/hub/interfaces/cruncher/class_CruncherHelper.php b/application/hub/interfaces/cruncher/class_CruncherHelper.php index acc8fd00f..5f6fb41f2 100644 --- a/application/hub/interfaces/cruncher/class_CruncherHelper.php +++ b/application/hub/interfaces/cruncher/class_CruncherHelper.php @@ -74,7 +74,7 @@ interface CruncherHelper extends HubInterface { * @param $version Version number of this cruncher * @return void */ - function enableIsActive ($isActive = TRUE); + function enableIsActive (bool $isActive = TRUE); /** * Determines whether the cruncher is active @@ -90,6 +90,3 @@ interface CruncherHelper extends HubInterface { */ function initBufferQueues (); } - -// [EOF] -?> diff --git a/application/hub/interfaces/database/frontend/class_NodeDhtWrapper.php b/application/hub/interfaces/database/frontend/class_NodeDhtWrapper.php index e73f9720f..4447fd20f 100644 --- a/application/hub/interfaces/database/frontend/class_NodeDhtWrapper.php +++ b/application/hub/interfaces/database/frontend/class_NodeDhtWrapper.php @@ -172,7 +172,7 @@ interface NodeDhtWrapper extends DatabaseWrapper { * @param $value Value to compare if key matches * @return $recipients An indexed array with DHT recipients */ - function getResultFromKeyValue ($key, $value); + function getResultFromKeyValue (string $key, $value); /** * Enable DHT bootstrap request acceptance for local node diff --git a/application/hub/interfaces/discovery/recipient/socket/class_DiscoverableSocket.php b/application/hub/interfaces/discovery/recipient/socket/class_DiscoverableSocket.php index d1acb3b18..64637efbf 100644 --- a/application/hub/interfaces/discovery/recipient/socket/class_DiscoverableSocket.php +++ b/application/hub/interfaces/discovery/recipient/socket/class_DiscoverableSocket.php @@ -40,7 +40,7 @@ interface DiscoverableSocket extends DiscoverableRecipient { * @throws NoListGroupException If the procol group is not found in peer list * @throws NullPointerException If listenerInstance is NULL */ - function discoverSocket (DeliverablePackage $packageInstance, $connectionType); + function discoverSocket (DeliverablePackage $packageInstance, string $connectionType); /** * Tries to dicover the right listener instance diff --git a/application/hub/interfaces/distributable/class_Distributable.php b/application/hub/interfaces/distributable/class_Distributable.php index 1388ed7dc..cb497e733 100644 --- a/application/hub/interfaces/distributable/class_Distributable.php +++ b/application/hub/interfaces/distributable/class_Distributable.php @@ -112,7 +112,7 @@ interface Distributable extends HubInterface { * @param $value Value to check on found key * @return $recipientList Array with DHT recipients from given key/value pair */ - function findRecipientsByKey ($key, $value); + function findRecipientsByKey (string $key, $value); /** * Enable DHT bootstrap request acceptance for local node diff --git a/application/hub/interfaces/miner/class_MinerHelper.php b/application/hub/interfaces/miner/class_MinerHelper.php index 64f08745d..656ee3f44 100644 --- a/application/hub/interfaces/miner/class_MinerHelper.php +++ b/application/hub/interfaces/miner/class_MinerHelper.php @@ -75,7 +75,7 @@ interface MinerHelper extends HubInterface { * @param $version Version number of this miner * @return void */ - function enableIsActive ($isActive = TRUE); + function enableIsActive (bool $isActive = TRUE); /** * Determines whether the miner is active diff --git a/application/hub/interfaces/pool/peer/class_PoolablePeer.php b/application/hub/interfaces/pool/peer/class_PoolablePeer.php index f28774d05..17b50a40c 100644 --- a/application/hub/interfaces/pool/peer/class_PoolablePeer.php +++ b/application/hub/interfaces/pool/peer/class_PoolablePeer.php @@ -38,7 +38,7 @@ interface PoolablePeer extends Poolable, SocketTag { * @return void * @throws InvalidConnectionTypeException If the provided connection type is not valid */ - function addPeer (StorableSocket $socketInstance, $connectionType); + function addPeer (StorableSocket $socketInstance, string $connectionType); /** * Getter for array of all socket resources @@ -61,6 +61,6 @@ interface PoolablePeer extends Poolable, SocketTag { * @return $sockets An array with sockets of given type * @throws InvalidConnectionTypeException If the found connection type is not valid */ - function getSocketsByConnectionType ($connectionType); + function getSocketsByConnectionType (string $connectionType); } diff --git a/application/hub/interfaces/socket/class_SocketTag.php b/application/hub/interfaces/socket/class_SocketTag.php index 1f955dc46..936540dbc 100644 --- a/application/hub/interfaces/socket/class_SocketTag.php +++ b/application/hub/interfaces/socket/class_SocketTag.php @@ -37,6 +37,6 @@ interface SocketTag extends HubInterface { * @return $socketInstance An instance of a StorableSocket class * @throws InvalidConnectionTypeException If the provided connection type is not valid */ - function getSocketFromPackageInstance (DeliverablePackage $packageInstance, $connectionType = NULL); + function getSocketFromPackageInstance (DeliverablePackage $packageInstance, string $connectionType = NULL); } diff --git a/core b/core index 6d6b58a10..c15d02389 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit 6d6b58a1042e6ad5d6277f8ff5144c95f1abd427 +Subproject commit c15d02389e67a880e7b4c6b19f2b06722efa4e6f -- 2.39.5