*
* @return $selfInstance An instance of this class
*/
- public static final function getSelfInstance () {
+ public static final function getSelfInstance (): ManageableApplication {
// Is the instance there?
- if (is_null(self::getApplicationInstance())) {
+ if (!self::isApplicationInstanceSet()) {
self::setApplicationInstance(new ApplicationHelper());
}
*
* @return void
*/
- public function setupApplicationData () {
+ public function setupApplicationData (): void {
// Set all application data
$this->setAppName('Generic Object Sharing Hub');
$this->setAppVersion('0.0.0');
*
* @return void
*/
- public function initApplication () {
+ public function initApplication (): void {
// Get config instance
$cfg = FrameworkBootstrap::getConfigurationInstance();
*
* @return void
*/
- public function launchApplication () {
+ public function launchApplication (): void {
// Get request/response instances
$requestInstance = FrameworkBootstrap::getRequestInstance();
$responseInstance = FrameworkBootstrap::getResponseInstance();
* @return void
* @todo Nothing to add?
*/
- public function assignExtraTemplateData (CompileableTemplate $templateInstance) {
+ public function assignExtraTemplateData (CompileableTemplate $templateInstance): void {
}
/**
* @param $messageList An array of fatal messages
* @return void
*/
- public function handleFatalMessages (array $messageList) {
+ public function handleFatalMessages (array $messageList): void {
// Walk through all messages
foreach ($messageList as $message) {
exit(__METHOD__ . ':MSG:' . $message);
*
* @return $masterTemplateName Name of the master template
*/
- public function buildMasterTemplateName () {
+ public function buildMasterTemplateName (): string {
return 'node_daemon';
}
+
}
// Import application-specific stuff
use Org\Shipsimu\Hub\Container\BaseHubContainer;
+use Org\Shipsimu\Hub\Container\Socket\StorableSocket;
use Org\Shipsimu\Hub\Factory\Network\Locator\UniversalNodeLocatorFactory;
use Org\Shipsimu\Hub\Factory\Socket\SocketFactory;
use Org\Shipsimu\Hub\Handler\Package\NetworkPackageHandler;
* @return $containerInstance An instance of a StorableSocket class
* @throws InvalidArgumentException If a parameter is not valid
*/
- public static final function createSocketContainer (Socket $socketResource, string $socketProtocol, DeliverablePackage $packageInstance, string $socketType) {
+ public static final function createSocketContainer (Socket $socketResource, string $socketProtocol, DeliverablePackage $packageInstance, string $socketType): StorableSocket {
// Validate parameter
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-CONTAINER: socketResource[]=%s,socketProtocol=%s,packageInstance=%s,socketType=%s - CALLED!', gettype($socketResource), $socketProtocol, $packageInstance->__toString(), $socketType));
if (empty($socketProtocol)) {
* @return $matches Whether $address matches with the one from package data
* @throws InvalidArgumentException If a parameter is not valid
*/
- public function ifAddressMatches (string $unl) {
+ public function ifAddressMatches (string $unl): bool {
// Is parameter valid?
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: unl=%s - CALLED!', strtoupper($this->getSocketProtocol()), $unl));
if (empty($unl)) {
* @param $socketResource An instance of a Socket class
* @return $matches Whether given socket matches
*/
- public function ifSocketResourceMatches (Socket $socketResource) {
+ public function ifSocketResourceMatches (Socket $socketResource): bool {
// So, does both match?
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: socketResource[]=%s,storedResource[]=%s - CALLED!', strtoupper($this->getSocketProtocol()), gettype($socketResource)), gettype($this->getSocketResource()));
$matches = ($socketResource === $this->getSocketResource());
*
* @return void
*/
- public function shutdownSocket () {
+ public function shutdownSocket (): void {
// Debug message
- self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(strtoupper($this->getSocketProtocol()) . '-SOCKET: Shutting down socket ' . $this->getPrintableName() . ' with state ' . ($this->getHelperInstance() instanceof Helper ? $this->getHelperInstance()->getPrintableState() : 'NULL') . ' ...');
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(strtoupper($this->getSocketProtocol()) . '-SOCKET: Shutting down socket ' . $this->getPrintableName() . ' with state ' . ($this->isHelperInstanceSet() ? $this->getHelperInstance()->getPrintableState() : 'NULL') . ' ...');
// Get a visitor instance
$visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
*
* @return void
*/
- public function halfShutdownSocket () {
+ public function halfShutdownSocket (): void {
// Debug message
self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(strtoupper($this->getSocketProtocol()) . '-SOCKET: Half-shutting down socket resource ' . $this->getPrintableName() . ' with state ' . $this->getHelperInstance()->getPrintableState() . ' ...');
* @return $result Result from asking for peer address
* @throws InvalidSocketException If socket is invalid
*/
- public function determineSocketPeerName (string &$peerAddress, int &$peerPort) {
+ public function determineSocketPeerName (string &$peerAddress, int &$peerPort): bool {
// Should be valid socket
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: peerAddress[%s]=%s,peerPort[%s]=%d - CALLED!', strtoupper($this->getSocketProtocol()), gettype($peerAddress), $peerAddress, gettype($peerPort), $peerPort));
if (!$this->isValidSocket()) {
*
* @return $socketProtocol Socket protocol
*/
- public function getSocketProtocol () {
+ public function getSocketProtocol (): string {
// Return it
return $this->socketProtocol;
}
* @throws LogicException If 'recipient' array element is not found
* @throws InvalidSocketException If socket is invalid
*/
- public function getSocketRecipientUnl () {
+ public function getSocketRecipientUnl (): string {
// Should be valid socket
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
if (!$this->isValidSocket()) {
* @return $recipientAddress Recipient's address part
* @throws InvalidSocketException If socket is invalid
*/
- public function getSocketRecipientAddress () {
+ public function getSocketRecipientAddress (): string {
// Should be valid socket
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
if (!$this->isValidSocket()) {
* @return $recipientPort Recipient's port part
* @throws InvalidSocketException If socket is invalid
*/
- public function getSocketRecipientPort () {
+ public function getSocketRecipientPort (): int {
// Should be valid socket
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
if (!$this->isValidSocket()) {
*
* @return $isValidSocket Whether the stored socket is valid
*/
- public function isValidSocket () {
+ public function isValidSocket (): bool {
// Is it valid?
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
// @TODO maybe add more checks? instanceof is still to less
* @return $errorCode Last socket error
* @throws InvalidSocketException If socket is invalid
*/
- public function getLastSocketErrorCode () {
+ public function getLastSocketErrorCode (): int {
// Should be valid socket
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
if (!$this->isValidSocket()) {
* @return $errorMessage Last socket error message
* @throws InvalidSocketException If socket is invalid
*/
- public function getLastSocketErrorMessage () {
+ public function getLastSocketErrorMessage (): string {
// Should be valid socket
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
if (!$this->isValidSocket()) {
*
* @return $codeName Code name to used e.g. with some_$codeName_socket_error_class or so
*/
- public function translateLastSocketErrorCodeToName () {
+ public function translateLastSocketErrorCodeToName (): string {
// Get last error code
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
$errorCode = $this->getLastSocketErrorCode();
* @throws InvalidSocketException If socket is invalid
* @throws NullPointerException If listener instance is not given
*/
- public function bindSocketToFile () {
+ public function bindSocketToFile (): bool {
// Should be valid socket
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
if (!$this->isValidSocket()) {
// Throw exception
throw new InvalidSocketException([$this], self::EXCEPTION_INVALID_SOCKET);
- } elseif (is_null($this->getSocketFile())) {
+ } elseif (!$this->isSocketFileSet()) {
// Throw exception
throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
}
* @throws InvalidSocketException If socket is invalid
* @throws NullPointerException If listener instance is not given
*/
- public function bindSocketToListener () {
+ public function bindSocketToListener (): bool {
// Should be valid socket
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
if (!$this->isValidSocket()) {
* @return $result Result from listening on socket
* @throws InvalidSocketException If stored socket is invalid
*/
- public function listenToSocket () {
+ public function listenToSocket (): bool {
// Should be valid socket
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
if (!$this->isValidSocket()) {
* @return $result Result of changing to non-blocking I/O
* @throws InvalidSocketException If stored socket is invalid
*/
- public function enableSocketNonBlocking () {
+ public function enableSocketNonBlocking (): bool {
// Should be valid socket
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
if (!$this->isValidSocket()) {
/**
* Tries to enable option "reuse address"
*
- * @return void
+ * @return $result Result of setting socket option
* @throws InvalidSocketException If stored socket is invalid
*/
- public function enableSocketReuseAddress () {
+ public function enableSocketReuseAddress (): bool {
// Should be valid socket
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
if (!$this->isValidSocket()) {
* @return $result Result from calling socket_connect()
* @throws InvalidSocketException If stored socket is invalid
*/
- public function connectToSocketRecipient () {
+ public function connectToSocketRecipient (): bool {
// Should be valid socket
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
if (!$this->isValidSocket()) {
* @return $isValid Whether the provided connection type is valid
* @throws InvalidArgumentException If $connectionType is empty
*/
- public function isValidConnectionType (string $connectionType) {
+ public function isValidConnectionType (string $connectionType): bool {
// Validate parameter
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: connectionType=%d - CALLED!', strtoupper($this->getSocketProtocol()), $connectionType));
if (empty($connectionType)) {
/**
* Calls socket_select() on stored socket resource
*
- * @return $socketInstance An instance of a StorableSocket class
+ * @return $socketInstance An instance of a StorableSocket class or NULL if no new socket was detected
* @throws InvalidSocketException If stored socket is invalid
*/
- public function acceptNewIncomingSocket () {
+ public function acceptNewIncomingSocket (): ?StorableSocket {
// Should be valid socket
/* EXTREME-NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
if (!$this->isValidSocket()) {
/**
* Reads (binary) data from socket instance
*
- * @return $rawData Raw data being read
+ * @return $rawData Raw data being read or FALSE on error
* @throws InvalidSocketException If the stored socket is not valid
*/
- public function readDataFromSocket () {
+ public function readDataFromSocket (): mixed {
// Should be valid socket
/* EXTREME-NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
if (!$this->isValidSocket()) {
*
* @return $result Whether identifying socket peer was successfull
*/
- public function identifySocketPeer () {
+ public function identifySocketPeer (): bool {
// Init peer address (IP)/port
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
$peerAddress = '0.0.0.0';
*
* @return $result Whether the option has been set
*/
- public function setSocketTimeoutOptions () {
+ public function setSocketTimeoutOptions (): bool {
// Call setter method with configured values
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
$result = $this->setSocketOption(SOL_SOCKET, SO_RCVTIMEO, [
*
* @return $result Whether OOB has been enabled
*/
- public function enableSocketOutOfBandData () {
+ public function enableSocketOutOfBandData (): bool {
// Call inner method
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
$result = $this->setSocketOption(SOL_SOCKET, SO_OOBINLINE, 1);
* @throws InvalidSocketException If stored socket is invalid
* @throws BadMethodCallException If no socket error was reported but method called
*/
- public function clearLastSocketError () {
+ public function clearLastSocketError (): void {
// Should be valid socket
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: Clearing socket error, this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
if (!$this->isValidSocket()) {
* @param $infoInstance An instance of a ShareableInfo class
* @return void
*/
- public function registerInfoInstance (ShareableInfo $infoInstance) {
+ public function registerInfoInstance (ShareableInfo $infoInstance): void {
// Get listener/helper from info class
/* NOSY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: infoInstance=%s,this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $infoInstance->__toString(), $this->getPrintableName()));
$listenerInstance = $infoInstance->getListenerInstance();
- $helperInstance = $infoInstance->getHelperInstance();
+ $helperInstance = $infoInstance->isHelperInstanceSet() ? $infoInstance->getHelperInstance() : NULL;
// Is there a listener or a connection helper instance set?
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-SOCKET: listenerInstance[]=%s,helperInstance[]=%s', strtoupper($this->getSocketProtocol()), gettype($listenerInstance), gettype($helperInstance)));
* @throws InvalidSocketException If stored socket is invalid
* @throws InvalidArgumentException If an array element is missing
*/
- public function writeBufferToSocketByArray (array &$socketBuffer, &$sentBytes) {
+ public function writeBufferToSocketByArray (array &$socketBuffer, &$sentBytes): bool {
// Should be valid socket
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: socketBuffer()=%d,sentBytes=%d - CALLED!', strtoupper($this->getSocketProtocol()), count($socketBuffer), $sentBytes));
//* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-SOCKET: socketBuffer=%s', strtoupper($this->getSocketProtocol()), print_r($socketBuffer, TRUE)));
* @throws InvalidSocketException If the stored socket resource is no socket resource
* @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
*/
- public function handleSocketError (string $method, int $line) {
+ public function handleSocketError (string $method, int $line): void {
// This method handles only socket resources
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: method=%s,line=%d,lastSocketErrorCode=%d - CALLED!', strtoupper($this->getSocketProtocol()), $method, $line, $this->getLastSocketErrorCode()));
if (!$this->isValidSocket()) {
* @return $handlerName Call-back method name for the error handler
* @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
*/
- protected function getSocketErrorHandlerFromCode (int $errorCode) {
+ protected function getSocketErrorHandlerFromCode (int $errorCode): string {
// Create a name from translated error code
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: errorCode=%d - CALLED!', strtoupper($this->getSocketProtocol()), $errorCode));
$handlerName = 'handleSocketError' . StringUtils::convertToClassName($this->translateSocketErrorCodeToName($errorCode));
* @return void
* @throws SocketBindingException The socket could not be bind to
*/
- protected function handleSocketErrorPermissionDenied () {
+ protected function handleSocketErrorPermissionDenied (): void {
// Get socket error code for verification
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
$socketError = $this->getLastSocketErrorCode();
* @return void
* @throws SocketConnectionException The connection attempts fails with a time-out
*/
- protected function handleSocketErrorConnectionTimedOut () {
+ protected function handleSocketErrorConnectionTimedOut (): void {
// Get socket error code for verification
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
$socketError = $this->getLastSocketErrorCode();
* @return void
* @throws SocketConnectionException The connection attempts fails with a time-out
*/
- protected function handleSocketErrorResourceUnavailable () {
+ protected function handleSocketErrorResourceUnavailable (): void {
// Get socket error code for verification
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
$socketError = $this->getLastSocketErrorCode();
* @return void
* @throws SocketConnectionException The connection attempts fails with a time-out
*/
- protected function handleSocketErrorConnectionRefused () {
+ protected function handleSocketErrorConnectionRefused (): void {
// Get socket error code for verification
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
$socketError = $this->getLastSocketErrorCode();
* @return void
* @throws SocketConnectionException The connection attempts fails with a time-out
*/
- protected function handleSocketErrorNoRouteToHost () {
+ protected function handleSocketErrorNoRouteToHost (): void {
// Get socket error code for verification
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
$socketError = $this->getLastSocketErrorCode();
* @return void
* @throws SocketConnectionException The connection attempts fails with a time-out
*/
- protected function handleSocketErrorOperationAlreadyProgress () {
+ protected function handleSocketErrorOperationAlreadyProgress (): void {
// Get socket error code for verification
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
$socketError = $this->getLastSocketErrorCode();
* @return void
* @throws SocketConnectionException The connection attempts fails with a time-out
*/
- protected function handleSocketErrorConnectionResetByPeer () {
+ protected function handleSocketErrorConnectionResetByPeer (): void {
// Get socket error code for verification
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
$socketError = $this->getLastSocketErrorCode();
* @return void
* @throws SocketOperationException The connection attempts fails with a time-out
*/
- protected function handleSocketErrorOperationNotSupported () {
+ protected function handleSocketErrorOperationNotSupported (): void {
// Get socket error code for verification
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
$socketError = $this->getLastSocketErrorCode();
*
* @return void
*/
- protected function handleSocketErrorOperationInProgress () {
+ protected function handleSocketErrorOperationInProgress (): void {
// Very common with non-blocking I/O
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: this->socketResource=%s - CALLED!', strtoupper($this->getSocketProtocol()), $this->getPrintableName()));
self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(strtoupper($this->getSocketProtocol()) . '-HELPER: Operation is now in progress, this is usual for non-blocking connections and is no bug.');
* @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 (int $errorCode) {
+ private function translateSocketErrorCodeToName (int $errorCode): string {
// Unknown error code by default
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: errorCode=%d - CALLED!', strtoupper($this->getSocketProtocol()), $errorCode));
$errorName = StorableSocket::SOCKET_ERROR_UNKNOWN;
* @return $result Whether calling socket_set_option() was successfull
* @throws InvalidSocketException If stored socket is invalid
*/
- private function setSocketOption (int $level, int $optionName, $optionValue) {
+ private function setSocketOption (int $level, int $optionName, mixed $optionValue): bool {
// Should be valid socket
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-SOCKET: level=%d,optionName=%d,optionValue[]=%s - CALLED!', strtoupper($this->getSocketProtocol()), $level, $optionName, gettype($optionValue)));
if (!$this->isValidSocket()) {
* @param $socketProtocol Socket protocol
* @return void
*/
- private function setSocketProtocol (string $socketProtocol) {
+ private function setSocketProtocol (string $socketProtocol): void {
$this->socketProtocol = $socketProtocol;
}
* @param $packageDataInstance An instance of a DeliverablePackage class
* @return void
*/
- public function setPackageDataInstance (DeliverablePackage $packageDataInstance) {
+ public function setPackageDataInstance (DeliverablePackage $packageDataInstance): void {
$this->packageDataInstance = $packageDataInstance;
}
*
* @return $packageDataInstance An instance of a DeliverablePackage class
*/
- public function getPackageDataInstance () {
+ public function getPackageDataInstance (): DeliverablePackage {
return $this->packageDataInstance;
}
*
* @return $socketFile An instance of a SplFileInfo class
*/
- public function getSocketFile () {
+ public function getSocketFile (): SplFileInfo {
return $this->socketFile;
}
* @param $socketFile An instance of a SplFileInfo class
* @return void
*/
- public function setSocketFile (SplFileInfo $socketFile) {
+ public function setSocketFile (SplFileInfo $socketFile): void {
$this->socketFile = $socketFile;
}
+ /**
+ * Checks whether a socket file instance is set
+ *
+ * @return $isset Whether a socket file instance is set
+ */
+ public function isSocketFileSet (): bool {
+ return ($this->socketFile instanceof SplFileInfo);
+ }
+
/**
* Getter for socket type
*
* @return $socketType Socket type
*/
- public function getSocketType () {
+ public function getSocketType (): string {
return $this->socketType;
}
* @param $socketType Socket type
* @return void
*/
- protected function setSocketType (string $socketType) {
+ protected function setSocketType (string $socketType): void {
$this->socketType = $socketType;
}
*
* @return $peerAddress Peer address
*/
- public function getPeerAddress () {
+ public function getPeerAddress (): string {
return $this->peerAddress;
}
* @param $peerAddress Peer address
* @return void
*/
- public function setPeerAddress (string $peerAddress) {
+ public function setPeerAddress (string $peerAddress): void {
$this->peerAddress = $peerAddress;
}
*
* @return $peerPort Peer port
*/
- public function getPeerPort () {
+ public function getPeerPort (): int {
return $this->peerPort;
}
* @param $peerPort Peer port
* @return void
*/
- public function setPeerPort (int $peerPort) {
+ public function setPeerPort (int $peerPort): void {
$this->peerPort = $peerPort;
}
*
* @return $senderAddress Sender address
*/
- public function getSenderAddress () {
+ public function getSenderAddress (): string {
return $this->senderAddress;
}
* @param $senderAddress Sender address
* @return void
*/
- public function setSenderAddress (string $senderAddress) {
+ public function setSenderAddress (string $senderAddress): void {
$this->senderAddress = $senderAddress;
}
*
* @return $senderPort Sender port
*/
- public function getSenderPort () {
+ public function getSenderPort (): int {
return $this->senderPort;
}
* @param $senderPort Sender port
* @return void
*/
- public function setSenderPort (int $senderPort) {
+ public function setSenderPort (int $senderPort): void {
$this->senderPort = $senderPort;
}
* @param $socketResource An instance of a Socket class
* @return void
*/
- public final function setSocketResource (Socket $socketResource) {
+ public final function setSocketResource (Socket $socketResource): void {
$this->socketResource = $socketResource;
}
*
* @return $socketResource A valid socket resource
*/
- public final function getSocketResource () {
+ public final function getSocketResource (): Socket {
return $this->socketResource;
}
*
* @return $frontendInstance An instance of the created frontend class
*/
- public static final function createNodeDistributedHashTableDatabaseFrontend () {
+ public static final function createNodeDistributedHashTableDatabaseFrontend (): NodeDhtFrontend {
// Get a new instance
$frontendInstance = new NodeDistributedHashTableDatabaseFrontend();
*
* @return $elements All elements for the DHT dabase
*/
- public static final function getAllElements () {
+ public static final function getAllElements (): array {
// Create array and ...
$elements = [
self::DB_COLUMN_NODE_ID,
* @param $nodeData An array with valid node data
* @return $searchInstance An instance of a SearchCriteria class
*/
- private function prepareSearchInstance (array $nodeData) {
+ private function prepareSearchInstance (array $nodeData): SearchableResult {
// Assert on array elements
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
assert(isset($nodeData[self::DB_COLUMN_NODE_ID]));
*
* @return $dataSetInstance An instance of a StoreableCriteria class
*/
- private function prepareLocalDataSetInstance () {
+ private function prepareLocalDataSetInstance (): StoreableCriteria {
// Debug message
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
*
* @return $unpublishedEntriesInstance Result instance
*/
- public final function getUnpublishedEntriesInstance () {
+ public final function getUnpublishedEntriesInstance (): SearchableResult {
return $this->unpublishedEntriesInstance;
}
*
* @return $isRegistered Whether *this* node is registered in the DHT
*/
- public function isLocalNodeRegistered () {
+ public function isLocalNodeRegistered (): bool {
// Get a search criteria instance
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
$searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
*
* @return void
*/
- public function registerLocalNode () {
+ public function registerLocalNode (): void {
// Debug message
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
* @return void
* @throws BadMethodCallException If node is not locally registered
*/
- public function updateLocalNode () {
+ public function updateLocalNode (): void {
// Check condition
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
if (!$this->isLocalNodeRegistered()) {
* @return $resultInstance An instance of a SearchableResult class
* @throws InvalidArgumentException If parameter $sessionId is not valid
*/
- public function findNodeLocalBySessionId (string $sessionId) {
+ public function findNodeLocalBySessionId (string $sessionId): SearchableResult {
// Validate parameter
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: sessionId=%s - CALLED!', $sessionId));
if (empty($sessionId)) {
* @param $locatorInstance An instance of a LocateableNode class
* @return $resultInstance An instance of a SearchableResult class
*/
- public function findNodeLocalByLocatorInstance (LocateableNode $locatorInstance) {
+ public function findNodeLocalByLocatorInstance (LocateableNode $locatorInstance): SearchableResult {
// Get search criteria
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: locatorInstance=%s - CALLED!', $locatorInstance->__toString()));
$searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
* @param $handlerInstance An instance of a HandleableDataSet class
* @return void
*/
- public function registerNodeByMessageInstance (DeliverableMessage $messageInstance, HandleableDataSet $handlerInstance) {
+ public function registerNodeByMessageInstance (DeliverableMessage $messageInstance, HandleableDataSet $handlerInstance): void {
// Get a data set instance
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: handlerInstance=' . $handlerInstance->__toString() . ' - CALLED!');
$dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_DHT));
* @param $searchInstance An instance of LocalSearchCriteria class
* @return void
*/
- public function updateNodeByMessageInstance (DeliverableMessage $messageInstance, HandleableDataSet $handlerInstance, LocalSearchCriteria $searchInstance) {
+ public function updateNodeByMessageInstance (DeliverableMessage $messageInstance, HandleableDataSet $handlerInstance, LocalSearchCriteria $searchInstance): void {
// Debug message
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
* @param $nodeData An array with valid node data
* @return $isRegistered Whether the given node data is already inserted
*/
- public function isNodeRegistered (array $nodeData) {
+ public function isNodeRegistered (array $nodeData): bool {
// Debug message
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
* @return void
* @throws NodeAlreadyRegisteredException If the node is already registered
*/
- public function registerNode (array $nodeData) {
+ public function registerNode (array $nodeData): void {
// Debug message
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
* @return void
* @throws NodeDataMissingException If the node's data is missing
*/
- public function updateNode (array $nodeData) {
+ public function updateNode (array $nodeData): void {
// Debug message
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: nodeData=' . print_r($nodeData, TRUE));
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
* @return $hasUnpublished Whether there are unpublished entries
* @todo Add minimum/maximum age limitations
*/
- public function hasUnpublishedEntries () {
+ public function hasUnpublishedEntries (): bool {
// Get search instance
$searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
* @return void
* @todo Add timestamp to dataset instance
*/
- public function initEntryPublication () {
+ public function initEntryPublication (): void {
// Debug message
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
* @param $data An array with possible non-public data that needs to be removed.
* @return $data A cleaned up array with only public data.
*/
- public function removeNonPublicDataFromArray(array $data) {
+ public function removeNonPublicDataFromArray(array $data): array {
// Currently call only inner method
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: Invoking parent::removeNonPublicDataFromArray(data) ...');
$data = parent::removeNonPublicDataFromArray($data);
* Find recipients for given package data and exclude the sender
*
* @param $packageInstance An instance of a DeliverablePackage class
- * @return $recipients An indexed array with DHT recipients
+ * @return $resultInstance An instance of a SearchableResult class
*/
- public function getResultFromExcludedSender (DeliverablePackage $packageInstance) {
+ public function getResultFromExcludedSender (DeliverablePackage $packageInstance): SearchableResult {
// Debug message
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: CALLED!');
* @return $recipients An indexed array with DHT recipients
* @throws InvalidArgumentException If $key is empty
*/
- public function getResultFromKeyValue (string $key, $value) {
+ public function getResultFromKeyValue (string $key, mixed $value): array {
// Is key parameter valid?
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('DHT-FRONTEND: key=%s,value[%s]=%s - CALLED!', $key, gettype($value), $value));
if (empty($key)) {
*
* @return void
*/
- public function enableAcceptDhtBootstrap () {
+ public function enableAcceptDhtBootstrap (): void {
// Debug message
/* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DHT-FRONTEND: Enabling DHT bootstrap requests ...');
use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Registry\Registerable;
+use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
/**
* A database frontend for node informations
*
* @return $frontendInstance An instance of the created frontend class
*/
- public static final function createNodeInformationDatabaseFrontend () {
+ public static final function createNodeInformationDatabaseFrontend (): NodeInformationFrontend {
// Get a new instance
$frontendInstance = new NodeInformationDatabaseFrontend();
*
* @return $resultInstance An instance of a SearchableResult class
*/
- public function findFirstNodeData () {
+ public function findFirstNodeData (): ?SearchableResult {
// Is there cache?
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NODE-FRONTEND: CALLED!');
if (!isset($GLOBALS[__METHOD__])) {
* @param $nodeInstance An instance of a Node class
* @return void
*/
- public function registerNodeId (Node $nodeInstance) {
+ public function registerNodeId (Node $nodeInstance): void {
// Get a dataset instance
$dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_INFORMATION));
* @param $searchInstance An instance of a LocalSearchCriteria class
* @return void
*/
- public function registerSessionId (Node $nodeInstance, LocalSearchCriteria $searchInstance) {
+ public function registerSessionId (Node $nodeInstance, LocalSearchCriteria $searchInstance): void {
// Get a dataset instance
$dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_INFORMATION));
* @param $searchInstance An instance of a LocalSearchCriteria class
* @return void
*/
- public function registerPrivateKey (Node $nodeInstance, LocalSearchCriteria $searchInstance) {
+ public function registerPrivateKey (Node $nodeInstance, LocalSearchCriteria $searchInstance): void {
// Get a dataset instance
$dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_NODE_INFORMATION));
* @param $data An array with possible non-public data that needs to be removed.
* @return $data A cleaned up array with only public data.
*/
- public function removeNonPublicDataFromArray(array $data) {
+ public function removeNonPublicDataFromArray(array $data): array {
// Currently call only inner method
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('NODE-FRONTEND: Invoking parent::removeNonPublicDataFromArray(data) ...');
$data = parent::removeNonPublicDataFromArray($data);
// Import application-specific stuff
use Org\Shipsimu\Hub\Discovery\Node\BaseNodeDiscovery;
use Org\Shipsimu\Hub\Factory\Tag\Package\PackageTagsFactory;
+use Org\Shipsimu\Hub\Handler\Protocol\HandleableProtocol;
use Org\Shipsimu\Hub\Network\Package\DeliverablePackage;
// Import framework stuff
* @param $packageInstance An instance of a DeliverablePackage class
* @return $protocolInstance An instance of a HandleableProtocol class
*/
- public static final function determineProtocolByPackageInstance (DeliverablePackage $packageInstance) {
+ public static final function determineProtocolByPackageInstance (DeliverablePackage $packageInstance): HandleableProtocol {
// First we need a tags instance
$tagsInstance = PackageTagsFactory::createPackageTagsInstance();
* @return $protocolType Type of protocol, e.g. 'tcp' for TCP/IPv4 connections
* @throws InvalidArgumentException If $packageInstance has no valid recipient UNL set
*/
- public static final function discoverProtocolByPackageInstance (DeliverablePackage $packageInstance) {
+ public static final function discoverProtocolByPackageInstance (DeliverablePackage $packageInstance): string {
/*
* "Explode" the 'recipient' array element into a new one, giving at
* least two entries: protocol://address
*
* @return $discoveryInstance An instance of this discovery class
*/
- public static final function createPackageSocketDiscovery () {
+ public static final function createPackageSocketDiscovery (): DiscoverableSocket {
// Get an instance of this class
$discoveryInstance = new PackageSocketDiscovery();
* @param $packageInstance An instance of a DeliverablePackage class
* @return $listenerInstance An instance of a Listenable instance or null
*/
- public function discoverListenerInstance (HandleableProtocol $protocolInstance, DeliverablePackage $packageInstance) {
+ public function discoverListenerInstance (HandleableProtocol $protocolInstance, DeliverablePackage $packageInstance): Listenable {
// Debug message
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('PACKAGE-SOCKET-DISCOVERY: protocolInstance=' . $protocolInstance->__toString() . ',packageInstance=' . $packageInstance->__toString() . ' - CALLED!');
* @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, string $connectionType) {
+ public function discoverSocket (DeliverablePackage $packageInstance, string $connectionType): StorableSocket {
// 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 (is_null($listenerInstance)) {
// Abort with no resource
throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } elseif (is_null($listenerInstance->getPoolInstance())) {
+ } elseif (!$listenerInstance->isPoolInstanceSet()) {
// Opps another one
throw new LogicException(sprintf('PACKAGE-SOCKET-DISCOVERY: listenerInstance=%s has no poolInstance set.', $listenerInstance->__toString()), self::EXCEPTION_IS_NULL_POINTER);
}
$helperInstance = ObjectRegistry::getRegistry('hub')->getInstance('connection');
// Is a state set and it's name is other than socket's error code?
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('PACKAGE-SOCKET-DISCOVERY: helperInstance->stateInstance[]=%s', gettype($helperInstance->getStateInstance())));
- if ($helperInstance->getStateInstance() instanceof PeerStateable && $helperInstance->getPrintableState() !== $socketInstance->translateLastSocketErrorCodeToName()) {
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('PACKAGE-SOCKET-DISCOVERY: helperInstance->isStateInstanceSet()=%d', $helperInstance->isStateInstanceSet()));
+ if ($helperInstance->isStateInstanceSet() && $helperInstance->getStateInstance() instanceof PeerStateable && $helperInstance->getPrintableState() !== $socketInstance->translateLastSocketErrorCodeToName()) {
// Resolve the peer's state (but ignore return value)
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('PACKAGE-SOCKET-DISCOVERY: Going to resolve socket from peer state and given package data ...');
PeerStateResolver::createStateByPackageInstance($helperInstance, $packageInstance, $socketInstance);
// Import application-specific stuff
use Org\Shipsimu\Hub\Container\Socket\StorableSocket;
+use Org\Shipsimu\Hub\Information\ShareableInfo;
// Import framework stuff
use Org\Mxchange\CoreFramework\Factory\BaseFactory;
* @throws InvalidArgumentException If one of the arguments are not valid
* @todo Also validate protocol to be sure if there is really a protocol handler for it available
*/
- public static final function createConnectionInfoInstance (string $protocolName, string $connectionType) {
+ public static final function createConnectionInfoInstance (string $protocolName, string $connectionType): ShareableInfo {
// Init factory instance
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-INFO-FACTORY: protocolName=%s,connectionType=%s - CALLED!', $protocolName, $connectionType));
$factoryInstance = new ConnectionInfoFactory();
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Shipsimu\Hub\Factory\Registry\Object;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\BaseFactory;
-use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
-
-/**
- * A factory class for network packages
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2022 Hub Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.shipsimu.org
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-class ObjectTypeRegistryFactory extends BaseFactory {
- /**
- * Protected constructor
- *
- * @return void
- */
- private function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Returns a singleton object type regsitry.
- *
- * @return $registryInstance A registry for object types
- */
- public static final function createObjectTypeRegistryInstance () {
- // Do we have an instance in the registry?
- if (ObjectRegistry::getRegistry('factory')->instanceExists('object_type_registry')) {
- // Then use this instance
- $registryInstance = ObjectRegistry::getRegistry('factory')->getInstance('object_type_registry');
- } else {
- // Now prepare the tags instance
- $registryInstance = ObjectFactory::createObjectByConfiguredName('node_object_type_registry_class');
-
- // Set the instance in registry for further use
- ObjectRegistry::getRegistry('factory')->addInstance('object_type_registry', $registryInstance);
- }
-
- // Return the instance
- return $registryInstance;
- }
-
-}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Shipsimu\Hub\Factory\Registry\Object;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Factory\BaseFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
+
+/**
+ * A factory class for network packages
+ *
+ * @author Roland Haeder <webmaster@shipsimu.org>
+ * @version 0.0.0
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2022 Hub Developer Team
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.shipsimu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class ObjectTypeRegistryFactory extends BaseFactory {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Returns a singleton object type regsitry.
+ *
+ * @return $registryInstance A registry for object types
+ */
+ public static final function createObjectTypeRegistryInstance () {
+ // Do we have an instance in the registry?
+ if (ObjectRegistry::getRegistry('factory')->instanceExists('object_type_registry')) {
+ // Then use this instance
+ $registryInstance = ObjectRegistry::getRegistry('factory')->getInstance('object_type_registry');
+ } else {
+ // Now prepare the tags instance
+ $registryInstance = ObjectFactory::createObjectByConfiguredName('node_object_type_registry_class');
+
+ // Set the instance in registry for further use
+ ObjectRegistry::getRegistry('factory')->addInstance('object_type_registry', $registryInstance);
+ }
+
+ // Return the instance
+ return $registryInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Shipsimu\Hub\Factory\Registry\Socket;
+
+// Import application-specific stuff
+use Org\Shipsimu\Hub\Registry\Socket\RegisterableSocket;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Factory\BaseFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
+use Org\Mxchange\CoreFramework\Registry\Registerable;
+
+/**
+ * A factory class for socket registries
+ *
+ * @author Roland Haeder <webmaster@shipsimu.org>
+ * @version 0.0.0
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.shipsimu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class SocketRegistryFactory extends BaseFactory {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Returns a singleton socket registry instance. If an instance is found in
+ * the registry it will be returned, else a new instance is created and
+ * stored in the same registry entry.
+ *
+ * @return $registryInstance A socket registry instance
+ */
+ public static final function createSocketRegistryInstance (): RegisterableSocket {
+ // Get registry instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('SOCKET-REGISTRY-FACTORY: CALLED!');
+ $objectRegistryInstance = ObjectRegistry::getRegistry('factory');
+
+ // Do we have an instance in the registry?
+ if ($objectRegistryInstance->instanceExists('socket_registry')) {
+ // Then use this instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('SOCKET-REGISTRY-FACTORY: Getting socket registry instance ...');
+ $registryInstance = $objectRegistryInstance->getInstance('socket_registry');
+ } else {
+ // Get the registry instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('SOCKET-REGISTRY-FACTORY: Creating new socket registry instance ...');
+ $registryInstance = ObjectFactory::createObjectByConfiguredName('socket_registry_class');
+
+ // Set the instance in registry for further use
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('SOCKET-REGISTRY-FACTORY: Adding socket registry instance ...');
+ $objectRegistryInstance->addInstance('socket_registry', $registryInstance);
+ }
+
+ // Return the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-REGISTRY-FACTORY: registryInstance=%s - EXIT!', $registryInstance->__toString()));
+ return $registryInstance;
+ }
+
+}
*
* @return void
*/
- public final static function staticInitializer () {
+ public final static function staticInitializer (): void {
// Is it initialized?
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-FACTORY: self::socketRegistryInstance[]=%s - CALLED!', gettype(self::$socketRegistryInstance)));
if (is_null(self::$socketRegistryInstance)) {
* @param $protocolInstance An instance of a HandleableProtocol class
* @return $socketInstance An instance of a StorableSocket class
*/
- public static function createSocketFromPackageInstance (DeliverablePackage $packageInstance, HandleableProtocol $protocolInstance) {
+ public static function createSocketFromPackageInstance (DeliverablePackage $packageInstance, HandleableProtocol $protocolInstance): StorableSocket {
// Invoke static initializer
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-FACTORY: packageInstance=%s,protocolInstance=%s - CALLED!', $packageInstance->__toString(), $protocolInstance->__toString()));
self::staticInitializer();
* @throws InvalidSocketException If the socket cannot be completed
* @throws UnexpectedValueException If $socketFile is empty
*/
- public static final function createListenFileSocket (Listenable $listenerInstance) {
+ public static final function createListenFileSocket (Listenable $listenerInstance): StorableSocket {
// Create SplFileInfo
/* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-FACTORY: listenerInstance=%s - CALLED!', $listenerInstance->__toString()));
$fileInfo = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('ipc_socket_file_name'));
* @throws SocketCreationException If the socket cannot be created
* @todo Rewrite this to also handle IPv6 addresses and sockets
*/
- public static final function createTcpOutgoingSocketFromPackageInstance (DeliverablePackage $packageInstance) {
+ public static final function createTcpOutgoingSocketFromPackageInstance (DeliverablePackage $packageInstance): StorableSocket {
// Create a socket instance
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-FACTORY: packageInstance=%s - CALLED!', $packageInstance->__toString()));
$socketResource = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
* @throws UnexpectedValueException If a socket resource has not been created
* @throws InvalidSocketException Thrown if the socket could not be initialized
*/
- public static function createListenTcpSocket (Listenable $listenerInstance) {
+ public static function createListenTcpSocket (Listenable $listenerInstance): StorableSocket {
// Create a streaming socket, of type TCP/IP
/* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-FACTORY: listenerInstance=%s - CALLED!', $listenerInstance->__toString()));
$socketResource = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
* @throws UnexpectedValueException If a socket resource has not been created
* @throws InvalidSocketException Thrown if the socket could not be initialized
*/
- public static function createListenUdpSocket (Listenable $listenerInstance) {
+ public static function createListenUdpSocket (Listenable $listenerInstance): StorableSocket {
// Create a streaming socket, of type UDP
/* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-FACTORY: listenerInstance=%s - CALLED!', $listenerInstance->__toString()));
$socketResource = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
* @return $socketInstance A new instance of a StorableSocket or NULL if no changes has been detected.
* @throws LogicException If the current instance is not valid
*/
- public static final function createNextAcceptedSocketFromPool (Poolable $poolInstance, StorableSocket $socketInstance) {
+ public static final function createNextAcceptedSocketFromPool (Poolable $poolInstance, StorableSocket $socketInstance): ?StorableSocket {
// Invoke static initializer
/* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-FACTORY: poolInstance=%s,socketInstance->socketResource=%s - CALLED!', $poolInstance->__toString(), $socketInstance->getPrintableName()));
self::staticInitializer();
* @return $socketInstance An instance of a StorableSocket class
* @throws InvalidArgumentException If a parameter is not valid
*/
- public static final function createIncomingSocketInstance (Socket $socketResource, string $socketProtocol) {
+ public static final function createIncomingSocketInstance (Socket $socketResource, string $socketProtocol): StorableSocket {
// Validate parameter
/* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-FACTORY: socketResource[]=%s,socketProtocol=%s - CALLED!', gettype($socketResource), $socketProtocol));
if (empty($socketProtocol)) {
// Set all socket data
$socketInstance->setPeerAddress('invalid');
- $socketInstance->setPeerPort('0');
+ $socketInstance->setPeerPort(0);
// Is the socket resource valid?
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SOCKET-FACTORY: socketInstance=%s', $socketInstance->__toString()));
use Org\Shipsimu\Hub\Factory\Network\Locator\UniversalNodeLocatorFactory;
use Org\Shipsimu\Hub\Factory\Network\Message\NetworkMessageFactory;
use Org\Shipsimu\Hub\Factory\Node\NodeObjectFactory;
+use Org\Shipsimu\Hub\Factory\Registry\Socket\SocketRegistryFactory;
use Org\Shipsimu\Hub\Generic\BaseHubSystem;
use Org\Shipsimu\Hub\Handler\BaseHubHandler;
use Org\Shipsimu\Hub\Helper\Connection\ConnectionHelper;
use Org\Mxchange\CoreFramework\Compressor\Compressor;
use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
-use Org\Mxchange\CoreFramework\Factory\Registry\Socket\SocketRegistryFactory;
use Org\Mxchange\CoreFramework\Feature\FrameworkFeature;
use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
* @param $compressorInstance A Compressor instance for compressing the content
* @return $handlerInstance An instance of a Deliverable class
*/
- public static final function createNetworkPackageHandler (Compressor $compressorInstance) {
+ public static final function createNetworkPackageHandler (Compressor $compressorInstance): NetworkPackageHandler {
// Get new instance
$handlerInstance = new NetworkPackageHandler();
* @param $compressorInstance An instance of a Compressor class
* @return void
*/
- protected final function setCompressorInstance (Compressor $compressorInstance) {
+ protected final function setCompressorInstance (Compressor $compressorInstance): void {
$this->compressorInstance = $compressorInstance;
}
*
* @return $compressorInstance An instance of a Compressor class
*/
- private function getCompressorInstance () {
+ private function getCompressorInstance (): Compressor {
return $this->compressorInstance;
}
* @param $forceReInit Whether to force reinitialization of all stacks
* @return void
*/
- protected function initStacks ($forceReInit = FALSE) {
+ protected function initStacks ($forceReInit = FALSE): void {
// Initialize all
$this->getStackInstance()->initStacks([
self::STACKER_NAME_UNDECLARED,
* Determines private key hash from given session id
*
* @param $packageInstance An instance of a DeliverablePackage class
- * @return $hash Private key's hash
+ * @return $hash Private key's hash
*/
- private function determineSenderPrivateKeyHash (DeliverablePackage $packageInstance) {
+ private function determineSenderPrivateKeyHash (DeliverablePackage $packageInstance): string {
// Get DHT instance
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NETWORK-PACKAGE-HANDLER: packageInstance=%s - CALLED!', $packageInstance->__toString()));
$dhtInstance = DhtObjectFactory::createDhtInstance('node');
* @param $content Raw package content
* @return $hash Hash for given package content
*/
- private function getHashFromContent ($content) {
+ private function getHashFromContent ($content): string {
// Create the hash
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NETWORK-PACKAGE-HANDLER: content[md5]=%s - CALLED!', md5($content)));
// @TODO md5() is very weak, but it needs to be fast
* @param $packageInstance An instance of a DeliverablePackage class
* @return $isChecksumValid Whether the checksum is the same
*/
- private function isChecksumValid (DeliverablePackage $packageInstance) {
+ private function isChecksumValid (DeliverablePackage $packageInstance): bool {
// Get checksum
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NETWORK-PACKAGE-HANDLER: packageInstance=%s - CALLED!', $packageInstance->__toString()));
$checksum = $this->getHashFromPackageSessionId($packageInstance);
* @return void
* @throws InvalidArgumentException If hashes are mismatching
*/
- private function changePackageStatus (DeliverablePackage $packageInstance, $stackerName, $newStatus) {
+ private function changePackageStatus (DeliverablePackage $packageInstance, $stackerName, $newStatus): void {
// Skip this for empty stacks
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NETWORK-PACKAGE-HANDLER: packageInstance=%s,stackerName=%s,newStatus=%s - CALLED!', $packageInstance->__toString(), $stackerName, $newStatus));
if ($this->getStackInstance()->isStackEmpty($stackerName)) {
* @return $hash Hash for given package content
* @throws InvalidArgumentException If $packageInstance has no sessionId set
*/
- public function getHashFromPackageSessionId (DeliverablePackage $packageInstance) {
+ public function getHashFromPackageSessionId (DeliverablePackage $packageInstance): string {
// Is session id set?
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NETWORK-PACKAGE-HANDLER: packageInstance=%s - CALLED!', $packageInstance->__toString()));
/* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: packageInstance=%s', __METHOD__, __LINE__, print_r($packageInstance, TRUE)));
* @param $packageInstance An instance of a DeliverablePackage class in an array
* @return void
*/
- private function declareRawPackageData (DeliverablePackage $packageInstance) {
+ private function declareRawPackageData (DeliverablePackage $packageInstance): void {
/*
* We need to disover every recipient, just in case we have a
* multi-recipient entry like 'upper' is. 'all' may be a not so good
* @param $packageInstance An instance of a DeliverablePackage class in an array
* @return void
*/
- private function deliverRawPackageData (DeliverablePackage $packageInstance) {
+ private function deliverRawPackageData (DeliverablePackage $packageInstance): void {
/*
* This package may become big, depending on the shared object size or
* delivered message size which shouldn't be so long (to save
* @param $packageInstance An instance of a DeliverablePackage class
* @return void
*/
- private function sendOutgoingRawPackageData (DeliverablePackage $packageInstance) {
+ private function sendOutgoingRawPackageData (DeliverablePackage $packageInstance): void {
// Init sent bytes
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NETWORK-PACKAGE-HANDLER: packageInstance=%s - CALLED!', $packageInstance->__toString()));
$sentBytes = 0;
* @param $senderId Sender id to generate a hash for
* @return $hash Hash as hex-encoded string
*/
- private function generatePackageHash (string $content, string $senderId) {
+ private function generatePackageHash (string $content, string $senderId): string {
// Assert on variables
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: content()=' . strlen($content) . ',senderId=' . $senderId . ' - CALLED!');
assert(!empty($content));
* @param $packageInstance An instance of a DeliverablePackage class
* @return $isHashValid Whether the hash is valid
*/
- private function isPackageContentHashValid (DeliverablePackage $packageInstance) {
+ private function isPackageContentHashValid (DeliverablePackage $packageInstance): bool {
// Is the feature enabled?
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NETWORK-PACKAGE-HANDLER: packageInstance=%s - CALLED!', $packageInstance->__toString()));
if (!FrameworkFeature::isFeatureAvailable('hubcoin_reward')) {
* @return void
* @throws UnexpectedValueException If the helper instance contains now raw template data
*/
- public function enqueueRawDataFromTemplate (HubHelper $helperInstance) {
+ public function enqueueRawDataFromTemplate (HubHelper $helperInstance): void {
// Get the raw content ...
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: helperInstance=' . $helperInstance->__toString() . ' - CALLED!');
$rawTemplateData = $helperInstance->getTemplateInstance()->getRawTemplateData();
*
* @return $isEnqueued Whether a package is enqueued
*/
- public function isPackageEnqueued () {
+ public function isPackageEnqueued (): bool {
// Check whether the stacker is not empty
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: CALLED!');
$isEnqueued = (
*
* @return $isDeclared Whether a package is declared
*/
- public function isPackageDeclared () {
+ public function isPackageDeclared (): bool {
// Check whether the stacker is not empty
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: CALLED!');
$isDeclared = (
*
* @return $isWaitingDelivery Whether a package is waiting for delivery
*/
- public function isPackageWaitingForDelivery () {
+ public function isPackageWaitingForDelivery (): bool {
// Check whether the stacker is not empty
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: CALLED!');
$isWaitingDelivery = (
*
* @return $isPending Whether encoded data is pending
*/
- public function isEncodedDataPending () {
+ public function isEncodedDataPending (): bool {
// Check whether the stacker is not empty
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: CALLED!');
$isPending = (
* @return void
* @throws NoTargetException If no target can't be determined
*/
- public function declareEnqueuedPackage () {
+ public function declareEnqueuedPackage (): void {
// Make sure this method isn't working if there is no package enqueued
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: CALLED!');
if (!$this->isPackageEnqueued()) {
*
* @return void
*/
- public function processDeclaredPackage () {
+ public function processDeclaredPackage (): void {
// Debug message
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: CALLED!');
* @return void
* @throws UnexpectedValueException If $sessionId is empty
*/
- public function sendWaitingPackage () {
+ public function sendWaitingPackage (): void {
// Sanity check if we have packages waiting for delivery
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: CALLED!');
if (!$this->isPackageWaitingForDelivery()) {
* @throws UnexpectedValueException If an instance of StorableSocket was expected but not provided
* @throws LogicException If the socket is somehow invalid but this method was called
*/
- public function sendEncodedData () {
+ public function sendEncodedData (): void {
// Make sure there is pending encoded data
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: CALLED!');
if (!$this->isEncodedDataPending()) {
*
* @return $isPending Whether decoded raw data is pending
*/
- private function isRawDataPending () {
+ private function isRawDataPending (): bool {
// Just return whether the stack is not empty
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: CALLED!');
$isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
*
* @return $hasArrived Whether new raw package data has arrived for processing
*/
- public function isNewRawDataPending () {
+ public function isNewRawDataPending (): bool {
// Visit the pool. This monitors the pool for incoming raw data.
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NETWORK-PACKAGE-HANDLER: Invoking this->getListenerPoolInstance()->accept(%s) ... - CALLED!', $this->getVisitorInstance()));
$this->getListenerPoolInstance()->accept($this->getVisitorInstance());
* @return void
* @throws BadMethodCallException If no incoming decoded data was on stack
*/
- public function handleIncomingDecodedData () {
+ public function handleIncomingDecodedData (): void {
/*
* This method should only be called if decoded raw data is pending,
* so check it again.
* @param $handlerInstance An instance of a Networkable class
* @return void
*/
- public function addRawDataToIncomingStack (Networkable $handlerInstance) {
+ public function addRawDataToIncomingStack (Networkable $handlerInstance): void {
/*
* Get the decoded data from the handler, this is an array with
* 'raw_data' and 'error_code' as elements.
*
* @return $isHandled Whether incoming decoded data is handled
*/
- public function isIncomingRawDataHandled () {
+ public function isIncomingRawDataHandled (): bool {
// Determine if the stack is not empty
$isHandled = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
*
* @return $isHandled Whether the assembler has pending data left
*/
- public function ifAssemblerHasPendingDataLeft () {
+ public function ifAssemblerHasPendingDataLeft (): bool {
// Determine if the stack is not empty
$isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
*
* @return $isPending Whether the assembler has multiple packages pending
*/
- public function ifMultipleMessagesPending () {
+ public function ifMultipleMessagesPending (): bool {
// Determine if the stack is not empty
$isPending = ($this->getAssemblerInstance()->ifMultipleMessagesPending());
*
* @return void
*/
- public function handleAssemblerPendingData () {
+ public function handleAssemblerPendingData (): void {
// Handle it
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: Invoking this->getAssemblerInstance()->handlePendingData() ...');
$this->getAssemblerInstance()->handlePendingData();
*
* @return void
*/
- public function handleMultipleMessages () {
+ public function handleMultipleMessages (): void {
// Handle it
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: Invoking this->getAssemblerInstance()->handleMultipleMessages() ...');
$this->getAssemblerInstance()->handleMultipleMessages();
*
* @return void
*/
- public function assembleDecodedDataToPackage () {
+ public function assembleDecodedDataToPackage (): void {
// Make sure the raw decoded package data is handled
assert($this->isIncomingRawDataHandled());
*
* @return void
*/
- public function clearAllStacks () {
+ public function clearAllStacks (): void {
// Call the init method to force re-initialization
$this->initStacks(TRUE);
* @throws UnexpectedPackageStatusException If the package status is not 'failed'
* @todo This may be enchanced for outgoing packages?
*/
- public function removeFirstFailedPackage () {
+ public function removeFirstFailedPackage (): void {
// Get the package again
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: CALLED!');
$packageInstance = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
* @return $packageInstance An instance of a DeliverablePackage class
* @throws InvalidArgumentException If $rawPackageContent contains double seperators
*/
- public function decodeRawContent ($rawPackageContent) {
+ public function decodeRawContent (string $rawPackageContent): DeliverablePackage {
// Check if no double seperator is found
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NETWORK-PACKAGE-HANDLER: rawPackageContent(%d)=%s - CALLED!', strlen($rawPackageContent), $rawPackageContent));
if (strpos($rawPackageContent, self::PACKAGE_DATA_SEPARATOR . self::PACKAGE_DATA_SEPARATOR) !== FALSE) {
* @return void
* @throws InvalidArgumentException If the package content does not have expected amount of entries
*/
- public function handleReceivedPackageInstance (DeliverablePackage $packageInstance) {
+ public function handleReceivedPackageInstance (DeliverablePackage $packageInstance): void {
// Is the package content set?
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NETWORK-PACKAGE-HANDLER: packageInstance=%s - CALLED!', $packageInstance->__toString()));
if (empty($packageInstance->getPackageContent())) {
*
* @return $hasArrived Whether a new message has arrived for processing
*/
- public function isNewMessageArrived () {
+ public function isNewMessageArrived (): bool {
// Determine if the stack is not empty
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: CALLED!');
$hasArrived = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE));
*
* @return $hasArrived Whether a new package has arrived for processing
*/
- public function isDecodedPackageXmlPending () {
+ public function isDecodedPackageXmlPending (): bool {
// Determine if the stack is not empty
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: CALLED!');
$hasArrived = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_PACKAGE_DECOMPRESSED_XML));
* @throws InvalidPrivateKeyHashException If the private key-hash is empty
* @todo Implement verification of all sent tags here?
*/
- public function handleNewlyArrivedMessage () {
+ public function handleNewlyArrivedMessage (): void {
// Make sure there is at least one message
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: CALLED!');
if (!$this->isNewMessageArrived()) {
* @throws InvalidPrivateKeyHashException If the private key-hash is empty
* @todo Implement verification of all sent tags here?
*/
- public function handleDecodedPackageXml () {
+ public function handleDecodedPackageXml (): void {
// Make sure there is at least one package
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: CALLED!');
if (!$this->isDecodedPackageXmlPending()) {
*
* @return $isPending Whether a processed message is pending
*/
- public function isProcessedMessagePending () {
+ public function isProcessedMessagePending (): bool {
// Check it
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: CALLED!');
$isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_PROCESSED_MESSAGE));
*
* @return void
*/
- public function handleProcessedMessage () {
+ public function handleProcessedMessage (): void {
// Get it from the stacker, it is the full array with the processed message
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('NETWORK-PACKAGE-HANDLER: CALLED!');
$messageInstance = $this->getStackInstance()->popNamed(self::STACKER_NAME_PROCESSED_MESSAGE);
* @return void
* @todo ~10% done?
*/
- public function feedHashToMiner (DeliverableMessage $messageInstance) {
+ public function feedHashToMiner (DeliverableMessage $messageInstance): void {
// Is the feature enabled?
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NETWORK-PACKAGE-HANDLER: messageInstance=%s - CALLED!', $messageInstance->__toString()));
if (!FrameworkFeature::isFeatureAvailable('hubcoin_reward')) {
namespace Org\Shipsimu\Hub\Handler\Protocol;
// Import application-specific sutff
+use Org\Shipsimu\Hub\Container\Socket\StorableSocket;
use Org\Shipsimu\Hub\Handler\BaseHubHandler;
use Org\Shipsimu\Hub\Handler\Protocol\HandleableProtocol;
use Org\Shipsimu\Hub\Tools\HubTools;
/**
* Name of used protocol
*/
- private $protocolName = 'invalid';
+ private $protocolName = StorableSocket::SOCKET_PROTOCOL_INVALID;
/**
* Protected constructor
*
* @return $protocolName Name of used protocol
*/
- public final function getProtocolName () {
+ public final function getProtocolName (): string {
return $this->protocolName;
}
* @param $protocolName Name of used protocol
* @return void
*/
- protected final function setProtocolName (string $protocolName) {
+ protected final function setProtocolName (string $protocolName): void {
$this->protocolName = $protocolName;
}
*
* @return $address Address part for the final UNL
*/
- public function getAddressPart () {
+ public function getAddressPart (): string {
// Get UNL instance
$locatorInstance = $this->getUniversalNodeLocatorInstance();
die(__METHOD__.':'.print_r($locatorInstance, TRUE));
* @param $unl UNL to test
* @return $ifMatches Whether the found UNL matches own addresss
*/
- public function isOwnAddress (string $unl) {
+ public function isOwnAddress (string $unl): bool {
// Get own external UNL
$externalUnl = HubTools::determineOwnExternalAddress();
* @para $port The port number
* @return void
*/
- protected final function setPort ($port) {
+ protected final function setPort (int $port): void {
// Set new port number
$this->port = $port;
}
*
* @return $port The port number
*/
- public final function getPort () {
+ public final function getPort (): int {
// Return port number
return $this->port;
}
* @return $isValid Whether the UNL can be validated
* @throws BadMethodCallException If protocol of package's recipient UNL is not matching handler's name
*/
- public function isValidUniversalNodeLocatorByPackageInstance (DeliverablePackage $packageInstance) {
+ public function isValidUniversalNodeLocatorByPackageInstance (DeliverablePackage $packageInstance): bool {
// Is the correct handler choosen?
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('IPV4-PROTOCOL-HANDLER: packageInstance=%s - CALLED!', $packageInstance->__toString()));
if (substr($packageInstance->getRecipientUnl(), 0, strlen($this->getProtocolName())) != $this->getProtocolName()) {
*
* @return $address Address part for the final UNL
*/
- public function getAddressPart () {
+ public function getAddressPart (): string {
// Construct address
$address = sprintf('%s:%s',
parent::getAddressPart(),
$recipientPort = 0;
// Is a socket instance set?
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-CONNECTION-HELPER: socketInstance[]=%s', gettype($this->getSocketInstance())));
- if ($this->getSocketInstance() instanceof StorableSocket) {
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-CONNECTION-HELPER: this->isSocketInstanceSet()=%d', $this->isSocketInstanceSet()));
+ if ($this->isSocketInstanceSet()) {
// Get recipient address/port
$recipientAddress = $this->getSocketInstance()->getSocketRecipientAddress();
$recipientPort = $this->getSocketInstance()->getSocketRecipientPort();
* @param $protocolName Name of used protocol
* @return void
*/
- protected final function setProtocolName (string $protocolName) {
+ protected final function setProtocolName (string $protocolName): void {
$this->protocolName = $protocolName;
}
*
* @return $protocolName Name of used protocol
*/
- public final function getProtocolName () {
+ public final function getProtocolName (): string {
return $this->protocolName;
}
* @see Please see http://de.php.net/manual/en/function.socket-connect.php#84465 for original code
* @todo Rewrite the while() loop to a iterator to not let the software stay very long here
*/
- protected function connectToPeerBySocketRecipient () {
+ protected function connectToPeerBySocketRecipient (): bool {
// Only call this if the connection is fully initialized
//* DEBUG-DIE: */ die(__METHOD__.':socketInstance='.print_r($this->getSocketInstance(), TRUE));
if (!$this->isInitialized()) {
*
* @return void
*/
- protected final function markConnectionShuttedDown () {
+ protected final function markConnectionShuttedDown (): void {
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-IPV4-CONNECTION-HELPER: ' . $this->__toString() . ' has been marked as shutted down');
$this->shuttedDown = TRUE;
/**
* Connection type: 'incoming', 'outgoing', 'server'
*/
- private $connectionType = 'invalid';
+ private $connectionType = StorableSocket::CONNECTION_TYPE_INVALID;
/**
* Name of used protocol
*/
- private $protocolName = 'invalid';
+ private $protocolName = StorableSocket::SOCKET_PROTOCOL_INVALID;
/**
* Protected constructor
* @return $infoInstance An instance of a ShareableInfo class
* @throws InvalidArgumentException If $connectionType is empty
*/
- public final static function createConnectionInfo (string $connectionType) {
+ public final static function createConnectionInfo (string $connectionType): ShareableInfo {
// Validate parameter
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-INFO: connectionType=%s - CALLED!', $connectionType));
if (empty($connectionType)) {
* @param $connectionType Connection type
* @return void
*/
- private function setConnectionType (string $connectionType) {
+ private function setConnectionType (string $connectionType): void {
$this->connectionType = $connectionType;
}
*
* @return $connectionType Connection type
*/
- public final function getConnectionType () {
+ public final function getConnectionType (): string {
return $this->connectionType;
}
*
* @return $protocolName Name of used protocol
*/
- public final function getProtocolName () {
+ public final function getProtocolName (): string {
return $this->protocolName;
}
* @param $protocolName Name of used protocol
* @return void
*/
- protected final function setProtocolName (string $protocolName) {
+ protected final function setProtocolName (string $protocolName): void {
$this->protocolName = $protocolName;
}
*
* @return $address Address from shared information
*/
- public final function getAddress () {
+ public final function getAddress (): string {
// Return it from generic array
return $this->getGenericArrayElement('connection', 'dummy', 'dummy', LocateableNode::UNL_PART_ADDRESS);
}
*
* @return $port Port from shared information
*/
- public final function getPort () {
+ public final function getPort (): int {
// Return it from generic array
return $this->getGenericArrayElement('connection', 'dummy', 'dummy', LocateableNode::UNL_PART_PORT);
}
* @param $listenerInstance An instance of a Listenable class
* @return void
*/
- public function fillWithListenerInformation (Listenable $listenerInstance) {
+ public function fillWithListenerInformation (Listenable $listenerInstance): void {
// Fill the generic array with several data from the listener:
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-INFO: protocolName=%s,listenerInstance=%s - CALLED!', $listenerInstance->getProtocolName(), $listenerInstance->__toString()));
$this->setProtocolName($listenerInstance->getProtocolName());
* @param $helperInstance An instance of a ConnectionHelper class
* @return void
*/
- public function fillWithConnectionHelperInformation (ConnectionHelper $helperInstance) {
+ public function fillWithConnectionHelperInformation (ConnectionHelper $helperInstance): void {
// Fill the generic array with several data from the listener:
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-INFO: protocolName=%s,helperInstance=%s - CALLED!', $helperInstance->getProtocolName(), $helperInstance->__toString()));
$this->setProtocolName($helperInstance->getSocketInstance()->getSocketProtocol());
* @return void
* @throws InvalidSocketException If no peer data can be retrived from socket
*/
- public function fillWithSocketPeerInformation (StorableSocket $socketInstance) {
+ public function fillWithSocketPeerInformation (StorableSocket $socketInstance): void {
// Init variables
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CONNECTION-INFO: socketInstance=%s - CALLED!', $socketInstance->__toString()));
$socketAddress = '0.0.0.0';
use Org\Shipsimu\Hub\Factory\Information\Connection\ConnectionInfoFactory;
use Org\Shipsimu\Hub\Factory\Network\Locator\UniversalNodeLocatorFactory;
use Org\Shipsimu\Hub\Factory\Node\NodeObjectFactory;
+use Org\Shipsimu\Hub\Factory\Registry\Socket\SocketRegistryFactory;
use Org\Shipsimu\Hub\Factory\Socket\SocketFactory;
use Org\Shipsimu\Hub\Generic\BaseHubSystem;
use Org\Shipsimu\Hub\Handler\Package\NetworkPackageHandler;
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
-use Org\Mxchange\CoreFramework\Factory\Registry\Socket\SocketRegistryFactory;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
use Org\Mxchange\CoreFramework\Socket\InvalidServerSocketException;
use Org\Mxchange\CoreFramework\Socket\SocketAlreadyRegisteredException;
* @param $socketInstance An instance of a StorableSocket class
* @return void
*/
- private function handleIncomingSocket (StorableSocket $socketInstance) {
+ private function handleIncomingSocket (StorableSocket $socketInstance): void {
// Handle it here, if not main server socket
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-LISTENER: socketInstance=%s - CALLED!', strtoupper($this->getProtocolName()), $socketInstance->__toString()));
$this->getHandlerInstance()->processRawDataFromSocketInstance($socketInstance);
* @param $listenAddress The address this listener should listen on
* @return void
*/
- protected final function setListenAddress (string $listenAddress) {
+ protected final function setListenAddress (string $listenAddress): void {
$this->listenAddress = $listenAddress;
}
*
* @return $listenAddress The address this listener should listen on
*/
- public final function getListenAddress () {
+ public final function getListenAddress (): string {
return $this->listenAddress;
}
* @param $listenPort The port this listener should listen on
* @return void
*/
- protected final function setListenPort (int $listenPort) {
+ protected final function setListenPort (int $listenPort): void {
$this->listenPort = $listenPort;
}
*
* @return $listenPort The port this listener should listen on
*/
- public final function getListenPort () {
+ public final function getListenPort (): int {
return $this->listenPort;
}
* @param $configEntry The configuration entry holding our listen address
* @return void
*/
- public final function setListenAddressByConfiguration (string $configEntry) {
+ public final function setListenAddressByConfiguration (string $configEntry): void {
$this->setListenAddress(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($configEntry));
}
* @param $configEntry The configuration entry holding our listen port
* @return void
*/
- public final function setListenPortByConfiguration (string $configEntry) {
+ public final function setListenPortByConfiguration (string $configEntry): void {
$this->setListenPort(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($configEntry));
}
* @param $poolInstance An instance of a PoolablePeer class
* @return void
*/
- protected final function setPoolInstance (PoolablePeer $poolInstance) {
+ protected final function setPoolInstance (PoolablePeer $poolInstance): void {
$this->poolInstance = $poolInstance;
}
*
* @return $poolInstance An instance of a PoolablePeer class
*/
- public final function getPoolInstance () {
+ public final function getPoolInstance (): PoolablePeer {
return $this->poolInstance;
}
+ /**
+ * Checks whether a pool instance is set
+ *
+ * @return $isset Whether a pool instance is set
+ */
+ public final function isPoolInstanceSet (): bool {
+ return ($this->poolInstance instanceof PoolablePeer);
+ }
+
/**
* Getter for protocol name
*
* @return $protocolName Name of used protocol
*/
- public final function getProtocolName () {
+ public final function getProtocolName (): string {
return $this->protocolName;
}
* @param $protocolName Name of used protocol
* @return void
*/
- protected final function setProtocolName (string $protocolName) {
+ protected final function setProtocolName (string $protocolName): void {
$this->protocolName = $protocolName;
}
* @throws SocketAlreadyRegisteredException If the given resource is already registered
* @throws LogicException If no info instance can be created
*/
- protected function registerServerSocketInstance (StorableSocket $socketInstance) {
+ protected function registerServerSocketInstance (StorableSocket $socketInstance): void {
// First check if it is valid
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-LISTENER: socketInstance=%s - CALLED!', strtoupper($this->getProtocolName()), $socketInstance->__toString()));
if ($this->isServerSocketRegistered($socketInstance)) {
* @return $isRegistered Whether given server socket is registered
* @throws LogicException If no info instance can be created
*/
- protected function isServerSocketRegistered (StorableSocket $socketInstance) {
+ protected function isServerSocketRegistered (StorableSocket $socketInstance): bool {
// Get a connection info instance
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-LISTENER: socketInstance=%s - CALLED!', strtoupper($this->getProtocolName()), $socketInstance->__toString()));
$infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), StorableSocket::CONNECTION_TYPE_SERVER);
$visitorInstance->visitListener($this);
// Visit the pool if set
- if ($this->getPoolInstance() instanceof Poolable) {
+ if ($this->isPoolInstanceSet()) {
// Visit pool instance
$this->getPoolInstance()->accept($visitorInstance);
}
*
* @return void
*/
- public function monitorIncomingRawData () {
+ public function monitorIncomingRawData (): void {
// Check if an incoming socket is registered
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-LISTENER: CALLED!', strtoupper($this->getProtocolName())));
if (!$this->getRegistryInstance()->isIncomingSocketRegistered($this)) {
* @return void
* @throws LogicException If no info instance can be created
*/
- protected function doListenSocketSelect () {
+ protected function doListenSocketSelect (): void {
// Validate parameter and socket instance
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-LISTENER: CALLED!', strtoupper($this->getProtocolName())));
if(!$this->getSocketInstance()->isValidSocket()) {
* @param $packageInstance An instance of a DeliverablePackage class
* @return $accepts Whether this listener does accept
*/
- public function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance) {
+ public function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance): bool {
// Check if same socket protocol
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-LISTENER: packageInstance=%s - CALLED!', strtoupper($this->getProtocolName()), $packageInstance));
$socketProtocol = $this->getSocketInstance()->getSocketProtocol();
use Org\Shipsimu\Hub\Factory\Handler\Network\NetworkPackageHandlerFactory;
use Org\Shipsimu\Hub\Factory\Network\NetworkPackageFactory;
use Org\Shipsimu\Hub\Network\Networkable;
+use Org\Shipsimu\Hub\Pool\Peer\PoolablePeer;
use Org\Shipsimu\Hub\Traits\Listener\ListenableTrait;
use Org\Shipsimu\Hub\Traits\Container\Socket\StorableSocketTrait;
/**
* Name of used protocol
*/
- private $protocolName = 'invalid';
+ private $protocolName = StorableSocket::SOCKET_PROTOCOL_INVALID;
/**
* Protected constructor
* @param $protocolName Name of used protocol
* @return void
*/
- protected final function setProtocolName (string $protocolName) {
+ protected final function setProtocolName (string $protocolName): void {
$this->protocolName = $protocolName;
}
*
* @return $listenAddress The address this listener should listen on
*/
- public final function getListenAddress () {
+ public final function getListenAddress (): string {
// Trace message
//* NOSY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER-DECORATOR: Invoking this->getListenerInstance()->getListenAddress() ...');
return $this->getListenerInstance()->getListenAddress();
*
* @return $listenPort The port this listener should listen on
*/
- public final function getListenPort () {
+ public final function getListenPort (): int {
// Trace message
//* NOSY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER-DECORATOR: Invoking this->getListenerInstance()->getListenPort() ...');
return $this->getListenerInstance()->getListenPort();
*
* @return $listenerType The listener's type (hub/peer)
*/
- public final function getListenerType () {
+ public final function getListenerType (): string {
return $this->listenerType;
}
* @param $listenerType The listener's type (hub/peer)
* @return void
*/
- protected final function setListenerType (string $listenerType) {
+ protected final function setListenerType (string $listenerType): void {
$this->listenerType = $listenerType;
}
*
* @return $poolInstance A peer pool instance
*/
- public final function getPoolInstance () {
- // Trace message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('%s-LISTENER-DECORATOR: Getting poolInstance from inner listenerInstance=%s - CALLED!', strtoupper($this->getProtocolName()), $this->getListenerInstance()->__toString()));
-
+ public final function getPoolInstance (): PoolablePeer {
// Get it
return $this->getListenerInstance()->getPoolInstance();
}
+ /**
+ * Checks whether a pool instance is set
+ *
+ * @return $isset Whether a pool instance is set
+ */
+ public final function isPoolInstanceSet (): bool {
+ return $this->getListenerInstance()->isPoolInstanceSet();
+ }
+
/**
* Monitors incoming raw data from the handler and transfers it to the
* given receiver instance.
* @throws NullPointerException If no handler instance is set in listener instance
* @throws LogicException If the given handler instance is not implementing a required interface
*/
- public function monitorIncomingRawData () {
+ public function monitorIncomingRawData (): void {
// Get the handler instance
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER-DECORATOR: CALLED!');
$handlerInstance = $this->getListenerInstance()->getHandlerInstance();
*
* @return $protocolName Name of used protocol
*/
- public final function getProtocolName () {
+ public final function getProtocolName (): string {
return $this->protocolName;
}
*
* @return $listenerInstance An instance a prepared listener class
*/
- public final static function createSocketFileListener () {
+ public final static function createSocketFileListener (): Listenable {
// Get new instance
$listenerInstance = new SocketFileListener();
*
* @return void
*/
- public function initListener () {
+ public function initListener (): void {
// Create socket with factory
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SOCKET-FILE-LISTENER: CALLED!');
$socketInstance = SocketFactory::createListenFileSocket($this);
*
* @return void
*/
- public function doListen() {
+ public function doListen(): void {
// Trace message
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SOCKET-FILE-LISTENER: Invoking this->doListenSocketSelect() ... - CALLED!');
* @param $packageInstance An instance of a DeliverablePackage class
* @return $accepts Whether this listener does accept
*/
- public function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance) {
+ public function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance): bool {
// Trace message
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('SOCKET-FILE-LISTENER: packageInstance=%s - CALLED!', $packageInstance->__toString()));
*
* @return void
*/
- public function monitorIncomingRawData () {
+ public function monitorIncomingRawData (): void {
DebugMiddleware::getSelfInstance()->partialStub('Need to implement this method.');
}
* @param $listenerInstance A Listener instance
* @return $decoratorInstance An instance a prepared listener decorator class
*/
- public static final function createSocketFileListenerDecorator (Listenable $listenerInstance) {
+ public static final function createSocketFileListenerDecorator (Listenable $listenerInstance): Listenable {
// Get new instance
$decoratorInstance = new SocketFileListenerDecorator();
*
* @return void
*/
- public function initListener () {
+ public function initListener (): void {
DebugMiddleware::getSelfInstance()->partialStub('WARNING: This method should not be called.');
}
*
* @return void
*/
- public function doListen () {
+ public function doListen (): void {
// Trace message
/* NOSY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SOCKET-FILE-LISTENER: Invoking this->getListenerInstance()->doListen() ...');
* @param $packageInstance An instance of a DeliverablePackage class
* @return $accepts Whether this listener does accept
*/
- public function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance) {
+ public function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance): bool {
// Debug message
/* NOSY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SOCKET-FILE-LISTENER: Invoking this->getListenerInstance()->ifListenerAcceptsPackageData() ...');
*
* @return $listenerInstance An instance a prepared listener class
*/
- public static final function createTcpListener () {
+ public static final function createTcpListener (): Listenable {
// Get new instance
$listenerInstance = new TcpListener();
*
* @return void
*/
- public function initListener () {
+ public function initListener (): void {
// Get instance from socket factory
$socketInstance = SocketFactory::createListenTcpSocket($this);
*
* @return void
*/
- public function doListen () {
+ public function doListen (): void {
// Trace message
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER: Invoking this->doListenSocketSelect() ... - CALLED!');
* @param $listenerInstance A Listener instance
* @return $decoratorInstance An instance a prepared listener decorator class
*/
- public static final function createClientTcpListenerDecorator (Listenable $listenerInstance) {
+ public static final function createClientTcpListenerDecorator (Listenable $listenerInstance): Listenable {
// Get new instance
$decoratorInstance = new ClientTcpListenerDecorator();
*
* @return void
*/
- public function initListener () {
+ public function initListener (): void {
DebugMiddleware::getSelfInstance()->partialStub('WARNING: This method should not be called.');
}
*
* @return void
*/
- public function doListen () {
+ public function doListen (): void {
// Trace message
/* NOSY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CLIENT-TCP-LISTENER: Invoking this->getListenerInstance() ...');
* @param $packageInstance An instance of a DeliverablePackage class
* @return $accepts Whether this listener does accept
*/
- public function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance) {
+ public function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance): bool {
// Trace message
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CLIENT-TCP-LISTENER: packageInstance=%s - CALLED!', $packageInstance->__toString()));
* @param $listenerInstance A Listener instance
* @return $decoratorInstance An instance a prepared listener decorator class
*/
- public static final function createHubTcpListenerDecorator (Listenable $listenerInstance) {
+ public static final function createHubTcpListenerDecorator (Listenable $listenerInstance): Listenable {
// Get new instance
$decoratorInstance = new HubTcpListenerDecorator();
*
* @return void
*/
- public function initListener () {
+ public function initListener (): void {
DebugMiddleware::getSelfInstance()->partialStub('WARNING: This method should not be called.');
}
*
* @return void
*/
- public function doListen () {
+ public function doListen (): void {
// Trace message
/* NOSY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-TCP-LISTENER: Invoking this->getListenerInstance() ...');
* @param $packageInstance An instance of a DeliverablePackage class
* @return $accepts Whether this listener does accept
*/
- public function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance) {
+ public function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance): bool {
// Trace message
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HUB-TCP-LISTENER: packageInstance=%s - CALLED!', $packageInstance->__toString()));
*
* @return $listenerInstance An instance a prepared listener class
*/
- public static final function createUdpListener () {
+ public static final function createUdpListener (): Listenable {
// Get new instance
$listenerInstance = new UdpListener();
*
* @return void
*/
- public function initListener () {
+ public function initListener (): void {
// Get instance from socket factory
$socketInstance = SocketFactory::createListenUdpSocket($this);
*
* @return void
*/
- public function doListen () {
+ public function doListen (): void {
// Trace message
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('UDP-LISTENER: Invoking this->doListenSocketSelect() ... - CALLED!');
* @return $accepts Whether this listener does accept
* @throws UnsupportedOperationException If this method is called
*/
- public function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance) {
+ public function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance): bool {
throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
* @param $listenerInstance A Listener instance
* @return $decoratorInstance An instance a prepared listener decorator class
*/
- public static final function createClientUdpListenerDecorator (Listenable $listenerInstance) {
+ public static final function createClientUdpListenerDecorator (Listenable $listenerInstance): Listenable {
// Get new instance
$decoratorInstance = new ClientUdpListenerDecorator();
*
* @return void
*/
- public function initListener () {
+ public function initListener (): void {
DebugMiddleware::getSelfInstance()->partialStub('WARNING: This method should not be called.');
}
*
* @return void
*/
- public function doListen () {
+ public function doListen (): void {
// Trace message
/* NOSY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CLIENT-UDP-LISTENER: Invoking this->getListenerInstance() ...');
* @param $packageInstance An instance of a DeliverablePackage class
* @return $accepts Whether this listener does accept
*/
- function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance) {
+ public function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance): bool {
// Trace message
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CLIENT-UDP-LISTENER: packageInstance=%s - CALLED!', $packageInstance->__toString()));
* @param $listenerInstance A Listener instance
* @return $decoratorInstance An instance a prepared listener decorator class
*/
- public static final function createHubUdpListenerDecorator (Listenable $listenerInstance) {
+ public static final function createHubUdpListenerDecorator (Listenable $listenerInstance): Listenable {
// Get new instance
$decoratorInstance = new HubUdpListenerDecorator();
*
* @return void
*/
- public function initListener () {
+ public function initListener (): void {
DebugMiddleware::getSelfInstance()->partialStub('WARNING: This method should not be called.');
}
*
* @return void
*/
- public function doListen () {
+ public function doListen (): void {
// Trace message
/* NOSY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-UDP-LISTENER: Invoking this->getListenerInstance() ...');
* @param $packageInstance An instance of a DeliverablePackage class
* @return $accepts Whether this listener does accept
*/
- public function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance) {
+ public function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance): bool {
// Trace message
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HUB-UDP-LISTENER: packageInstance=%s - CALLED!', $packageInstance->__toString()));
use Org\Mxchange\CoreFramework\Lists\BaseList;
use Org\Mxchange\CoreFramework\Lists\Listable;
+// Import SPL stuff
+use \Iterator;
+
/**
* A Hub list
*
*
* @return $listInstance An instance a Listable class
*/
- public static final function createHubList () {
+ public static final function createHubList (): Listable {
// Get new instance
$listInstance = new HubList();
*
* @return $iteratorInstance An instance of a Iterator class
*/
- public function getListIterator () {
+ public function getListIterator (): Iterator {
$this->debugInstance(sprintf('[%s:%d]: uses the default iterator. Please call getIterator() instead!', __METHOD__, __LINE__));
}
*
* @return void
*/
- public function clearList () {
+ public function clearList (): void {
// Clear both groups together
- $this->clearGroups(array('connected', 'disconnected'));
+ $this->clearGroups(['connected', 'disconnected']);
}
}
use Org\Mxchange\CoreFramework\Lists\BaseList;
use Org\Mxchange\CoreFramework\Lists\Listable;
+// Import SPL stuff
+use \Iterator;
+
/**
* A list for pool entries
*
/**
* Creates an instance of this class
*
- * @return $listInstance An instance a Listable class
+ * @return $listInstance An instance a Listable class
*/
- public static final function createPoolEntriesList () {
+ public static final function createPoolEntriesList (): Listable {
// Get new instance
$listInstance = new PoolEntriesList();
*
* @return $iteratorInstance An instance of a Iterator class
*/
- public function getListIterator () {
+ public function getListIterator (): Iterator {
// Get the iterator instance from the factory
$iteratorInstance = ObjectFactory::createObjectByConfiguredName('node_ping_iterator_class', [$this]);
*
* @return void
*/
- public function clearList () {
+ public function clearList (): void {
// Clear the only one group
$this->clearGroup('pool');
}
use Org\Mxchange\CoreFramework\Lists\Listable;
use Org\Mxchange\CoreFramework\Registry\Registerable;
+// Import SPL stuff
+use \Iterator;
+
/**
* A Recipient list
*
/**
* Creates an instance of this class
*
- * @return $listInstance An instance a Listable class
+ * @return $listInstance An instance a Listable class
*/
- public static final function createRecipientList () {
+ public static final function createRecipientList (): Listable {
// Get new instance
$listInstance = new RecipientList();
*
* @return $iteratorInstance An instance of a Iterator class
*/
- public function getListIterator () {
+ public function getListIterator (): Iterator {
$this->debugInstance(sprintf('[%s:%d]: uses the default iterator. Please call getIterator() instead!', __METHOD__, __LINE__));
}
*
* @return void
*/
- public function clearList () {
+ public function clearList (): void {
// Clear both groups
$this->clearGroups(['unl', 'session_id']);
}
*
* @return void
*/
- private function initState() {
+ private function initState(): void {
// Get the state factory and create the initial state.
NodeStateFactory::createNodeStateInstanceByName('init');
}
* @param $searchInstance An instance of a LocalSearchCriteria class
* @return void
*/
- private function generatePrivateKeyAndHash (LocalSearchCriteria $searchInstance) {
+ private function generatePrivateKeyAndHash (LocalSearchCriteria $searchInstance): void {
// Get an RNG instance
$rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
* @return $randomString Random string
* @todo Make this code more generic and move it to CryptoHelper or
*/
- protected function generateRamdomString ($length) {
+ protected function generateRamdomString (int $length): string {
// Get an RNG instance
$rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
*
* @return $bootUnl The UNL (Universal Node Locator) of the boot node
*/
- protected final function getBootUniversalNodeLocator () {
+ protected final function getBootUniversalNodeLocator (): string {
return $this->bootUnl;
}
* @return $isFound Whether the IP is found
* @throws InvalidArgumentException If a parameter is empty
*/
- protected function ifAddressMatchesBootstrapNodes (string $remoteAddr) {
+ protected function ifAddressMatchesBootstrapNodes (string $remoteAddr): bool {
// Check parameter
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HUB-NODE: remoteAddr=%s - CALLED!', $remoteAddr));
if (empty($remoteAddr)) {
*
* @return $unl Node's own universal node locator
*/
- public function detectOwnUniversalNodeLocator () {
+ public function detectOwnUniversalNodeLocator (): string {
// Is "cache" set?
if (!isset($GLOBALS[__METHOD__])) {
// Get the UNL array back
*
* @return void
*/
- public function outputConsoleTeaser () {
+ public function outputConsoleTeaser (): void {
// Get the app instance (for shortening our code)
$applicationInstance = ApplicationHelper::getSelfInstance();
* @param $responseInstance A Responseable class
* @return void
*/
- public function bootstrapAcquireNodeId (Requestable $requestInstance, Responseable $responseInstance) {
+ public function bootstrapAcquireNodeId (Requestable $requestInstance, Responseable $responseInstance): void {
// Find node by id
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HUB-NODE: requestInstance=%s,responseInstance=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString()));
$resultInstance = $this->getFrontendInstance()->findFirstNodeData();
*
* @return void
*/
- public function bootstrapGenerateSessionId () {
+ public function bootstrapGenerateSessionId (): void {
// Now get a search criteria instance
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB-NODE: CALLED!');
$searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
* @throws UnexpectedValueException If private_key_hash is "invalid"
* @throws OutOfBoundsException If an array element is not found
*/
- public function bootstrapGeneratePrivateKey () {
+ public function bootstrapGeneratePrivateKey (): void {
// Find node by id
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB-NODE: CALLED!');
$resultInstance = $this->getFrontendInstance()->findFirstNodeData();
* @param $criteriaInstance An instance of a StoreableCriteria class
* @return void
*/
- public function addElementsToDataSet (StoreableCriteria $criteriaInstance) {
+ public function addElementsToDataSet (StoreableCriteria $criteriaInstance): void {
// Get request instance
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HUB-NODE: criteriaInstance=%s - CALLED!', $criteriaInstance->__toString()));
$requestInstance = FrameworkBootstrap::getRequestInstance();
* @throws DatabaseUpdateSupportException If this class does not support database updates
* @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
*/
- public function updateDatabaseField ($fieldName, $fieldValue) {
+ public function updateDatabaseField (string $fieldName, mixed $fieldValue): void {
// Unfinished
DebugMiddleware::getSelfInstance()->partialStub('Unfinished!');
return;
* @throws NodeAlreadyAnnouncedException If this hub is already announced
* @todo Change the first if() block to check for a specific state
*/
- public function announceToUpperNodes (Taskable $taskInstance) {
+ public function announceToUpperNodes (Taskable $taskInstance): void {
// Is this hub node announced?
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HUB-NOCE: taskInstance=%s - CALLED!', $taskInstance->__toString()));
if ($this->hubIsAnnounced === TRUE) {
* @param $taskInstance The task instance running this announcement
* @return void
*/
- public function doSelfConnection (Taskable $taskInstance) {
+ public function doSelfConnection (Taskable $taskInstance): void {
// Debug output
self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB-NODE: Self Connection: START (taskInstance=' . $taskInstance->__toString(). ')');
* @param $responseInstance A Responseable class
* @return void
*/
- public function activateNode (Requestable $requestInstance, Responseable $responseInstance) {
+ public function activateNode (Requestable $requestInstance, Responseable $responseInstance): void {
// Checks whether a listener is still active and shuts it down if one
// is still listening.
if (($this->determineIfListenerIsActive()) && ($this->isNodeActive())) {
*
* @return void
*/
- public function initializeListenerPool () {
+ public function initializeListenerPool (): void {
// Debug output
self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB-NODE: Initialize listener: START');
*
* @return $isActive Whether the hub is active
*/
- public final function isNodeActive () {
+ public final function isNodeActive (): bool {
return $this->isActive;
}
* @param $isActive Whether the hub is active
* @return void
*/
- public final function enableIsActive (bool $isActive = TRUE) {
+ public final function enableIsActive (bool $isActive = TRUE): void {
$this->isActive = $isActive;
}
* @param $acceptAnnouncements Whether this node accepts announcements (default: TRUE)
* @return void
*/
- protected final function enableAcceptingAnnouncements (bool $acceptAnnouncements = TRUE) {
+ protected final function enableAcceptingAnnouncements (bool $acceptAnnouncements = TRUE): void {
$this->acceptAnnouncements = $acceptAnnouncements;
}
* @param $acceptDhtBootstrap Whether this node accepts DHT bootstrap requests (default: TRUE)
* @return void
*/
- public final function enableAcceptDhtBootstrap (bool $acceptDhtBootstrap = TRUE) {
+ public final function enableAcceptDhtBootstrap (bool $acceptDhtBootstrap = TRUE): void {
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB-NODE: Enabling DHT bootstrap requests ...');
$this->acceptDhtBootstrap = $acceptDhtBootstrap;
}
* @param $listenerPoolInstance The new listener pool instance
* @return void
*/
- protected final function setListenerPoolInstance (Poolable $listenerPoolInstance) {
+ protected final function setListenerPoolInstance (Poolable $listenerPoolInstance): void {
$this->listenerPoolInstance = $listenerPoolInstance;
}
*
* @return $listenerPoolInstance Our current listener pool instance
*/
- public final function getListenerPoolInstance () {
+ public final function getListenerPoolInstance (): Poolable {
return $this->listenerPoolInstance;
}
* @param $nodeId The new node id
* @return void
*/
- protected final function setNodeId (string $nodeId) {
+ protected final function setNodeId (string $nodeId): void {
$this->nodeId = $nodeId;
}
*
* @return $nodeId Current node id
*/
- public final function getNodeId () {
+ public final function getNodeId (): string {
return $this->nodeId;
}
* @param $privateKey The new private key
* @return void
*/
- protected final function setPrivateKey (string $privateKey) {
+ protected final function setPrivateKey (string $privateKey): void {
$this->privateKey = $privateKey;
}
*
* @return $privateKey Current private key
*/
- public final function getPrivateKey () {
+ public final function getPrivateKey (): string {
return $this->privateKey;
}
* @param $nodePrivateKeyHash The new private key hash
* @return void
*/
- protected final function setNodePrivateKeyHash (string $nodePrivateKeyHash) {
+ protected final function setNodePrivateKeyHash (string $nodePrivateKeyHash): void {
$this->nodePrivateKeyHash = $nodePrivateKeyHash;
}
*
* @return $privateKeyHash Current private key hash
*/
- public final function getNodePrivateKeyHash () {
+ public final function getNodePrivateKeyHash (): string {
return $this->nodePrivateKeyHash;
}
* @param $sessionId The new session id
* @return void
*/
- protected final function setSessionId (string $sessionId) {
+ protected final function setSessionId (string $sessionId): void {
$this->sessionId = $sessionId;
}
*
* @return $sessionId Current session id
*/
- public final function getSessionId () {
+ public final function getSessionId (): string {
return $this->sessionId;
}
*
* @return $acceptAnnouncements Whether this node accepts announcements
*/
- public final function isAcceptingAnnouncements () {
+ public final function isAcceptingAnnouncements (): bool {
// Check it (this node must be active and not shutdown!)
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB-NODE: CALLED!');
$acceptAnnouncements = (($this->acceptAnnouncements === TRUE) && ($this->isNodeActive()));
*
* @return $acceptDhtBootstrap Whether this node accepts DHT bootstrap requests
*/
- public final function isAcceptingDhtBootstrap () {
+ public final function isAcceptingDhtBootstrap (): bool {
// Check it (this node must be active and not shutdown!)
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB-NODE: CALLED!');
$acceptDhtBootstrap = (($this->acceptDhtBootstrap === TRUE) && ($this->isNodeActive()));
* @return $hasAnnounced Whether this node has attempted to announce itself
* @todo Add checking if this node has been announced to the sender node
*/
- public function ifNodeIsAnnouncing () {
+ public function ifNodeIsAnnouncing (): bool {
// Simply check the state of this node
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB-NODE: state=' . $this->getStateInstance()->getStateName());
- $hasAnnounced = ($this->getStateInstance() instanceof NodeAnnouncingState);
+ $hasAnnounced = ($this->isStateInstanceSet() && $this->getStateInstance() instanceof NodeAnnouncingState);
// Return it
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB-NODE: hasAnnounced=' . intval($hasAnnounced));
* @return $hasAnnouncementCompleted Whether this node has attempted to announce itself and completed it
* @todo Add checking if this node has been announced to the sender node
*/
- public function ifNodeHasAnnouncementCompleted () {
+ public function ifNodeHasAnnouncementCompleted (): bool {
// Simply check the state of this node
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB-NODE: state=' . $this->getStateInstance()->getStateName());
- $hasAnnouncementCompleted = ($this->getStateInstance() instanceof NodeAnnouncementCompletedState);
+ $hasAnnouncementCompleted = ($this->isStateInstanceSet() && $this->getStateInstance() instanceof NodeAnnouncementCompletedState);
// Return it
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB-NODE: hasAnnouncementCompleted=' . intval($hasAnnouncementCompleted));
*
* @return $acceptsRequest Wether this node accepts node-list requests
*/
- public function isAcceptingNodeListRequests () {
+ public function isAcceptingNodeListRequests (): bool {
/*
* Only 'regular' nodes does not accept such requests, checking
* HubRegularNode is faster, but if e.g. HubRegularI2PNode will be
*
* @return $locatorInstance An instance of a LocateableNode class for this node
*/
- public function determineUniversalNodeLocator () {
+ public function determineUniversalNodeLocator (): LocateableNode {
// Is there cache?
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB-NODE: CALLED!');
if (!isset($GLOBALS[__METHOD__])) {
* @return void
* @todo Find more to do here
*/
- public function updateNodeData () {
+ public function updateNodeData (): void {
// Set some dummy configuration entries, e.g. node_status
FrameworkBootstrap::getConfigurationInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
}
* @return void
* @todo Handle thrown exception
*/
- public function handleAnswerStatusByMessageInstance (DeliverableMessage $messageInstance, Receivable $handlerInstance) {
+ public function handleAnswerStatusByMessageInstance (DeliverableMessage $messageInstance, Receivable $handlerInstance): void {
// Construct configuration entry for handling class' name
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HUB-NODE: messageInstance=%s,handlerInstance=%s - CALLED!', $messageInstance->__toString(), $handlerInstance->__toString()));
$classConfigEntry = strtolower($messageData[NetworkPackageHandler::MESSAGE_ARRAY_TYPE] . '_status_' . $messageData[BaseXmlAnswerTemplateEngine::ANSWER_STATUS]) . '_handler_class';
*
* @return $objectList Array of all accepted object types
*/
- public function getListFromAcceptedObjectTypes () {
+ public function getListFromAcceptedObjectTypes (): array {
// Get registry instance
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB-NODE: CALLED!');
$objectRegistryInstance = ObjectTypeRegistryFactory::createObjectTypeRegistryInstance();
* @return void
* @throws InvalidArgumentException If $nodeData is empty
*/
- public function addArrayToDataSet (StoreableCriteria $dataSetInstance, array $nodeData) {
+ public function addArrayToDataSet (StoreableCriteria $dataSetInstance, array $nodeData): void {
// Validate parameter
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HUB-NODE: dataSetInstance=%s,nodeData()=%d - EXIT!', $dataSetInstance->__toString(), count($nodeData)));
if (count($nodeData) == 0) {
*
* @return $nodeData Node's data
*/
- public function createNodeDataArray () {
+ public function createNodeDataArray (): array {
// Get request instance
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB-NODE: CALLED!');
$requestInstance = FrameworkBootstrap::getRequestInstance();
* @param $listenerInstance A Listenable instance
* @return $poolInstance An instance a PoolablePeer class
*/
- public static final function createDefaultPeerPool (Listenable $listenerInstance) {
+ public static final function createDefaultPeerPool (Listenable $listenerInstance): PoolablePeer {
// Get new instance
$poolInstance = new DefaultPeerPool();
* @return void
* @throws InvalidSocketException If the given socket has an error
*/
- private function validateSocket (StorableSocket $socketInstance) {
+ private function validateSocket (StorableSocket $socketInstance): void {
// Is it a valid resource?
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('HUB-SYSTEM: socketInstance->socketResource=%s - CALLED!', $socketInstance->getPrintableName()));
if (!$socketInstance->isValidSocket()) {
*
* @param $packageInstance An instance of a DeliverablePackage class
* @param $connectionType Type of connection, can be 'incoming', 'outgoing', 'server' or default
- * @return $socketInstance An instance of a StorableSocket class
+ * @return $socketInstance An instance of a StorableSocket class or NULL if it cannot be discovered
* @throws InvalidArgumentException If a parameter is not valid
* @throws InvalidConnectionTypeException If the provided connection type is not valid
* @throws LogicException If an expected array element is missing
*/
- public function getSocketFromPackageInstance (DeliverablePackage $packageInstance, string $connectionType = NULL) {
+ public function getSocketFromPackageInstance (DeliverablePackage $packageInstance, string $connectionType = NULL): ?StorableSocket {
// Validate parameter
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DEFAULT-PEER-POOL: packageInstance=%s,connectionType[%s]=%s - CALLED!', $packageInstance->__toString(), gettype($connectionType), $connectionType));
if (empty($connectionType)) {
*
* @return $registryInstance An instance of this class
*/
- public static final function createSocketRegistry () {
+ public static final function createSocketRegistry (): RegisterableSocket {
// Is there an instance?
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-REGISTRY: self::selfInstance[]=%s - CALLED!', gettype(self::$selfInstance)));
if (is_null(self::$selfInstance)) {
*
* @return $registryInstances An array with all registry instances
*/
- public final function getInstanceRegistry () {
+ public final function getInstanceRegistry (): array {
return self::$registryInstances;
}
* @param $infoInstance An instance of a ShareableInfo class
* @return $key A string representation of the socket for the registry
*/
- private function generateObjectRegistryKeyFromInfoInstance (ShareableInfo $infoInstance) {
+ private function generateObjectRegistryKeyFromInfoInstance (ShareableInfo $infoInstance): string {
// Get connection type and port number and add both together
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-REGISTRY: infoInstance=%s - CALLED!', $infoInstance->__toString()));
$key = sprintf('%s:%s:%s:%s:%s',
* @param $infoInstance An instance of a ShareableInfo class
* @return $key A string representation of the listener for the registry
*/
- private function getRegistryKeyFromInfo (ShareableInfo $infoInstance) {
+ private function getRegistryKeyFromInfo (ShareableInfo $infoInstance): string {
// Get the key
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-REGISTRY: infoInstance=%s - CALLED!', $infoInstance->__toString()));
$key = $infoInstance->getProtocolName();
* @param $infoInstance An instance of a ShareableInfo class
* @return $isRegistered Whether the listener is registered
*/
- private function isInfoRegistered (ShareableInfo $infoInstance) {
+ private function isInfoRegistered (ShareableInfo $infoInstance): bool {
// Get the key
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('SOCKET-REGISTRY: protocolName=' . $infoInstance->getProtocolName() . ' - CALLED!');
$key = $this->generateObjectRegistryKeyFromInfoInstance($infoInstance);
* @param $socketInstance An instance of a StorableSocket class
* @return $isRegistered Whether the given socket resource is registered
*/
- public function isSocketRegistered (ShareableInfo $infoInstance, StorableSocket $socketInstance) {
+ public function isSocketRegistered (ShareableInfo $infoInstance, StorableSocket $socketInstance): bool {
// Default is not registered
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('SOCKET-REGISTRY: protocolName=' . $infoInstance->getProtocolName() . ',socketResource[' . gettype($socketInstance->getSocketResource()) . ']=' . $socketInstance->getPrintableName() . ' - CALLED!');
$isRegistered = FALSE;
* @throws SocketAlreadyRegisteredException If the given socket is already registered
* @return void
*/
- public function registerSocketInstance (ShareableInfo $infoInstance, StorableSocket $socketInstance) {
+ public function registerSocketInstance (ShareableInfo $infoInstance, StorableSocket $socketInstance): void {
// Is the socket already registered?
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-REGISTRY: infoInstance->protocolName=%s,infoInstance->socketResource[%s]=%s - CALLED!', $infoInstance->getProtocolName(), gettype($socketInstance->getSocketResource()), $socketInstance->getPrintableName()));
if ($this->isSocketRegistered($infoInstance, $socketInstance)) {
* @return $socketInstance An instance of a StorableSocket class
* @throws NoSocketRegisteredException If the requested socket is not registered
*/
- public function getRegisteredSocketResource (Listenable $listenerInstance) {
+ public function getRegisteredSocketResource (Listenable $listenerInstance): StorableSocket {
// The socket must be registered before we can return it
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-REGISTRY: listenerInstance=%s - CALLED!', $listenerInstance->__toString()));
if (!$this->isInfoRegistered($listenerInstance)) {
* @param $packageInstance An instance of a DeliverablePackage class
* @return $infoInstance An instance of a ShareableInfo class
*/
- public function determineInfoInstanceByPackageInstance (DeliverablePackage $packageInstance) {
+ public function determineInfoInstanceByPackageInstance (DeliverablePackage $packageInstance): ShareableInfo {
// Init info instance
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-REGISTRY: packageInstance=%s - CALLED!', $packageInstance));
$infoInstance = NULL;
/* NOSY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SOCKET-REGISTRY: key=%s,subKey=%s, calling socketInstance->getListenerInstance() ...', $key, $subKey));
//* DEBUG-DIE: */ die(__METHOD__ . ': socketInstance=' . print_r($socketInstance, TRUE));
$listenerInstance = $socketInstance->getListenerInstance();
- $helperInstance = $socketInstance->getHelperInstance();
+ $helperInstance = $socketInstance->isHelperInstanceSet() ? $socketInstance->getHelperInstance() : NULL;
// Is a listener or helper set?
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SOCKET-REGISTRY: key=%s,subKey=%s,listenerInstance[]=%s,helperInstance[]=%s', $key, $subKey, gettype($listenerInstance), gettype($helperInstance)));
* @return $isRegistered Whether such a socket is registered
* @todo May extract this loop into private method and invoke it with CONNECTION_TYPE_INCOMING for later expansion also on outgoing/file sockets?
*/
- public function isIncomingSocketRegistered (Listenable $listenerInstance) {
+ public function isIncomingSocketRegistered (Listenable $listenerInstance): bool {
// Default is not found
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SOCKET-REGISTRY: listenerInstance=%s (protocol: %s) - CALLED!', $listenerInstance->__toString(), strtoupper($listenerInstance->getProtocolName())));
//* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this=%s', __METHOD__, __LINE__, print_r($this, TRUE)));
*
* @return $protocolName Name of used protocol
*/
- public final function getProtocolName () {
+ public final function getProtocolName (): string {
return $this->protocolName;
}
* @param $protocolName Name of used protocol
* @return void
*/
- protected final function setProtocolName (string $protocolName) {
+ protected final function setProtocolName (string $protocolName): void {
$this->protocolName = $protocolName;
}
use Org\Shipsimu\Hub\Factory\Handler\Protocol\ProtocolHandlerFactory;
use Org\Shipsimu\Hub\Factory\Registry\Object\ObjectTypeRegistryFactory;
use Org\Shipsimu\Hub\Handler\Package\NetworkPackageHandler;
+use Org\Shipsimu\Hub\Handler\Protocol\HandleableProtocol;
use Org\Shipsimu\Hub\Listener\Listenable;
use Org\Shipsimu\Hub\Network\Package\DeliverablePackage;
use Org\Shipsimu\Hub\Node\Tagging\InvalidTagException;
*
* @return $tagsInstance An instance of a Tagable class
*/
- public static final function createPackageTags () {
+ public static final function createPackageTags (): Tagable {
// Get new instance
$tagsInstance = new PackageTags();
*
* @return void
*/
- private function initObjectRegistry () {
+ private function initObjectRegistry (): void {
// Get the application instance
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('PACKAGE-TAGS: Initializing object registry - CALLED!');
$applicationInstance = ApplicationHelper::getSelfInstance();
* @param $packageInstance An instance of a DeliverablePackage class
* @return void
*/
- private function extractTagsFromPackageInstance (DeliverablePackage $packageInstance) {
+ private function extractTagsFromPackageInstance (DeliverablePackage $packageInstance): void {
// Debug message
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('PACKAGE-TAGS: packageInstance=%s - CALLED!', $packageInstance->__toString()));
//* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('PACKAGE-TAGS: packageInstance' . print_r($packageInstance, TRUE));
* @return void
* @throws InvalidTagException If a provided tag from the package data is invalid
*/
- private function verifyAllTags (DeliverablePackage $packageInstance) {
+ private function verifyAllTags (DeliverablePackage $packageInstance): void {
// Get the registry
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('PACKAGE-TAGS: packageInstance=%s - CALLED!', $packageInstance->__toString()));
$objectRegistryInstance = ObjectTypeRegistryFactory::createObjectTypeRegistryInstance();
* @param $packageInstance An instance of a DeliverablePackage class
* @return $lastProtocol An instance of the last used HandleableProtocol class
*/
- public function chooseProtocolFromPackageInstance (DeliverablePackage $packageInstance) {
+ public function chooseProtocolFromPackageInstance (DeliverablePackage $packageInstance): HandleableProtocol {
// Extract the tags
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('PACKAGE-TAGS: packageInstance=%s - CALLED!', $packageInstance->__toString()));
$this->extractTagsFromPackageInstance($packageInstance);
* @param $listenerInstance A Listenable instance
* @return $accepts Whether it is accepted
*/
- public function ifPackageDataIsAcceptedByListener (DeliverablePackage $packageInstance, Listenable $listenerInstance) {
+ public function ifPackageDataIsAcceptedByListener (DeliverablePackage $packageInstance, Listenable $listenerInstance): bool {
// Extract the tags
/* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('PACKAGE-TAGS: packageInstance=%s - CALLED!', $packageInstance->__toString()));
$this->extractTagsFromPackageInstance($packageInstance);
* @throws BasePathReadProtectedException If $templateBasePath is
* read-protected
*/
- public static final function createXmlObjectRegistryTemplateEngine () {
+ public static final function createXmlObjectRegistryTemplateEngine (): CompileableXmlTemplate {
// Get a new instance
$templateInstance = new XmlObjectRegistryTemplateEngine();
* @param $characters Characters to handle
* @return void
*/
- public function characterHandler ($resource, string $characters) {
+ public function characterHandler ($resource, string $characters): void {
// Trim all spaces away
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('XML-OBJECT-REGISTRY-TEMPLATE-ENGINE: resource[%s]=%s,characters[%s]=%s - CALLED!', gettype($resource), $resource, gettype($characters), $characters));
$characters = trim($characters);
*
* @return $fqfn Full-qualified file name of the menu cache
*/
- public function getObjectRegistryCacheFqfn () {
+ public function getObjectRegistryCacheFqfn (): string {
DebugMiddleware::getSelfInstance()->partialStub('Please implement this method.');
}
*
* @return void
*/
- protected function startObjectRegistry () {
+ protected function startObjectRegistry (): void {
// Push the node name on the stacker
$this->getStackInstance()->pushNamed('node_object_registry', 'object-registry');
}
*
* @return void
*/
- protected function startObjectList () {
+ protected function startObjectList (): void {
// Push the node name on the stacker
$this->getStackInstance()->pushNamed('node_object_registry', 'object-list');
}
*
* @return void
*/
- protected function startObjectListEntry () {
+ protected function startObjectListEntry (): void {
// Push the node name on the stacker
$this->getStackInstance()->pushNamed('node_object_registry', 'object-list-entry');
}
*
* @return void
*/
- protected function startObjectName () {
+ protected function startObjectName (): void {
// Push the node name on the stacker
$this->getStackInstance()->pushNamed('node_object_registry', self::OBJECT_TYPE_DATA_NAME);
}
*
* @return void
*/
- protected function startObjectRecipientLimitation () {
+ protected function startObjectRecipientLimitation (): void {
// Push the node name on the stacker
$this->getStackInstance()->pushNamed('node_object_registry', self::OBJECT_TYPE_DATA_RECIPIENT_LIMITATION);
}
*
* @return void
*/
- protected function startObjectMaxSpread () {
+ protected function startObjectMaxSpread (): void {
// Push the node name on the stacker
$this->getStackInstance()->pushNamed('node_object_registry', self::OBJECT_TYPE_DATA_MAX_SPREAD);
}
*
* @return void
*/
- protected function startObjectProtocol () {
+ protected function startObjectProtocol (): void {
// Push the node name on the stacker
$this->getStackInstance()->pushNamed('node_object_registry', self::OBJECT_TYPE_DATA_PROTOCOL);
}
*
* @return void
*/
- protected function startObjectRecipientType () {
+ protected function startObjectRecipientType (): void {
// Push the node name on the stacker
$this->getStackInstance()->pushNamed('node_object_registry', self::OBJECT_TYPE_DATA_RECIPIENT_TYPE);
}
*
* @return void
*/
- protected function finishObjectRecipientType () {
+ protected function finishObjectRecipientType (): void {
// Pop the last entry
$this->getStackInstance()->popNamed('node_object_registry');
}
*
* @return void
*/
- protected function finishObjectProtocol () {
+ protected function finishObjectProtocol (): void {
// Pop the last entry
$this->getStackInstance()->popNamed('node_object_registry');
}
*
* @return void
*/
- protected function finishObjectMaxSpread () {
+ protected function finishObjectMaxSpread (): void {
// Pop the last entry
$this->getStackInstance()->popNamed('node_object_registry');
}
*
* @return void
*/
- protected function finishObjectRecipientLimitation () {
+ protected function finishObjectRecipientLimitation (): void {
// Pop the last entry
$this->getStackInstance()->popNamed('node_object_registry');
}
*
* @return void
*/
- protected function finishObjectName () {
+ protected function finishObjectName (): void {
// Pop the last entry
$this->getStackInstance()->popNamed('node_object_registry');
}
*
* @return void
*/
- protected function finishObjectListEntry () {
+ protected function finishObjectListEntry (): void {
// Pop the last entry
$this->getStackInstance()->popNamed('node_object_registry');
}
*
* @return void
*/
- protected function finishObjectList () {
+ protected function finishObjectList (): void {
// Pop the last entry
$this->getStackInstance()->popNamed('node_object_registry');
}
*
* @return void
*/
- protected function finishObjectRegistry () {
+ protected function finishObjectRegistry (): void {
// Pop the last entry
$this->getStackInstance()->popNamed('node_object_registry');
}
* @param $code Error code
* @return void
*/
- public function __construct (HandleableProtocol $protocolInstance, $code) {
+ public function __construct (HandleableProtocol $protocolInstance, int $code) {
// Construct the message
$message = sprintf('[%s:] Requested socket is not yet registered.',
$protocolInstance->__toString()
const SOCKET_PROTOCOL_TCP = 'tcp';
const SOCKET_PROTOCOL_UDP = 'udp';
- /**
- * Connection type 'incoming'
- */
+ // Connection types
+ const CONNECTION_TYPE_INVALID = 'invalid';
const CONNECTION_TYPE_INCOMING = 'incoming';
-
- /**
- * Connection type 'outgoing'
- */
const CONNECTION_TYPE_OUTGOING = 'outgoing';
-
- /**
- * Connection type 'server'
- */
const CONNECTION_TYPE_SERVER = 'server';
// Exception codes
* @throws InvalidSocketException If stored socket is invalid
* @throws NullPointerException If listener instance is not given
*/
- function bindSocketToFile ();
+ function bindSocketToFile (): bool;
/**
* Tries to bind to attached listener's address and port
* @throws InvalidSocketException If stored socket is invalid
* @throws NullPointerException If listener instance is not given
*/
- function bindSocketToListener ();
+ function bindSocketToListener (): bool;
/**
* Tries to listen on the socket
* @return $result Result from listening on socket
* @throws InvalidSocketException If stored socket is invalid
*/
- function listenToSocket ();
+ function listenToSocket (): bool;
/**
* Tries to set non-blocking I/O on stored socket
* @return $result Result of changing to non-blocking I/O
* @throws InvalidSocketException If stored socket is invalid
*/
- function enableSocketNonBlocking ();
+ function enableSocketNonBlocking (): bool;
/**
* Tries to enable option "reuse address"
* @return void
* @throws InvalidSocketException If stored socket is invalid
*/
- function enableSocketReuseAddress ();
+ function enableSocketReuseAddress (): bool;
/**
* Determines socket's "peer name", mostly address and port number.
* @return $result Result from asking for peer address
* @throws InvalidSocketException If stored socket is invalid
*/
- function determineSocketPeerName (string &$peerAddress, int &$peerPort);
+ function determineSocketPeerName (string &$peerAddress, int &$peerPort): bool;
/**
* Calls socket_select() on stored socket resource
*
- * @return $socketInstance An instance of a StorableSocket class
+ * @return $socketInstance An instance of a StorableSocket class or NULL if no new socket was detected
* @throws InvalidSocketException If stored socket is invalid
*/
- function acceptNewIncomingSocket ();
+ function acceptNewIncomingSocket (): ?StorableSocket;
/**
* Tries to identify the socket peer by calling socket_getpeer()
*
* @return $result Whether the peer has been identified
*/
- function identifySocketPeer ();
+ function identifySocketPeer (): bool;
/**
* Tries to set socket timeout option
*
* @return $result Whether the option has been set
*/
- function setSocketTimeoutOptions ();
+ function setSocketTimeoutOptions (): bool;
/**
* Tries to enable out-of-band (OOB) data
*
* @return $result Whether OOB has been enabled
*/
- function enableSocketOutOfBandData ();
+ function enableSocketOutOfBandData (): bool;
/**
* Connects to socket recipient (supplied in package data array
* @return $result Result from calling socket_connect()
* @throws InvalidSocketException If stored socket is invalid
*/
- function connectToSocketRecipient ();
+ function connectToSocketRecipient (): bool;
/**
* Writes given buffer array to socket by calling socket_write(). The sent
* @return $result Result of calling socket_write()
* @throws InvalidSocketException If stored socket is invalid
*/
- function writeBufferToSocketByArray (array &$socketBuffer, int &$sentBytes);
+ function writeBufferToSocketByArray (array &$socketBuffer, int &$sentBytes): bool;
/**
* Getter for socket procotol field
*
* @return $socketProtocol Socket protocol (e.g. 'tcp' for TCP/IPv4, 'file' for Uni* file sockets)
*/
- function getSocketProtocol ();
+ function getSocketProtocol (): string;
/**
* Getter for socket recipient UNL
* @throws LogicException If 'recipient' array element is not found
* @throws InvalidSocketException If stored socket is invalid
*/
- function getSocketRecipientUnl ();
+ function getSocketRecipientUnl (): string;
/**
* Getter for socket recipient's address part
* @return $recipientAddress Recipient's address part
* @throws InvalidSocketException If stored socket is invalid
*/
- function getSocketRecipientAddress ();
+ function getSocketRecipientAddress (): string;
/**
* Getter for socket recipient's port part
* @return $recipientPort Recipient's port part
* @throws InvalidSocketException If stored socket is invalid
*/
- function getSocketRecipientPort ();
+ function getSocketRecipientPort (): int;
/**
* Checks whether the given Universal Node Locator matches with the one from package data
* @param $unl A Universal Node Locator
* @return $matches Whether $address matches with the one from package data
*/
- function ifAddressMatches (string $unl);
+ function ifAddressMatches (string $unl): bool;
/**
* Checks whether the given socket matches with stored
* @param $socketResource An instance of a Socket class
* @return $matches Whether given socket matches
*/
- function ifSocketResourceMatches (Socket $socketResource);
+ function ifSocketResourceMatches (Socket $socketResource): bool;
/**
* Shuts down a given socket resource. This method does only ease calling
*
* @return void
*/
- function shutdownSocket ();
+ function shutdownSocket (): void;
/**
* Half-shuts down a given socket resource. This method does only ease calling
*
* @return void
*/
- function halfShutdownSocket ();
+ function halfShutdownSocket (): void;
/**
* Validates stored stocket
*
* @return $isValidSocket Whether the stored socket is valid
*/
- function isValidSocket ();
+ function isValidSocket (): bool;
/**
* Getter for last socket error
* @return $errorCode Last socket error
* @throws InvalidSocketException If stored socket is invalid
*/
- function getLastSocketErrorCode ();
+ function getLastSocketErrorCode (): int;
/**
* Getter for last socket error message
* @return $errorMessage Last socket error message
* @throws InvalidSocketException If stored socket is invalid
*/
- function getLastSocketErrorMessage ();
+ function getLastSocketErrorMessage (): string;
/**
* Translates last socket error code into a human-readable form
*
* @return $codeName Code name to used e.g. with some_$codeName_socket_error_class or so
*/
- function translateLastSocketErrorCodeToName ();
+ function translateLastSocketErrorCodeToName (): string;
/**
* Handles socket error for given socket resource and peer data. This method
* @throws InvalidSocketException If the stored socket resource is no socket resource
* @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
*/
- function handleSocketError (string $method, int $line);
+ function handleSocketError (string $method, int $line): void;
/**
* Do the shutdown sequence for this connection helper
* @throws SocketShutdownException If the current socket could not be shut down
* @throws BaseMethodCallException If this method is possibly called twice
*/
- function doShutdown ();
+ function doShutdown (): void;
/**
* Checks whether the given connection type is valid
* @param $connectionType Type of connection, can be 'incoming', 'outgoing' or 'server'
* @return $isValid Whether the provided connection type is valid
*/
- function isValidConnectionType (string $connectionType);
+ function isValidConnectionType (string $connectionType): bool;
/**
* Clears last socket error
* @throws InvalidSocketException If stored socket is invalid
* @throws BadMethodCallException If no socket error was reported but method called
*/
- function clearLastSocketError ();
+ function clearLastSocketError (): void;
/**
* Registers whether helper or listener instance found in given info
* @param $infoInstance An instance of a ShareableInfo class
* @return void
*/
- function registerInfoInstance (ShareableInfo $infoInstance);
+ function registerInfoInstance (ShareableInfo $infoInstance): void;
/**
* Reads (binary) data from socket instance
* @return $rawData Raw data being read
* @throws InvalidSocketException If the stored socket is not valid
*/
- function readDataFromSocket ();
+ function readDataFromSocket (): mixed;
/**
* Getter for socket file instance
*
* @return $socketFile An instance of a SplFileInfo class
*/
- public function getSocketFile ();
+ function getSocketFile (): SplFileInfo;
/**
* Setter for socket file instance
* @param $socketFile An instance of a SplFileInfo class
* @return void
*/
- public function setSocketFile (SplFileInfo $socketFile);
+ function setSocketFile (SplFileInfo $socketFile): void;
/**
* Getter for socket type
*
* @return $socketFile Stocket type
*/
- public function getSocketType ();
+ function getSocketType (): string;
}
use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseFrontend;
use Org\Mxchange\CoreFramework\Handler\DataSet\HandleableDataSet;
+use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
/**
* An interface for distributed hash tables for nodes
*
* @return $unpublishedEntriesInstance Result instance
*/
- function getUnpublishedEntriesInstance ();
+ function getUnpublishedEntriesInstance (): SearchableResult;
/**
* Checks whether the local (*this*) node is registered in the DHT by
*
* @return $isRegistered Whether *this* node is registered in the DHT
*/
- function isLocalNodeRegistered ();
+ function isLocalNodeRegistered (): bool;
/**
* Registeres the local (*this*) node with its data in the DHT.
*
* @return void
*/
- function registerLocalNode ();
+ function registerLocalNode (): void;
/**
* Updates local (*this*) node's data in DHT, this is but not limited to the
*
* @return void
*/
- function updateLocalNode ();
+ function updateLocalNode (): void;
/**
* Finds a node locally by given session id
* @return $resultInstance An instance of a SearchableResult class
* @throws InvalidArgumentException If parameter $sessionId is not valid
*/
- function findNodeLocalBySessionId (string $sessionId);
+ function findNodeLocalBySessionId (string $sessionId): SearchableResult;
/**
* Finds a node locally by given UNL instance
* @param $locatorInstance An instance of a LocateableNode class
* @return $resultInstance An instance of a SearchableResult class
*/
- function findNodeLocalByLocatorInstance (LocateableNode $locatorInstance);
+ function findNodeLocalByLocatorInstance (LocateableNode $locatorInstance): SearchableResult;
/**
* Registeres a node by given message data.
* @param $handlerInstance An instance of a HandleableDataSet class
* @return void
*/
- function registerNodeByMessageInstance (DeliverableMessage $messageInstance, HandleableDataSet $handlerInstance);
+ function registerNodeByMessageInstance (DeliverableMessage $messageInstance, HandleableDataSet $handlerInstance): void;
/**
* Updates an existing entry in node list
* @param $searchInstance An instance of LocalSearchCriteria class
* @return void
*/
- function updateNodeByMessageInstance (DeliverableMessage $messageInstance, HandleableDataSet $handlerInstance, LocalSearchCriteria $searchInstance);
+ function updateNodeByMessageInstance (DeliverableMessage $messageInstance, HandleableDataSet $handlerInstance, LocalSearchCriteria $searchInstance): void;
/**
* Determines whether the given node data is already inserted in the DHT
* @param $nodeData An array with valid node data
* @return $isRegistered Whether the given node data is already inserted
*/
- function isNodeRegistered (array $nodeData);
+ function isNodeRegistered (array $nodeData): bool;
/**
* Registers a node with given data in the DHT. If the node is already
* @return void
* @throws NodeAlreadyRegisteredException If the node is already registered
*/
- function registerNode (array $nodeData);
+ function registerNode (array $nodeData): void;
/**
* Updates a node's entry in the DHT with given data. This will enrich or
* @return void
* @throws NodeDataMissingException If the node's data is missing
*/
- function updateNode (array $nodeData);
+ function updateNode (array $nodeData): void;
/**
* Checks whether there are unpublished entries
* @return $hasUnpublished Whether there are unpublished entries
* @todo Add minimum/maximum age limitations
*/
- function hasUnpublishedEntries ();
+ function hasUnpublishedEntries (): bool;
/**
* Initializes publication of DHT entries. This does only prepare
* @return void
* @todo Add timestamp to dataset instance
*/
- function initEntryPublication ();
+ function initEntryPublication (): void;
/**
* Removes non-public data from given array.
* @param $data An array with possible non-public data that needs to be removed.
* @return $data A cleaned up array with only public data.
*/
- function removeNonPublicDataFromArray(array $data);
+ function removeNonPublicDataFromArray(array $data): array;
/**
* Find recipients for given package data and exclude the sender
*
* @param $packageInstance An instance of a DeliverablePackage class
- * @return $recipients An indexed array with DHT recipients
+ * @return $resultInstance An instance of a SearchableResult class
*/
- function getResultFromExcludedSender (DeliverablePackage $packageInstance);
+ function getResultFromExcludedSender (DeliverablePackage $packageInstance): SearchableResult;
/**
* Find recopients by given key/value pair. First look for the key and if it
* @param $value Value to compare if key matches
* @return $recipients An indexed array with DHT recipients
*/
- function getResultFromKeyValue (string $key, $value);
+ function getResultFromKeyValue (string $key, mixed $value): array;
/**
* Enable DHT bootstrap request acceptance for local node
*
* @return void
*/
- function enableAcceptDhtBootstrap ();
+ function enableAcceptDhtBootstrap (): void;
}
namespace Org\Shipsimu\Hub\Discovery\Socket;
// Import application-specific stuff
+use Org\Shipsimu\Hub\Container\Socket\StorableSocket;
use Org\Shipsimu\Hub\Discovery\Recipient\DiscoverableRecipient;
use Org\Shipsimu\Hub\Handler\Protocol\HandleableProtocol;
+use Org\Shipsimu\Hub\Listener\Listenable;
use Org\Shipsimu\Hub\Network\Package\DeliverablePackage;
/**
* @throws NoListGroupException If the procol group is not found in peer list
* @throws NullPointerException If listenerInstance is NULL
*/
- function discoverSocket (DeliverablePackage $packageInstance, string $connectionType);
+ function discoverSocket (DeliverablePackage $packageInstance, string $connectionType): StorableSocket;
/**
* Tries to dicover the right listener instance
* @param $packageInstance An instance of a DeliverablePackage class
* @return $listenerInstance An instance of a Listenable instance or null
*/
- function discoverListenerInstance (HandleableProtocol $protocolInstance, DeliverablePackage $packageInstance);
+ function discoverListenerInstance (HandleableProtocol $protocolInstance, DeliverablePackage $packageInstance): Listenable;
}
*
* @return $port The port number
*/
- function getPort ();
+ function getPort (): int;
/**
* Getter for protocol name
*
* @return $protocol Name of used protocol
*/
- function getProtocolName ();
+ function getProtocolName (): string;
/**
* Default implementation for returning address part, may not be suitable
*
* @return $address Address part for the UNL
*/
- function getAddressPart ();
+ function getAddressPart (): string;
/**
* Validates given 'recipient' if it is a valid UNL. This means that the UNL
* @param $packageInstance Valid raw package data
* @return $isValid Whether the UNL can be validated
*/
- function isValidUniversalNodeLocatorByPackageInstance (DeliverablePackage $packageInstance);
+ function isValidUniversalNodeLocatorByPackageInstance (DeliverablePackage $packageInstance): bool;
/**
* If the found UNL (address) matches own external or internal address
* @param $unl UNL to test
* @return $ifMatches Whether the found UNL matches own addresss
*/
- function isOwnAddress (string $unl);
+ function isOwnAddress (string $unl): bool;
}
* @param $socketInstance A StorableSocket instance
* @return void
*/
- function setSocketInstance (StorableSocket $socketInstance);
+ function setSocketInstance (StorableSocket $socketInstance): void;
/**
* Getter for socket instance
*
* @return $socketInstance An instance of a StorableSocket class
*/
- function getSocketInstance ();
+ function getSocketInstance (): StorableSocket;
}
use Org\Shipsimu\Hub\Container\Socket\StorableSocket;
use Org\Shipsimu\Hub\Generic\HubInterface;
use Org\Shipsimu\Hub\Network\Package\DeliverablePackage;
+use Org\Shipsimu\Hub\Pool\Peer\PoolablePeer;
/**
* An interface for listeners
*
* @return void
*/
- function initListener();
+ function initListener(): void;
/**
* "Listens" for incoming network packages
*
* @return void
*/
- function doListen();
+ function doListen(): void;
/**
* Checks whether the listener would accept the given package data array
* @param $packageInstance An instance of a DeliverablePackage class
* @return $accepts Whether this listener does accept
*/
- function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance);
+ function ifListenerAcceptsPackageData (DeliverablePackage $packageInstance): bool;
/**
* Monitors incoming raw data from the handler and transfers it to the
*
* @return void
*/
- function monitorIncomingRawData ();
+ function monitorIncomingRawData (): void;
/**
* Getter for listen address
*
* @return $listenAddress The address this listener should listen on
*/
- function getListenAddress ();
+ function getListenAddress (): string;
/**
* Getter for listen port
*
* @return $listenPort The port this listener should listen on
*/
- function getListenPort ();
+ function getListenPort (): int;
/**
* Getter for peer pool instance
*
* @return $poolInstance The peer pool instance we shall set
*/
- function getPoolInstance ();
+ function getPoolInstance (): PoolablePeer;
/**
* Setter for socket instance
* @param $socketInstance A StorableSocket instance
* @return void
*/
- function setSocketInstance (StorableSocket $socketInstance);
+ function setSocketInstance (StorableSocket $socketInstance): void;
/**
* Getter for socket instance
*
* @return $socketInstance An instance of a StorableSocket class
*/
- function getSocketInstance ();
+ function getSocketInstance (): StorableSocket;
}
* @return $sockets An array with sockets of given type
* @throws InvalidConnectionTypeException If the found connection type is not valid
*/
- function getSocketsByConnectionType (string $connectionType);
+ function getSocketsByConnectionType (string $connectionType): array;
}
* @param $socketInstance An instance of a StorableSocket class
* @return $isRegistered Whether the given socket resource is registered
*/
- function isSocketRegistered (ShareableInfo $infoInstance, StorableSocket $socketInstance);
+ function isSocketRegistered (ShareableInfo $infoInstance, StorableSocket $socketInstance): bool;
/**
* Registeres given socket for listener or throws an exception if it is already registered
* @return void
* @throws SocketAlreadyRegisteredException If the given socket is already registered
*/
- function registerSocketInstance (ShareableInfo $infoInstance, StorableSocket $socketInstance);
+ function registerSocketInstance (ShareableInfo $infoInstance, StorableSocket $socketInstance): void;
/**
* Getter for given listener's socket resource
* @param $packageInstance An instance of a DeliverablePackage class
* @return $infoInstance An instance of a ShareableInfo class
*/
- function determineInfoInstanceByPackageInstance (DeliverablePackage $packageInstance);
+ function determineInfoInstanceByPackageInstance (DeliverablePackage $packageInstance): ShareableInfo;
/**
* Checks whether a socket of a connection type 'incoming' is registered.
* @param $listenerInstance An instance of a Listenable class
* @return $isRegistered Whether such a socket is registered
*/
- function isIncomingSocketRegistered (Listenable $listenerInstance);
+ function isIncomingSocketRegistered (Listenable $listenerInstance): bool;
}
* @param $socketInstance A StorableSocket instance
* @return void
*/
- function setSocketInstance (StorableSocket $socketInstance);
+ function setSocketInstance (StorableSocket $socketInstance): void;
/**
* Getter for socket instance
*
* @return $socketInstance An instance of a StorableSocket class
*/
- function getSocketInstance ();
+ function getSocketInstance (): StorableSocket;
}
namespace Org\Shipsimu\Hub\Tag\Socket;
// Import application-specific stuff
+use Org\Shipsimu\Hub\Container\Socket\StorableSocket;
use Org\Shipsimu\Hub\Generic\HubInterface;
use Org\Shipsimu\Hub\Network\Package\DeliverablePackage;
* @return $socketInstance An instance of a StorableSocket class
* @throws InvalidConnectionTypeException If the provided connection type is not valid
*/
- function getSocketFromPackageInstance (DeliverablePackage $packageInstance, string $connectionType = NULL);
+ function getSocketFromPackageInstance (DeliverablePackage $packageInstance, string $connectionType = NULL): ?StorableSocket;
}
// Import application-specific stuff
use Org\Shipsimu\Hub\Generic\HubInterface;
+use Org\Shipsimu\Hub\Handler\Protocol\HandleableProtocol;
use Org\Shipsimu\Hub\Listener\Listenable;
use Org\Shipsimu\Hub\Network\Package\DeliverablePackage;
* @param $packageInstance An instance of a DeliverablePackage class
* @return $protocolInstance An instance of a HandleableProtocol class
*/
- function chooseProtocolFromPackageInstance (DeliverablePackage $packageInstance);
+ function chooseProtocolFromPackageInstance (DeliverablePackage $packageInstance): HandleableProtocol;
/**
* Checks whether the given package data is accepted by the listener
* @param $listenerInstance A Listenable instance
* @return $accepts Whether it is accepted
*/
- function ifPackageDataIsAcceptedByListener (DeliverablePackage $packageInstance, Listenable $listenerInstance);
+ function ifPackageDataIsAcceptedByListener (DeliverablePackage $packageInstance, Listenable $listenerInstance): bool;
}
* @param $socketInstance A StorableSocket instance
* @return void
*/
- public final function setSocketInstance (StorableSocket $socketInstance) {
+ public final function setSocketInstance (StorableSocket $socketInstance): void {
$this->socketInstance = $socketInstance;
}
*
* @return $socketInstance An instance of a StorableSocket class
*/
- public final function getSocketInstance () {
+ public final function getSocketInstance (): StorableSocket {
return $this->socketInstance;
}
+ /**
+ * Checks whether a socket instance is set
+ *
+ * @return $isset Whether a socket instance is set
+ */
+ public final function isSocketInstanceSet (): bool {
+ return ($this->socketInstance instanceof StorableSocket);
+ }
+
}
-Subproject commit 7c9c09a0065013ed20f8361e87ad6ceda7896cb9
+Subproject commit f661757540897e6a0ee26231ddba8de4835fdd04