# Autodetect text files
* text=auto
-# Force the following filetypes to have unix eols, so Windows does not break them
-*.* text eol=lf
-
# Force images/fonts to be handled as binaries
-*.jpg binary
-*.jpeg binary
-*.gif binary
-*.png binary
-*.t3x binary
-*.t3d binary
-*.exe binary
-*.data binary
-*.ttf binary
-*.eof binary
-*.eot binary
-*.swf binary
-*.mov binary
-*.mp4 binary
-*.mp3 binary
-*.ogg binary
-*.flv binary
-*.jar binary
-*.pdf binary
-*.woff* binary
-*.otf binary
-*.z binary
-*.docx binary
+*.jpg filter=lfs diff=lfs merge=lfs -text
+*.jpeg filter=lfs diff=lfs merge=lfs -text
+*.gif filter=lfs diff=lfs merge=lfs -text
+*.png filter=lfs diff=lfs merge=lfs -text
+*.t3x filter=lfs diff=lfs merge=lfs -text
+*.t3d filter=lfs diff=lfs merge=lfs -text
+*.exe filter=lfs diff=lfs merge=lfs -text
+*.data filter=lfs diff=lfs merge=lfs -text
+*.ttf filter=lfs diff=lfs merge=lfs -text
+*.eof filter=lfs diff=lfs merge=lfs -text
+*.eot filter=lfs diff=lfs merge=lfs -text
+*.swf filter=lfs diff=lfs merge=lfs -text
+*.mov filter=lfs diff=lfs merge=lfs -text
+*.mp4 filter=lfs diff=lfs merge=lfs -text
+*.mp3 filter=lfs diff=lfs merge=lfs -text
+*.ogg filter=lfs diff=lfs merge=lfs -text
+*.flv filter=lfs diff=lfs merge=lfs -text
+*.jar filter=lfs diff=lfs merge=lfs -text
+*.pdf filter=lfs diff=lfs merge=lfs -text
+*.woff* filter=lfs diff=lfs merge=lfs -text
+*.otf filter=lfs diff=lfs merge=lfs -text
+*.z filter=lfs diff=lfs merge=lfs -text
+*.docx filter=lfs diff=lfs merge=lfs -text
+
+# Force the following filetypes to have unix eols, so Windows does not break them
+*.php text eol=lf
+*.tpl text eol=lf
+*.sh text eol=lf
+*.json text eol=lf
+*.lock text eol=lf
+*.dist text eol=lf
+*.xml text eol=lf
+/*.log
+/*.diff
+/*.path
/contrib/chash/chash.pos
/contrib/lfdb2/*.bin*
/contrib/lfdb2/*.out*
/reports/
/vendor/
/phpunit.xml
-/*.log
+++ /dev/null
-Deny from all
// Import framework stuff
use Org\Mxchange\CoreFramework\Application\BaseApplication;
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Loader\ClassLoader;
use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
use Org\Mxchange\CoreFramework\Registry\Registerable;
use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
/**
* A class holding general data about the application and some methods for
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
*
* This program is free software: you can redistribute it and/or modify
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class ApplicationHelper extends BaseApplication implements ManageableApplication, Registerable {
- /**
- * The version number of this application
- */
- private $appVersion = '';
-
- /**
- * The human-readable name for this application
- */
- private $appName = '';
-
- /**
- * The short uni*-like name for this application
- */
- private $shortName = '';
-
- /**
- * An instance of this class
- */
- private static $selfInstance = NULL;
-
/**
* Private constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public static final function getSelfInstance () {
// Is the instance there?
- if (is_null(self::$selfInstance)) {
- self::$selfInstance = new ApplicationHelper();
- } // END - if
+ if (is_null(self::getApplicationInstance())) {
+ // Then set it
+ self::setApplicationInstance(new ApplicationHelper());
+ }
// Return the instance
- return self::$selfInstance;
- }
-
- /**
- * Getter for the version number
- *
- * @return $appVersion The application's version number
- */
- public final function getAppVersion () {
- return $this->appVersion;
- }
- /**
- * Setter for the version number
- *
- * @param $appVersion The application's version number
- * @return void
- */
- public final function setAppVersion ($appVersion) {
- // Cast and set it
- $this->appVersion = (string) $appVersion;
- }
-
- /**
- * Getter for human-readable name
- *
- * @return $appName The application's human-readable name
- */
- public final function getAppName () {
- return $this->appName;
- }
-
- /**
- * Setter for human-readable name
- *
- * @param $appName The application's human-readable name
- * @return void
- */
- public final function setAppName ($appName) {
- // Cast and set it
- $this->appName = (string) $appName;;
- }
-
- /**
- * Getter for short uni*-like name
- *
- * @return $shortName The application's short uni*-like name
- */
- public final function getAppShortName () {
- return $this->shortName;
- }
-
- /**
- * Setter for short uni*-like name
- *
- * @param $shortName The application's short uni*-like name
- * @return void
- */
- public final function setAppShortName ($shortName) {
- // Cast and set it
- $this->shortName = (string) $shortName;
+ return self::getApplicationInstance();
}
/**
* @return void
*/
public function initApplication () {
- // Get config instance
- $cfg = FrameworkBootstrap::getConfigurationInstance();
-
// Initialize output system
self::createDebugInstance('ApplicationHelper');
* method.
*/
FrameworkBootstrap::initDatabaseInstance();
-
- // Register core tests
- ClassLoader::registerTestsPath('framework/main/tests');
-
- // Register own tests
- ClassLoader::registerTestsPath('application/tests/tests');
-
- // Scan for them now
- ClassLoader::scanTestsClasses();
}
/**
// Set it in request
$requestInstance->setRequestElement('command', $commandName);
- } // END - if
+ }
- // Get a controller resolver
- $resolverClass = sprintf(
- 'Org\Mxchange\CoreFramework\Tests\Resolver\Controller\%s',
- self::convertToClassName(sprintf(
- '%s_%s_controller_resolver',
- $this->getAppShortName(),
- FrameworkBootstrap::getRequestTypeFromSystem()
- ))
+ // Configuration entry key
+ $configEntry = sprintf(
+ '%s_%s_controller_resolver_class',
+ $this->getAppShortName(),
+ FrameworkBootstrap::getRequestTypeFromSystem()
);
- $resolverInstance = ObjectFactory::createObjectByName($resolverClass, array($commandName));
+
+ // Get a controller resolver instance
+ $resolverInstance = ObjectFactory::createObjectByConfiguredName($configEntry, [
+ $commandName,
+ ]);
// Get a controller instance as well
$this->setControllerInstance($resolverInstance->resolveController());
$this->getControllerInstance()->handleRequest($requestInstance, $responseInstance);
// -------------------------- Shutdown phase --------------------------
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('MAIN: Shutdown in progress ...');
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('MAIN: Shutdown in progress ...');
$this->getControllerInstance()->executeShutdownFilters($requestInstance, $responseInstance);
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('MAIN: Shutdown completed. (This is the last line.)');
+ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('MAIN: Shutdown completed. (This is the last line.)');
}
/**
// Walk through all messages
foreach ($messageList as $message) {
exit(__METHOD__ . ':MSG:' . $message);
- } // END - foreach
+ }
}
/**
/**
* Assigns extra application-depending data
*
- * @param $templateInstance An instance of a CompileableTemplate
+ * @param $templateInstance An instance of a CompileableTemplate class
* @return void
* @todo Nothing to add?
*/
public function assignExtraTemplateData (CompileableTemplate $templateInstance) {
- $this->partialStub('Unfinished method. templateInstance=' . $templateInstance->__toString());
+ DebugMiddleware::getSelfInstance()->partialStub('Unfinished method. templateInstance=' . $templateInstance->__toString());
}
}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Tests\Command;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Command\BaseCommand;
+use Org\Mxchange\CoreFramework\Command\Commandable;
+use Org\Mxchange\CoreFramework\Controller\Controller;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
+use Org\Mxchange\CoreFramework\Request\Requestable;
+use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
+use Org\Mxchange\CoreFramework\Response\Responseable;
+
+/**
+ * A command for the 'main' routine
+ *
+ * @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 TestsConsoleMainCommand extends BaseCommand implements Commandable {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Creates an instance of this class
+ *
+ * @param $resolverInstance An instance of a command resolver class
+ * @return $commandInstance An instance a prepared command class
+ */
+ public static final function createTestsConsoleMainCommand (CommandResolver $resolverInstance) {
+ // Get new instance
+ $commandInstance = new TestsConsoleMainCommand();
+
+ // Set the application instance
+ $commandInstance->setResolverInstance($resolverInstance);
+
+ // Return the prepared instance
+ return $commandInstance;
+ }
+
+ /**
+ * Executes the given command with given request and response objects
+ *
+ * @param $requestInstance An instance of a class with an Requestable interface
+ * @param $responseInstance An instance of a class with an Responseable interface
+ * @return void
+ */
+ public function execute (Requestable $requestInstance, Responseable $responseInstance) {
+ // Debug message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TESTS-CONSOLE-MAIN-COMMAND: requestInstance=%s,responseInstance=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString()));
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('MAIN: --- Starting tests ... ---');
+
+ // Get controller
+ $controllerInstance = ObjectRegistry::getRegistry('generic')->getInstance('controller');
+
+ // Run all tests
+ $controllerInstance->executeTestsFilters($requestInstance, $responseInstance);
+
+ // Debug message
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('MAIN: --- Leaving main ... ---');
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TESTS-CONSOLE-MAIN-COMMAND: EXIT!');
+ }
+
+ /**
+ * Adds extra filters to the given controller instance
+ *
+ * @param $controllerInstance A controller instance
+ * @param $requestInstance An instance of a class with an Requestable interface
+ * @return void
+ */
+ public function addExtraFilters (Controller $controllerInstance, Requestable $requestInstance) {
+ // Add pre filters (e.g. for requirements checks)
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TESTS-CONSOLE-MAIN-COMMAND: controllerInstance=%s,requestInstance=%s - CALLED!', $controllerInstance->__toString(), $requestInstance->__toString()));
+ $controllerInstance->addPreFilter(ObjectFactory::createObjectByConfiguredName('tests_php_requirements_filter_class'));
+
+ // Add 'tests' filters which will run the actual tests
+ $controllerInstance->addTestsFilter(ObjectFactory::createObjectByConfiguredName('tests_configuration_classes_loadable_filter_class'));
+ $controllerInstance->addTestsFilter(ObjectFactory::createObjectByConfiguredName('tests_configuration_is_enabled_filter_class'));
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TESTS-CONSOLE-MAIN-COMMAND: EXIT!');
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Tests\Controller;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Controller\BaseController;
+use Org\Mxchange\CoreFramework\Controller\Controller;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Filter\Filterable;
+use Org\Mxchange\CoreFramework\Request\Requestable;
+use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
+use Org\Mxchange\CoreFramework\Response\Responseable;
+
+/**
+ * The default controller with news for e.g. home or news page
+ *
+ * @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 TestsConsoleDefaultNewsController extends BaseController implements Controller {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TEST-CONSOLE-DEFAULT-NEWS-CONTROLLER: CONSTRUCTED!');
+ parent::__construct(__CLASS__);
+
+ // Init additional filter chains
+ foreach (['bootstrap', 'tests', BaseController::FILTER_CHAIN_SHUTDOWN] as $filterChain) {
+ // Init filter chain
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TEST-CONSOLE-DEFAULT-NEWS-CONTROLLER: Initializing filterChain=%s ...', $filterChain));
+ $this->initFilterChain($filterChain);
+ }
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TEST-CONSOLE-DEFAULT-NEWS-CONTROLLER: EXIT!');
+ }
+
+ /**
+ * Creates an instance of this class
+ *
+ * @param $resolverInstance An instance of a command resolver class
+ * @return $controllerInstance A prepared instance of this class
+ */
+ public static final function createTestsConsoleDefaultNewsController (CommandResolver $resolverInstance) {
+ // Create the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TEST-CONSOLE-DEFAULT-NEWS-CONTROLLER: resolverInstance=%s - CALLED!', $resolverInstance->__toString()));
+ $controllerInstance = new TestsConsoleDefaultNewsController();
+
+ // Set the command resolver
+ $controllerInstance->setResolverInstance($resolverInstance);
+
+ // Add news filters to this controller
+ $controllerInstance->addPreFilter(ObjectFactory::createObjectByConfiguredName('news_download_filter_class'));
+ $controllerInstance->addPreFilter(ObjectFactory::createObjectByConfiguredName('news_process_filter_class'));
+
+ // Return the prepared instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TEST-CONSOLE-DEFAULT-NEWS-CONTROLLER: controllerInstance=%s - EXIT!', $controllerInstance->__toString()));
+ return $controllerInstance;
+ }
+
+ /**
+ * Handles the given request and response
+ *
+ * @param $requestInstance An instance of a request class
+ * @param $responseInstance An instance of a response class
+ * @return void
+ */
+ public function handleRequest (Requestable $requestInstance, Responseable $responseInstance) {
+ // Get the command instance from the resolver by sending a request instance to the resolver
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TEST-CONSOLE-DEFAULT-NEWS-CONTROLLER: requestInstance=%s,responseInstance=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString()));
+ $commandInstance = $this->getResolverInstance()->resolveCommandByRequest($requestInstance);
+
+ // Add more filters by the command
+ $commandInstance->addExtraFilters($this, $requestInstance);
+
+ // Run the pre filters
+ $this->executePreFilters($requestInstance, $responseInstance);
+
+ // This request was valid! :-D
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('TEST-CONSOLE-DEFAULT-NEWS-CONTROLLER: Invoking requestInstance->setIsRequestValid(TRUE) ...');
+ $requestInstance->setIsRequestValid(TRUE);
+
+ // Execute the command
+ $commandInstance->execute($requestInstance, $responseInstance);
+
+ // Run the post filters
+ $this->executePostFilters($requestInstance, $responseInstance);
+
+ // Flush the response out
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TEST-CONSOLE-DEFAULT-NEWS-CONTROLLER: Invoking responseInstance->flushBuffer() ...');
+ $responseInstance->flushBuffer();
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TEST-CONSOLE-DEFAULT-NEWS-CONTROLLER: EXIT!');
+ }
+
+ /**
+ * Add a bootstrap filter
+ *
+ * @param $filterInstance A Filterable class
+ * @return void
+ */
+ public function addBootstrapFilter (Filterable $filterInstance) {
+ $this->addFilter('bootstrap', $filterInstance);
+ }
+
+ /**
+ * Add a tests filter
+ *
+ * @param $filterInstance A Filterable class
+ * @return void
+ */
+ public function addTestsFilter (Filterable $filterInstance) {
+ $this->addFilter('tests', $filterInstance);
+ }
+
+ /**
+ * Executes all bootstrap filters
+ *
+ * @param $requestInstance A Requestable class
+ * @param $responseInstance A Responseable class
+ * @return void
+ */
+ public function executeBootstrapFilters (Requestable $requestInstance, Responseable $responseInstance) {
+ $this->executeFilters('bootstrap', $requestInstance, $responseInstance);
+ }
+
+ /**
+ * Executes all tests filters
+ *
+ * @param $requestInstance A Requestable class
+ * @param $responseInstance A Responseable class
+ * @return void
+ */
+ public function executeTestsFilters (Requestable $requestInstance, Responseable $responseInstance) {
+ $this->executeFilters('tests', $requestInstance, $responseInstance);
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Tests\Filter;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Filter\BaseFilter;
+
+/**
+ * A generic filter for tests
+ *
+ * @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/>.
+ */
+abstract class BaseTestsFilter extends BaseFilter {
+ /**
+ * Protected constructor
+ *
+ * @param $className Real name of class
+ * @return void
+ */
+ protected function __construct (string $className) {
+ // Call parent constructor
+ parent::__construct($className);
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Tests\Filter\???;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Filter\Filterable;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+use Org\Mxchange\CoreFramework\Request\Requestable;
+use Org\Mxchange\CoreFramework\Response\Responseable;
+use Org\Mxchange\CoreFramework\Tests\Filter\BaseTestsFilter;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+
+/**
+ * A ??? filter for tests
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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 Tests???Filter extends BaseTestsFilter implements Filterable {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Creates an instance of this filter class
+ *
+ * @return $filterInstance An instance of this filter class
+ */
+ public final static function createTests???Filter () {
+ // Get a new instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TESTS-|||-FILTER: CALLED!');
+ $filterInstance = new Tests???Filter();
+
+ // Return the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TESTS-|||-FILTER: filterInstance=%s - EXIT!', $filterInstance->__toString()));
+ return $filterInstance;
+ }
+
+ /**
+ * Executes the filter with given request and response objects
+ *
+ * @param $requestInstance An instance of a class with an Requestable interface
+ * @param $responseInstance An instance of a class with an Responseable interface
+ * @return void
+ * @todo 0% done
+ */
+ public function execute (Requestable $requestInstance, Responseable $responseInstance) {
+ // Init counter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TESTS-|||-FILTER: requestInstance=%s,responseInstance=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString()));
+ $passed = $failed = $skipped = $warning = 0;
+
+ // Implement this!
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this method.');
+
+ // Calculate percentage
+ $percent = (($passed + $failed) > 0 ? ($passed / ($passed + $failed) * 100) : 0);
+
+ // Output result
+ self::createDebugInstance(__CLASS__, __LINE__)->infoMessage(sprintf('Test result: %d okay, %d failed (%0.02f%% passed), %d skipped, %d warnings', $passed, $failed, $percent, $skipped, $warning));
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TESTS-|||-FILTER: EXIT!');
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Tests\Filter\Configuration\???;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Filter\Filterable;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+use Org\Mxchange\CoreFramework\Request\Requestable;
+use Org\Mxchange\CoreFramework\Response\Responseable;
+use Org\Mxchange\CoreFramework\Tests\Filter\BaseTestsFilter;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+
+/**
+ * A ??? filter for configuration tests
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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 TestsConfiguration???Filter extends BaseTestsFilter implements Filterable {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Creates an instance of this filter class
+ *
+ * @return $filterInstance An instance of this filter class
+ */
+ public final static function createTestsConfiguration???Filter () {
+ // Get a new instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TESTS-CONFIGURATION-|||-FILTER: CALLED!');
+ $filterInstance = new TestsConfiguration???Filter();
+
+ // Return the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TESTS-CONFIGURATION-|||-FILTER: filterInstance=%s - EXIT!', $filterInstance->__toString()));
+ return $filterInstance;
+ }
+
+ /**
+ * Executes the filter with given request and response objects
+ *
+ * @param $requestInstance An instance of a class with an Requestable interface
+ * @param $responseInstance An instance of a class with an Responseable interface
+ * @return void
+ * @todo 0% done
+ */
+ public function execute (Requestable $requestInstance, Responseable $responseInstance) {
+ // Init counter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TESTS-CONFIGURATION-|||-FILTER: requestInstance=%s,responseInstance=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString()));
+ $passed = $failed = $skipped = $warning = 0;
+
+ // Implement this!
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this method.');
+
+ // Calculate percentage
+ $percent = (($passed + $failed) > 0 ? ($passed / ($passed + $failed) * 100) : 0);
+
+ // Output result
+ self::createDebugInstance(__CLASS__, __LINE__)->infoMessage(sprintf('Test result: %d okay, %d failed (%0.02f%% passed), %d skipped, %d warning - EXIT!', $passed, $failed, $percent, $skipped, $warning));
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TESTS-CONFIGURATION-|||-FILTER: EXIT!');
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Tests\Filter\Configuration\Classes;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Filter\Filterable;
+use Org\Mxchange\CoreFramework\Request\Requestable;
+use Org\Mxchange\CoreFramework\Response\Responseable;
+use Org\Mxchange\CoreFramework\Tests\Filter\BaseTestsFilter;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+
+/**
+ * A LoadableClasses filter for tests
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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 TestConfigurationLoadableClassesFilter extends BaseTestsFilter implements Filterable {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Creates an instance of this filter class
+ *
+ * @return $filterInstance An instance of this filter class
+ */
+ public final static function createTestConfigurationLoadableClassesFilter () {
+ // Get a new instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TESTS-CONFIGURATION-LOADABLE-CLASSES-FILTER: CALLED!');
+ $filterInstance = new TestConfigurationLoadableClassesFilter();
+
+ // Return the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TESTS-CONFIGURATION-LOADABLE-CLASSES-FILTER: filterInstance=%s - EXIT!', $filterInstance->__toString()));
+ return $filterInstance;
+ }
+
+ /**
+ * Executes the filter with given request and response objects
+ *
+ * @param $requestInstance An instance of a class with an Requestable interface
+ * @param $responseInstance An instance of a class with an Responseable interface
+ * @return void
+ */
+ public function execute (Requestable $requestInstance, Responseable $responseInstance) {
+ // Init counter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TESTS-CONFIGURATION-LOADABLE-CLASSES-FILTER: requestInstance=%s,responseInstance=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString()));
+ $passed = $failed = $skipped = $warning = 0;
+
+ // Loop through all configuration keys
+ foreach (FrameworkBootstrap::getConfigurationInstance()->getConfigurationArray() as $configKey => $configValue) {
+ // Key must end with _class
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TESTS-CONFIGURATION-LOADABLE-CLASSES-FILTER: configKey[%s]=%s,configValue[%s]=%s', gettype($configKey), $configKey, gettype($configValue), $configValue));
+ if (substr($configKey, -6, 6) != '_class') {
+ // Skip this
+ $skipped++;
+ continue;
+ }
+
+ // This may throw exceptions
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('Testing configKey[%s]=%s,configValue[%s]=%s', gettype($configKey), $configKey, gettype($configValue), $configValue));
+ try {
+ // Is the config entry valid and class is there?
+ if (!is_string($configValue)) {
+ // Skip further tests
+ self::createDebugInstance(__CLASS__, __LINE__)->warningMessage(sprintf('configValue=%s has unexpected type "%s", required: string - FAILED!', $configValue, gettype($configValue)));
+ $failed++;
+ continue;
+ } elseif (!class_exists($configValue)) {
+ // Skip further tests
+ self::createDebugInstance(__CLASS__, __LINE__)->warningMessage(sprintf('Class "%s" not found. FAILED!', $configValue));
+ $failed++;
+ continue;
+ }
+ } catch (InvalidArgumentException $e) {
+ // Maybe not conform?
+ self::createDebugInstance(__CLASS__, __LINE__)->warningMessage(sprintf('Class "%s" failed to load. Message: "%s"', $configValue, $e->getMessage()));
+
+ // Skip further tests
+ $failed++;
+ continue;
+ }
+
+ // class_exists() didn't fail
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('Class "%s" loaded successfully. OKAY', $configValue));
+ $passed++;
+ }
+
+ // Calculate percentage
+ $percent = (($passed + $failed) > 0 ? ($passed / ($passed + $failed) * 100) : 0);
+
+ // Output result
+ self::createDebugInstance(__CLASS__, __LINE__)->infoMessage(sprintf('Test result: %d okay, %d failed (%0.02f%% passed), %d skipped, %d warning - EXIT!', $passed, $failed, $percent, $skipped, $warning));
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TESTS-CONFIGURATION-LOADABLE-CLASSES-FILTER: EXIT!');
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Tests\Filter\Configuration\IsEnabled;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Filter\Filterable;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+use Org\Mxchange\CoreFramework\Request\Requestable;
+use Org\Mxchange\CoreFramework\Response\Responseable;
+use Org\Mxchange\CoreFramework\Tests\Filter\BaseTestsFilter;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+
+/**
+ * A IsEnabled filter for configuration tests
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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 TestsConfigurationIsEnabledFilter extends BaseTestsFilter implements Filterable {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Creates an instance of this filter class
+ *
+ * @return $filterInstance An instance of this filter class
+ */
+ public final static function createTestsConfigurationIsEnabledFilter () {
+ // Get a new instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TESTS-CONFIGURATION-IS-ENABLED-FILTER: CALLED!');
+ $filterInstance = new TestsConfigurationIsEnabledFilter();
+
+ // Return the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TESTS-CONFIGURATION-IS-ENABLED-FILTER: filterInstance=%s - EXIT!', $filterInstance->__toString()));
+ return $filterInstance;
+ }
+
+ /**
+ * Executes the filter with given request and response objects
+ *
+ * @param $requestInstance An instance of a class with an Requestable interface
+ * @param $responseInstance An instance of a class with an Responseable interface
+ * @return void
+ * @todo 0% done
+ */
+ public function execute (Requestable $requestInstance, Responseable $responseInstance) {
+ // Init counter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TESTS-CONFIGURATION-IS-ENABLED-FILTER: requestInstance=%s,responseInstance=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString()));
+ $passed = $failed = $skipped = $warning = 0;
+
+ // Loop through all configuration keys
+ foreach (FrameworkBootstrap::getConfigurationInstance()->getConfigurationArray() as $configKey => $configValue) {
+ // Key must end with _class
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TESTS-CONFIGURATION-IS-ENABLED-FILTER: configKey[%s]=%s,configValue[%s]=%s', gettype($configKey), $configKey, gettype($configValue), $configValue));
+ if (substr($configKey, 0, 3) != 'is_' && substr($configKey, -8, 8) != '_enabled') {
+ // Is this a boolean value?
+ if (is_bool($configValue)) {
+ // Issue a warning
+ self::createDebugInstance(__CLASS__, __LINE__)->warningMessage(sprintf('TESTS-CONFIGURATION-IS-ENABLED-FILTER: comnfigKey=%s has a boolean value[]=%s', $configKey, gettype($configValue)));
+ $warning++;
+ } else {
+ // Mark as skipped
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TESTS-CONFIGURATION-IS-ENABLED-FILTER: comnfigKey=%s is not wanted here - SKIPPED!', $configKey));
+ $skipped++;
+ }
+
+ // Skip this
+ continue;
+ }
+
+ // Is it boolean?
+ if (!is_bool($configValue)) {
+ // Failed!
+ self::createDebugInstance(__CLASS__, __LINE__)->warningMessage(sprintf('Configuration key "%s" is NOT boolean. FAILED', $configKey));
+ $failed++;
+ } else {
+ // Count as success
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('Configuration key "%s" is a boolean feature. OKAY', $configKey));
+ $passed++;
+ }
+ }
+
+ // Calculate percentage
+ $percent = (($passed + $failed) > 0 ? ($passed / ($passed + $failed) * 100) : 0);
+
+ // Output result
+ self::createDebugInstance(__CLASS__, __LINE__)->infoMessage(sprintf('Test result: %d okay, %d failed (%0.02f%% passed), %d skipped, $d warnings', $passed, $failed, $percent, $skipped, $warning));
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TESTS-CONFIGURATION-IS-ENABLED-FILTER: EXIT!');
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Tests\Filter\PhpRequirements;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Filter\Filterable;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+use Org\Mxchange\CoreFramework\Request\Requestable;
+use Org\Mxchange\CoreFramework\Response\Responseable;
+use Org\Mxchange\CoreFramework\Tests\Filter\BaseTestsFilter;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+
+/**
+ * A PhpRequirements filter for tests
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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 TestsPhpRequirementsFilter extends BaseTestsFilter implements Filterable {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Creates an instance of this filter class
+ *
+ * @return $filterInstance An instance of this filter class
+ */
+ public final static function createTestsPhpRequirementsFilter () {
+ // Get a new instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TESTS-PHP-REQUIREMENTS-FILTER: CALLED!');
+ $filterInstance = new TestsPhpRequirementsFilter();
+
+ // Return the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TESTS-PHP-REQUIREMENTS-FILTER: filterInstance=%s - EXIT!', $filterInstance->__toString()));
+ return $filterInstance;
+ }
+
+ /**
+ * Executes the filter with given request and response objects
+ *
+ * @param $requestInstance An instance of a class with an Requestable interface
+ * @param $responseInstance An instance of a class with an Responseable interface
+ * @return void
+ * @todo 0% done
+ */
+ public function execute (Requestable $requestInstance, Responseable $responseInstance) {
+ // Init counter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TESTS-PHP-REQUIREMENTS-FILTER: requestInstance=%s,responseInstance=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString()));
+ $passed = $failed = $skipped = $warning = 0;
+
+ // Implement this!
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this method.');
+
+ // Calculate percentage
+ $percent = (($passed + $failed) > 0 ? ($passed / ($passed + $failed) * 100) : 0);
+
+ // Output result
+ self::createDebugInstance(__CLASS__, __LINE__)->infoMessage(sprintf('Test result: %d okay, %d failed (%0.02f%% passed), %d skipped, %d warnings', $passed, $failed, $percent, $skipped, $warning));
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TESTS-PHP-REQUIREMENTS-FILTER: EXIT!');
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Tests\Resolver\Command;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Command\InvalidCommandException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Resolver\Command\BaseCommandResolver;
+use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+
+/**
+ * A command resolver for console commands
+ *
+ * @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 TestsConsoleCommandResolver extends BaseCommandResolver implements CommandResolver {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+
+ // Set prefix to "TestsConsole"
+ $this->setClassPrefix('tests_console');
+ }
+
+ /**
+ * Creates an instance of a TestsConsole command resolver with a given default command
+ *
+ * @param $commandName The default command we shall execute
+ * @return $resolverInstance The prepared command resolver instance
+ * @throws InvalidArgumentException Thrown if default command is not set
+ * @throws InvalidCommandException Thrown if default command is invalid
+ */
+ public static final function createTestsConsoleCommandResolver (string $commandName) {
+ // Create the new instance
+ $resolverInstance = new TestsConsoleCommandResolver();
+
+ // Is the variable $commandName set and the command is valid?
+ if (empty($commandName)) {
+ // Then thrown an exception here
+ throw new InvalidArgumentException('Parameter "commandName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($resolverInstance->isCommandValid('Org\Mxchange\CoreFramework\Tests\Command', $commandName) === false) {
+ // Invalid command found
+ throw new InvalidCommandException(array($resolverInstance, $commandName), self::EXCEPTION_INVALID_COMMAND);
+ }
+
+ // Set namespace for command
+ $resolverInstance->setNamespace('Org\Mxchange\CoreFramework\Tests\Command');
+ $resolverInstance->setCommandName($commandName);
+
+ // Return the prepared instance
+ return $resolverInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Tests\Resolver\Controller;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Controller\BaseController;
+use Org\Mxchange\CoreFramework\Controller\Controller;
+use Org\Mxchange\CoreFramework\Controller\InvalidControllerException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Resolver\Controller\BaseControllerResolver;
+use Org\Mxchange\CoreFramework\Resolver\Controller\ControllerResolver;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+
+/**
+ * A resolver for resolving controllers locally
+ *
+ * @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 TestsConsoleControllerResolver extends BaseControllerResolver implements ControllerResolver {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+
+ // Set prefix to "TestsConsole"
+ $this->setClassPrefix('tests_console');
+ }
+
+ /**
+ * Creates an instance of a resolver class with a given command
+ *
+ * @param $controllerName The controller we shall resolve
+ * @return $resolverInstance The prepared controller resolver instance
+ * @throws InvalidArgumentException Thrown if default command is not set
+ * @throws InvalidControllerException Thrown if default controller is invalid
+ */
+ public static final function createTestsConsoleControllerResolver (string $controllerName) {
+ // Create the new instance
+ $resolverInstance = new TestsConsoleControllerResolver();
+
+ // Is the variable $controllerName set and the command is valid?
+ if (empty($controllerName)) {
+ // Then thrown an exception here
+ throw new InvalidArgumentException('Parameter "controllerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($resolverInstance->isControllerValid('Org\Mxchange\CoreFramework\Tests\Controller', $controllerName) === false) {
+ // Invalid command found
+ throw new InvalidControllerException(array($resolverInstance, $controllerName), self::EXCEPTION_INVALID_CONTROLLER);
+ }
+
+ // Set namespace and controller name
+ $resolverInstance->setNamespace('Org\Mxchange\CoreFramework\Tests\Controller');
+ $resolverInstance->setControllerName($controllerName);
+
+ // Return the prepared instance
+ return $resolverInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+
+/**
+ * Local configuration entries which you can customize. Please keep the
+ * comments starting with CFG: as-is or else, the later configuration wizard
+ * (aka. 'admin' project) will not be able to parse it. You need to rename this
+ * file to config-local.php and make in that new file your changes.
+ *
+ * If you want to start an own network (which may accept different types of
+ * objects which would be rejected by the global network) please change
+ * hub_bootstrap_nodes (semicolon-seperated list) to your bootstrapper.
+ *
+ * You can set external_address to a hostname, e.g. me.homelinux.org, which will be
+ * included in the announcement. This is very useful for consumer DSL
+ * connections because they might be disconnected every 24 hours and rotate the
+ * IP number.
+ *
+ * @author Roland Haeder <webmaster@shipsimu.org>
+ * @version 0.0
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
+ * @license GNU GPL 3.0 or any newer version
+ *
+ * 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/>.
+ */
+
+// Some hub-specific configuration like port hostname where we will listen, etc.
+$cfg = FrameworkBootstrap::getConfigurationInstance();
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
*
* This program is free software: you can redistribute it and/or modify
$cfg->setConfigEntry('news_main_limit', 5);
// CFG: TESTS-PHP-REQUIREMENTS-FILTER
-$cfg->setConfigEntry('tests_php_requirements_filter_class', 'Org\Mxchange\CoreFramework\Tests\Filter\Requirements\TestsPhpRequirementsFilter');
+$cfg->setConfigEntry('tests_php_requirements_filter_class', 'Org\Mxchange\CoreFramework\Tests\Filter\PhpRequirements\TestsPhpRequirementsFilter');
// CFG: TEST-CONFIGURATION-CLASSES-LOADABLE-TEST-FILTER-CLASS
-$cfg->setConfigEntry('tests_configuration_classes_loadable_test_filter_class', 'Org\Mxchange\CoreFramework\Tests\Filter\Configuration\Classes\TestConfigurationLoadableClassesFilter');
+$cfg->setConfigEntry('tests_configuration_classes_loadable_filter_class', 'Org\Mxchange\CoreFramework\Tests\Filter\Configuration\Classes\TestConfigurationLoadableClassesFilter');
+
+// CFG: TEST-CONFIGURATION-IS-ENABLED-TEST-FILTER-CLASS
+$cfg->setConfigEntry('tests_configuration_is_enabled_filter_class', 'Org\Mxchange\CoreFramework\Tests\Filter\Configuration\IsEnabled\TestsConfigurationIsEnabledFilter');
+
+// CFG: TEST-CONSOLE-CONTROLLER-RESOLVER-CLASS
+$cfg->setConfigEntry('tests_console_controller_resolver_class', 'Org\Mxchange\CoreFramework\Tests\Resolver\Controller\TestsConsoleControllerResolver');
+++ /dev/null
-<?php
-/**
- * Application data
- *
- * Please remember that this include file is being loaded *before* the class
- * loader is loading classes from "exceptions", "interfaces" and "main"!
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 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/>.
- */
-
-// Get config instance
-$cfg = FrameworkConfiguration::getSelfInstance();
-
-// Get an instance of the helper
-$app = call_user_func_array(
- array($cfg->getConfigEntry('app_helper_class'), 'getSelfInstance'),
- array()
-);
-
-// Set application name and version
-$app->setAppName('Unit tests and more');
-$app->setAppVersion('0.0.0');
-$app->setAppShortName('tests');
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
*
* This program is free software: you can redistribute it and/or modify
<?php
// Import framework stuff
use Org\Mxchange\CoreFramework\Assertion\AssertionException;
+use Org\Mxchange\CoreFramework\Error\FatalErrorException;
use Org\Mxchange\CoreFramework\Generic\FrameworkException;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
*
* This program is free software: you can redistribute it and/or modify
*/
// The node's own exception handler
-function tests_exception_handler ($exceptionInstance) {
+function core_exception_handler ($exceptionInstance) {
// Is it an object and a valid instance?
if ((is_object($exceptionInstance)) && ($exceptionInstance instanceof Exception)) {
// Init variable
$backTrace = '';
+ // Generate exception code
+ $exceptionCode = ($exceptionInstance instanceof FrameworkException ? $exceptionInstance->getHexCode() : '0x' . bin2hex($exceptionInstance->getCode()));
+
// Get all call levels from backtrace
foreach ($exceptionInstance->getTrace() as $idx => $traceArray) {
// Init argument string
$argsString = '';
- // Convert arguments type into human-readable
- foreach ($traceArray['args'] as $arg) {
- $argsString .= ', ' . gettype($arg);
- } // END - foreach
- $argsString = substr($argsString, 2);
+ // Arguments given?
+ if (isset($traceArray['args'])) {
+ // Convert arguments type into human-readable
+ foreach ($traceArray['args'] as $arg) {
+ $argsString .= ', ' . gettype($arg);
+ }
+ $argsString = substr($argsString, 2);
+ }
// Set missing file/line
if (!isset($traceArray['file'])) $traceArray['file'] = 'unknown';
basename($traceArray['file']),
$traceArray['line']
);
- } // END - foreach
+ }
// Construct the message
$message = sprintf("--------------------------------------------------------------------------------
--------------------------------------------------------------------------------\n",
trim(html_entity_decode(strip_tags(get_class($exceptionInstance)))),
trim(html_entity_decode(strip_tags($exceptionInstance->getMessage()))),
- ($exceptionInstance instanceof FrameworkException ? $exceptionInstance->getHexCode() : '0x' . bin2hex($exceptionInstance->getCode())),
+ $exceptionCode,
$exceptionInstance->getFile(),
$exceptionInstance->getLine(),
trim($backTrace)
// Output the message
print($message);
+
+ // Exit with code
+ exit(hexdec($exceptionCode));
} elseif (is_object($exceptionInstance)) {
// Output more details
printf('exceptionInstance=%s', print_r($exceptionInstance, true));
+ exit(255);
} else {
/*
* Invalid exception instance detected! Do *only* throw exceptions that
* outputs like above.
*/
printf('exceptionInstance[]=%s is invalid! Please inform the core developer team.' . PHP_EOL, gettype($exceptionInstance));
+ exit(255);
}
}
// Error handler
-function tests_error_handler ($errno, $errstr, $errfile, $errline, array $errcontext) {
+function core_error_handler (int $errno, string $errstr, string $errfile, int $errline, array $errcontext) {
// Construct the message
- $message = sprintf('File: %s, Line: %s, Code: %s, Message: %s',
+ $message = sprintf('File: %s, Line: %d, Code: %d, Message: %s',
basename($errfile),
$errline,
$errno,
// Throw an exception here
throw new FatalErrorException($message, BaseFrameworkSystem::EXCEPTION_FATAL_ERROR);
-} // END - function
+}
// Assertion handler
-function tests_assert_handler ($file, $line, $code) {
+function core_assert_handler (string $file, int $line, int $code) {
// Empty code?
- if ($code === '') {
+ if (empty($code)) {
$code = '<em>Unknown</em>';
- } // END - if
+ }
// Create message
$message = sprintf('File: %s, Line: %s, Code: %s',
// Throw an exception here
throw new AssertionException($message, BaseFrameworkSystem::EXCEPTION_ASSERTION_FAILED);
-} // END - function
+}
// Set error handler
-//set_error_handler('tests_error_handler');
+//set_error_handler('core_error_handler');
// Set the new handler
-set_exception_handler('tests_exception_handler');
+set_exception_handler('core_exception_handler');
// Init assert handling
assert_options(ASSERT_ACTIVE , true);
-assert_options(ASSERT_WARNING , false);
+assert_options(ASSERT_WARNING , true);
assert_options(ASSERT_BAIL , true);
assert_options(ASSERT_QUIET_EVAL, false);
-assert_options(ASSERT_CALLBACK , 'tests_assert_handler');
+assert_options(ASSERT_CALLBACK , 'core_assert_handler');
+++ /dev/null
-<?php
-// @DEPRECATED
+++ /dev/null
-<?php
-/**
- * The application's class loader
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- *
- * 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/>.
- */
-
-// Scan for application's classes, exceptions and interfaces
-ClassLoader::scanApplicationClasses();
+++ /dev/null
-<?php
-/**
- * The application launcher
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 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/>.
- */
-
-// Is there an application helper instance? We need the method main() for
-// maining the application
-$app = call_user_func_array(
- array(
- FrameworkConfiguration::getSelfInstance()->getConfigEntry('app_helper_class'), 'getSelfInstance'
- ), array()
-);
-
-// Some sanity checks
-if ((empty($app)) || (is_null($app))) {
- // Something went wrong!
- ApplicationEntryPoint::app_exit(sprintf("[Main:] The application <span class=\"app_name\">%s</span> could not be launched because the helper class <span class=\"class_name\">%s</span> is not loaded.",
- $application,
- FrameworkConfiguration::getSelfInstance()->getConfigEntry('app_helper_class')
- ));
-} elseif (!is_object($app)) {
- // No object!
- ApplicationEntryPoint::app_exit(sprintf("[Main:] The application <span class=\"app_name\">%s</span> could not be launched because 'app' is not an object.",
- $application
- ));
-} elseif (!method_exists($app, FrameworkConfiguration::getSelfInstance()->getConfigEntry('entry_method'))) {
- // Method not found!
- ApplicationEntryPoint::app_exit(sprintf("[Main:] The application <span class=\"app_name\">%s</span> could not be launched because the method <span class=\"method_name\">%s</span> is missing.",
- $application,
- FrameworkConfiguration::getSelfInstance()->getConfigEntry('entry_method')
- ));
-}
-
-// Call user function
-call_user_func_array(array($app, FrameworkConfiguration::getSelfInstance()->getConfigEntry('entry_method')), array());
{
- "require-dev": {
- "phpunit/phpunit": "^6.3"
- }
+ "name": "quix0r/core",
+ "description": "Core Object-Oriented Framework",
+ "type": "library",
+ "license": "GPLv3+",
+ "authors": [
+ {
+ "name": "Roland Häder",
+ "email": "roland@mxchange.org"
+ }
+ ],
+ "minimum-stability": "stable",
+ "require-dev": {
+ "phpunit/phpunit": "^6.3"
+ }
}
{
"_readme": [
"This file locks the dependencies of your project to a known state",
- "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
+ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
- "content-hash": "3830d829257bdec3f238d83dd18c474e",
+ "content-hash": "ed9acb2394cfd19378859e9f830535f2",
"packages": [],
"packages-dev": [
+ {
+ "name": "doctrine/deprecations",
+ "version": "1.1.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/doctrine/deprecations.git",
+ "reference": "4f2d4f2836e7ec4e7a8625e75c6aa916004db931"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/doctrine/deprecations/zipball/4f2d4f2836e7ec4e7a8625e75c6aa916004db931",
+ "reference": "4f2d4f2836e7ec4e7a8625e75c6aa916004db931",
+ "shasum": ""
+ },
+ "require": {
+ "php": "^7.1 || ^8.0"
+ },
+ "require-dev": {
+ "doctrine/coding-standard": "^9",
+ "phpstan/phpstan": "1.4.10 || 1.10.15",
+ "phpstan/phpstan-phpunit": "^1.0",
+ "phpunit/phpunit": "^7.5 || ^8.5 || ^9.5",
+ "psalm/plugin-phpunit": "0.18.4",
+ "psr/log": "^1 || ^2 || ^3",
+ "vimeo/psalm": "4.30.0 || 5.12.0"
+ },
+ "suggest": {
+ "psr/log": "Allows logging deprecations via PSR-3 logger implementation"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Doctrine\\Deprecations\\": "lib/Doctrine/Deprecations"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "description": "A small layer on top of trigger_error(E_USER_DEPRECATED) or PSR-3 logging with options to disable all deprecations or selectively for packages.",
+ "homepage": "https://www.doctrine-project.org/",
+ "support": {
+ "issues": "https://github.com/doctrine/deprecations/issues",
+ "source": "https://github.com/doctrine/deprecations/tree/1.1.2"
+ },
+ "time": "2023-09-27T20:04:15+00:00"
+ },
{
"name": "doctrine/instantiator",
- "version": "1.1.0",
+ "version": "1.5.0",
"source": {
"type": "git",
"url": "https://github.com/doctrine/instantiator.git",
- "reference": "185b8868aa9bf7159f5f953ed5afb2d7fcdc3bda"
+ "reference": "0a0fa9780f5d4e507415a065172d26a98d02047b"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/doctrine/instantiator/zipball/185b8868aa9bf7159f5f953ed5afb2d7fcdc3bda",
- "reference": "185b8868aa9bf7159f5f953ed5afb2d7fcdc3bda",
+ "url": "https://api.github.com/repos/doctrine/instantiator/zipball/0a0fa9780f5d4e507415a065172d26a98d02047b",
+ "reference": "0a0fa9780f5d4e507415a065172d26a98d02047b",
"shasum": ""
},
"require": {
- "php": "^7.1"
+ "php": "^7.1 || ^8.0"
},
"require-dev": {
- "athletic/athletic": "~0.1.8",
+ "doctrine/coding-standard": "^9 || ^11",
"ext-pdo": "*",
"ext-phar": "*",
- "phpunit/phpunit": "^6.2.3",
- "squizlabs/php_codesniffer": "^3.0.2"
+ "phpbench/phpbench": "^0.16 || ^1",
+ "phpstan/phpstan": "^1.4",
+ "phpstan/phpstan-phpunit": "^1",
+ "phpunit/phpunit": "^7.5 || ^8.5 || ^9.5",
+ "vimeo/psalm": "^4.30 || ^5.4"
},
"type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "1.2.x-dev"
- }
- },
"autoload": {
"psr-4": {
"Doctrine\\Instantiator\\": "src/Doctrine/Instantiator/"
{
"name": "Marco Pivetta",
"email": "ocramius@gmail.com",
- "homepage": "http://ocramius.github.com/"
+ "homepage": "https://ocramius.github.io/"
}
],
"description": "A small, lightweight utility to instantiate objects in PHP without invoking their constructors",
- "homepage": "https://github.com/doctrine/instantiator",
+ "homepage": "https://www.doctrine-project.org/projects/instantiator.html",
"keywords": [
"constructor",
"instantiate"
],
- "time": "2017-07-22T11:58:36+00:00"
+ "support": {
+ "issues": "https://github.com/doctrine/instantiator/issues",
+ "source": "https://github.com/doctrine/instantiator/tree/1.5.0"
+ },
+ "funding": [
+ {
+ "url": "https://www.doctrine-project.org/sponsorship.html",
+ "type": "custom"
+ },
+ {
+ "url": "https://www.patreon.com/phpdoctrine",
+ "type": "patreon"
+ },
+ {
+ "url": "https://tidelift.com/funding/github/packagist/doctrine%2Finstantiator",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2022-12-30T00:15:36+00:00"
},
{
"name": "myclabs/deep-copy",
- "version": "1.8.1",
+ "version": "1.11.1",
"source": {
"type": "git",
"url": "https://github.com/myclabs/DeepCopy.git",
- "reference": "3e01bdad3e18354c3dce54466b7fbe33a9f9f7f8"
+ "reference": "7284c22080590fb39f2ffa3e9057f10a4ddd0e0c"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/3e01bdad3e18354c3dce54466b7fbe33a9f9f7f8",
- "reference": "3e01bdad3e18354c3dce54466b7fbe33a9f9f7f8",
+ "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/7284c22080590fb39f2ffa3e9057f10a4ddd0e0c",
+ "reference": "7284c22080590fb39f2ffa3e9057f10a4ddd0e0c",
"shasum": ""
},
"require": {
- "php": "^7.1"
+ "php": "^7.1 || ^8.0"
},
- "replace": {
- "myclabs/deep-copy": "self.version"
+ "conflict": {
+ "doctrine/collections": "<1.6.8",
+ "doctrine/common": "<2.13.3 || >=3,<3.2.2"
},
"require-dev": {
- "doctrine/collections": "^1.0",
- "doctrine/common": "^2.6",
- "phpunit/phpunit": "^7.1"
+ "doctrine/collections": "^1.6.8",
+ "doctrine/common": "^2.13.3 || ^3.2.2",
+ "phpunit/phpunit": "^7.5.20 || ^8.5.23 || ^9.5.13"
},
"type": "library",
"autoload": {
- "psr-4": {
- "DeepCopy\\": "src/DeepCopy/"
- },
"files": [
"src/DeepCopy/deep_copy.php"
- ]
+ ],
+ "psr-4": {
+ "DeepCopy\\": "src/DeepCopy/"
+ }
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"object",
"object graph"
],
- "time": "2018-06-11T23:09:50+00:00"
+ "support": {
+ "issues": "https://github.com/myclabs/DeepCopy/issues",
+ "source": "https://github.com/myclabs/DeepCopy/tree/1.11.1"
+ },
+ "funding": [
+ {
+ "url": "https://tidelift.com/funding/github/packagist/myclabs/deep-copy",
+ "type": "tidelift"
+ }
+ ],
+ "time": "2023-03-08T13:26:56+00:00"
},
{
"name": "phar-io/manifest",
}
],
"description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)",
+ "support": {
+ "issues": "https://github.com/phar-io/manifest/issues",
+ "source": "https://github.com/phar-io/manifest/tree/master"
+ },
"time": "2017-03-05T18:14:27+00:00"
},
{
}
],
"description": "Library for handling version information and constraints",
+ "support": {
+ "issues": "https://github.com/phar-io/version/issues",
+ "source": "https://github.com/phar-io/version/tree/master"
+ },
"time": "2017-03-05T17:38:23+00:00"
},
{
"name": "phpdocumentor/reflection-common",
- "version": "1.0.1",
+ "version": "2.2.0",
"source": {
"type": "git",
"url": "https://github.com/phpDocumentor/ReflectionCommon.git",
- "reference": "21bdeb5f65d7ebf9f43b1b25d404f87deab5bfb6"
+ "reference": "1d01c49d4ed62f25aa84a747ad35d5a16924662b"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/21bdeb5f65d7ebf9f43b1b25d404f87deab5bfb6",
- "reference": "21bdeb5f65d7ebf9f43b1b25d404f87deab5bfb6",
+ "url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/1d01c49d4ed62f25aa84a747ad35d5a16924662b",
+ "reference": "1d01c49d4ed62f25aa84a747ad35d5a16924662b",
"shasum": ""
},
"require": {
- "php": ">=5.5"
- },
- "require-dev": {
- "phpunit/phpunit": "^4.6"
+ "php": "^7.2 || ^8.0"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "1.0.x-dev"
+ "dev-2.x": "2.x-dev"
}
},
"autoload": {
"psr-4": {
- "phpDocumentor\\Reflection\\": [
- "src"
- ]
+ "phpDocumentor\\Reflection\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"reflection",
"static analysis"
],
- "time": "2017-09-11T18:02:19+00:00"
+ "support": {
+ "issues": "https://github.com/phpDocumentor/ReflectionCommon/issues",
+ "source": "https://github.com/phpDocumentor/ReflectionCommon/tree/2.x"
+ },
+ "time": "2020-06-27T09:03:43+00:00"
},
{
"name": "phpdocumentor/reflection-docblock",
- "version": "4.3.0",
+ "version": "5.3.0",
"source": {
"type": "git",
"url": "https://github.com/phpDocumentor/ReflectionDocBlock.git",
- "reference": "94fd0001232e47129dd3504189fa1c7225010d08"
+ "reference": "622548b623e81ca6d78b721c5e029f4ce664f170"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/94fd0001232e47129dd3504189fa1c7225010d08",
- "reference": "94fd0001232e47129dd3504189fa1c7225010d08",
+ "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/622548b623e81ca6d78b721c5e029f4ce664f170",
+ "reference": "622548b623e81ca6d78b721c5e029f4ce664f170",
"shasum": ""
},
"require": {
- "php": "^7.0",
- "phpdocumentor/reflection-common": "^1.0.0",
- "phpdocumentor/type-resolver": "^0.4.0",
- "webmozart/assert": "^1.0"
+ "ext-filter": "*",
+ "php": "^7.2 || ^8.0",
+ "phpdocumentor/reflection-common": "^2.2",
+ "phpdocumentor/type-resolver": "^1.3",
+ "webmozart/assert": "^1.9.1"
},
"require-dev": {
- "doctrine/instantiator": "~1.0.5",
- "mockery/mockery": "^1.0",
- "phpunit/phpunit": "^6.4"
+ "mockery/mockery": "~1.3.2",
+ "psalm/phar": "^4.8"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "4.x-dev"
+ "dev-master": "5.x-dev"
}
},
"autoload": {
"psr-4": {
- "phpDocumentor\\Reflection\\": [
- "src/"
- ]
+ "phpDocumentor\\Reflection\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
{
"name": "Mike van Riel",
"email": "me@mikevanriel.com"
+ },
+ {
+ "name": "Jaap van Otterdijk",
+ "email": "account@ijaap.nl"
}
],
"description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.",
- "time": "2017-11-30T07:14:17+00:00"
+ "support": {
+ "issues": "https://github.com/phpDocumentor/ReflectionDocBlock/issues",
+ "source": "https://github.com/phpDocumentor/ReflectionDocBlock/tree/5.3.0"
+ },
+ "time": "2021-10-19T17:43:47+00:00"
},
{
"name": "phpdocumentor/type-resolver",
- "version": "0.4.0",
+ "version": "1.8.0",
"source": {
"type": "git",
"url": "https://github.com/phpDocumentor/TypeResolver.git",
- "reference": "9c977708995954784726e25d0cd1dddf4e65b0f7"
+ "reference": "fad452781b3d774e3337b0c0b245dd8e5a4455fc"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/9c977708995954784726e25d0cd1dddf4e65b0f7",
- "reference": "9c977708995954784726e25d0cd1dddf4e65b0f7",
+ "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/fad452781b3d774e3337b0c0b245dd8e5a4455fc",
+ "reference": "fad452781b3d774e3337b0c0b245dd8e5a4455fc",
"shasum": ""
},
"require": {
- "php": "^5.5 || ^7.0",
- "phpdocumentor/reflection-common": "^1.0"
+ "doctrine/deprecations": "^1.0",
+ "php": "^7.4 || ^8.0",
+ "phpdocumentor/reflection-common": "^2.0",
+ "phpstan/phpdoc-parser": "^1.13"
},
"require-dev": {
- "mockery/mockery": "^0.9.4",
- "phpunit/phpunit": "^5.2||^4.8.24"
+ "ext-tokenizer": "*",
+ "phpbench/phpbench": "^1.2",
+ "phpstan/extension-installer": "^1.1",
+ "phpstan/phpstan": "^1.8",
+ "phpstan/phpstan-phpunit": "^1.1",
+ "phpunit/phpunit": "^9.5",
+ "rector/rector": "^0.13.9",
+ "vimeo/psalm": "^4.25"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "1.0.x-dev"
+ "dev-1.x": "1.x-dev"
}
},
"autoload": {
"psr-4": {
- "phpDocumentor\\Reflection\\": [
- "src/"
- ]
+ "phpDocumentor\\Reflection\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"email": "me@mikevanriel.com"
}
],
- "time": "2017-07-14T14:27:02+00:00"
+ "description": "A PSR-5 based resolver of Class names, Types and Structural Element Names",
+ "support": {
+ "issues": "https://github.com/phpDocumentor/TypeResolver/issues",
+ "source": "https://github.com/phpDocumentor/TypeResolver/tree/1.8.0"
+ },
+ "time": "2024-01-11T11:49:22+00:00"
},
{
"name": "phpspec/prophecy",
- "version": "1.8.0",
+ "version": "v1.10.3",
"source": {
"type": "git",
"url": "https://github.com/phpspec/prophecy.git",
- "reference": "4ba436b55987b4bf311cb7c6ba82aa528aac0a06"
+ "reference": "451c3cd1418cf640de218914901e51b064abb093"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/phpspec/prophecy/zipball/4ba436b55987b4bf311cb7c6ba82aa528aac0a06",
- "reference": "4ba436b55987b4bf311cb7c6ba82aa528aac0a06",
+ "url": "https://api.github.com/repos/phpspec/prophecy/zipball/451c3cd1418cf640de218914901e51b064abb093",
+ "reference": "451c3cd1418cf640de218914901e51b064abb093",
"shasum": ""
},
"require": {
"doctrine/instantiator": "^1.0.2",
"php": "^5.3|^7.0",
- "phpdocumentor/reflection-docblock": "^2.0|^3.0.2|^4.0",
- "sebastian/comparator": "^1.1|^2.0|^3.0",
- "sebastian/recursion-context": "^1.0|^2.0|^3.0"
+ "phpdocumentor/reflection-docblock": "^2.0|^3.0.2|^4.0|^5.0",
+ "sebastian/comparator": "^1.2.3|^2.0|^3.0|^4.0",
+ "sebastian/recursion-context": "^1.0|^2.0|^3.0|^4.0"
},
"require-dev": {
- "phpspec/phpspec": "^2.5|^3.2",
+ "phpspec/phpspec": "^2.5 || ^3.2",
"phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.5 || ^7.1"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "1.8.x-dev"
+ "dev-master": "1.10.x-dev"
}
},
"autoload": {
- "psr-0": {
- "Prophecy\\": "src/"
+ "psr-4": {
+ "Prophecy\\": "src/Prophecy"
}
},
"notification-url": "https://packagist.org/downloads/",
"spy",
"stub"
],
- "time": "2018-08-05T17:53:17+00:00"
+ "support": {
+ "issues": "https://github.com/phpspec/prophecy/issues",
+ "source": "https://github.com/phpspec/prophecy/tree/v1.10.3"
+ },
+ "time": "2020-03-05T15:02:03+00:00"
+ },
+ {
+ "name": "phpstan/phpdoc-parser",
+ "version": "1.25.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/phpstan/phpdoc-parser.git",
+ "reference": "bd84b629c8de41aa2ae82c067c955e06f1b00240"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/bd84b629c8de41aa2ae82c067c955e06f1b00240",
+ "reference": "bd84b629c8de41aa2ae82c067c955e06f1b00240",
+ "shasum": ""
+ },
+ "require": {
+ "php": "^7.2 || ^8.0"
+ },
+ "require-dev": {
+ "doctrine/annotations": "^2.0",
+ "nikic/php-parser": "^4.15",
+ "php-parallel-lint/php-parallel-lint": "^1.2",
+ "phpstan/extension-installer": "^1.0",
+ "phpstan/phpstan": "^1.5",
+ "phpstan/phpstan-phpunit": "^1.1",
+ "phpstan/phpstan-strict-rules": "^1.0",
+ "phpunit/phpunit": "^9.5",
+ "symfony/process": "^5.2"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "PHPStan\\PhpDocParser\\": [
+ "src/"
+ ]
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "description": "PHPDoc parser with support for nullable, intersection and generic types",
+ "support": {
+ "issues": "https://github.com/phpstan/phpdoc-parser/issues",
+ "source": "https://github.com/phpstan/phpdoc-parser/tree/1.25.0"
+ },
+ "time": "2024-01-04T17:06:16+00:00"
},
{
"name": "phpunit/php-code-coverage",
"testing",
"xunit"
],
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues",
+ "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/5.3"
+ },
"time": "2018-04-06T15:36:58+00:00"
},
{
"filesystem",
"iterator"
],
+ "support": {
+ "irc": "irc://irc.freenode.net/phpunit",
+ "issues": "https://github.com/sebastianbergmann/php-file-iterator/issues",
+ "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/1.4.5"
+ },
"time": "2017-11-27T13:52:08+00:00"
},
{
"keywords": [
"template"
],
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/php-text-template/issues",
+ "source": "https://github.com/sebastianbergmann/php-text-template/tree/1.2.1"
+ },
"time": "2015-06-21T13:50:34+00:00"
},
{
"keywords": [
"timer"
],
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/php-timer/issues",
+ "source": "https://github.com/sebastianbergmann/php-timer/tree/master"
+ },
"time": "2017-02-26T11:10:40+00:00"
},
{
"keywords": [
"tokenizer"
],
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/php-token-stream/issues",
+ "source": "https://github.com/sebastianbergmann/php-token-stream/tree/master"
+ },
+ "abandoned": true,
"time": "2017-11-27T05:48:46+00:00"
},
{
"name": "phpunit/phpunit",
- "version": "6.5.13",
+ "version": "6.5.14",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
- "reference": "0973426fb012359b2f18d3bd1e90ef1172839693"
+ "reference": "bac23fe7ff13dbdb461481f706f0e9fe746334b7"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/0973426fb012359b2f18d3bd1e90ef1172839693",
- "reference": "0973426fb012359b2f18d3bd1e90ef1172839693",
+ "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/bac23fe7ff13dbdb461481f706f0e9fe746334b7",
+ "reference": "bac23fe7ff13dbdb461481f706f0e9fe746334b7",
"shasum": ""
},
"require": {
"testing",
"xunit"
],
- "time": "2018-09-08T15:10:43+00:00"
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/phpunit/issues",
+ "source": "https://github.com/sebastianbergmann/phpunit/tree/6.5.14"
+ },
+ "time": "2019-02-01T05:22:47+00:00"
},
{
"name": "phpunit/phpunit-mock-objects",
"mock",
"xunit"
],
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/phpunit-mock-objects/issues",
+ "source": "https://github.com/sebastianbergmann/phpunit-mock-objects/tree/5.0.10"
+ },
+ "abandoned": true,
"time": "2018-08-09T05:50:03+00:00"
},
{
"name": "sebastian/code-unit-reverse-lookup",
- "version": "1.0.1",
+ "version": "1.0.2",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git",
- "reference": "4419fcdb5eabb9caa61a27c7a1db532a6b55dd18"
+ "reference": "1de8cd5c010cb153fcd68b8d0f64606f523f7619"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/4419fcdb5eabb9caa61a27c7a1db532a6b55dd18",
- "reference": "4419fcdb5eabb9caa61a27c7a1db532a6b55dd18",
+ "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/1de8cd5c010cb153fcd68b8d0f64606f523f7619",
+ "reference": "1de8cd5c010cb153fcd68b8d0f64606f523f7619",
"shasum": ""
},
"require": {
- "php": "^5.6 || ^7.0"
+ "php": ">=5.6"
},
"require-dev": {
- "phpunit/phpunit": "^5.7 || ^6.0"
+ "phpunit/phpunit": "^8.5"
},
"type": "library",
"extra": {
],
"description": "Looks up which function or method a line of code belongs to",
"homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/",
- "time": "2017-03-04T06:30:41+00:00"
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/issues",
+ "source": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/tree/1.0.2"
+ },
+ "funding": [
+ {
+ "url": "https://github.com/sebastianbergmann",
+ "type": "github"
+ }
+ ],
+ "time": "2020-11-30T08:15:22+00:00"
},
{
"name": "sebastian/comparator",
"compare",
"equality"
],
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/comparator/issues",
+ "source": "https://github.com/sebastianbergmann/comparator/tree/master"
+ },
"time": "2018-02-01T13:46:46+00:00"
},
{
"keywords": [
"diff"
],
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/diff/issues",
+ "source": "https://github.com/sebastianbergmann/diff/tree/master"
+ },
"time": "2017-08-03T08:09:46+00:00"
},
{
"environment",
"hhvm"
],
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/environment/issues",
+ "source": "https://github.com/sebastianbergmann/environment/tree/master"
+ },
"time": "2017-07-01T08:51:00+00:00"
},
{
"name": "sebastian/exporter",
- "version": "3.1.0",
+ "version": "3.1.5",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/exporter.git",
- "reference": "234199f4528de6d12aaa58b612e98f7d36adb937"
+ "reference": "73a9676f2833b9a7c36968f9d882589cd75511e6"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/234199f4528de6d12aaa58b612e98f7d36adb937",
- "reference": "234199f4528de6d12aaa58b612e98f7d36adb937",
+ "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/73a9676f2833b9a7c36968f9d882589cd75511e6",
+ "reference": "73a9676f2833b9a7c36968f9d882589cd75511e6",
"shasum": ""
},
"require": {
- "php": "^7.0",
+ "php": ">=7.0",
"sebastian/recursion-context": "^3.0"
},
"require-dev": {
"ext-mbstring": "*",
- "phpunit/phpunit": "^6.0"
+ "phpunit/phpunit": "^8.5"
},
"type": "library",
"extra": {
"BSD-3-Clause"
],
"authors": [
+ {
+ "name": "Sebastian Bergmann",
+ "email": "sebastian@phpunit.de"
+ },
{
"name": "Jeff Welch",
"email": "whatthejeff@gmail.com"
"name": "Volker Dusch",
"email": "github@wallbash.com"
},
- {
- "name": "Bernhard Schussek",
- "email": "bschussek@2bepublished.at"
- },
- {
- "name": "Sebastian Bergmann",
- "email": "sebastian@phpunit.de"
- },
{
"name": "Adam Harvey",
"email": "aharvey@php.net"
+ },
+ {
+ "name": "Bernhard Schussek",
+ "email": "bschussek@gmail.com"
}
],
"description": "Provides the functionality to export PHP variables for visualization",
"export",
"exporter"
],
- "time": "2017-04-03T13:19:02+00:00"
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/exporter/issues",
+ "source": "https://github.com/sebastianbergmann/exporter/tree/3.1.5"
+ },
+ "funding": [
+ {
+ "url": "https://github.com/sebastianbergmann",
+ "type": "github"
+ }
+ ],
+ "time": "2022-09-14T06:00:17+00:00"
},
{
"name": "sebastian/global-state",
"keywords": [
"global state"
],
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/global-state/issues",
+ "source": "https://github.com/sebastianbergmann/global-state/tree/2.0.0"
+ },
"time": "2017-04-27T15:39:26+00:00"
},
{
"name": "sebastian/object-enumerator",
- "version": "3.0.3",
+ "version": "3.0.4",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/object-enumerator.git",
- "reference": "7cfd9e65d11ffb5af41198476395774d4c8a84c5"
+ "reference": "e67f6d32ebd0c749cf9d1dbd9f226c727043cdf2"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/7cfd9e65d11ffb5af41198476395774d4c8a84c5",
- "reference": "7cfd9e65d11ffb5af41198476395774d4c8a84c5",
+ "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/e67f6d32ebd0c749cf9d1dbd9f226c727043cdf2",
+ "reference": "e67f6d32ebd0c749cf9d1dbd9f226c727043cdf2",
"shasum": ""
},
"require": {
- "php": "^7.0",
+ "php": ">=7.0",
"sebastian/object-reflector": "^1.1.1",
"sebastian/recursion-context": "^3.0"
},
],
"description": "Traverses array structures and object graphs to enumerate all referenced objects",
"homepage": "https://github.com/sebastianbergmann/object-enumerator/",
- "time": "2017-08-03T12:35:26+00:00"
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/object-enumerator/issues",
+ "source": "https://github.com/sebastianbergmann/object-enumerator/tree/3.0.4"
+ },
+ "funding": [
+ {
+ "url": "https://github.com/sebastianbergmann",
+ "type": "github"
+ }
+ ],
+ "time": "2020-11-30T07:40:27+00:00"
},
{
"name": "sebastian/object-reflector",
- "version": "1.1.1",
+ "version": "1.1.2",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/object-reflector.git",
- "reference": "773f97c67f28de00d397be301821b06708fca0be"
+ "reference": "9b8772b9cbd456ab45d4a598d2dd1a1bced6363d"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/773f97c67f28de00d397be301821b06708fca0be",
- "reference": "773f97c67f28de00d397be301821b06708fca0be",
+ "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/9b8772b9cbd456ab45d4a598d2dd1a1bced6363d",
+ "reference": "9b8772b9cbd456ab45d4a598d2dd1a1bced6363d",
"shasum": ""
},
"require": {
- "php": "^7.0"
+ "php": ">=7.0"
},
"require-dev": {
"phpunit/phpunit": "^6.0"
],
"description": "Allows reflection of object attributes, including inherited and non-public ones",
"homepage": "https://github.com/sebastianbergmann/object-reflector/",
- "time": "2017-03-29T09:07:27+00:00"
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/object-reflector/issues",
+ "source": "https://github.com/sebastianbergmann/object-reflector/tree/1.1.2"
+ },
+ "funding": [
+ {
+ "url": "https://github.com/sebastianbergmann",
+ "type": "github"
+ }
+ ],
+ "time": "2020-11-30T07:37:18+00:00"
},
{
"name": "sebastian/recursion-context",
- "version": "3.0.0",
+ "version": "3.0.1",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/recursion-context.git",
- "reference": "5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8"
+ "reference": "367dcba38d6e1977be014dc4b22f47a484dac7fb"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8",
- "reference": "5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8",
+ "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/367dcba38d6e1977be014dc4b22f47a484dac7fb",
+ "reference": "367dcba38d6e1977be014dc4b22f47a484dac7fb",
"shasum": ""
},
"require": {
- "php": "^7.0"
+ "php": ">=7.0"
},
"require-dev": {
"phpunit/phpunit": "^6.0"
"BSD-3-Clause"
],
"authors": [
- {
- "name": "Jeff Welch",
- "email": "whatthejeff@gmail.com"
- },
{
"name": "Sebastian Bergmann",
"email": "sebastian@phpunit.de"
},
+ {
+ "name": "Jeff Welch",
+ "email": "whatthejeff@gmail.com"
+ },
{
"name": "Adam Harvey",
"email": "aharvey@php.net"
],
"description": "Provides functionality to recursively process PHP variables",
"homepage": "http://www.github.com/sebastianbergmann/recursion-context",
- "time": "2017-03-03T06:23:57+00:00"
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/recursion-context/issues",
+ "source": "https://github.com/sebastianbergmann/recursion-context/tree/3.0.1"
+ },
+ "funding": [
+ {
+ "url": "https://github.com/sebastianbergmann",
+ "type": "github"
+ }
+ ],
+ "time": "2020-11-30T07:34:24+00:00"
},
{
"name": "sebastian/resource-operations",
],
"description": "Provides a list of PHP built-in functions that operate on resources",
"homepage": "https://www.github.com/sebastianbergmann/resource-operations",
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/resource-operations/issues",
+ "source": "https://github.com/sebastianbergmann/resource-operations/tree/master"
+ },
"time": "2015-07-28T20:34:47+00:00"
},
{
],
"description": "Library that helps with managing the version number of Git-hosted PHP projects",
"homepage": "https://github.com/sebastianbergmann/version",
+ "support": {
+ "issues": "https://github.com/sebastianbergmann/version/issues",
+ "source": "https://github.com/sebastianbergmann/version/tree/master"
+ },
"time": "2016-10-03T07:35:21+00:00"
},
{
"name": "theseer/tokenizer",
- "version": "1.1.0",
+ "version": "1.2.2",
"source": {
"type": "git",
"url": "https://github.com/theseer/tokenizer.git",
- "reference": "cb2f008f3f05af2893a87208fe6a6c4985483f8b"
+ "reference": "b2ad5003ca10d4ee50a12da31de12a5774ba6b96"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/theseer/tokenizer/zipball/cb2f008f3f05af2893a87208fe6a6c4985483f8b",
- "reference": "cb2f008f3f05af2893a87208fe6a6c4985483f8b",
+ "url": "https://api.github.com/repos/theseer/tokenizer/zipball/b2ad5003ca10d4ee50a12da31de12a5774ba6b96",
+ "reference": "b2ad5003ca10d4ee50a12da31de12a5774ba6b96",
"shasum": ""
},
"require": {
"ext-dom": "*",
"ext-tokenizer": "*",
"ext-xmlwriter": "*",
- "php": "^7.0"
+ "php": "^7.2 || ^8.0"
},
"type": "library",
"autoload": {
}
],
"description": "A small library for converting tokenized PHP source code into XML and potentially other formats",
- "time": "2017-04-07T12:08:54+00:00"
+ "support": {
+ "issues": "https://github.com/theseer/tokenizer/issues",
+ "source": "https://github.com/theseer/tokenizer/tree/1.2.2"
+ },
+ "funding": [
+ {
+ "url": "https://github.com/theseer",
+ "type": "github"
+ }
+ ],
+ "time": "2023-11-20T00:12:19+00:00"
},
{
"name": "webmozart/assert",
- "version": "1.3.0",
+ "version": "1.11.0",
"source": {
"type": "git",
- "url": "https://github.com/webmozart/assert.git",
- "reference": "0df1908962e7a3071564e857d86874dad1ef204a"
+ "url": "https://github.com/webmozarts/assert.git",
+ "reference": "11cb2199493b2f8a3b53e7f19068fc6aac760991"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/webmozart/assert/zipball/0df1908962e7a3071564e857d86874dad1ef204a",
- "reference": "0df1908962e7a3071564e857d86874dad1ef204a",
+ "url": "https://api.github.com/repos/webmozarts/assert/zipball/11cb2199493b2f8a3b53e7f19068fc6aac760991",
+ "reference": "11cb2199493b2f8a3b53e7f19068fc6aac760991",
"shasum": ""
},
"require": {
- "php": "^5.3.3 || ^7.0"
+ "ext-ctype": "*",
+ "php": "^7.2 || ^8.0"
+ },
+ "conflict": {
+ "phpstan/phpstan": "<0.12.20",
+ "vimeo/psalm": "<4.6.1 || 4.6.2"
},
"require-dev": {
- "phpunit/phpunit": "^4.6",
- "sebastian/version": "^1.0.1"
+ "phpunit/phpunit": "^8.5.13"
},
"type": "library",
"extra": {
"branch-alias": {
- "dev-master": "1.3-dev"
+ "dev-master": "1.10-dev"
}
},
"autoload": {
"check",
"validate"
],
- "time": "2018-01-29T19:49:41+00:00"
+ "support": {
+ "issues": "https://github.com/webmozarts/assert/issues",
+ "source": "https://github.com/webmozarts/assert/tree/1.11.0"
+ },
+ "time": "2022-06-03T18:03:27+00:00"
}
],
"aliases": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": [],
- "platform-dev": []
+ "platform-dev": [],
+ "plugin-api-version": "2.3.0"
}
<?php
-$GLOBALS['options'] = array(
+$GLOBALS['options'] = [
'analyze_input' => FALSE,
'reduce_noise' => FALSE,
'ignore_noise' => FALSE,
'keep_noise' => FALSE,
'buffer_size' => 8,
-);
+];
if (isset($_SERVER['argv'][1]) && $_SERVER['argv'][1] == 'a') {
$GLOBALS['options']['analyze_input'] = TRUE;
}
function analyzeForNoiseOnly ($data) {
- $GLOBALS['analysis']['breakdown'] = array();
+ $GLOBALS['analysis']['breakdown'] = [];
$GLOBALS['analysis']['average'] = 0;
for ($i = 0; $i < strlen($data); $i++) {
if (!$GLOBALS['options']['keep_noise'] && !$GLOBALS['options']['ignore_noise'] && count($GLOBALS['analysis']['breakdown']) == 2 && isset($GLOBALS['analysis']['breakdown'][127]) && isset($GLOBALS['analysis']['breakdown'][128])) {
if ($GLOBALS['options']['analyze_input']) {
- //echo 'NOISE1!' . PHP_EOL;
+ //* NOISY: */ echo 'NOISE1!' . PHP_EOL;
}
return NULL;
} elseif (!$GLOBALS['options']['keep_noise'] && !$GLOBALS['options']['ignore_noise'] && count($GLOBALS['analysis']['breakdown']) == 1 && isset($GLOBALS['analysis']['breakdown'][127])) {
if ($GLOBALS['options']['analyze_input']) {
- //echo 'NOISE2!' . PHP_EOL;
+ //* NOISY: */ echo 'NOISE2!' . PHP_EOL;
}
return NULL;
} elseif (!$GLOBALS['options']['keep_noise'] && $GLOBALS['options']['ignore_noise'] && count($GLOBALS['analysis']['breakdown']) < 2) {
if ($GLOBALS['options']['analyze_input']) {
- //echo 'NOISE3!' . PHP_EOL;
+ //* NOISY: */ echo 'NOISE3!' . PHP_EOL;
}
return NULL;
}
}
//$pcm = fopen('output1.pcm', 'rb') or die('Cannot read from audio');
-$pcm = fopen('/dev/dsp2', 'rb') or die('Cannot read from audio' . PHP_EOL);
+$pcm = fopen('/dev/dsp', 'rb') or die('Cannot read from audio' . PHP_EOL);
$empty = str_repeat(chr(128), $GLOBALS['options']['buffer_size']);
$data = trim(fread($pcm, $GLOBALS['options']['buffer_size']));
if ((empty($data)) || ($data == $empty)) {
if ($GLOBALS['options']['analyze_input']) {
- //echo 'EMPTY!' . PHP_EOL;
+ //* NOISY: */ echo 'EMPTY!' . PHP_EOL;
}
continue;
}
if (empty($data)) {
// Skip this
continue;
- } // END - if
+ }
$GLOBALS['analysis']['average'] = floor($GLOBALS['analysis']['average'] / strlen($data));
if (empty($out)) {
// Skip this
continue;
- } // END - if
+ }
echo $out;
} else {
// Reset timer
$timeDisplay = microtime(true);
$GLOBALS['iteration_second'] = 0;
- } // END - if
+ }
// Time spend from last flush
$testTime = abs(microtime(true) - $GLOBALS['time_flush']);
if ($testTime >= $GLOBALS['flush_file_time']) {
// Flush check-point file
flushCheckPointFile($GLOBALS['current_hash']);
- } // END - if
+ }
// Time spend from last found block
$testTime = abs(microtime(true) - $GLOBALS['found_time']);
if (!isset($hash['root_hash'])) {
// Bad file
die('INCONSISTENCY: hash=' . print_r($hash, true));
- } // END - if
+ }
if (isset($rootHashes[$hash['root_hash']])) {
// Count up
// First entry found
$rootHashes[$hash['root_hash']] = 1;
}
- } // END - foreach
- } // END - foreach
+ }
+ }
// Find best root hash
$bestRootHash = '';
$bestRootCount = 0;
foreach ($rootHashes as $hash => $count) {
- // Debug message
- //* NOISY-DEBUG: */ print ('hash=' . $hash . ',count=' . $count . ',bestRootHash=' . $bestRootHash . ',bestRootCount=' . $bestRootCount . PHP_EOL);
-
// Is a better one found?
+ //* NOISY-DEBUG: */ print ('hash=' . $hash . ',count=' . $count . ',bestRootHash=' . $bestRootHash . ',bestRootCount=' . $bestRootCount . PHP_EOL);
if ($count > $bestRootCount) {
// Remember it
$bestRootHash = $hash;
$bestRootCount = $count;
- } // END - if
- } // END - foreach
+ }
+ }
// Output message
print ('bestRootHash=' . $bestRootHash . ',bestRootCount=' . $bestRootCount . PHP_EOL);
// Abort search
break;
- } // END - if
- } // END - for
- } // END - foreach
- } // END - if
+ }
+ }
+ }
+ }
// Next round
$GLOBALS['iteration']++;
$GLOBALS['iteration_second']++;
- //print ('nonce=' . $GLOBALS['nonce'] . ',iteration=' . $GLOBALS['iteration'] . PHP_EOL);
- //print ('nonceHash=' . $nonceHash . PHP_EOL);
- //print ('sumNonce=' . $sumNonce . PHP_EOL);
- //print ('sumGenesis=' . $GLOBALS['sum_genesis'] . PHP_EOL);
- } // END - while
+ //* NOISY-DEBUG: */ print('nonce=' . $GLOBALS['nonce'] . ',iteration=' . $GLOBALS['iteration'] . PHP_EOL);
+ //* NOISY-DEBUG: */ print('nonceHash=' . $nonceHash . PHP_EOL);
+ //* NOISY-DEBUG: */ print('sumNonce=' . $sumNonce . PHP_EOL);
+ //* NOISY-DEBUG: */ print('sumGenesis=' . $GLOBALS['sum_genesis'] . PHP_EOL);
+ }
// If the iteration is zero, then no hash is found
if ($GLOBALS['iteration'] == 0) {
// Bad hash found
$timeBadHashes += abs(microtime(true) - $timeHash);
- // And next round
- print('BAD:nonce=' . $GLOBALS['nonce'] . PHP_EOL);
-
// Nothing found, so calculate new nonce
+ //* NOISY-DEBUG: */ print('BAD:nonce=' . $GLOBALS['nonce'] . PHP_EOL);
calculateNonce();
continue;
- } // END - if
+ }
// Add amount of hashes per block (multiple-hash)
$GLOBALS['hashes_block'] += $GLOBALS['iteration'] * $GLOBALS['hash_cycles'] + $GLOBALS['hash_cycles'];
// Push found hash
addFoundHash($nonceHash);
- } // END - while
+ }
+
+ // Flush check-point file
+ flushCheckPointFile($GLOBALS['current_hash']);
// Time taken for one
$timeBlock = abs(microtime(true) - $timeBlock);
// Calculate reward
- $reward = abs($timeBlock - $timeBadHashes) / $hashRate * $GLOBALS['hashes_block'] / max(1, $GLOBALS['block_size']) * 1000;
+ $reward = abs($timeBlock - $timeBadHashes) / max(1, $hashRate) * $GLOBALS['hashes_block'] / max(1, $GLOBALS['block_size']) * 1000;
print('timeBlock=' . $timeBlock . ',timeBadHashes=' . $timeBadHashes . ',hashesPerBlock=' . $GLOBALS['hashes_block'] .',reward=' . $reward . PHP_EOL);
- // Double difficulty
- $GLOBALS['difficulty'] = $GLOBALS['difficulty'] * 2;
+ // Increase difficulty
+ $GLOBALS['difficulty'] = $GLOBALS['difficulty']++;
// Block completed
$GLOBALS['total_hashes'] += $GLOBALS['hashes_block'];
$rewardPerHour = $GLOBALS['total_reward'] / abs(microtime(true) - START_TIME) * 3600;
print ('totalReward=' . $GLOBALS['total_reward'] . ',blockValue=' . $blockValue . ',rewardPerHour=' . $rewardPerHour . PHP_EOL);
-} // END - while
+}
for ($idx = 0; $idx < ($GLOBALS['hash_cycles'] - 1); $idx++) {
// Over-hash the given hash
$hash = hashString($hash);
- } // END - for
+ }
// Return it
return $hash;
*/
function calculateSumFromHash ($hash) {
// Everything starts with zero ...
+ //* NOISY-DEBUG: */ printf('[%s:%d]: hash(%d)=%s - CALLED!'. PHP_EOL, __FUNCTION__, __LINE__, strlen($hash), $hash);
$sum = 0;
+ // Part of the hash is not decodeable
+ $decodeA = explode('$', $hash);
+ $decode = $decodeA[4];
+
// Loop through hash
- for ($idx = 0; $idx < (strlen($hash) / 2); $idx++) {
+ //* NOISY-DEBUG: */ printf('[%s:%d]: decode=%s' . PHP_EOL, __FUNCTION__, __LINE__, $decode);
+ for ($idx = 0; $idx < (strlen($decode) / 2); $idx++) {
// And add it
- $sum = $sum + hexdec(substr($hash, $idx, 2));
- } // END - for
+ $sum = $sum + hexdec(substr($decode, $idx, 2));
+ }
// And return it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: sum=%d - EXIT!' . PHP_EOL, __FUNCTION__, __LINE__, $sum);
return $sum;
}
// Flush data
file_put_contents(
CHECKPOINT_FILE,
- $GLOBALS['total_blocks'] . '|' .
- $GLOBALS['total_reward'] . '|' .
- $GLOBALS['total_hashes'] . '|' .
- $GLOBALS['total_found'] . '|' .
- $GLOBALS['total_restarts'] . '|' .
- $GLOBALS['hash_cycles'] . '|' .
- $GLOBALS['salt'] . '|' .
- $GLOBALS['difficulty'] . '|' .
- base64_encode((float) $GLOBALS['nonce']) . '|' .
- $hash . '|' .
- $GLOBALS['root_hash'] . '|' .
- base64_encode(gzcompress(json_encode($GLOBALS['found_hashes'])))
+ // 0 1 2 3 4 5 6 7 8 9 10 11
+ sprintf('%d|%s|%d|%d|%d|%d|%s|%d|%s|%s|%s|%s',
+ // 0
+ $GLOBALS['total_blocks'],
+ // 1
+ $GLOBALS['total_reward'],
+ // 2
+ $GLOBALS['total_hashes'],
+ // 3
+ $GLOBALS['total_found'],
+ // 4
+ $GLOBALS['total_restarts'],
+ // 5
+ $GLOBALS['hash_cycles'],
+ // 6
+ $GLOBALS['salt'],
+ // 7
+ $GLOBALS['difficulty'],
+ // 8
+ base64_encode((float) $GLOBALS['nonce']),
+ // 9
+ $hash,
+ // 10
+ $GLOBALS['root_hash'],
+ // 11
+ base64_encode(gzcompress(json_encode($GLOBALS['found_hashes'])))
+ )
);
// Set time
]);
// Found hash:
- print ('FOUND: hash=' . $hash . ',nonce=' . $GLOBALS['nonce'] . ',total_found=' . $GLOBALS['total_found'] . PHP_EOL);
+ //* NOISY-DEBUG: */ print ('FOUND: hash=' . $hash . ',nonce=' . $GLOBALS['nonce'] . ',total_found=' . $GLOBALS['total_found'] . PHP_EOL);
// Set time as a new hash was found
$GLOBALS['found_time'] = microtime(true);
-
- // Flush check-point file after new hash is found
- flushCheckPointFile($hash);
}
/**
$GLOBALS['difficulty'] = $data[7];
$GLOBALS['nonce'] = (float) base64_decode($data[8]);
$GLOBALS['current_hash'] = $data[9];
- $GLOBALS['root_hash'] = $data[9];
+ $GLOBALS['root_hash'] = $data[10];
$GLOBALS['found_hashes'] = json_decode(gzuncompress(base64_decode($data[11])), TRUE);
- } // END - if
+ }
}
--- /dev/null
+#!/bin/sh
+
+# Cleans up all created files to start from scratch
+
+echo "$0: Cleaning up database ..."
+rm -f db/*/*.serial*
+rm -f db/*.cache
+
+echo "$0: All done."
+exit 0
for ($i = 1; $i <= $totalDays; $i++) {
$x = bcmul($x, 2);
$y = bcadd($y, $x);
-} // END - foreach
+}
print 'After ' . $totalDays . ' days (' . $years . ' years) you have eaten ' . $y . ' fruits.' . PHP_EOL;
print 'Length:' . strlen($y) . PHP_EOL;
$balance = bcadd($balance, $interest);
print 'Month ' . $i . ': rate=' . bcmul($rate, 100) . '%,interest=' . $interest . ',balance=' . $balance . PHP_EOL;
-} // END - foreach
+}
print 'After ' . $totalMonths . ' months (' . $years . ' years) you have ' . $balance . ' EUR back.' . PHP_EOL;
//print 'Length:' . strlen($balance) . PHP_EOL;
--- /dev/null
+#!/usr/bin/env php
+<?php
+error_reporting(0);
+set_time_limit(0);
+
+/*
+ * Note: I could use mhash_count() here but I like to see unavailable hashers
+ * because this is important to me to choose the most-available hasher(s) and
+ * those with the best speed/secure tradeoff.
+ */
+$hasher = hash_algos();
+
+$timers = array();
+$count = 500 * 1000;
+
+print 'Iterating ' . $count . 'x over all ' . count($hasher) . ' hash functions ...' . "\r\n";
+
+foreach ($hasher as $hash) {
+ $time = microtime(true);
+ for ($idx = 0; $idx <= $count; $idx++) {
+ $dummy = hash($hash, 'hash-test-abc-123-foo-bar');
+ }
+
+ $timers[$hash] = (microtime(true) - $time);
+ print '.';
+}
+
+print "\r\n\r\n";
+asort($timers);
+
+print 'Result from hash() benchmark (in seconds per hasher):' . "\r\n";
+print_r($timers) . "\n";
$__factor = constant('__FACTOR_64');
$__format = constant('__FORMAT_READ_64');
$__step = constant('__STEP_64');
-} // END - if
+}
$buffer = file_get_contents('test.data.bin' . ($__factor * 2)) or die('Please run write.php first!' . PHP_EOL);
//print 'chr=' . $chr . PHP_EOL;
$decoded .= chr($chr);
- } // END - for
-} // END - for
+ }
+}
$decoded = gzuncompress($decoded);
$__right = constant('__RIGHT_64');
$__format = constant('__FORMAT_WRITE_64');
$__step = constant('__STEP_64');
-} // END - if
+}
$str = gzcompress(file_get_contents('test.data'), 9);
$big += $add;
//print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
- } // END - if
- } // END - for
+ }
+ }
$l = ($big & $__left) >>$__factor;
$r = $big & $__right;
//print 'big=' . $big . ',unpacked('.strlen($unpacked) . ')='.md5($unpacked).PHP_EOL;
$encoded .= $unpacked;
-} // END - for
+}
print 'Hash(' . strlen($encoded) . ')=' . md5($encoded) . PHP_EOL;
print 'Encoded ' . strlen($str) . ' bytes into ' . strlen($encoded) . ' bytes ...' . PHP_EOL;
--- /dev/null
+#!/bin/sh
+
+DEBUG_FILE="./debug.log"
+
+if [ -f "$1" ]
+then
+ DEBUG_FILE="$1"
+fi
+
+if [ ! -f "${DEBUG_FILE}" ]
+then
+ echo "$0: DEBUG_FILE='${DEBUG_FILE}' does not exist."
+ exit 255
+fi
+
+grep -a __call "${DEBUG_FILE}" | cut -d "[" -f 4 | cut -d "]" -f 1
#!/bin/sh
# Really lame ...
-find */ -type f -print0 | xargs -0 sed -i 's/2016 Core/2017 Core/g'
+find */ -type f -print0 | xargs -0 sed -i 's/2023 Core/2023 Core/g'
+++ /dev/null
-Deny from all
+++ /dev/null
-Deny from all
### WARNING: THIS FILE IS AUTO-GENERATED BY ./contrib/todo-builder.sh ###
### DO NOT EDIT THIS FILE. ###
-./application/tests/class_ApplicationHelper.php:272: * @todo Nothing to add?
+./application/tests/class_ApplicationHelper.php:195: * @todo Nothing to add?
./contrib/audio.php:96: // @TODO What do here to remove noise?
-./framework/bootstrap/class_FrameworkBootstrap.php:421: * @todo Have to check some more entries from $_SERVER here
-./framework/bootstrap/class_FrameworkBootstrap.php:493: * @todo Test more fields
-./framework/loader/class_ClassLoader.php:181: // @TODO Add some uglifying code (compress) here
-./framework/loader/class_ClassLoader.php:247: // @TODO Throw exception instead of break
-./framework/loader/class_ClassLoader.php:441: /* @TODO: Do not exit here. */
-./framework/main/classes/cache/class_MemoryCache.php:17: * @todo Rename to InProgressCache
-./framework/main/classes/class_BaseFrameworkSystem.php:2133: // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
-./framework/main/classes/class_BaseFrameworkSystem.php:2248: * @todo Write a logging mechanism for productive mode
-./framework/main/classes/class_BaseFrameworkSystem.php:2263: // @TODO Finish this part!
-./framework/main/classes/class_BaseFrameworkSystem.php:3249: * @todo Improve documentation
-./framework/main/classes/class_BaseFrameworkSystem.php:344: // @todo Try to clean these constants up
-./framework/main/classes/class_BaseFrameworkSystem.php:589: // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
-./framework/main/classes/class_BaseFrameworkSystem.php:693: * @todo SearchableResult and UpdateableResult shall have a super interface to use here
+./framework/bootstrap/class_FrameworkBootstrap.php:441: * @todo Have to check some more entries from $_SERVER here
+./framework/bootstrap/class_FrameworkBootstrap.php:506: * @todo Test more fields
+./framework/loader/class_ClassLoader.php:196: // @TODO Add some uglifying code (compress) here
+./framework/loader/class_ClassLoader.php:241: // @TODO Throw exception instead of break
+./framework/loader/class_ClassLoader.php:468: /* @TODO: Do not exit here. */
+./framework/main/classes/cache/class_MemoryCache.php:18: * @todo Rename to InProgressCache
+./framework/main/classes/class_BaseFrameworkSystem.php:1625: * @todo Move this class away from this monolithic place (not whole class is monolithic)
+./framework/main/classes/class_BaseFrameworkSystem.php:291: // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
+./framework/main/classes/class_BaseFrameworkSystem.php:762: * @todo Monolithic method, should be moved to proper classes
+./framework/main/classes/class_BaseFrameworkSystem.php:776: // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
+./framework/main/classes/class_BaseFrameworkSystem.php:869: * @todo Write a logging mechanism for productive mode
+./framework/main/classes/class_BaseFrameworkSystem.php:87: // @todo Try to clean these constants up
+./framework/main/classes/class_BaseFrameworkSystem.php:884: // @TODO Finish this part!
./framework/main/classes/commands/console/class_ConsoleFuseCommand.php:84: // @TODO Unfinished
-./framework/main/classes/commands/html/class_HtmlLoginAreaCommand.php:78: * @todo Add some stuff here: Some personal data, app/game related data
+./framework/main/classes/commands/html/class_HtmlLoginAreaCommand.php:81: * @todo Add some stuff here: Some personal data, app/game related data
./framework/main/classes/commands/html/class_HtmlProblemCommand.php:70: * @todo 0% done
-./framework/main/classes/commands/html/class_HtmlStatusCommand.php:70: * @todo 0% done
+./framework/main/classes/commands/html/class_HtmlStatusCommand.php:72: * @todo 0% done
./framework/main/classes/controller/console/class_ConsoleDefaultController.php:19: * @todo This controller shall still provide some headlines for sidebars
./framework/main/classes/controller/html/class_HtmlConfirmController.php:51: * @todo Add some filters to this controller
./framework/main/classes/controller/html/class_HtmlDefaultController.php:20: * @todo This controller shall still provide some headlines for sidebars
./framework/main/classes/controller/html/class_HtmlRegisterController.php:50: * @todo Add some filters to this controller
./framework/main/classes/controller/html/class_HtmlStatusController.php:20: * @todo This controller shall still provide some headlines for sidebars
./framework/main/classes/controller/html/login/class_HtmlLoginAreaController.php:51: * @todo Add some morer filters to this controller
-./framework/main/classes/criteria/dataset/class_DataSetCriteria.php:158: // @TODO Issue a warning
-./framework/main/classes/criteria/search/class_SearchCriteria.php:109: * @todo Find a nice casting here. (int) allows until and including 32766.
-./framework/main/classes/criteria/search/class_SearchCriteria.php:77: * @todo Find a nice casting here. (int) allows until and including 32766.
-./framework/main/classes/crypto/class_CryptoHelper.php:104: // @TODO Maybe rewrite this with DirectoryIterator, similar to Compressor thing?
-./framework/main/classes/database/backend/lfdb_legacy/class_CachedLocalFileDatabase.php:340: * @todo Do some checks on the database directory and files here
-./framework/main/classes/database/backend/lfdb_legacy/class_CachedLocalFileDatabase.php:632: * @todo Add more generic non-public data for removal
-./framework/main/classes/database/class_BaseDatabaseWrapper.php:214: // @TODO Minor: Update above comment to e.g. BaseDatabaseResult
-./framework/main/classes/database/frontend/class_NewsDatabaseWrapper.php:17: * @todo Add missing own interface for public methods
-./framework/main/classes/database/frontend/class_PaymentsDatabaseWrapper.php:17: * @todo Add missing own interface for public methods
-./framework/main/classes/database/result/class_CachedDatabaseResult.php:260: * @todo 0% done
-./framework/main/classes/database/result/class_CachedDatabaseResult.php:414: * @todo Find a caching way without modifying the result array
-./framework/main/classes/decorator/template/class_XmlRewriterTemplateDecorator.php:415: * @todo Find something useful with this!
-./framework/main/classes/discovery/payment/class_LocalPaymentDiscovery.php:98: * @todo 0% done
+./framework/main/classes/criteria/dataset/class_DataSetCriteria.php:223: // @TODO Issue a warning
+./framework/main/classes/criteria/search/class_SearchCriteria.php:113: * @todo Find a nice casting here. (int) allows until and including 32766.
+./framework/main/classes/criteria/search/class_SearchCriteria.php:81: * @todo Find a nice casting here. (int) allows until and including 32766.
+./framework/main/classes/crypto/class_CryptoHelper.php:130: // @TODO Maybe rewrite this with DirectoryIterator, similar to Compressor thing?
+./framework/main/classes/database/backend/lfdb_legacy/class_CachedLocalFileDatabase.php:351: * @todo Do some checks on the database directory and files here
+./framework/main/classes/database/backend/lfdb_legacy/class_CachedLocalFileDatabase.php:652: * @todo Rename method to getPrimaryKeyFromTableInfo()
+./framework/main/classes/database/backend/lfdb_legacy/class_CachedLocalFileDatabase.php:679: * @todo Add more generic non-public data for removal
+./framework/main/classes/database/frontend/class_BaseDatabaseFrontend.php:249: // @TODO Minor: Update above comment to e.g. BaseDatabaseResult
+./framework/main/classes/database/frontend/news/class_NewsDatabaseFrontend.php:17: * @todo Add missing own interface for public methods
+./framework/main/classes/database/frontend/payments/class_PaymentsDatabaseFrontend.php:17: * @todo Add missing own interface for public methods
+./framework/main/classes/database/result/class_CachedDatabaseResult.php:306: * @todo 0% done
+./framework/main/classes/database/result/class_CachedDatabaseResult.php:459: * @todo Find a caching way without modifying the result array
+./framework/main/classes/decorator/xml/template/class_XmlRewriterTemplateDecorator.php:417: * @todo Find something useful with this!
+./framework/main/classes/discovery/payment/class_LocalPaymentDiscovery.php:102: * @todo 0% done
./framework/main/classes/factories/logger/class_LoggerFactory.php:53: // @TODO Unfinished work
-./framework/main/classes/factories/login/class_LoginFactory.php:47: * @return $loginInstance An instance of a login helper (@TODO Use actual interface name)
+./framework/main/classes/factories/login/class_LoginFactory.php:48: * @return $loginInstance An instance of a login helper (@TODO Use actual interface name)
./framework/main/classes/factories/user/class_UserFactory.php:48: * @return $userInstance An instance of a user class (@TODO use actual interface name)
./framework/main/classes/feature/fuse/class_FuseFeature.php:59: * @todo 0% done
-./framework/main/classes/file_directories/binary/class_BaseBinaryFile.php:860: // @TODO Unfinished
-./framework/main/classes/file_directories/class_BaseAbstractFile.php:135: * @todo Handle seekStatus
-./framework/main/classes/file_directories/class_BaseFileIo.php:166: * @todo Handle seekStatus
-./framework/main/classes/file_directories/io/class_FrameworkFileInputOutputPointer.php:106: * @todo Add more checks
+./framework/main/classes/file_directories/binary/class_BaseBinaryFile.php:1028: // @TODO Unfinished
+./framework/main/classes/file_directories/class_BaseAbstractFile.php:186: * @todo Handle seekStatus
+./framework/main/classes/file_directories/class_BaseFileIo.php:176: * @todo Handle seekStatus
./framework/main/classes/file_directories/io_stream/class_FileIoStream.php:279: * @todo 0% done
./framework/main/classes/file_directories/io_stream/class_FileIoStream.php:89: * @todo This method needs heavy rewrite
-./framework/main/classes/filter/change/class_EmailChangeFilter.php:65: * @todo Implement email change of the user here. HINT: Use the User class!
-./framework/main/classes/filter/change/class_PasswordChangeFilter.php:65: * @todo Finished updating user password hash here. HINT: Use the User class again.
+./framework/main/classes/filter/change/class_EmailChangeFilter.php:66: * @todo Implement email change of the user here. HINT: Use the User class!
+./framework/main/classes/filter/change/class_PasswordChangeFilter.php:66: * @todo Finished updating user password hash here. HINT: Use the User class again.
./framework/main/classes/filter/news/class_NewsProcessFilter.php:64: * @todo Unfinished stub, add functionality here
-./framework/main/classes/filter/payment/class_PaymentDiscoveryFilter.php:111: * @todo 0% done
+./framework/main/classes/filter/payment/class_PaymentDiscoveryFilter.php:113: * @todo 0% done
./framework/main/classes/filter/update/class_UserUpdateFilter.php:65: * @todo Add more user updates here
-./framework/main/classes/filter/verifier/class_AccountPasswordVerifierFilter.php:69: * @todo Rewrite handling of different password fields
-./framework/main/classes/filter/verifier/class_EmailVerifierFilter.php:64: * @todo 0% done
+./framework/main/classes/filter/verifier/class_AccountPasswordVerifierFilter.php:70: * @todo Rewrite handling of different password fields
+./framework/main/classes/filter/verifier/class_EmailVerifierFilter.php:65: * @todo 0% done
./framework/main/classes/handler/class_BaseHandler.php:74: * @todo Rewrite this to use DHT
-./framework/main/classes/handler/tasks/class_TaskHandler.php:153: // @TODO Messurement can be added around this call
-./framework/main/classes/helper/class_BaseHelper.php:193: * @todo Rewrite this method using a helper class for filtering data
-./framework/main/classes/helper/class_BaseHelper.php:222: // @TODO Try to log it here
-./framework/main/classes/helper/class_BaseHelper.php:488: $this->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] fieldName=' . $fieldName . ' is not set! - @TODO');
-./framework/main/classes/helper/html/forms/class_HtmlFormHelper.php:116: * @todo Add some unique PIN here to bypass problems with some browser and/or extensions
-./framework/main/classes/helper/html/forms/class_HtmlFormHelper.php:629: * @todo Add checking if sub option is already added
-./framework/main/classes/helper/html/forms/class_HtmlFormHelper.php:657: * @todo Add checking if sub option is already added
-./framework/main/classes/helper/html/forms/class_HtmlFormHelper.php:691: // @TODO We need to log this later
-./framework/main/classes/helper/html/forms/class_HtmlFormHelper.php:860: * @todo Implement check if rules have been changed
-./framework/main/classes/helper/html/links/class_HtmlLinkHelper.php:195: * @todo Completely unimplemented
-./framework/main/classes/images/class_BaseImage.php:179: * @todo Find something usefull for this method.
-./framework/main/classes/images/class_BaseImage.php:189: * @todo Find something usefull for this method.
-./framework/main/classes/images/class_BaseImage.php:199: * @todo Find something usefull for this method.
-./framework/main/classes/images/class_BaseImage.php:209: * @todo Find something usefull for this method.
-./framework/main/classes/images/class_BaseImage.php:219: * @todo Find something usefull for this method.
-./framework/main/classes/images/class_BaseImage.php:238: * @todo Find something usefull for this method.
-./framework/main/classes/images/class_BaseImage.php:257: * @todo Find something usefull for this method.
-./framework/main/classes/images/class_BaseImage.php:268: * @todo Find something usefull for this method.
-./framework/main/classes/images/class_BaseImage.php:278: * @todo Find something usefull for this method.
-./framework/main/classes/images/extended/class_PngImage.php:69: * @todo Rewrite this to SplFileInfo/Object
-./framework/main/classes/index/class_BaseIndex.php:160: * @todo Currently the index file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole index file.
-./framework/main/classes/language/class_LanguageSystem.php:73: * @throws InvalidArgumentException If languageBasePath remains empty (@TODO Get rid of that old-lost code)
+./framework/main/classes/handler/tasks/class_TaskHandler.php:163: // @TODO Messurement can be added around this call
+./framework/main/classes/helper/class_BaseHelper.php:194: * @todo Rewrite this method using a helper class for filtering data
+./framework/main/classes/helper/class_BaseHelper.php:229: // @TODO Try to log it here
+./framework/main/classes/helper/class_BaseHelper.php:501: $this->debugOutput('BASE-HELPER: fieldName=' . $fieldName . ' is not set! - @TODO');
+./framework/main/classes/helper/html/forms/class_HtmlFormHelper.php:122: * @todo Add some unique PIN here to bypass problems with some browser and/or extensions
+./framework/main/classes/helper/html/forms/class_HtmlFormHelper.php:637: * @todo Add checking if sub option is already added
+./framework/main/classes/helper/html/forms/class_HtmlFormHelper.php:665: * @todo Add checking if sub option is already added
+./framework/main/classes/helper/html/forms/class_HtmlFormHelper.php:699: // @TODO We need to log this later
+./framework/main/classes/helper/html/forms/class_HtmlFormHelper.php:887: * @todo Implement check if rules have been changed
+./framework/main/classes/helper/html/links/class_HtmlLinkHelper.php:198: * @todo Completely unimplemented
+./framework/main/classes/images/class_BaseImage.php:183: * @todo Find something usefull for this method.
+./framework/main/classes/images/class_BaseImage.php:193: * @todo Find something usefull for this method.
+./framework/main/classes/images/class_BaseImage.php:203: * @todo Find something usefull for this method.
+./framework/main/classes/images/class_BaseImage.php:213: * @todo Find something usefull for this method.
+./framework/main/classes/images/class_BaseImage.php:223: * @todo Find something usefull for this method.
+./framework/main/classes/images/class_BaseImage.php:242: * @todo Find something usefull for this method.
+./framework/main/classes/images/class_BaseImage.php:261: * @todo Find something usefull for this method.
+./framework/main/classes/images/class_BaseImage.php:272: * @todo Find something usefull for this method.
+./framework/main/classes/images/class_BaseImage.php:282: * @todo Find something usefull for this method.
+./framework/main/classes/images/png/class_PngImage.php:69: * @todo Rewrite this to SplFileInfo/Object
+./framework/main/classes/index/file/class_BaseFileIndex.php:179: * @todo Currently the index file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole index file.
+./framework/main/classes/index/file/class_BaseFileIndex.php:287: * @todo Unfinished work
+./framework/main/classes/language/class_LanguageSystem.php:76: * @throws InvalidArgumentException If languageBasePath remains empty (@TODO Get rid of that old-lost code)
./framework/main/classes/lists/groups/class_ListGroupList.php:68: * @todo 0% done
./framework/main/classes/mailer/debug/class_DebugMailer.php:137: * @todo 0% done
-./framework/main/classes/menu/class_BaseMenu.php:76: // Log exception @TODO Maybe to intrusive?
-./framework/main/classes/output/console/class_ConsoleOutput.php:65: // @TODO Need to rewrite this to $requestInstance->addHeader()
-./framework/main/classes/parser/xml/class_XmlParser.php:87: // @TODO We need to find a fallback solution here
-./framework/main/classes/points/class_UserPoints.php:112: * @todo Finish loading part of points
-./framework/main/classes/points/class_UserPoints.php:184: * @todo $requestInstance is currently unused
+./framework/main/classes/menu/class_BaseMenu.php:80: // Log exception @TODO Maybe to intrusive?
+./framework/main/classes/output/console/class_ConsoleOutput.php:64: // @TODO Need to rewrite this to $requestInstance->addHeader()
+./framework/main/classes/parser/xml/class_XmlParser.php:82: // @TODO We need to find a fallback solution here
+./framework/main/classes/points/class_UserPoints.php:118: * @todo Finish loading part of points
+./framework/main/classes/points/class_UserPoints.php:189: * @todo $requestInstance is currently unused
+./framework/main/classes/registry/format_upgrade/database/class_LocalFileDatabaseFormatUpgradeRegistry.php:70: * @todo 0% done
./framework/main/classes/request/console/class_ConsoleRequest.php:119: // @TODO Can't this be 'CONSOLE' ?
-./framework/main/classes/request/html/class_HtmlRequest.php:16: * @todo Move out the cookie part to a seperate class, e.g. Cookie
-./framework/main/classes/response/html/class_HtmlResponse.php:80: * @todo Encryption of cookie data not yet supported.
-./framework/main/classes/response/html/class_HtmlResponse.php:81: * @todo Why are these parameters conflicting?
-./framework/main/classes/response/html/class_HtmlResponse.php:82: * @todo If the return statement is removed and setcookie() commented out,
-./framework/main/classes/response/html/class_HtmlResponse.php:83: * @todo this will send only one cookie out, the first one.
-./framework/main/classes/response/image/class_ImageResponse.php:76: // @TODO Please fix this
-./framework/main/classes/response/image/class_ImageResponse.php:92: * @todo Encryption of cookie data not yet supported.
-./framework/main/classes/response/image/class_ImageResponse.php:93: * @todo Why are these parameters conflicting?
-./framework/main/classes/response/image/class_ImageResponse.php:94: * @todo If the return statement is removed and setcookie() commented out,
-./framework/main/classes/response/image/class_ImageResponse.php:95: * @todo this will send only one cookie out, the first one.
+./framework/main/classes/request/html/class_HtmlRequest.php:17: * @todo Move out the cookie part to a seperate class, e.g. Cookie
+./framework/main/classes/resolver/command/html/class_HtmlCommandResolver.php:71: // @TODO Missing namespace!
+./framework/main/classes/resolver/command/image/class_ImageCommandResolver.php:70: // @TODO Missing namespace!
+./framework/main/classes/response/html/class_HtmlResponse.php:73: * @todo Encryption of cookie data not yet supported.
+./framework/main/classes/response/html/class_HtmlResponse.php:74: * @todo If the return statement is removed and setcookie() commented out,
+./framework/main/classes/response/html/class_HtmlResponse.php:75: * @todo this will send only one cookie out, the first one.
+./framework/main/classes/response/image/class_ImageResponse.php:100: * @todo this will send only one cookie out, the first one.
+./framework/main/classes/response/image/class_ImageResponse.php:98: * @todo Encryption of cookie data not yet supported.
+./framework/main/classes/response/image/class_ImageResponse.php:99: * @todo If the return statement is removed and setcookie() commented out,
./framework/main/classes/rng/class_RandomNumberGenerator.php:105: * @todo Add site key for stronger salt!
./framework/main/classes/rng/class_RandomNumberGenerator.php:183: * @todo I had a better random number generator here but now it is somewhere lost :(
-./framework/main/classes/stacker/file/class_BaseFileStack.php:172: * @todo Currently the stack file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole stack file.
-./framework/main/classes/stacker/file/class_BaseFileStack.php:347: // @TODO Please implement this, returning false
-./framework/main/classes/stacker/file/class_BaseFileStack.php:70: * @todo To hard assertions here, better rewrite them to exceptions
-./framework/main/classes/streams/crypto/class_McryptStream.php:18: * @todo mcrypt will become deprecated, rewrite to OpenSSL
-./framework/main/classes/streams/crypto/class_OpenSslStream.php:138: // @TODO unfinished
-./framework/main/classes/streams/crypto/class_OpenSslStream.php:68: // @TODO unfinished
-./framework/main/classes/template/class_BaseTemplateEngine.php:1070: // @TODO This silent abort should be logged, maybe.
-./framework/main/classes/template/class_BaseTemplateEngine.php:1078: // @TODO Old behaviour, will become obsolete!
-./framework/main/classes/template/class_BaseTemplateEngine.php:1081: // @TODO Yet another old way
-./framework/main/classes/template/class_BaseTemplateEngine.php:1304: * @todo Make this code some nicer...
-./framework/main/classes/template/class_BaseTemplateEngine.php:967: * @todo Unfinished work or don't die here.
-./framework/main/classes/template/class_BaseTemplateEngine.php:992: // @TODO Non-string found so we need some deeper analysis...
-./framework/main/classes/template/console/class_ConsoleTemplateEngine.php:22: * @todo This template engine does not make use of setTemplateType()
-./framework/main/classes/template/image/class_ImageTemplateEngine.php:233: * @todo Find something usefull with this!
-./framework/main/classes/template/image/class_ImageTemplateEngine.php:253: * @todo Add cache creation here
+./framework/main/classes/stacker/file/class_BaseFileStack.php:222: * @todo Currently the stack file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole stack file.
+./framework/main/classes/stacker/file/class_BaseFileStack.php:464: // @TODO Please implement this, returning false
+./framework/main/classes/stacker/file/class_BaseFileStack.php:72: * @todo To hard assertions here, better rewrite them to exceptions
+./framework/main/classes/stacker/file/fifo/class_FiFoFileStack.php:176: // @TODO Unfinished method or invoke inner iterator's method?
+./framework/main/classes/streams/crypto/mcrypt/class_McryptStream.php:19: * @todo mcrypt will become deprecated, rewrite to OpenSSL
+./framework/main/classes/streams/crypto/openssl/class_OpenSslStream.php:139: // @TODO unfinished
+./framework/main/classes/streams/crypto/openssl/class_OpenSslStream.php:69: // @TODO unfinished
+./framework/main/classes/template/class_BaseTemplateEngine.php:1065: // @TODO This silent abort should be logged, maybe.
+./framework/main/classes/template/class_BaseTemplateEngine.php:1073: // @TODO Old behaviour, will become obsolete!
+./framework/main/classes/template/class_BaseTemplateEngine.php:1076: // @TODO Yet another old way
+./framework/main/classes/template/class_BaseTemplateEngine.php:1300: * @todo Make this code some nicer...
+./framework/main/classes/template/class_BaseTemplateEngine.php:962: * @todo Unfinished work or don't die here.
+./framework/main/classes/template/class_BaseTemplateEngine.php:987: // @TODO Non-string found so we need some deeper analysis...
+./framework/main/classes/template/console/class_ConsoleTemplateEngine.php:24: * @todo This template engine does not make use of setTemplateType()
+./framework/main/classes/template/image/class_ImageTemplateEngine.php:255: * @todo Find something usefull with this!
+./framework/main/classes/template/image/class_ImageTemplateEngine.php:275: * @todo Add cache creation here
+./framework/main/classes/template/image/class_ImageTemplateEngine.php:522: * @todo Nothing to really "transfer" here?
./framework/main/classes/template/mail/class_MailTemplateEngine.php:245: * @todo Add cache creation here
./framework/main/classes/template/mail/class_MailTemplateEngine.php:255: * @todo Should we call back the mailer class here?
-./framework/main/classes/template/mail/class_MailTemplateEngine.php:25: * @todo This template engine does not make use of setTemplateType()
-./framework/main/classes/template/menu/class_MenuTemplateEngine.php:321: * @todo Find something useful with this!
-./framework/main/classes/template/menu/class_MenuTemplateEngine.php:367: * @todo Add cache creation here
-./framework/main/classes/tools/console/class_ConsoleTools.php:179: * @todo This should be connected to a caching class to cache DNS requests
-./framework/main/classes/tools/console/class_ConsoleTools.php:207: // @TODO Here should the cacher be implemented
-./framework/main/classes/tools/console/class_ConsoleTools.php:308: * @todo This should be moved out to an external class, e.g. HttpClient
-./framework/main/classes/tools/console/class_ConsoleTools.php:309: * @todo Make IP, host name, port and script name configurable
-./framework/main/classes/tools/console/class_ConsoleTools.php:316: // @TODO Add some DNS caching here
-./framework/main/classes/user/class_BaseUser.php:320: * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
-./framework/main/classes/user/class_BaseUser.php:92: * @todo Find a way of casting here. "(int)" might destroy the user id > 32766
-./framework/main/classes/user/guest/class_Guest.php:55: * @todo Add more ways over creating user classes
-./framework/main/classes/user/member/class_Member.php:98: * @todo Add more ways over creating user classes
+./framework/main/classes/template/mail/class_MailTemplateEngine.php:28: * @todo This template engine does not make use of setTemplateType()
+./framework/main/classes/template/menu/class_MenuTemplateEngine.php:342: * @todo Find something useful with this!
+./framework/main/classes/template/menu/class_MenuTemplateEngine.php:388: * @todo Add cache creation here
+./framework/main/classes/template/xml/class_BaseXmlTemplateEngine.php:29: * @todo This template engine does not make use of setTemplateType()
+./framework/main/classes/tools/console/class_ConsoleTools.php:211: * @todo This should be connected to a caching class to cache DNS requests
+./framework/main/classes/tools/console/class_ConsoleTools.php:242: // @TODO Here should the cacher be implemented
+./framework/main/classes/tools/console/class_ConsoleTools.php:343: * @todo This should be moved out to an external class, e.g. HttpClient
+./framework/main/classes/tools/console/class_ConsoleTools.php:344: * @todo Make IP, host name, port and script name configurable
+./framework/main/classes/tools/console/class_ConsoleTools.php:351: // @TODO Add some DNS caching here
+./framework/main/classes/user/class_BaseUser.php:325: * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
+./framework/main/classes/user/class_BaseUser.php:97: * @todo Find a way of casting here. "(int)" might destroy the user id > 32766
+./framework/main/classes/user/guest/class_Guest.php:56: * @todo Add more ways over creating user classes
+./framework/main/classes/user/member/class_Member.php:100: * @todo Add more ways over creating user classes
+./framework/main/classes/utils/strings/class_StringUtils.php:395: * @todo Improve documentation
./framework/main/exceptions/compressor/class_MismatchingCompressorsException.php:16: * @todo Rename to CompressorMismatchException
./framework/main/exceptions/config/class_ConfigValueTypeUnsupportedException.php:18: * @todo These are invalid argument exceptions
./framework/main/exceptions/config/class_NoConfigEntryException.php:16: * @todo Rename this class to NoFoundEntryException
-./framework/main/exceptions/language/class_LanguagePathIsNoDirectoryException.php:16: * @todo Don't use this anymore
./framework/main/exceptions/socket/class_NoSocketErrorDetectedException.php:15: * @todo Those are logic exceptions and should be rewritten
./framework/main/exceptions/user/class_UserNoGuestException.php:17: * @todo Better rename this
-./framework/main/interfaces/application/class_ManageableApplication.php:79: * @todo Nothing to add?
+./framework/main/interfaces/application/class_ManageableApplication.php:124: * @todo Nothing to add?
./framework/main/interfaces/class_FrameworkInterface.php:14: * @todo Find a better name for this interface
-./framework/main/interfaces/criteria/extended/class_LocalSearchCriteria.php:36: * @todo Find a nice casting here. (int) allows until and including 32766.
-./framework/main/interfaces/criteria/extended/class_LocalSearchCriteria.php:60: * @todo Find a nice casting here. (int) allows until and including 32766.
+./framework/main/interfaces/criteria/search/class_LocalSearchCriteria.php:36: * @todo Find a nice casting here. (int) allows until and including 32766.
+./framework/main/interfaces/criteria/search/class_LocalSearchCriteria.php:60: * @todo Find a nice casting here. (int) allows until and including 32766.
./framework/main/interfaces/database/backend/class_DatabaseBackend.php:117: * @todo Add more generic non-data for removal
./framework/main/interfaces/database/backend/class_DatabaseBackend.php:69: * @todo Do some checks on the database directory and files here
./framework/main/interfaces/handler/task/class_HandleableTask.php:18: * @todo HandleableDataSet looks strange here
+./framework/main/interfaces/stacker/file/class_StackableFile.php:70: * @todo To hard assertions here, better rewrite them to exceptions
./framework/main/interfaces/visitor/decorator/class_DecoratorVisitor.php:37: * @todo Find interface for this type-hint (only interface/array as type-hints rule)
-./framework/main/middleware/compressor/class_CompressorChannel.php:121: // @TODO Is there a configurable fall-back compressor needed, or is NullCompressor okay?
-./framework/main/middleware/database/class_DatabaseConnection.php:70: * @todo $debugInstance is currently not used
-./framework/main/middleware/debug/class_DebugMiddleware.php:125: // @TODO Initialization phase
-./framework/main/middleware/io/class_FileIoHandler.php:189: * @todo 0% done
-./framework/main/tests/filter/tests/configuration/classes/class_TestConfigurationLoadableClassesFilter.php:66: * @todo 0% done
+./framework/main/middleware/compressor/class_CompressorChannel.php:122: // @TODO Is there a configurable fall-back compressor needed, or is NullCompressor okay?
+./framework/main/middleware/database/class_DatabaseConnection.php:73: * @todo $debugInstance is currently not used
+./framework/main/middleware/debug/class_DebugMiddleware.php:119: // @TODO Initialization phase
+./framework/main/middleware/io/class_FileIoHandler.php:146: * @todo 0% done
+./framework/main/middleware/io/class_FileIoHandler.php:176: * @todo 0% done
+./framework/main/tests/filter/tests/configuration/classes/class_TestConfigurationLoadableClassesFilter.php:67: * @todo 0% done
./framework/main/tests/filter/tests/requirements/class_TestsPhpRequirementsFilter.php:63: * @todo 0% done
-./framework/main/third_party/api/wernisportal/class_WernisApi.php:16: * @todo Out-dated since 0.6-BETA
-./index.php:58: * @todo This method is old code and needs heavy rewrite and should be moved to ApplicationHelper
+./framework/main/traits/manager/account/class_ManageableAccountTrait.php:33: * @todo Rename to $accountInstance ?
+./framework/main/traits/result/search/class_SearchableResultTrait.php:41: * @todo SearchableResult and UpdateableResult shall have a super interface to use here
+./index.php:59: * @todo This method is old code and needs heavy rewrite and should be moved to ApplicationHelper
### ### DEPRECATION FOLLOWS: ### ###
-./framework/main/classes/class_BaseFrameworkSystem.php:1846: * @deprecated Not fully, as the new Logger facilities are not finished yet.
+./framework/main/classes/class_BaseFrameworkSystem.php:603: * @deprecated Not fully, as the new Logger facilities are not finished yet.
./framework/main/exceptions/base64/class_Base64EncodingBadException.php:17: * @deprecated Don't use this anymore
./framework/main/exceptions/base64/class_Base64EncodingModuloException.php:16: * @deprecated Don't use this anymore
-./framework/main/exceptions/crypto/class_EncryptInvalidLengthException.php:17: * @deprecated Don't use this anymore
+./framework/main/exceptions/crypto/class_EncryptInvalidLengthException.php:18: * @deprecated Don't use this anymore
./framework/main/exceptions/crypto/class_EncryptMissingException.php:17: * @deprecated Don't use this anymore
./framework/main/exceptions/database/local_file/class_SavePathIsNoDirectoryException.php:16: * @deprecated Don't use this
./framework/main/exceptions/database/local_file/class_SavePathReadProtectedException.php:16: * @deprecated Please don't use this
./framework/main/exceptions/helper/class_InvalidFormNameException.php:17: * @deprecated Don't use this anymore
./framework/main/exceptions/helper/class_NoGroupOpenedException.php:16: * @deprecated Don't use this anymore
./framework/main/exceptions/helper/class_UserInstanceMissingException.php:16: * @deprecated Don't use this anymore
-./framework/main/exceptions/language/class_InvalidLanguagePathStringException.php:16: * @deprecated Don't use this anymore
-./framework/main/exceptions/language/class_LanguagePathReadProtectedException.php:16: * @deprecated Don't use this anymore
./framework/main/exceptions/main/class_DimNotFoundInArrayException.php:17: * @deprecated Please don't use this anymore
./framework/main/exceptions/main/class_InvalidArrayCountException.php:16: * @deprecated Don't use this anymore
-./framework/main/exceptions/main/class_InvalidClassNameException.php:17: * @deprecated Don't use this anymore
-./framework/main/exceptions/main/class_InvalidObjectException.php:17: * @deprecated Don't use this anymore
-./framework/main/exceptions/main/class_MissingDecimalsThousandsSeparatorException.php:16: * @deprecated Don't use this anymore
./framework/main/exceptions/main/class_VariableIsNotSetException.php:16: * @deprecated Don't use this anymore
-./framework/main/exceptions/stacker/class_EmptyStackerException.php:16: * @deprecated Don't use this anymore
./framework/main/exceptions/template/class_BasePathReadProtectedException.php:16: * @deprecated Don't use this anymore
./framework/main/exceptions/template/class_NoVariableException.php:16: * @deprecated Don't use this anymore
./framework/main/exceptions/template/class_UnexpectedTemplateTypeException.php:16: * @deprecated Don't use this anymore
--- /dev/null
+scrypt
+Dominic Black
\ No newline at end of file
--- /dev/null
+Original Scrypt Implementation;
+ Copyright (c) 2009 Colin Percival
+
+PHP Module;
+ Copyright (c) 2012, Dominic Black
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--- /dev/null
+PHP scrypt module
+=================
+
+[![Build Status](https://travis-ci.org/DomBlack/php-scrypt.svg?branch=master)](https://travis-ci.org/DomBlack/php-scrypt)
+
+This is a PHP library providing a wrapper to [Colin Percival's scrypt implementation](http://www.tarsnap.com/scrypt.html). Scrypt is a key derivation function designed to be far more secure against hardware brute-force attacks than alternative functions such as PBKDF2 or bcrypt.
+
+Details of the scrypt key derivation function are given in a paper by Colin Percival, Stronger Key Derivation via Sequential Memory-Hard Functions: [PDF](http://www.tarsnap.com/scrypt/scrypt-slides.pdf).
+
+An example class using this module can be found in; scrypt.php
+
+Join in!
+--------
+
+We are happy to receive bug reports, fixes, documentation enhancements, and other improvements.
+
+Please report bugs via the [github issue tracker](http://github.com/DomBlack/php-scrypt/issues).
+
+Master [git repository](https://github.com/DomBlack/php-scrypt):
+
+ git clone git://github.com/DomBlack/php-scrypt.git
+
+Authors
+-------
+
+This library is written and maintained by Dominic Black, <thephenix@gmail.com>.
+
+----
+
+PECL Install
+============
+
+This extension is now avaible through PECL.
+
+```
+pecl install scrypt
+```
+
+Build From Source
+=================
+
+Unix/OSX
+--------
+
+1. `phpize`
+2. If on OSX; `export CFLAGS='-arch i386 -arch x86_64'`
+3. `./configure --enable-scrypt`
+4. `make`
+5. `make install`
+6. Add the extension to your php.ini
+
+````
+ ; Enable scrypt extension module
+ extension=scrypt.so
+````
+
+Windows
+-------
+
+Using Visual Studio 2008 (or Visual C++ Express 2008) open up the attached project
+inside the VS2008 folder. This project assumes you have the PHP thread safe source at;
+`C:\phpsrcts\`, a PHP install at `C:\php\` and this source code extracted to
+`C:\php-scrypt\`.
+
+1. Build the project.
+2. Copy the resultant `scrypt.dll` to your ext directory in PHP.
+3. Add the extension to your php.ini
+
+````
+ ; Enable scrypt extension module
+ extension=scrypt.dll
+````
+
+Legal Stuff
+===========
+This works is licensed under the BSD 2-Clause license.
+
+Original Scrypt Implementation;
+ Copyright (c) 2009 Colin Percival
+
+PHP Module;
+ Copyright (c) 2012, Dominic Black
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
use Org\Mxchange\CoreFramework\Connector\Database\DatabaseConnector;
use Org\Mxchange\CoreFramework\Console\Tools\ConsoleTools;
use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
+use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
use Org\Mxchange\CoreFramework\Loader\ClassLoader;
use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
// Import SPL stuff
use \BadMethodCallException;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*/
private static $databaseInstance = NULL;
+ /**
+ * Language system instance
+ */
+ private static $languageInstance = NULL;
+
/*
* Includes applications may have. They will be tried in the given order,
* some will become soon deprecated.
*/
- private static $configAppIncludes = array(
+ private static $configAppIncludes = [
// The ApplicationHelper class (required)
'class_ApplicationHelper' => 'required',
// Some debugging stuff (optional but can be committed)
'init' => 'deprecated',
// Application starter (deprecated)
'starter' => 'deprecated',
- );
+ ];
+
+ /**
+ * Detected application's name
+ */
+ private static $detectedApplicationName;
+
+ /**
+ * Detected application's full path
+ */
+ private static $detectedApplicationPath;
/**
* Private constructor, no instance is needed from this class as only
if (is_null(self::$configurationInstance)) {
// Init new instance
self::$configurationInstance = new FrameworkConfiguration();
- } // END - if
+ }
// Return it
return self::$configurationInstance;
}
+ /**
+ * Getter for detected application name
+ *
+ * @return $detectedApplicationName Detected name of application
+ */
+ public static function getDetectedApplicationName () {
+ return self::$detectedApplicationName;
+ }
+
+ /**
+ * Getter for detected application's full path
+ *
+ * @return $detectedApplicationPath Detected full path of application
+ */
+ public static function getDetectedApplicationPath () {
+ return self::$detectedApplicationPath;
+ }
+
/**
* "Getter" to get response/request type from analysis of the system.
*
if (isset($_SERVER['HTTP_HOST'])) {
// Then it is a HTML response/request.
$requestType = 'html';
- } // END - if
+ }
// Return it
return $requestType;
*/
public static function isReachableFilePath (SplFileInfo $fileInstance) {
// Is not reachable by default
+ //* NOISY-DEBUG: */ printf('[%s:%d]: fileInstance=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, get_class($fileInstance));
$isReachable = false;
// Get open_basedir parameter
$openBaseDir = trim(ini_get('open_basedir'));
// Is it set?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: openBaseDir=%s' . PHP_EOL, __METHOD__, __LINE__, $openBaseDir);
if (!empty($openBaseDir)) {
// Check all entries
foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
// Check on existence
+ //* NOISY-DEBUG: */ printf('[%s:%d]: dir=%s' . PHP_EOL, __METHOD__, __LINE__, $dir);
if (substr($fileInstance->getPathname(), 0, strlen($dir)) == $dir) {
// Is reachable
$isReachable = true;
// Abort lookup as it has been found in open_basedir
+ //* NOISY-DEBUG: */ printf('[%s:%d]: BREAK!' . PHP_EOL, __METHOD__, __LINE__);
break;
- } // END - if
- } // END - foreach
+ }
+ }
} else {
// If open_basedir is not set, all is allowed
+ //* NOISY-DEBUG: */ printf('[%s:%d]: All is allowed - BREAK!' . PHP_EOL, __METHOD__, __LINE__);
$isReachable = true;
}
// Return status
+ //* NOISY-DEBUG: */ printf('[%s:%d]: isReachable=%d - EXIT' . PHP_EOL, __METHOD__, __LINE__, intval($isReachable));
return $isReachable;
}
* @return $isReadable Whether the file is readable (and therefor exists)
*/
public static function isReadableFile (SplFileInfo $fileInstance) {
- // Default is not readable
- $isReadable = false;
-
// Check if it is a file and readable
+ //* NOISY-DEBUG: */ printf('[%s:%d]: fileInstance=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, get_class($fileInstance));
$isReadable = (
(
self::isReachableFilePath($fileInstance)
);
// Return status
+ //* NOISY-DEBUG: */ printf('[%s:%d]: isReadable=%d - EXIT!' . PHP_EOL, __METHOD__, __LINE__, intval($isReadable));
return $isReadable;
}
* @throws InvalidArgumentException If file was not found or not readable or deprecated
*/
public static function loadInclude (SplFileInfo $fileInstance) {
- // Trace message
- //* NOISY-DEBUG: */ printf('[%s:%d]: fileInstance=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $fileInstance);
-
// Should be there ...
+ //* NOISY-DEBUG: */ printf('[%s:%d]: fileInstance=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $fileInstance->__toString());
if (!self::isReadableFile($fileInstance)) {
// Abort here
throw new InvalidArgumentException(sprintf('Cannot find fileInstance.pathname=%s.', $fileInstance->getPathname()));
- } // END - if
+ } elseif (!$fileInstance->isFile()) {
+ // Not a file
+ throw new InvalidArgumentException(sprintf('fileInstance.pathname=%s is not a file', $fileInstance->getPathname()));
+ } elseif (substr($fileInstance->__toString(), -4, 4) != '.php') {
+ // Not PHP script
+ throw new InvalidArgumentException(sprintf('fileInstance.pathname=%s is not a PHP script', $fileInstance->getPathname()));
+ }
// Load it
require_once $fileInstance->getPathname();
}
/**
- * Does the actual bootstrap
+ * Does the actual bootstrap. I think the amount of statically loaded
+ * include files cannot be reduced here as those files are need to early
+ * in the bootstrap phase. If you can find an other solution than this, with
+ * lesser "static includes" (means not loaded by the class loader), please
+ * let me know.
*
* @return void
*/
public static function doBootstrap () {
// Load basic include files to continue bootstrapping
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
self::loadInclude(new SplFileInfo(sprintf('%smain%sinterfaces%sclass_FrameworkInterface.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
self::loadInclude(new SplFileInfo(sprintf('%smain%sclasses%sclass_BaseFrameworkSystem.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
- self::loadInclude(new SplFileInfo(sprintf('%smain%sclasses%sutils%sclass_StringUtils.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
+ self::loadInclude(new SplFileInfo(sprintf('%smain%sclasses%sutils%sstrings%sclass_StringUtils.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
self::loadInclude(new SplFileInfo(sprintf('%smain%sinterfaces%sregistry%sclass_Registerable.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR)));
self::loadInclude(new SplFileInfo(sprintf('%sconfig%sclass_FrameworkConfiguration.php', ApplicationEntryPoint::detectFrameworkPath(), DIRECTORY_SEPARATOR)));
// Load global configuration
self::loadInclude(new SplFileInfo(sprintf('%s%s', ApplicationEntryPoint::detectFrameworkPath(), 'config-global.php')));
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
/**
* 1) Load class loader and scan framework classes, interfaces and
* exceptions.
*/
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
self::scanFrameworkClasses();
/*
* 2) Determine the request type, console or web and store request and
- * response here. This also initializes the request instance will
+ * response here. This also initializes the request instance with
* all given parameters (see doc-tag for possible sources of
* parameters).
*/
* found, continue below with next step.
*/
self::validateApplicationParameter();
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
/**
* @return void
*/
public static function prepareApplication () {
- // Configuration entry 'detected_app_name' must be set, get it here, including full path
- $application = self::getConfigurationInstance()->getConfigEntry('detected_app_name');
- $fullPath = self::getConfigurationInstance()->getConfigEntry('detected_full_app_path');
-
/*
* Now check and load all files, found deprecated files will throw a
* warning at the user.
*/
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::configAppIncludes()=%d - CALLED!' . PHP_EOL, __METHOD__, __LINE__, count(self::$configAppIncludes));
foreach (self::$configAppIncludes as $fileName => $status) {
// Construct file instance
- $fileInstance = new SplFileInfo(sprintf('%s%s.php', $fullPath, $fileName));
+ //* NOISY-DEBUG: */ printf('[%s:%d]: fileName=%s,status=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $status);
+ $fileInstance = new SplFileInfo(sprintf('%s%s.php', self::getDetectedApplicationPath(), $fileName));
// Determine if this file is wanted/readable/deprecated
if (($status == 'required') && (!self::isReadableFile($fileInstance))) {
// Nope, required file cannot be found/read from
- ApplicationEntryPoint::exitApplication(sprintf('Application "%s" does not have required file "%s.php". Please add it.', $application, $fileInstance->getBasename()));
+ ApplicationEntryPoint::exitApplication(sprintf('Application "%s" does not have required file "%s.php". Please add it.', self::getDetectedApplicationName(), $fileInstance->getBasename()));
} elseif (($fileInstance->isFile()) && (!$fileInstance->isReadable())) {
// Found, not readable file
- ApplicationEntryPoint::exitApplication(sprintf('File "%s.php" from application "%s" cannot be read. Please fix CHMOD.', $fileInstance->getBasename(), $application));
+ ApplicationEntryPoint::exitApplication(sprintf('File "%s.php" from application "%s" cannot be read. Please fix CHMOD.', $fileInstance->getBasename(), self::getDetectedApplicationName()));
} elseif (($status != 'required') && (!self::isReadableFile($fileInstance))) {
// Not found but optional/deprecated file, skip it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: fileName=%s,status=%s - SKIPPED!' . PHP_EOL, __METHOD__, __LINE__, $fileName, $status);
continue;
}
// Is the file deprecated?
if ($status == 'deprecated') {
// Issue warning
- trigger_error(sprintf('Deprecated file "%s.php" found, will not load it to avoid problems. Please remove it from your application "%s" to avoid this warning.', $fileName, $application), E_USER_WARNING);
+ trigger_error(sprintf('Deprecated file "%s.php" found, will not load it to avoid problems. Please remove it from your application "%s" to avoid this warning.', $fileName, self::getDetectedApplicationName()), E_USER_WARNING);
// Skip loading deprecated file
continue;
- } // END - if
+ }
// Load it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Invoking self::loadInclude(%s) ...' . PHP_EOL, __METHOD__, __LINE__, $fileInstance->__toString());
self::loadInclude($fileInstance);
- } // END - foreach
+ }
+
+ // After this, sort the configuration array
+ self::getConfigurationInstance()->sortConfigurationArray();
// Scan for application's classes, exceptions and interfaces
ClassLoader::scanApplicationClasses();
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
/**
* @return void
*/
public static function startApplication () {
- // Configuration entry 'detected_app_name' must be set, get it here
- $application = self::getConfigurationInstance()->getConfigEntry('detected_app_name');
-
// Is there an application helper instance?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
$applicationInstance = call_user_func_array(
- array(
+ [
'Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper', 'getSelfInstance'
- ), array()
+ ], []
);
// Some sanity checks
+ //* NOISY-DEBUG: */ printf('[%s:%d]: applicationInstance=%s' . PHP_EOL, __METHOD__, __LINE__, $applicationInstance->__toString());
if ((empty($applicationInstance)) || (is_null($applicationInstance))) {
// Something went wrong!
ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application <span class="app_name">%s</span> could not be launched because the helper class <span class="class_name">%s</span> is not loaded.',
- $application,
+ self::getDetectedApplicationName(),
'Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper'
));
} elseif (!is_object($applicationInstance)) {
// No object!
ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application <span class="app_name">%s</span> could not be launched because 'app' is not an object (%s).',
- $application,
+ self::getDetectedApplicationName(),
gettype($applicationInstance)
));
} elseif (!($applicationInstance instanceof ManageableApplication)) {
// Missing interface
ApplicationEntryPoint::exitApplication(sprintf('[Main:] The application <span class="app_name">%s</span> could not be launched because 'app' is lacking required interface ManageableApplication.',
- $application
+ self::getDetectedApplicationName()
));
}
// Now call all methods in one go
- foreach (array('setupApplicationData', 'initApplication', 'launchApplication') as $methodName) {
- // Debug message
- //*NOISY-DEBUG: */ printf('[%s:%d]: Calling methodName=%s ...' . PHP_EOL, __METHOD__, __LINE__, $methodName);
-
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Initializing application ...' . PHP_EOL, __METHOD__, __LINE__);
+ foreach (['setupApplicationData', 'initApplication', 'launchApplication'] as $methodName) {
// Call method
- call_user_func(array($applicationInstance, $methodName));
- } // END - foreach
+ //*NOISY-DEBUG: */ printf('[%s:%d]: Invoking methodName=%s ...' . PHP_EOL, __METHOD__, __LINE__, $methodName);
+ call_user_func([$applicationInstance, $methodName]);
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
/**
* Initializes database instance, no need to double-call this method
*
* @return void
+ * @throws BadMethodCallException If this method was invoked twice
*/
public static function initDatabaseInstance () {
// Get application instance
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
$applicationInstance = ApplicationHelper::getSelfInstance();
// Is the database instance already set?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::databaseInstance[]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype(self::getDatabaseInstance()));
if (self::getDatabaseInstance() instanceof DatabaseConnector) {
// Yes, then abort here
throw new BadMethodCallException('Method called twice.');
- } // END - if
+ }
// Initialize database layer
$databaseInstance = ObjectFactory::createObjectByConfiguredName(self::getConfigurationInstance()->getConfigEntry('database_type') . '_class');
// Prepare database instance
- $connectionInstance = DatabaseConnection::createDatabaseConnection(DebugMiddleware::getSelfInstance(), $databaseInstance);
+ $connectionInstance = DatabaseConnection::createDatabaseConnection($databaseInstance);
// Set it in application helper
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Setting connectionInstance=%s ...' . PHP_EOL, __METHOD__, __LINE__, $connectionInstance->__toString());
self::setDatabaseInstance($connectionInstance);
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
/**
*/
public static function detectServerAddress () {
// Is the entry set?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
if (!isset(self::$serverAddress)) {
// Is it set in $_SERVER?
if (!empty($_SERVER['SERVER_ADDR'])) {
// Set it from $_SERVER
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Setting self::serverAddress=%s from SERVER_ADDR ...' . PHP_EOL, __METHOD__, __LINE__, $_SERVER['SERVER_ADDR']);
self::$serverAddress = $_SERVER['SERVER_ADDR'];
} elseif (isset($_SERVER['SERVER_NAME'])) {
// Resolve IP address
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Resolving SERVER_NAME=%s ...' . PHP_EOL, __METHOD__, __LINE__, $_SERVER['SERVER_NAME']);
$serverIp = ConsoleTools::resolveIpAddress($_SERVER['SERVER_NAME']);
// Is it valid?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: serverId[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($serverIp), $serverIp);
if ($serverIp === false) {
/*
* Why is gethostbyname() returning the host name and not
* false as many other PHP functions are doing? ;-(
*/
throw new UnknownHostnameException(sprintf('Cannot resolve "%s" to an IP address. Please fix your setup.', $_SERVER['SERVER_NAME']));
- } // END - if
+ }
// Al fine, set it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Setting self::serverAddress=%s from resolver ...' . PHP_EOL, __METHOD__, __LINE__, $serverAddress);
self::$serverAddress = $serverIp;
} else {
// Run auto-detecting through console tools lib
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Invoking ConsoleTools::acquireSelfIpAddress() ...' . PHP_EOL, __METHOD__, __LINE__);
self::$serverAddress = ConsoleTools::acquireSelfIpAddress();
}
- } // END - if
+ }
// Return it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::serverAddress=%s - EXIT!' . PHP_EOL, __METHOD__, __LINE__, self::$serverAddress);
return self::$serverAddress;
}
*
* @param $timezone The timezone string (e.g. Europe/Berlin)
* @return $success If timezone was accepted
- * @throws NullPointerException If $timezone is NULL
* @throws InvalidArgumentException If $timezone is empty
*/
- public static function setDefaultTimezone ($timezone) {
- // Is it null?
- if (is_null($timezone)) {
- // Throw NPE
- throw new NullPointerException(NULL, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
- } elseif (!is_string($timezone)) {
- // Is not a string
- throw new InvalidArgumentException(sprintf('timezone[]=%s is not a string', gettype($timezone)));
- } elseif ((is_string($timezone)) && (empty($timezone))) {
+ public static function setDefaultTimezone (string $timezone) {
+ // Is it set?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: timezone=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $timezone);
+ if (empty($timezone)) {
// Entry is empty
- throw new InvalidArgumentException('timezone is empty');
+ throw new InvalidArgumentException('Parameter "timezone" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
}
// Default success
$success = date_default_timezone_set($timezone);
// Return status
+ //* NOISY-DEBUG: */ printf('[%s:%d]: success=%d - EXIT!' . PHP_EOL, __METHOD__, __LINE__, intval($success));
return $success;
}
* @todo Test more fields
*/
public static function isHttpSecured () {
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
return (
(
(
*/
public static function detectBaseUrl () {
// Initialize the URL
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
$protocol = 'http';
// Do we have HTTPS?
if (self::isHttpSecured()) {
// Add the >s< for HTTPS
$protocol = 'https';
- } // END - if
+ }
// Construct the full URL and secure it against CSRF attacks
$baseUrl = sprintf('%s://%s%s', $protocol, self::detectDomain(), self::detectScriptPath());
// Return the URL
+ //* NOISY-DEBUG: */ printf('[%s:%d]: baseUrl=%s - EXIT!' . PHP_EOL, __METHOD__, __LINE__, $baseUrl);
return $baseUrl;
}
*/
public static function detectDomain () {
// Full domain is localnet.invalid by default
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
$fullDomain = 'localnet.invalid';
// Is the server name there?
if (isset($_SERVER['SERVER_NAME'])) {
// Detect the full domain
$fullDomain = htmlentities(strip_tags($_SERVER['SERVER_NAME']), ENT_QUOTES);
- } // END - if
+ }
// Return it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: fullDomain=%s - EXIT!' . PHP_EOL, __METHOD__, __LINE__, $fullDomain);
return $fullDomain;
}
*/
public static function detectScriptPath () {
// Default is empty
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
$scriptPath = '';
// Is the scriptname set?
if (isset($_SERVER['SCRIPT_NAME'])) {
// Get dirname from it and replace back-slashes with slashes for lame OSes...
$scriptPath = str_replace("\\", '/', dirname($_SERVER['SCRIPT_NAME']));
- } // END - if
+ }
// Return it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: scriptPath=%s - EXIT!' . PHP_EOL, __METHOD__, __LINE__, $scriptPath);
return $scriptPath;
}
* @return void
*/
private static function scanFrameworkClasses () {
- // Include the class loader function
+ // Include class loader
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
require self::getConfigurationInstance()->getConfigEntry('framework_base_path') . 'loader/class_ClassLoader.php';
// Register auto-load function with the SPL
// Scan for all framework classes, exceptions and interfaces
ClassLoader::scanFrameworkClasses();
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
/**
*/
private static function determineRequestType () {
// Determine request type
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
$request = self::getRequestTypeFromSystem();
$requestType = self::getRequestTypeFromSystem();
// Create a new request object
- $requestInstance = ObjectFactory::createObjectByName(sprintf('Org\Mxchange\CoreFramework\Request\%sRequest', BaseFrameworkSystem::convertToClassName($request)));
+ //* NOISY-DEBUG: */ printf('[%s:%d]: request=%s,requestType=%s' . PHP_EOL, __METHOD__, __LINE__, $request, $requestType);
+ $requestInstance = ObjectFactory::createObjectByName(sprintf('Org\Mxchange\CoreFramework\Request\%sRequest', StringUtils::convertToClassName($request)));
// Remember request instance here
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Setting requestInstance=%s ...' . PHP_EOL, __METHOD__, __LINE__, $requestInstance->__toString());
self::setRequestInstance($requestInstance);
// Do we have another response?
// Then use it
$request = strtolower($requestInstance->getRequestElement('request'));
$requestType = $request;
- } // END - if
+ }
// ... and a new response object
- $responseClass = sprintf('Org\Mxchange\CoreFramework\Response\%sResponse', BaseFrameworkSystem::convertToClassName($request));
- $responseInstance = ObjectFactory::createObjectByName($responseClass);
+ //* NOISY-DEBUG: */ printf('[%s:%d]: request=%s,requestType=%s - AFTER!' . PHP_EOL, __METHOD__, __LINE__, $request, $requestType);
+ $responseInstance = ObjectFactory::createObjectByName(sprintf('Org\Mxchange\CoreFramework\Response\%sResponse', StringUtils::convertToClassName($request)));
// Remember response instance here
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Setting responseInstance=%s ...' . PHP_EOL, __METHOD__, __LINE__, $responseInstance->__toString());
self::setResponseInstance($responseInstance);
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
/**
*/
private static function validateApplicationParameter () {
// Is the parameter set?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
if (!self::getRequestInstance()->isRequestElementSet('app')) {
/*
* Don't continue here, the application 'selector' is no longer
* application (by user).
*/
ApplicationEntryPoint::exitApplication('No application specified. Please provide a parameter "app" and retry.');
- } // END - if
+ }
// Get it for local usage
- $application = self::getRequestInstance()->getRequestElement('app');
+ $applicationName = self::getRequestInstance()->getRequestElement('app');
// Secure it, by keeping out tags
- $application = htmlentities(strip_tags($application), ENT_QUOTES);
+ //* NOISY-DEBUG: */ printf('[%s:%d]: applicationName=%s' . PHP_EOL, __METHOD__, __LINE__, $applicationName);
+ $applicationName = htmlentities(strip_tags($applicationName), ENT_QUOTES);
// Secure it a little more with a reg.exp.
- $application = preg_replace('/([^a-z0-9_-])+/i', '', $application);
+ //* NOISY-DEBUG: */ printf('[%s:%d]: applicationName=%s' . PHP_EOL, __METHOD__, __LINE__, $applicationName);
+ $applicationName = preg_replace('/([^a-z0-9_-])+/i', '', $applicationName);
// Construct FQPN (Full-Qualified Path Name) for ApplicationHelper class
+ //* NOISY-DEBUG: */ printf('[%s:%d]: applicationName=%s' . PHP_EOL, __METHOD__, __LINE__, $applicationName);
$applicationPath = sprintf(
'%s%s%s',
self::getConfigurationInstance()->getConfigEntry('application_base_path'),
- $application,
+ $applicationName,
DIRECTORY_SEPARATOR
);
// Full path for application
// Is the path there? This secures a bit the parameter (from untrusted source).
+ //* NOISY-DEBUG: */ printf('[%s:%d]: applicationPath=%s' . PHP_EOL, __METHOD__, __LINE__, $applicationPath);
if ((!is_dir($applicationPath)) || (!is_readable($applicationPath))) {
// Not found or not readable
- ApplicationEntryPoint::exitApplication(sprintf('Application "%s" not found.', $application));
- } // END - if
+ ApplicationEntryPoint::exitApplication(sprintf('Application "%s" not found.', $applicationName));
+ }
// Set the detected application's name and full path for later usage
- self::getConfigurationInstance()->setConfigEntry('detected_full_app_path', $applicationPath);
- self::getConfigurationInstance()->setConfigEntry('detected_app_name' , $application);
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Setting applicationPath=%s,applicationName=%s' . PHP_EOL, __METHOD__, __LINE__, $applicationPath, $applicationName);
+ self::$detectedApplicationPath = $applicationPath;
+ self::$detectedApplicationName = $applicationName;
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
/**
return self::$databaseInstance;
}
+ /**
+ * Private getter for language instance
+ *
+ * @return $languageInstance An instance of a ManageableLanguage class
+ */
+ public static function getLanguageInstance () {
+ return self::$languageInstance;
+ }
+
+ /**
+ * Setter for language instance
+ *
+ * @param $languageInstance An instance of a ManageableLanguage class
+ * @return void
+ */
+ public static function setLanguageInstance (ManageableLanguage $languageInstance) {
+ self::$languageInstance = $languageInstance;
+ }
+
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
// CFG: CODE-TEMPLATE-EXTENSION
$cfg->setConfigEntry('code_template_extension', '.ctp');
-// CFG: SELECTOR-PATH
-$cfg->setConfigEntry('selector_path', 'selector');
-
// CFG: TEMPLATE-BASE-PATH
$cfg->setConfigEntry('tpl_base_path', 'templates/');
// CFG: LANGUAGE-SYSTEM-CLASS
$cfg->setConfigEntry('language_system_class', 'Org\Mxchange\CoreFramework\Localization\LanguageSystem');
-// CFG: SELECTOR-TEMPLATE-PREFIX
-$cfg->setConfigEntry('tpl_selector_prefix', 'selector');
-
// CFG: WEB-CONTENT-TYPE
$cfg->setConfigEntry('web_content_type', 'text/html');
// CFG: META-DESCRIPTION
$cfg->setConfigEntry('meta_description', 'A description for your website');
-// CFG: SELECTOR-MAIN-TEMPLATE
-$cfg->setConfigEntry('selector_main_tpl', 'selector_main');
-
-// CFG: SELECTOR-APPS-TEMPLATE
-$cfg->setConfigEntry('selector_apps_tpl', 'selector_apps');
-
-// CFG: SELECTOR-NAME
-$cfg->setConfigEntry('selector_name', 'selector');
-
-// CFG: DEFAULT-APPLICATION
-$cfg->setConfigEntry('default_application', 'selector');
-
-// CFG: VERBOSE-LEVEL
-$cfg->setConfigEntry('verbose_level', 0);
-
// CFG: CACHE-CLASS
$cfg->setConfigEntry('cache_class', 'Org\Mxchange\CoreFramework\Cache\Memory\MemoryCache');
// CFG: RNG-CLASS
$cfg->setConfigEntry('rng_class', 'Org\Mxchange\CoreFramework\Crypto\RandomNumber\RandomNumberGenerator');
-// CFG: USER-DB-WRAPPER-CLASS
-$cfg->setConfigEntry('user_db_wrapper_class', 'Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseWrapper');
+// CFG: USER-DB-FRONTEND-CLASS
+$cfg->setConfigEntry('user_db_frontend_class', 'Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseFrontend');
-// CFG: NEWS-DB-WRAPPER-CLASS
-$cfg->setConfigEntry('news_db_wrapper_class', 'Org\Mxchange\CoreFramework\Database\Frontend\News\NewsDatabaseWrapper');
+// CFG: NEWS-DB-FRONTEND-CLASS
+$cfg->setConfigEntry('news_db_frontend_class', 'Org\Mxchange\CoreFramework\Database\Frontend\News\NewsDatabaseFrontend');
// CFG: HTML-CMD-RESOLVER-CLASS
$cfg->setConfigEntry('html_cmd_resolver_class', 'Org\Mxchange\CoreFramework\Resolver\Command\HtmlCommandResolver');
// CFG: HASH-NORMAL-MASK
$cfg->setConfigEntry('hash_normal_mask', '%1s:%2s'); // 1=salt, 2=plain password/string
-// CFG: IS-SINGLE-SERVER
-$cfg->setConfigEntry('is_single_server', 'Y');
-
// CFG: POST-REGISTRATION-CLASS
$cfg->setConfigEntry('post_registration_class', 'Org\Mxchange\CoreFramework\Action\PostRegistration\Login\LoginAfterRegistrationAction');
// CFG: COOKIE-SSL
$cfg->setConfigEntry('cookie_ssl', FrameworkBootstrap::isHttpSecured());
-// CFG: CRYPT-FIXED-SALT
-$cfg->setConfigEntry('crypt_fixed_salt', 'N');
-
-// CFG: DB-UPDATE-PRIMARY-FORCED
-$cfg->setConfigEntry('db_update_primary_forced', 'Y');
-
// CFG: GERMAN-DATE-TIME
$cfg->setConfigEntry('german_date_time', "%3\$s.%2\$s.%1\$s, %4\$s:%5\$s:%6\$s");
$cfg->setConfigEntry('decimals', 3);
// CFG: MENU-STACKER-CLASS
-$cfg->setConfigEntry('menu_stacker_class', 'Org\Mxchange\CoreFramework\Stacker\FiLoStacker');
+$cfg->setConfigEntry('menu_stacker_class', 'Org\Mxchange\CoreFramework\Stack\FiLoStacker');
// CFG: STACKER-GENERIC-MAX-SIZE
$cfg->setConfigEntry('stacker_generic_max_size', 100);
// CFG: COMPRESSOR-CHANNEL-CLASS
$cfg->setConfigEntry('compressor_channel_class', 'Org\Mxchange\CoreFramework\Middleware\Compressor\CompressorChannel');
-// CFG: DEBUG-HTML-OUTPUT-TIMINGS
-$cfg->setConfigEntry('debug_html_output_timings', 'N');
-
-// CFG: DEBUG-CONSOLE-OUTPUT-TIMINGS
-$cfg->setConfigEntry('debug_console_output_timings', 'Y');
-
// CFG: PROXY-HOST
$cfg->setConfigEntry('proxy_host', '');
// CFG: PROXY-PASSWORD
$cfg->setConfigEntry('proxy_password', '');
-// CFG: PROXY-CONNECT-METHOD
-$cfg->setConfigEntry('proxy_connect_method', 'Y');
-
// CFG: HOSTNAME-FILE
$cfg->setConfigEntry('hostname_file', '/etc/hostname');
-// CFG: DATABASE-CACHE-ENABLED
-$cfg->setConfigEntry('database_cache_enabled', false);
-
// CFG: DIRECTORY-CLASS
$cfg->setConfigEntry('directory_class', 'Org\Mxchange\CoreFramework\Filesytem\Pointer\FrameworkDirectoryPointer');
// CFG: FILE-ITERATOR-CLASS
$cfg->setConfigEntry('file_iterator_class', 'Org\Mxchange\CoreFramework\Iterator\File\FileIterator');
-// CFG: FILE-STACK-PRE-ALLOCATE-ENABLED
-$cfg->setConfigEntry('file_stack_pre_allocate_enabled', 'Y');
-
// CFG: FILE-STACK-PRE-ALLOCATE-COUNT
$cfg->setConfigEntry('file_stack_pre_allocate_count', 10000);
// CFG: INDEX-INDEX-CLASS
-$cfg->setConfigEntry('file_stack_index_class', 'Org\Mxchange\CoreFramework\Index\Stack\FileStackIndex');
-
-// CFG: INDEX-PRE-ALLOCATE-ENABLED
-$cfg->setConfigEntry('index_pre_allocate_enabled', 'Y');
+$cfg->setConfigEntry('file_stack_index_class', 'Org\Mxchange\CoreFramework\Index\File\Stack\FileStackIndex');
// CFG: INDEX-PRE-ALLOCATE-COUNT
$cfg->setConfigEntry('index_pre_allocate_count', 10000);
// CFG: STACK-FILE-CLASS
-$cfg->setConfigEntry('stack_file_class', 'Org\Mxchange\CoreFramework\Filesystem\Stack\StackFile');
+$cfg->setConfigEntry('stack_file_class', 'Org\Mxchange\CoreFramework\Stack\File\StackFile');
// CFG: INDEX-FILE-CLASS
$cfg->setConfigEntry('index_file_class', 'Org\Mxchange\CoreFramework\Filesystem\Index\IndexFile');
// CFG: MENU-TEMPLATE-CLASS
$cfg->setConfigEntry('menu_template_class', 'Org\Mxchange\CoreFramework\Template\Engine\MenuTemplateEngine');
+// CFG: CONSOLE-TEMPLATE-CLASS
+$cfg->setConfigEntry('console_template_class', 'Org\Mxchange\CoreFramework\Template\Engine\ConsoleTemplateEngine');
+
// CFG: MENU-TEMPLATE-EXTENSION
$cfg->setConfigEntry('menu_template_extension', '.xml');
// CFG: REGISTRY-ITERATOR-CLASS
$cfg->setConfigEntry('registry_iterator_class', 'Org\Mxchange\CoreFramework\Iterator\Registry\RegistryIterator');
-// CFG: QUIET-DNS-RESOLVER
-$cfg->setConfigEntry('quiet_dns_resolver', FALSE);
+// CFG: THOUSANDS-SEPARATOR
+$cfg->setConfigEntry('thousands_separator', '.');
+
+// CFG: DECIMALS-SEPARATOR
+$cfg->setConfigEntry('decimals_separator', ',');
+
+// CFG: CRYPTO-OPENSSL-STREAM-CLASS
+$cfg->setConfigEntry('crypto_openssl_stream_class', 'Org\Mxchange\CoreFramework\Stream\Crypto\OpenSsl\OpenSslStream');
+
+// CFG: CRYPTO-NULL-STREAM-CLASS
+$cfg->setConfigEntry('crypto_null_stream_class', 'Org\Mxchange\CoreFramework\Stream\Crypto\Null\NullCryptoStream');
+
+// CFG: CRYPTO-HASH-FUNCTION-NAME
+$cfg->setConfigEntry('crypto_hash_function_name', 'sha256');
+
+/**
+ * -------------------------------------------------------------
+ * Boolean is_*_enabled configuration keys
+ * -------------------------------------------------------------
+ */
+
+// CFG: IS-DEVELOPER-MODE-ENABLED
+$cfg->setConfigEntry('is_developer_mode_enabled', true);
+
+// CFG: IS-DATABASE-CACHE-ENABLED
+$cfg->setConfigEntry('is_database_cache_enabled', false);
+
+// CFG: IS-DEBUG-HTML-OUTPUT-TIMINGS-ENABLED
+$cfg->setConfigEntry('is_debug_html_output_timings_enabled', false);
+
+// CFG: IS-DEBUG-CONSOLE-OUTPUT-TIMINGS-ENABLED
+$cfg->setConfigEntry('is_debug_console_output_timings_enabled', true);
+
+// CFG: IS-REGISTER-EMAIL-UNIQUE-ENABLED
+$cfg->setConfigEntry('is_register_email_unique_enabled', true);
+
+// CFG: IS-BLOCK-SHOWS-REGISTRATION-ENABLED
+$cfg->setConfigEntry('is_block_shows_registration_enabled', true);
+
+// CFG: IS-REGISTER-REQUIRES-EMAIl-ENABLED
+$cfg->setConfigEntry('is_register_requires_email_enabled', true);
+
+// CFG: IS-REGISTER-INCLUDES-PROFILE-ENABLED
+$cfg->setConfigEntry('is_register_includes_profile_enabled', true);
+
+// CFG: IS-REGISTER-PERSONAL-DATA-ENABLED
+$cfg->setConfigEntry('is_register_personal_data_enabled', true);
+
+// CFG: IS-PROFILE-INCLUDES-BIRTHDAY-ENABLED
+$cfg->setConfigEntry('is_profile_includes_birthday_enabled', true);
+
+// CFG: IS-USER-LOGIN-ENABLED
+$cfg->setConfigEntry('is_user_login_enabled', true);
+
+// CFG: IS-GUEST-LOGIN-ENABLED
+$cfg->setConfigEntry('is_guest_login_enabled', true);
+
+// CFG: IS-EMAIL-CHANGE-CONFIRMATION-ENABLED
+$cfg->setConfigEntry('is_email_change_confirmation_enabled', true);
+
+// CFG: IS-EMAIL-CHANGE-ENABLED
+$cfg->setConfigEntry('is_email_change_enabled', true);
+
+// CFG: IS-REFILL-PAGE-ACTIVE-ENABLED
+$cfg->setConfigEntry('is_refill_page_active_enabled', true);
+
+// CFG: IS-PROXY-CONNECT-METHOD-ENABLED
+$cfg->setConfigEntry('is_proxy_connect_method_enabled', true);
+
+// CFG: IS-SINGLE-SERVER-ENABLED
+$cfg->setConfigEntry('is_single_server_enabled', true);
+
+// CFG: IS-CRYPT-FIXED-SALT-ENABLED
+$cfg->setConfigEntry('is_crypt_fixed_salt_enabled', false);
+
+// CFG: IS-DB-UPDATE-PRIMARY-FORCED-ENABLED
+$cfg->setConfigEntry('is_db_update_primary_forced_enabled', true);
+
+// CFG: IS-QUIET-DNS-RESOLVER-ENABLED
+$cfg->setConfigEntry('is_quiet_dns_resolver_enabled', false);
+
+// CFG: IS-FILE-STACK-PRE-ALLOCATE-ENABLED
+$cfg->setConfigEntry('is_file_stack_pre_allocate_enabled', true);
-// Remove config from this name-space. Don't worry, no configuration is cleared.
-unset($cfg);
+// CFG: IS-INDEX-PRE-ALLOCATE-ENABLED
+$cfg->setConfigEntry('is_index_pre_allocate_enabled', true);
namespace Org\Mxchange\CoreFramework\Configuration;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Configuration\NoConfigEntryException;
use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
-use Org\Mxchange\CoreFramework\Generic\NullPointerException;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
-use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
use Org\Mxchange\CoreFramework\Registry\Registerable;
-use Org\Mxchange\CoreFramework\String\Utils\StringUtils;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
// Import SPL stuff
use \InvalidArgumentException;
+use \UnexpectedValueException;
/**
- * A class for the configuration stuff implemented in a singleton design paddern
+ * A class for the configuration stuff implemented in a singleton design pattern
*
* NOTE: We cannot put this in framework/main/ because it would be loaded (again) in
* class loader. See framework/loader/class_ClassLoader.php for instance
* @see ClassLoader
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 1.0.1
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class FrameworkConfiguration implements Registerable {
+ // Some constants for the configuration system
+ const EXCEPTION_CONFIG_KEY_IS_EMPTY = 0x130;
+ const EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND = 0x131;
+ const EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED = 0x132;
/**
* The framework's main configuration array which will be initialized with
* hard-coded configuration data and might be overwritten/extended by
* config data from the database.
*/
- private static $config = array();
+ private static $configData = [];
/**
* Call-back instance (unused)
*/
private $callbackInstance = NULL;
- // Some constants for the configuration system
- const EXCEPTION_CONFIG_KEY_IS_EMPTY = 0x130;
- const EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND = 0x131;
- const EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED = 0x132;
-
/**
* Default constructor, the configuration entries are static, not the
* whole instance.
*
* @param $configKey The configuration key we shall check
* @return $isset Whether the given configuration key is set
- * @throws NullPointerException If $configKey is NULL
* @throws InvalidArgumentException If $configKey is empty
*/
- public function isConfigurationEntrySet ($configKey) {
+ public function isConfigurationEntrySet (string $configKey) {
// Is it null?
- if (is_null($configKey)) {
- // Throw NPE
- throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
- } elseif (!is_string($configKey)) {
- // Is not a string
- throw new InvalidArgumentException(sprintf('configKey[]=%s is not a string', gettype($configKey)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
- } elseif ((is_string($configKey)) && (empty($configKey))) {
+ //* NOISY-DEBUG: */ printf('[%s:%d]: configKey=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $configKey);
+ if (empty($configKey)) {
// Entry is empty
- throw new InvalidArgumentException('configKey is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
+ throw new InvalidArgumentException('Parameter "configKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
}
// Is it set?
- $isset = ((isset(self::$config[$configKey])) || (array_key_exists($configKey, self::$config)));
+ $isset = ((isset(self::$configData[$configKey])) || (array_key_exists($configKey, self::$configData)));
// Return the result
+ //* NOISY-DEBUG: */ printf('[%s:%d]: isset=%s - EXIT!' . PHP_EOL, __METHOD__, __LINE__, intval($isset));
return $isset;
}
*
* @param $configKey The configuration element
* @return $configValue The fetched configuration value
- * @throws NullPointerException If $configKey is NULL
* @throws InvalidArgumentException If $configKey is empty
* @throws NoConfigEntryException If a configuration element was not found
*/
- public function getConfigEntry ($configKey) {
+ public function getConfigEntry (string $configKey) {
// Is it null?
- if (is_null($configKey)) {
- // Throw NPE
- throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
- } elseif (!is_string($configKey)) {
- // Is not a string
- throw new InvalidArgumentException(sprintf('configKey[]=%s is not a string', gettype($configKey)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
- } elseif ((is_string($configKey)) && (empty($configKey))) {
+ //* NOISY-DEBUG: */ printf('[%s:%d]: configKey=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $configKey);
+ if (empty($configKey)) {
// Entry is empty
- throw new InvalidArgumentException('configKey is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
+ throw new InvalidArgumentException('Parameter "configKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
}
// Convert dashes to underscore
- $configKey = StringUtils::convertDashesToUnderscores($configKey);
+ $configKey = str_replace('-', '_', $configKey);
// Is a valid configuration key provided?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: configKey=%s - AFTER!' . PHP_EOL, __METHOD__, __LINE__, $configKey);
if (!$this->isConfigurationEntrySet($configKey)) {
// Entry was not found!
throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
- } // END - if
+ }
// Return the requested value
- return self::$config[$configKey];
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Returning configData[%s]=[%s]:%s - EXIT!' . PHP_EOL, __METHOD__, __LINE__, $configKey, gettype(self::$configData[$configKey]), self::$configData[$configKey]);
+ return self::$configData[$configKey];
}
/**
* @param $configKey The configuration key we want to add/change
* @param $configValue The configuration value we want to set
* @return void
- * @throws NullPointerException If $configKey is NULL
* @throws InvalidArgumentException If $configKey is empty
* @throws InvalidArgumentException If $configValue has an unsupported variable type
*/
- public final function setConfigEntry ($configKey, $configValue) {
+ public final function setConfigEntry (string $configKey, $configValue) {
// Is a valid configuration key key provided?
- if (is_null($configKey)) {
- // Configuration key is null
- throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
- } elseif (!is_string($configKey)) {
- // Is not a string
- throw new InvalidArgumentException(sprintf('configKey[]=%s is not a string', gettype($configKey)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
- } elseif ((is_string($configKey)) && (empty($configKey))) {
+ //* NOISY-DEBUG: */ printf('[%s:%d]: configKey=%s,configValue[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $configKey, gettype($configValue));
+ if (empty($configKey)) {
// Entry is empty
- throw new InvalidArgumentException('configKey is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
+ throw new InvalidArgumentException('Parameter "configKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif ((is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
// These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
throw new InvalidArgumentException(sprintf('configValue[]=%s for configKey=%s is not supported.', gettype($configValue), $configKey), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
}
// Cast to string
- $configKey = StringUtils::convertDashesToUnderscores($configKey);
+ $configKey = str_replace('-', '_', $configKey);
// Set the configuration value
- //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
- self::$config[$configKey] = $configValue;
-
- // Resort the array
- ksort(self::$config);
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Setting configKey=%s,configValue[%s]=%s - EXIT!' . PHP_EOL, __METHOD__, __LINE__, $configKey, gettype($configValue), $configValue);
+ self::$configData[$configKey] = $configValue;
}
/**
*/
public final function getConfigurationArray () {
// Return it
- return self::$config;
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::configData()=%d - EXIT!' . PHP_EOL, __METHOD__, __LINE__, count(self::$configData));
+ return self::$configData;
+ }
+
+ /**
+ * Sorts the configuration array, saves A LOT calls if done after all configuration files have been loaded. You should NOT
+ * set any configuration entries by your own, means outside any configuration file. If you still do so, you HAVE to call
+ * this method afterwards
+ *
+ * @return void
+ */
+ public final function sortConfigurationArray () {
+ // Resort the array
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Sorting %d records - CALLED!' . PHP_EOL, __METHOD__, __LINE__, count(self::$configData));
+ ksort(self::$configData);
+
+ // Debug message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
/**
*
* @param $configKey Configuration key to unset
* @return void
- * @throws NullPointerException If $configKey is NULL
* @throws InvalidArgumentException If $configKey is empty
* @throws NoConfigEntryException If a configuration element was not found
*/
- public final function unsetConfigEntry ($configKey) {
+ public final function unsetConfigEntry (string $configKey) {
// Validate parameters
- if (is_null($configKey)) {
- // Configuration key is null
- throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
- } elseif (!is_string($configKey)) {
- // Entry is empty
- throw new InvalidArgumentException(sprintf('configKey[]=%s is not a string', gettype($configKey)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
- } elseif ((is_string($configKey)) && (empty($configKey))) {
+ //* NOISY-DEBUG: */ printf('[%s:%d]: configKey=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $configKey);
+ if (empty($configKey)) {
// Entry is empty
- throw new InvalidArgumentException('configKey is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
+ throw new InvalidArgumentException('Parameter "configKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
}
// Convert dashes to underscore
- $configKey = StringUtils::convertDashesToUnderscores($configKey);
+ $configKey = str_replace('-', '_', $configKey);
// Is the configuration key there?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: configKey=%s - AFTER!' . PHP_EOL, __METHOD__, __LINE__, $configKey);
if (!$this->isConfigurationEntrySet($configKey)) {
// Entry was not found!
throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
- } // END - if
+ }
// Unset it
- unset(self::$config[$configKey]);
- }
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Unsetting configKey=%s ...' . PHP_EOL, __METHOD__, __LINE__, $configKey);
+ unset(self::$configData[$configKey]);
- /**
- * Getter for field name
- *
- * @param $fieldName Field name which we shall get
- * @return $fieldValue Field value from the user
- * @throws NullPointerException If the result instance is null
- */
- public final function getField ($fieldName) {
- // The super interface "FrameworkInterface" requires this
- throw new UnsupportedOperationException(array($this, __FUNCTION__), BaseFrameworkSystem::EXCEPTION_UNSPPORTED_OPERATION);
+ // Debug message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
/**
- * Checks if given field is set
+ * Checks if a configuration entry is_*_enabled set to 'Y'
*
- * @param $fieldName Field name to check
- * @return $isSet Whether the given field name is set
- * @throws NullPointerException If the result instance is null
+ * @param $keyPart Configuration to expand with is_$keyPart_enabled
+ * @return $enabled Whether it has been set to Y or N
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws UnexpectedValueException If a returned value is of an unexpected type or value
*/
- public function isFieldSet ($fieldName) {
- // The super interface "FrameworkInterface" requires this
- throw new UnsupportedOperationException(array($this, __FUNCTION__), BaseFrameworkSystem::EXCEPTION_UNSPPORTED_OPERATION);
+ public function isEnabled (string $keyPart) {
+ // Validate parameters
+ //* NOISY-DEBUG: */ printf('[%s:%d]: keyPart=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $keyPart);
+ if (empty($keyPart)) {
+ // Entry is empty
+ throw new InvalidArgumentException('Parameter "keyPart" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Construct final config key
+ $configKey = sprintf('is_%s_enabled', $keyPart);
+
+ // Get value from it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: configKey=%s' . PHP_EOL, __METHOD__, __LINE__, $configKey);
+ $isEnabled = $this->getConfigEntry($configKey);
+
+ // Is it Y/N?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: isEnabled[]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($isEnabled));
+ if (!is_bool($isEnabled)) {
+ // Throw exception
+ throw new UnexpectedValueException(sprintf('isEnabled[]=%s is unexpected', gettype($isEnabled)), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
+
+ // Return it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: isEnabled=%d - EXIT!' . PHP_EOL, __METHOD__, __LINE__, intval($isEnabled));
+ return $isEnabled;
}
/**
$this->callbackInstance = $callbackInstance;
}
+ /**
+ * Getter for field name
+ *
+ * @param $fieldName Field name which we shall get
+ * @return $fieldValue Field value from the user
+ * @throws NullPointerException If the result instance is null
+ */
+ public final function getField (string $fieldName) {
+ // The super interface "FrameworkInterface" requires this
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
+ }
+
+ /**
+ * Checks if given field is set
+ *
+ * @param $fieldName Field name to check
+ * @return $isSet Whether the given field name is set
+ * @throws NullPointerException If the result instance is null
+ */
+ public function isFieldSet (string $fieldName) {
+ // The super interface "FrameworkInterface" requires this
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
+ }
+
}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
*
* This program is free software: you can redistribute it and/or modify
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\Configuration\FrameworkConfiguration;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
// Import SPL stuff
use \InvalidArgumentException;
use \RecursiveDirectoryIterator;
use \RecursiveIteratorIterator;
use \SplFileInfo;
+use \UnexpectedValueException;
/**
* This class loads class include files with a specific prefix and suffix
*
* @author Roland Haeder <webmaster@shipsimu.org>
- * @version 1.5.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @version 1.7.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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* ----------------------------------
- * 1.5
+ * 1.7.0
+ * - "Cached" more like config instance and root/application base path for
+ * shorter call stacks and lesser methods invoked
+ * - More debug logging
+ * 1.6.0
+ * - This class loader is now 100% singleton, no other instance is really
+ * required, therefore the factory method can be removed safely
+ * - renamed initLoader() to initClassLoader()
+ * - An instance of a FrameworkConfiguration is no longer set here as this
+ * violated the rule that there shall be no instance set of that class
+ * - .htaccess is marked as deprecated as this should be no longer done
+ * - scanClassPath() is now protected, please use other scan*() methods
+ * 1.5.0
* - Namespace scheme Project\Package[\SubPackage...] is fully supported and
* throws an InvalidArgumentException if not present. The last part will be
* always the class' name.
- * 1.4
+ * 1.4.0
* - Some comments improved, other minor improvements
- * 1.3
+ * 1.3.0
* - Constructor is now empty and factory method 'createClassLoader' is created
* - renamed loadClasses to scanClassPath
* - Added initLoader()
- * 1.2
+ * 1.2.0
* - ClassLoader rewritten to PHP SPL's own RecursiveIteratorIterator class
- * 1.1
+ * 1.1.0
* - loadClasses rewritten to fix some notices
- * 1.0
+ * 1.0.0
* - Initial release
* ----------------------------------
*/
-class ClassLoader {
+final class ClassLoader {
/**
* Instance of this class
*/
private static $selfInstance = NULL;
/**
- * Array with all found classes
+ * Instance of a FrameworkConfiguration class
*/
- private $foundClasses = array();
+ private static $configInstance = NULL;
+
+ /**
+ * Cached configuration entry 'is_developer_mode_enabled'
+ */
+ private static $developerModeEnabled = NULL;
+
+ /**
+ * Array with all valid but pending for loading file names (class,
+ * interfaces, traits must start with below prefix).
+ */
+ private $pendingFiles = [];
/**
* List of loaded classes
*/
- private $loadedClasses = array();
+ private $loadedClasses = [];
/**
* Suffix with extension for all class files
* A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner
* @see scanLocalPath
*/
- private $ignoreList = array();
+ private $ignoreList = [];
/**
* Debug this class loader? (true = yes, false = no)
/**
* Framework/application paths for classes, etc.
*/
- private static $frameworkPaths = array(
+ private static $frameworkPaths = [
+ 'classes', // Classes
'exceptions', // Exceptions
'interfaces', // Interfaces
- 'classes', // Classes
- 'middleware' // The middleware
- );
+ 'middleware', // The middleware
+ 'traits', // Traits
+ ];
/**
* Registered paths where test classes can be found. These are all relative
* to base_path .
*/
- private static $testPaths = array();
+ private static $testPaths = [];
+
+ /**
+ * Cached includes that needs to be flushed
+ */
+ private $flushCache = [];
/**
* The protected constructor. Please use the factory method below, or use
*
* @return void
*/
- protected function __construct () {
- // This is empty for now
+ private function __construct () {
+ // Is developerModeEnabled set?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CONSTRUCTED!' . PHP_EOL, __METHOD__, __LINE__);
+ if (is_null(self::$developerModeEnabled)) {
+ // Cache config instance
+ self::$configInstance = FrameworkBootstrap::getConfigurationInstance();
+
+ // Cache config entry
+ self::$developerModeEnabled = self::$configInstance->isEnabled('developer_mode');
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::developerModeEnabled=%d - EXIT!' . PHP_EOL, __METHOD__, __LINE__, intval(self::$developerModeEnabled));
}
/**
*/
public function __destruct () {
// Skip here if dev-mode
- if (defined('DEVELOPER')) {
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::developerModeEnabled=%d - DESTRUCTED!' . PHP_EOL, __METHOD__, __LINE__, intval(self::$developerModeEnabled));
+ if (self::$developerModeEnabled) {
+ // Is enabled, don't cache
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Developer mode enabled, not caching classes - EXIT!' . PHP_EOL, __METHOD__, __LINE__);
return;
- } // END - if
+ }
+
+ // Init content
+ $cacheContent = '';
// Skip here if already cached
+ //* NOISY-DEBUG: */ printf('[%s:%d]: this->listCached=%d' . PHP_EOL, __METHOD__, __LINE__, intval($this->listCached));
if ($this->listCached === false) {
// Writes the cache file of our list away
- $cacheContent = json_encode($this->foundClasses);
+ $cacheContent = json_encode($this->pendingFiles);
// Open cache instance
+ //* NOISY-DEBUG: */ printf('[%s:%d]: cacheContent()=%d' . PHP_EOL, __METHOD__, __LINE__, strlen($cacheContent));
$fileObject = $this->listCacheFile->openFile('w');
// And write whole list
$fileObject->fwrite($cacheContent);
- } // END - if
+
+ // Close it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Closing file %s ...' . PHP_EOL, __METHOD__, __LINE__, $fileObject->getPathName());
+ unset($fileObject);
+ }
+
+ // Init content
+ $cacheContent = '';
// Skip here if already cached
+ //* NOISY-DEBUG: */ printf('[%s:%d]: this->classesCached=%d' . PHP_EOL, __METHOD__, __LINE__, intval($this->classesCached));
if ($this->classesCached === false) {
// Generate a full-cache of all classes
- $cacheContent = '';
- foreach (array_keys($this->loadedClasses) as $fileInstance) {
+ //* NOISY-DEBUG: */ printf('[%s:%d]: this->flushCache()=%d' . PHP_EOL, __METHOD__, __LINE__, count($this->flushCache));
+ foreach ($this->flushCache as $key => $fileInstance) {
// Open file
+ //* NOISY-DEBUG: */ printf('[%s:%d]: key=%s,fileInstance[]=%s' . PHP_EOL, __METHOD__, __LINE__, $key, gettype($fileInstance));
$fileObject = $fileInstance->openFile('r');
// Load the file
// @TODO Add some uglifying code (compress) here
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Adding fileInstance->size=%d bytes ...' . PHP_EOL, __METHOD__, __LINE__, $fileInstance->getSize());
$cacheContent .= $fileObject->fread($fileInstance->getSize());
- } // END - foreach
+ }
// Open file
+ //* NOISY-DEBUG: */ printf('[%s:%d]: cacheContent()=%d' . PHP_EOL, __METHOD__, __LINE__, strlen($cacheContent));
$fileObject = $this->classCacheFile->openFile('w');
// And write it away
$fileObject->fwrite($cacheContent);
- } // END - if
- }
-
- /**
- * Creates an instance of this class loader for given configuration instance
- *
- * @param $configInstance Configuration class instance
- * @return void
- */
- public static final function createClassLoader (FrameworkConfiguration $configInstance) {
- // Get a new instance
- $loaderInstance = new ClassLoader();
- // Init the instance
- $loaderInstance->initLoader($configInstance);
+ // Close it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Closing file %s ...' . PHP_EOL, __METHOD__, __LINE__, $fileObject->getPathName());
+ unset($fileObject);
+ }
- // Return the prepared instance
- return $loaderInstance;
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
/**
* @return void
*/
public static function scanFrameworkClasses () {
- // Trace message
- //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
-
// Get loader instance
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
$loaderInstance = self::getSelfInstance();
- // Get config instance
- $configInstance = FrameworkBootstrap::getConfigurationInstance();
+ // "Cache" configuration instance and framework base path
+ $frameworkBasePath = self::$configInstance->getConfigEntry('framework_base_path');
// Load all classes
+ //* NOISY-DEBUG: */ printf('[%s:%d]: frameworkBasePath=%s,self::$frameworkPaths()=%d,' . PHP_EOL, __METHOD__, __LINE__, $frameworkBasePath, count(self::$frameworkPaths));
foreach (self::$frameworkPaths as $shortPath) {
- // Debug message
- //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
-
// Generate full path from it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($shortPath), $shortPath);
$realPathName = realpath(sprintf(
'%smain%s%s%s',
- $configInstance->getConfigEntry('framework_base_path'),
+ $frameworkBasePath,
DIRECTORY_SEPARATOR,
$shortPath,
DIRECTORY_SEPARATOR
));
- // Debug message
- //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName=%s' . PHP_EOL, __METHOD__, __LINE__, $realPathName);
-
// Is it not false and accessible?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($realPathName), $realPathName);
if (is_bool($realPathName)) {
- // Skip this
+ // Skip this, it is not accessible
continue;
} elseif (!is_readable($realPathName)) {
// @TODO Throw exception instead of break
// Try to load the framework classes
$loaderInstance->scanClassPath($realPathName);
- } // END - foreach
+ }
// Trace message
//* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
* Scans for application's classes, etc.
*
* @return void
+ * @throws UnexpectedValueException If a given path isn't one or not readable
*/
public static function scanApplicationClasses () {
- // Trace message
- //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
-
// Get loader instance
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
$loaderInstance = self::getSelfInstance();
- // Get config instance
- $configInstance = FrameworkBootstrap::getConfigurationInstance();
+ // "Cache" application base path
+ $basePath = self::$configInstance->getConfigEntry('application_base_path');
// Load all classes for the application
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::frameworkPaths()=%d,basePath=%s' . PHP_EOL, __METHOD__, __LINE__, count(self::$frameworkPaths), $basePath);
foreach (self::$frameworkPaths as $shortPath) {
- // Debug message
- //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
-
// Create path name
- $pathName = realpath(sprintf(
+ //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
+ $realPathName = realpath(sprintf(
'%s%s%s%s%s',
- $configInstance->getConfigEntry('application_base_path'),
+ $basePath,
DIRECTORY_SEPARATOR,
- $configInstance->getConfigEntry('detected_app_name'),
+ FrameworkBootstrap::getDetectedApplicationName(),
DIRECTORY_SEPARATOR,
$shortPath
));
- // Debug message
- //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
-
// Is the path readable?
- if (is_dir($pathName)) {
- // Try to load the application classes
- $loaderInstance->scanClassPath($pathName);
- } // END - if
- } // END - foreach
-
- // Trace message
- //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
- }
-
- /**
- * Scans for test classes, etc.
- *
- * @return void
- */
- public static function scanTestsClasses () {
- // Trace message
- //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
-
- // Get config instance
- $configInstance = FrameworkBootstrap::getConfigurationInstance();
-
- // Load all classes for the application
- foreach (self::$testPaths as $shortPath) {
- // Debug message
- //* NOISY-DEBUG: */ printf('[%s:%d]: shortPath=%s' . PHP_EOL, __METHOD__, __LINE__, $shortPath);
-
- // Construct path name
- $pathName = sprintf(
- '%s%s%s',
- $configInstance->getConfigEntry('root_base_path'),
- DIRECTORY_SEPARATOR,
- $shortPath
- );
-
- // Debug message
- //* NOISY-DEBUG: */ printf('[%s:%d]: pathName[%s]=%s - BEFORE!' . PHP_EOL, __METHOD__, __LINE__, gettype($pathName), $pathName);
-
- // Try to find it
- $realPathName = realpath($pathName);
-
- // Debug message
//* NOISY-DEBUG: */ printf('[%s:%d]: realPathName[%s]=%s - AFTER!' . PHP_EOL, __METHOD__, __LINE__, gettype($realPathName), $realPathName);
+ if (!is_string($realPathName)) {
+ // Skip this cone
+ //* NOISY-DEBUG: */ printf('[%s:%d]: realPathName[]=%s - SKIPPED!' . PHP_EOL, __METHOD__, __LINE__, gettype($realPathName));
+ continue;
+ } elseif (!is_dir($realPathName)) {
+ // Is not a directory
+ throw new UnexpectedValueException(sprintf('realPathName=%s is not a directory', $realPathName), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ } elseif (!is_readable($realPathName)) {
+ // Not readable
+ throw new UnexpectedValueException(sprintf('realPathName=%s cannot be read from', $realPathName), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
- // Is the path readable?
- if ((is_dir($realPathName)) && (is_readable($realPathName))) {
- // Try to load the application classes
- ClassLoader::getSelfInstance()->scanClassPath($realPathName);
- } // END - if
- } // END - foreach
+ // Try to load the application classes
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Scanning for classes/interfaces at realPathName=%s ...' . PHP_EOL, __METHOD__, __LINE__, $realPathName);
+ $loaderInstance->scanClassPath($realPathName);
+ }
// Trace message
//* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
* @param $strictNamingConvention Whether to strictly check naming-convention
* @return void
*/
- public static function enableStrictNamingConventionCheck ($strictNamingConvention = true) {
+ public static function enableStrictNamingConventionCheck (bool $strictNamingConvention = true) {
self::$strictNamingConvention = $strictNamingConvention;
}
- /**
- * Registeres given relative path where test classes reside. For regular
- * framework uses, they should not be loaded (and used).
- *
- * @param $relativePath Relative path to test classes
- * @return void
- */
- public static function registerTestsPath ($relativePath) {
- // Trace message
- //* NOISY-DEBUG: */ printf('[%s:%d]: relativePath=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $relativePath);
-
- // "Register" it
- self::$testPaths[$relativePath] = $relativePath;
-
- // Trace message
- //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
- }
-
/**
* Autoload-function
*
* @param $className Name of the class to load
* @return void
+ * @throws InvalidArgumentException If the class' name does not contain a namespace: Tld\Domain\Project is AT LEAST recommended!
*/
- public static function autoLoad ($className) {
- // Trace message
- //* NOISY-DEBUG: */ printf('[%s:%d]: className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
+ public static function autoLoad (string $className) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
+ if (empty($className)) {
+ // Should not be empty
+ throw new InvalidArgumentException('Parameter "className" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // The class name MUST be at least Tld\Domain\Project\Package\SomeFooBar so split at them
+ $classNameParts = explode("\\", $className);
+
+ // At least 3 parts should be there
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::strictNamingConvention=%d,classNameParts()=%d' . PHP_EOL, __METHOD__, __LINE__, intval(self::$strictNamingConvention), count($classNameParts));
+ if ((self::$strictNamingConvention === true) && (count($classNameParts) < 5)) {
+ // Namespace scheme is: Tld\Domain\Project\Package[\SubPackage...]
+ throw new InvalidArgumentException(sprintf('Class name "%s" is not conform to naming-convention: Tld\Domain\Project\Package[\SubPackage...]\SomeFooBar', $className));
+ }
// Try to include this class
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Invoking self->loadClassFile(%s) ...' . PHP_EOL, __METHOD__, __LINE__, $className);
self::getSelfInstance()->loadClassFile($className);
// Trace message
*/
public static final function getSelfInstance () {
// Is the instance there?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::selfInstance[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, gettype(self::$selfInstance));
if (is_null(self::$selfInstance)) {
- // Get a new one
- self::$selfInstance = ClassLoader::createClassLoader(FrameworkBootstrap::getConfigurationInstance());
- } // END - if
+ // Get a new one and initialize it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Initializing class loader ...' . PHP_EOL, __METHOD__, __LINE__);
+ self::$selfInstance = new ClassLoader();
+ self::$selfInstance->initClassLoader();
+ }
// Return the instance
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::selfInstance=%s - EXIT!' . PHP_EOL, __METHOD__, __LINE__, get_class(self::$selfInstance));
return self::$selfInstance;
}
+ /**
+ * Getter for total include counter
+ *
+ * @return $total Total loaded include files
+ */
+ public final function getTotal () {
+ return $this->total;
+ }
+
+ /**
+ * Getter for a printable list of included main/interfaces/exceptions
+ *
+ * @param $includeList A printable include list
+ */
+ public function getPrintableIncludeList () {
+ // Prepare the list
+ $includeList = '';
+ foreach (array_keys($this->loadedClasses) as $classFile) {
+ $includeList .= basename($classFile) . '<br />' . PHP_EOL;
+ }
+
+ // And return it
+ return $includeList;
+ }
+
/**
* Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
*
* @param $basePath The relative base path to 'framework_base_path' constant for all classes
* @param $ignoreList An optional list (array forced) of directory and file names which shall be ignored
* @return void
+ * @throws InvalidArgumentException If a parameter is invalid
*/
- public function scanClassPath ($basePath, array $ignoreList = array() ) {
+ protected function scanClassPath (string $basePath, array $ignoreList = [] ) {
// Is a list has been restored from cache, don't read it again
- if ($this->listCached === true) {
+ //* NOISY-DEBUG: */ printf('[%s:%d] basePath=%s,ignoreList()=%d - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $basePath, count($ignoreList));
+ if (empty($basePath)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "basePath" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($this->listCached === true) {
// Abort here
+ //* NOISY-DEBUG: */ printf('[%s:%d] this->listCache=true - EXIT!' . PHP_EOL, __METHOD__, __LINE__);
return;
- } // END - if
-
- // Keep it in class for later usage
- $this->ignoreList = $ignoreList;
+ }
- /*
- * Ignore .htaccess by default as it is for protection of directories
- * on Apache servers.
- */
- array_push($ignoreList, '.htaccess');
+ // Keep it in class for later usage, but flip index<->value
+ $this->ignoreList = array_flip($ignoreList);
/*
* Set base directory which holds all our classes, an absolute path
* should be used here so is_dir(), is_file() and so on will always
* find the correct files and dirs.
*/
- $basePath2 = realpath($basePath);
+ $basePath = realpath($basePath);
// If the basePath is false it is invalid
- if ($basePath2 === false) {
+ //* NOISY-DEBUG: */ printf('[%s:%d] basePath[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($basePath), $basePath);
+ if (!is_string($basePath)) {
/* @TODO: Do not exit here. */
exit(__METHOD__ . ': Cannot read ' . $basePath . ' !' . PHP_EOL);
- } else {
- // Set base path
- $basePath = $basePath2;
}
// Get a new iterator
$currentEntry = $iteratorInstance->current();
// Get filename from iterator which is the class' name (according naming-convention)
+ //* NOISY-DEBUG: */ printf('[%s:%d] currentEntry=%s,currentEntry->size=%d' . PHP_EOL, __METHOD__, __LINE__, $currentEntry->__toString(), $currentEntry->getSize());
$fileName = $currentEntry->getFilename();
// Current entry must be a file, not smaller than 100 bytes and not on ignore list
- if ((!$currentEntry->isFile()) || (in_array($fileName, $this->ignoreList)) || ($currentEntry->getSize() < 100)) {
+ //* NOISY-DEBUG: */ printf('[%s:%d] fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ if (!$currentEntry->isFile() || isset($this->ignoreList[$fileName]) || $currentEntry->getSize() < 100) {
// Advance to next entry
$iteratorInstance->next();
// Skip non-file entries
- //* NOISY-DEBUG: */ printf('[%s:%d] SKIP: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ //* NOISY-DEBUG: */ printf('[%s:%d] SKIP: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
continue;
- } // END - if
+ }
// Is this file wanted?
- //* NOISY-DEBUG: */ printf('[%s:%d] FOUND: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ //* NOISY-DEBUG: */ printf('[%s:%d] FOUND: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
if ((substr($fileName, 0, strlen($this->prefix)) == $this->prefix) && (substr($fileName, -strlen($this->suffix), strlen($this->suffix)) == $this->suffix)) {
// Add it to the list
- //* NOISY-DEBUG: */ printf('[%s:%d] ADD: %s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
- $this->foundClasses[$fileName] = $currentEntry;
+ //* NOISY-DEBUG: */ printf('[%s:%d] ADD: fileName=%s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
+ $this->pendingFiles[$fileName] = $currentEntry;
} else {
// Not added
- //* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: %s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
+ //* NOISY-DEBUG: */ printf('[%s:%d] NOT ADDED: fileName=%s,currentEntry=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName, $currentEntry);
}
// Advance to next entry
- //* NOISY-DEBUG: */ printf('[%s:%d] NEXT: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ //* NOISY-DEBUG: */ printf('[%s:%d] NEXT: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
$iteratorInstance->next();
- } // END - while
- }
-
- /**
- * Getter for total include counter
- *
- * @return $total Total loaded include files
- */
- public final function getTotal () {
- return $this->total;
- }
-
- /**
- * Getter for a printable list of included main/interfaces/exceptions
- *
- * @param $includeList A printable include list
- */
- public function getPrintableIncludeList () {
- // Prepare the list
- $includeList = '';
- foreach ($this->loadedClasses as $classFile) {
- $includeList .= basename($classFile) . '<br />' . PHP_EOL;
- } // END - foreach
+ }
- // And return it
- return $includeList;
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
/**
* Initializes our loader class
*
- * @param $configInstance Configuration class instance
* @return void
*/
- private function initLoader (FrameworkConfiguration $configInstance) {
- // Set configuration instance
- $this->configInstance = $configInstance;
-
- // Construct the FQFN for the cache
- if (!defined('DEVELOPER')) {
- $this->listCacheFile = new SplFileInfo($this->configInstance->getConfigEntry('local_database_path') . 'list-' . $this->configInstance->getConfigEntry('detected_app_name') . '.cache');
- $this->classCacheFile = new SplFileInfo($this->configInstance->getConfigEntry('local_database_path') . 'class-' . $this->configInstance->getConfigEntry('detected_app_name') . '.cache');
- } // END - if
-
+ private function initClassLoader () {
// Set suffix and prefix from configuration
- $this->suffix = $configInstance->getConfigEntry('class_suffix');
- $this->prefix = $configInstance->getConfigEntry('class_prefix');
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
+ $this->suffix = self::$configInstance->getConfigEntry('class_suffix');
+ $this->prefix = self::$configInstance->getConfigEntry('class_prefix');
// Set own instance
+ //* NOISY-DEBUG: */ printf('[%s:%d]: this->suffix=%s,this->prefix=%s' . PHP_EOL, __METHOD__, __LINE__, $this->suffix, $this->prefix);
self::$selfInstance = $this;
// Skip here if no dev-mode
- if (defined('DEVELOPER')) {
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::developerModeEnabled=%d' . PHP_EOL, __METHOD__, __LINE__, intval(self::$developerModeEnabled));
+ if (self::$developerModeEnabled) {
+ // Developer mode is enabled
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Developer mode is enabled - EXIT!' . PHP_EOL, __METHOD__, __LINE__);
return;
- } // END - if
+ }
+
+ // Init cache instances
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Initializing cache file instances ...' . PHP_EOL, __METHOD__, __LINE__);
+ $this->listCacheFile = new SplFileInfo(self::$configInstance->getConfigEntry('local_database_path') . 'list-' . FrameworkBootstrap::getDetectedApplicationName() . '.cache');
+ $this->classCacheFile = new SplFileInfo(self::$configInstance->getConfigEntry('local_database_path') . 'class-' . FrameworkBootstrap::getDetectedApplicationName() . '.cache');
// Is the cache there?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Checking this->listCacheFile=%s ...' . PHP_EOL, __METHOD__, __LINE__, $this->listCacheFile);
if (FrameworkBootstrap::isReadableFile($this->listCacheFile)) {
// Load and convert it
- $this->foundClasses = json_decode(file_get_contents($this->listCacheFile->getPathname()));
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Loading %s ...' . PHP_EOL, __METHOD__, __LINE__, $this->listCacheFile);
+ $this->pendingFiles = json_decode(file_get_contents($this->listCacheFile->getPathname()));
// List has been restored from cache!
$this->listCached = true;
- } // END - if
+ }
// Does the class cache exist?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Checking this->classCacheFile=%s ...' . PHP_EOL, __METHOD__, __LINE__, $this->classCacheFile);
if (FrameworkBootstrap::isReadableFile($this->classCacheFile)) {
// Then include it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Invoking FrameworkBootstrap::loadInclude(%s) ...' . PHP_EOL, __METHOD__, __LINE__, $this->classCacheFile);
FrameworkBootstrap::loadInclude($this->classCacheFile);
// Mark the class cache as loaded
$this->classesCached = true;
- } // END - if
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
/**
- * Tries to find the given class in our list. This method ignores silently
- * missing classes or interfaces. So if you use class_exists() this method
- * does not interrupt your program.
+ * Tries to find the given class in our list. It will ignore already loaded
+ * (to the program available) class/interface/trait files. But you SHOULD
+ * save below "expensive" code by pre-checking this->loadedClasses[], if
+ * possible.
*
* @param $className The class that shall be loaded
* @return void
- * @throws InvalidArgumentException If strict-checking is enabled and class name is not following naming-convention
*/
- private function loadClassFile ($className) {
- // Trace message
- //* NOISY-DEBUG: */ printf('[%s:%d] className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
-
+ private function loadClassFile (string $className) {
// The class name should contain at least 2 back-slashes, so split at them
+ //* NOISY-DEBUG: */ printf('[%s:%d]: className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className);
$classNameParts = explode("\\", $className);
- // At least 3 parts should be there
- if ((self::$strictNamingConvention === true) && (count($classNameParts) < 5)) {
- // Namespace scheme is: Project\Package[\SubPackage...]
- throw new InvalidArgumentException(sprintf('Class name "%s" is not conform to naming-convention: Tld\Domain\Project\Package[\SubPackage...]\SomeFooBar', $className));
- } // END - if
-
// Get last element
+ //* NOISY-DEBUG: */ printf('[%s:%d]: classNameParts()=%d' . PHP_EOL, __METHOD__, __LINE__, count($classNameParts));
$shortClassName = array_pop($classNameParts);
// Create a name with prefix and suffix
+ //* NOISY-DEBUG: */ printf('[%s:%d]: this->prefix=%s,shortClassName=%s,this->suffix=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $this->prefix, $shortClassName, $this->suffix);
$fileName = sprintf('%s%s%s', $this->prefix, $shortClassName, $this->suffix);
// Now look it up in our index
- //* NOISY-DEBUG: */ printf('[%s:%d] ISSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
- if ((isset($this->foundClasses[$fileName])) && (!isset($this->loadedClasses[$this->foundClasses[$fileName]->getPathname()]))) {
+ //* DEBUG-DIE: */ die(sprintf('[%s:%d]: this->pendingFiles=%s', __METHOD__, __LINE__, print_r($this->pendingFiles, TRUE)));
+ //* NOISY-DEBUG: */ printf('[%s:%d] ISSET: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ if ((isset($this->pendingFiles[$fileName])) && (!isset($this->loadedClasses[$this->pendingFiles[$fileName]->getPathname()]))) {
// File is found and not loaded so load it only once
- //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
- FrameworkBootstrap::loadInclude($this->foundClasses[$fileName]);
- //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: %s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: fileName=%s - START' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ FrameworkBootstrap::loadInclude($this->pendingFiles[$fileName]);
+ //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: fileName=%s - END' . PHP_EOL, __METHOD__, __LINE__, $fileName);
// Count this loaded class/interface/exception
$this->total++;
// Mark this class as loaded for other purposes than loading it.
- $this->loadedClasses[$this->foundClasses[$fileName]->getPathname()] = true;
-
- // Remove it from classes list so it won't be found twice.
- //* NOISY-DEBUG: */ printf('[%s:%d] UNSET: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
- unset($this->foundClasses[$fileName]);
+ //* NOISY-DEBUG: */ printf('[%s:%d] LOAD: fileName=%s marked as loaded ...' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ $this->loadedClasses[$this->pendingFiles[$fileName]->getPathname()] = true;
// Developer mode excludes caching (better debugging)
- if (!defined('DEVELOPER')) {
- // Reset cache
- //* NOISY-DEBUG: */ printf('[%s:%d] classesCached=false' . PHP_EOL, __METHOD__, __LINE__);
+ //* NOISY-DEBUG: */ printf('[%s:%d] self::developerModeEnabled=%d' . PHP_EOL, __METHOD__, __LINE__, intval(self::$developerModeEnabled));
+ if (!self::$developerModeEnabled) {
+ // Reset cache and mark file for flushing
+ //* NOISY-DEBUG: */ printf('[%s:%d] Setting this->classesCached=false ...' . PHP_EOL, __METHOD__, __LINE__);
$this->classesCached = false;
- } // END - if
+ $this->flushCache[$fileName] = $this->pendingFiles[$fileName];
+ }
+
+ // Remove it from classes list so it won't be found twice.
+ //* NOISY-DEBUG: */ printf('[%s:%d] UNSET: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ unset($this->pendingFiles[$fileName]);
} else {
// Not found
- //* NOISY-DEBUG: */ printf('[%s:%d] 404: %s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
+ //* NOISY-DEBUG: */ printf('[%s:%d] 404: fileName=%s' . PHP_EOL, __METHOD__, __LINE__, $fileName);
}
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d] EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
}
<?php
// Own namespace
-namespace CoreFramework\Action\!!!;
+namespace Org\Mxchange\CoreFramework\Action\!!!;
// Import framework stuff
use Org\Mxchange\CoreFramework\Action\BaseAction;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
/**
* An action for ???
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @todo 0% done
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
- $this->partialStub("You have to implement me.");
+ DebugMiddleware::getSelfInstance()->partialStub("You have to implement me.");
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+use Org\Mxchange\CoreFramework\Traits\Resolver\ResolverTrait;
/**
* A general action class. You shall extend this class if you are going to write
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseAction extends BaseFrameworkSystem {
+ // Load traits
+ use ResolverTrait;
+
/**
* Protected constructor
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
use Org\Mxchange\CoreFramework\Action\BaseAction;
use Org\Mxchange\CoreFramework\Action\PerformableAction;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Registry\Registerable;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public static final function createHtmlLoginProfileAction (ActionResolver $resolverInstance) {
// Get a new instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('HTML-LOGIN-PROFILE-ACTION: resolverInstance=%s - CALLED!', $resolverInstance->__toString()));
$actionInstance = new HtmlLoginProfileAction();
// Set the resolver instance
$actionInstance->setResolverInstance($resolverInstance);
// Return the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('HTML-LOGIN-PROFILE-ACTION: actionInstance=%s - EXIT!', $actionInstance->__toString()));
return $actionInstance;
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Dummy method
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('HTML-LOGIN-PROFILE-ACTION: requestInstance=%s,responseInstance=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString()));
}
/**
*/
public function addExtraFilters (Controller $controllerInstance, Requestable $requestInstance) {
// Add user status filter here
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('HTML-LOGIN-PROFILE-ACTION: controllerInstance=%s,requestInstance=%s - CALLED!', $controllerInstance->__toString(), $requestInstance->__toString()));
$controllerInstance->addPreFilter(ObjectFactory::createObjectByConfiguredName('user_status_filter_class'));
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('HTML-LOGIN-PROFILE-ACTION: EXIT!');
}
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public static final function createLoginAfterRegistrationAction () {
// Get a new instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('LOGIN-REGISTRATION-ACTION: CALLED!');
$actionInstance = new LoginAfterRegistrationAction();
// Return the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('LOGIN-REGISTRATION-ACTION: actionInstance=%s - EXIT!', $actionInstance->__toString()));
return $actionInstance;
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Get a login class from factory
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('LOGIN-REGISTRATION-ACTION: requestInstance=%s,responseInstance=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString()));
$loginInstance = LoginFactory::createLoginObjectByRequest($requestInstance);
// Login the user by the request instance
// Attach error message to the response
$responseInstance->addFatalMessage('failed_login_after_registration');
}
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('LOGIN-REGISTRATION-ACTION: EXIT!');
}
}
namespace Org\Mxchange\CoreFramework\Application;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Controller\Controller;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
+use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
/**
* A general application class for the ApplicationHelper classes.
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseApplication extends BaseFrameworkSystem {
+ /**
+ * The version number of this application
+ */
+ private $appVersion = '';
+
+ /**
+ * The human-readable name for this application
+ */
+ private $appName = '';
+
+ /**
+ * The short uni*-like name for this application
+ */
+ private $shortName = '';
+
+ /**
+ * Own singleton instance of this application helper
+ */
+ private static $applicationInstance = NULL;
+
+ /**
+ * A controller instance
+ */
+ private $controllerInstance = NULL;
+
/**
* Protected constructor
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
+ }
+
+ /**
+ * Getter for own instance
+ *
+ * @return $applicationInstance An instance of a ManageableApplication class
+ */
+ public static final function getApplicationInstance () {
+ return self::$applicationInstance;
+ }
+
+ /**
+ * Setter for own instance
+ *
+ * @param $applicationInstance An instance of a ManageableApplication class
+ */
+ public static final function setApplicationInstance (ManageableApplication $applicationInstance) {
+ self::$applicationInstance = $applicationInstance;
+ }
+
+ /**
+ * Setter for controller instance (this surely breaks a bit the MVC patterm)
+ *
+ * @param $controllerInstance An instance of the controller
+ * @return void
+ */
+ public final function setControllerInstance (Controller $controllerInstance) {
+ $this->controllerInstance = $controllerInstance;
+ }
+
+ /**
+ * Getter for controller instance (this surely breaks a bit the MVC patterm)
+ *
+ * @return $controllerInstance An instance of the controller
+ */
+ public final function getControllerInstance () {
+ return $this->controllerInstance;
+ }
+
+ /**
+ * Getter for the version number
+ *
+ * @return $appVersion The application's version number
+ */
+ public final function getAppVersion () {
+ return $this->appVersion;
+ }
+
+ /**
+ * Setter for the version number
+ *
+ * @param $appVersion The application's version number
+ * @return void
+ */
+ public final function setAppVersion (string $appVersion) {
+ // Cast and set it
+ $this->appVersion = $appVersion;
+ }
+
+ /**
+ * Getter for human-readable name
+ *
+ * @return $appName The application's human-readable name
+ */
+ public final function getAppName () {
+ return $this->appName;
+ }
- // Set this instance as application instance
- GenericRegistry::getRegistry()->addInstance('application', $this);
+ /**
+ * Setter for human-readable name
+ *
+ * @param $appName The application's human-readable name
+ * @return void
+ */
+ public final function setAppName (string $appName) {
+ // Cast and set it
+ $this->appName = $appName;;
+ }
+
+ /**
+ * Getter for short uni*-like name
+ *
+ * @return $shortName The application's short uni*-like name
+ */
+ public final function getAppShortName () {
+ return $this->shortName;
+ }
+
+ /**
+ * Setter for short uni*-like name
+ *
+ * @param $shortName The application's short uni*-like name
+ * @return void
+ */
+ public final function setAppShortName (string $shortName) {
+ // Cast and set it
+ $this->shortName = $shortName;
}
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @param $userName The username from request we shall set
* @return void
*/
- public function setUserAuth ($userName) {
+ public function setUserAuth (string $userName) {
FrameworkBootstrap::getResponseInstance()->addCookie('username', $userName);
}
* @param $passHash The hashed password from request we shall set
* @return void
*/
- public function setPasswordAuth ($passHash) {
+ public function setPasswordAuth (string $passHash) {
FrameworkBootstrap::getResponseInstance()->addCookie('u_hash', $passHash);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @todo Rename to InProgressCache
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Not found
$exists = false;
}
- } // END - if
+ }
// Return status
return $exists;
if ($this->offsetExists($offset)) {
// Then get the data from it
$data = $this->dataCache->offsetGet($offset);
- } // END - if
+ }
// Return data
return $data;
// Purge only existing keys
//* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHE: Unsetting cache ' . $offset);
$this->dataCache->offsetUnset($offset);
- } // END - if
+ }
}
}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\Compressor\Compressor;
-use Org\Mxchange\CoreFramework\Configuration\FrameworkConfiguration;
-use Org\Mxchange\CoreFramework\Connection\Database\DatabaseConnection;
-use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Criteria\Criteria;
-use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
-use Org\Mxchange\CoreFramework\Criteria\Local\LocalUpdateCriteria;
-use Org\Mxchange\CoreFramework\Crypto\Cryptable;
-use Org\Mxchange\CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
-use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseWrapper;
use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
-use Org\Mxchange\CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Filesystem\Block;
-use Org\Mxchange\CoreFramework\Filesystem\FilePointer;
-use Org\Mxchange\CoreFramework\Filesystem\FrameworkDirectory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Filesystem\FileIoException;
use Org\Mxchange\CoreFramework\Filesystem\PathWriteProtectedException;
use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
-use Org\Mxchange\CoreFramework\Handler\Handleable;
-use Org\Mxchange\CoreFramework\Handler\Stream\IoHandler;
-use Org\Mxchange\CoreFramework\Helper\Helper;
-use Org\Mxchange\CoreFramework\Index\Indexable;
-use Org\Mxchange\CoreFramework\Lists\Listable;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Loader\ClassLoader;
-use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
-use Org\Mxchange\CoreFramework\Menu\RenderableMenu;
-use Org\Mxchange\CoreFramework\Middleware\Compressor\CompressorChannel;
use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
-use Org\Mxchange\CoreFramework\Parser\Parseable;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
-use Org\Mxchange\CoreFramework\Registry\Register;
-use Org\Mxchange\CoreFramework\Resolver\Resolver;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Result\Database\CachedDatabaseResult;
-use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
-use Org\Mxchange\CoreFramework\Stacker\Stackable;
use Org\Mxchange\CoreFramework\State\Stateable;
-use Org\Mxchange\CoreFramework\Stream\Input\InputStream;
use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
-use Org\Mxchange\CoreFramework\Stream\Output\OutputStream;
-use Org\Mxchange\CoreFramework\String\Utils\StringUtils;
-use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
-use Org\Mxchange\CoreFramework\User\ManageableAccount;
-use Org\Mxchange\CoreFramework\Visitor\Visitor;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
// Import SPL stuff
-use \stdClass;
+use \BadMethodCallException;
use \InvalidArgumentException;
-use \Iterator;
use \ReflectionClass;
use \SplFileInfo;
+use \stdClass;
/**
* The simulator system class is the super class of all other classes. This
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*/
abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
/**
- * Length of output from hash()
- */
- private static $hashLength = NULL;
-
- /**
- * The real class name
- */
- private $realClass = 'BaseFrameworkSystem';
-
- /**
- * Search criteria instance
- */
- private $searchInstance = NULL;
-
- /**
- * Update criteria instance
- */
- private $updateInstance = NULL;
-
- /**
- * The file I/O instance for the template loader
- */
- private $fileIoInstance = NULL;
-
- /**
- * Resolver instance
- */
- private $resolverInstance = NULL;
-
- /**
- * Template engine instance
- */
- private $templateInstance = NULL;
-
- /**
- * Database result instance
- */
- private $resultInstance = NULL;
-
- /**
- * Instance for user class
- */
- private $userInstance = NULL;
-
- /**
- * A controller instance
- */
- private $controllerInstance = NULL;
-
- /**
- * Instance of a RNG
- */
- private $rngInstance = NULL;
-
- /**
- * Instance of a crypto helper
- */
- private $cryptoInstance = NULL;
-
- /**
- * Instance of an Iterator class
- */
- private $iteratorInstance = NULL;
-
- /**
- * Instance of the list
- */
- private $listInstance = NULL;
-
- /**
- * Instance of a menu
- */
- private $menuInstance = NULL;
-
- /**
- * Instance of the image
- */
- private $imageInstance = NULL;
-
- /**
- * Instance of the stacker
- */
- private $stackInstance = NULL;
-
- /**
- * A Compressor instance
- */
- private $compressorInstance = NULL;
-
- /**
- * A Parseable instance
- */
- private $parserInstance = NULL;
-
- /**
- * A database wrapper instance
- */
- private $databaseInstance = NULL;
-
- /**
- * A helper instance for the form
- */
- private $helperInstance = NULL;
-
- /**
- * An instance of a InputStream class
- */
- private $inputStreamInstance = NULL;
-
- /**
- * An instance of a OutputStream class
- */
- private $outputStreamInstance = NULL;
-
- /**
- * Handler instance
- */
- private $handlerInstance = NULL;
-
- /**
- * Visitor handler instance
- */
- private $visitorInstance = NULL;
-
- /**
- * An instance of a database wrapper class
- */
- private $wrapperInstance = NULL;
-
- /**
- * An instance of a file I/O pointer class (not handler)
- */
- private $pointerInstance = NULL;
-
- /**
- * An instance of an Indexable class
- */
- private $indexInstance = NULL;
-
- /**
- * An instance of a Block class
- */
- private $blockInstance = NULL;
-
- /**
- * A Minable instance
- */
- private $minableInstance = NULL;
-
- /**
- * A FrameworkDirectory instance
+ * Self-referencing instance
*/
- private $directoryInstance = NULL;
+ private static $selfInstance = NULL;
/**
- * The concrete output instance
+ * Debug instance
*/
- private $outputInstance = NULL;
+ private static $debugInstance = NULL;
/**
- * State instance
+ * Stub methods
*/
- private $stateInstance = NULL;
+ private static $stubMethods = [
+ 'partialStub' => true,
+ '__call' => true,
+ '__callStatic' => true,
+ ];
/**
- * Registry instance (implementing Register)
+ * The real class name
*/
- private $registryInstance = NULL;
+ private $realClass = __CLASS__;
/**
* Call-back instance
*/
private $callbackInstance = NULL;
- /**
- * Thousands separator
- */
- private $thousands = '.'; // German
-
- /**
- * Decimal separator
- */
- private $decimals = ','; // German
-
- /**
- * Socket resource
- */
- private $socketResource = false;
-
/**
* Generic array
*/
- private $genericArray = array();
-
- /**
- * Command name
- */
- private $commandName = '';
-
- /**
- * Controller name
- */
- private $controllerName = '';
-
- /**
- * Array with bitmasks and such for pack/unpack methods to support both
- * 32-bit and 64-bit systems
- */
- private $packingData = array(
- 32 => array(
- 'step' => 3,
- 'left' => 0xffff0000,
- 'right' => 0x0000ffff,
- 'factor' => 16,
- 'format' => 'II',
- ),
- 64 => array(
- 'step' => 7,
- 'left' => 0xffffffff00000000,
- 'right' => 0x00000000ffffffff,
- 'factor' => 32,
- 'format' => 'NN'
- )
- );
-
- /**
- * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
- *
- * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
- */
- private $archArrayElement = false;
+ private $genericArray = [];
/***********************
* Exception codes.... *
***********************/
// @todo Try to clean these constants up
- const EXCEPTION_IS_NULL_POINTER = 0x001;
const EXCEPTION_IS_NO_OBJECT = 0x002;
const EXCEPTION_IS_NO_ARRAY = 0x003;
const EXCEPTION_MISSING_METHOD = 0x004;
const EXCEPTION_DIR_POINTER_INVALID = 0x019;
const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
const EXCEPTION_INVALID_RESOURCE = 0x01b;
- const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
const EXCEPTION_GETTER_IS_MISSING = 0x01e;
const EXCEPTION_ARRAY_EXPECTED = 0x01f;
const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
- const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
- const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
- const EXCEPTION_MISSING_ELEMENT = 0x030;
- const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
- const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
- const EXCEPTION_CLASS_NOT_FOUND = 0x033;
- const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
- const EXCEPTION_FATAL_ERROR = 0x035;
- const EXCEPTION_FILE_NOT_FOUND = 0x036;
- const EXCEPTION_ASSERTION_FAILED = 0x037;
- const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
- const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
- const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
- const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
- const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
- const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
- const EXCEPTION_INVALID_SOCKET = 0x03e;
-
- /**
- * Hexadecimal->Decimal translation array
- */
- private static $hexdec = array(
- '0' => 0,
- '1' => 1,
- '2' => 2,
- '3' => 3,
- '4' => 4,
- '5' => 5,
- '6' => 6,
- '7' => 7,
- '8' => 8,
- '9' => 9,
- 'a' => 10,
- 'b' => 11,
- 'c' => 12,
- 'd' => 13,
- 'e' => 14,
- 'f' => 15
- );
-
- /**
- * Decimal->hexadecimal translation array
- */
- private static $dechex = array(
- 0 => '0',
- 1 => '1',
- 2 => '2',
- 3 => '3',
- 4 => '4',
- 5 => '5',
- 6 => '6',
- 7 => '7',
- 8 => '8',
- 9 => '9',
- 10 => 'a',
- 11 => 'b',
- 12 => 'c',
- 13 => 'd',
- 14 => 'e',
- 15 => 'f'
- );
+ const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02e;
+ const EXCEPTION_MISSING_ELEMENT = 0x02f;
+ const EXCEPTION_HEADERS_ALREADY_SENT = 0x030;
+ const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x031;
+ const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x033;
+ const EXCEPTION_FATAL_ERROR = 0x034;
+ const EXCEPTION_FILE_NOT_FOUND = 0x035;
+ const EXCEPTION_ASSERTION_FAILED = 0x036;
+ const EXCEPTION_FILE_NOT_REACHABLE = 0x037;
+ const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
+ const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x039;
+ const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03a;
+ const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03b;
+ const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03c;
+ const EXCEPTION_INVALID_SOCKET = 0x03d;
+ const EXCEPTION_SELF_INSTANCE = 0x03e;
/**
* Startup time in miliseconds
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Set real class
$this->setRealClass($className);
- // Set configuration instance if no registry ...
- if (!$this instanceof Register) {
- // ... because registries doesn't need to be configured
- $this->setConfigInstance(FrameworkBootstrap::getConfigurationInstance());
- } // END - if
-
// Is the startup time set? (0 cannot be true anymore)
if (self::$startupTime == 0) {
// Then set it
self::$startupTime = microtime(true);
- } // END - if
-
- // Set array element
- $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
+ }
}
/**
* @return void
*/
public function __destruct () {
- // Flush any updated entries to the database
- $this->flushPendingUpdates();
-
// Is this object already destroyed?
if ($this->__toString() != 'DestructedObject') {
// Destroy all informations about this class but keep some text about it alive
$this->setRealClass('DestructedObject');
} elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
// Already destructed object
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
+ self::createDebugInstance(__CLASS__, __LINE__)->warningMessage(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
$this->__toString()
));
} else {
// Do not call this twice
trigger_error(__METHOD__ . ': Called twice.');
- exit;
+ exit(255);
}
}
* @args $args Arguments passed to the method
* @return void
*/
- public final function __call ($methodName, $args) {
- return self::__callStatic($methodName, $args);
+ public final function __call (string $methodName, array $args = NULL) {
+ // Set self-instance
+ self::$selfInstance = $this;
+
+ // Call static method
+ self::__callStatic($methodName, $args);
+
+ // Clear self-instance
+ self::$selfInstance = NULL;
}
/**
* The __callStatic() method where all non-implemented static methods end up
*
* @param $methodName Name of the missing method
- * @args $args Arguments passed to the method
+ * @param $args Arguments passed to the method
* @return void
+ * @throws InvalidArgumentException If self::$selfInstance is not a framework's own object
*/
- public static final function __callStatic ($methodName, $args) {
- // Trace message
+ public static final function __callStatic (string $methodName, array $args = NULL) {
+ // Init argument string and class name
//* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
-
- // Init argument string
$argsString = '';
+ $className = 'unknown';
+
+ // Is self-instance set?
+ if (self::$selfInstance instanceof FrameworkInterface) {
+ // Framework's own instance
+ $className = self::$selfInstance->__toString();
+ } elseif (!is_null(self::$selfInstance)) {
+ // Invalid argument!
+ throw new InvalidArgumentException(sprintf('self::instance[%s] is not expected.', gettype(self::$selfInstance)), self::EXCEPTION_SELF_INSTANCE);
+ }
// Is it NULL, empty or an array?
if (is_null($args)) {
// Comma for next one
$argsString .= ', ';
- } // END - foreach
+ }
- // Remove last comma
+ // Last comma found?
if (substr($argsString, -2, 1) == ',') {
+ // Remove last comma
$argsString = substr($argsString, 0, -2);
- } // END - if
+ }
// Close braces
$argsString .= ')';
- } else {
- // Invalid arguments!
- $argsString = '!INVALID:' . gettype($args) . '!';
}
// Output stub message
// @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
+ self::createDebugInstance(__CLASS__, __LINE__)->warningMessage(sprintf('[%s::%s]: Stub! Args: %s',
+ $className,
$methodName,
$argsString
));
* @param $value Value to store
* @return void
*/
- public final function __set ($name, $value) {
+ public final function __set (string $name, $value) {
$this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
$name,
gettype($value),
* @param $name Name of the field/attribute
* @return void
*/
- public final function __get ($name) {
+ public final function __get (string $name) {
$this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
$name
));
* @param $name Name of the field/attribute
* @return void
*/
- public final function __unset ($name) {
+ public final function __unset (string $name) {
$this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
$name
));
* @throws UnsupportedOperationException Objects of this framework cannot be serialized
*/
public final function __sleep () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException Objects of this framework cannot be serialized
*/
public final function __wakeup () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException Objects of this framework cannot be serialized
*/
public final function __invoke () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @param $realClass Class name (string)
* @return void
*/
- public final function setRealClass ($realClass) {
+ public final function setRealClass (string $realClass) {
// Set real class
- $this->realClass = (string) $realClass;
- }
-
- /**
- * Setter for database result instance
- *
- * @param $resultInstance An instance of a database result class
- * @return void
- * @todo SearchableResult and UpdateableResult shall have a super interface to use here
- */
- protected final function setResultInstance (SearchableResult $resultInstance) {
- $this->resultInstance = $resultInstance;
- }
-
- /**
- * Getter for database result instance
- *
- * @return $resultInstance An instance of a database result class
- */
- public final function getResultInstance () {
- return $this->resultInstance;
- }
-
- /**
- * Setter for template engine instances
- *
- * @param $templateInstance An instance of a template engine class
- * @return void
- */
- protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
- $this->templateInstance = $templateInstance;
- }
-
- /**
- * Getter for template engine instances
- *
- * @return $templateInstance An instance of a template engine class
- */
- protected final function getTemplateInstance () {
- return $this->templateInstance;
- }
-
- /**
- * Setter for search instance
- *
- * @param $searchInstance Searchable criteria instance
- * @return void
- */
- public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
- $this->searchInstance = $searchInstance;
- }
-
- /**
- * Getter for search instance
- *
- * @return $searchInstance Searchable criteria instance
- */
- public final function getSearchInstance () {
- return $this->searchInstance;
- }
-
- /**
- * Setter for update instance
- *
- * @param $updateInstance An instance of a LocalUpdateCriteria clase
- * @return void
- */
- public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
- $this->updateInstance = $updateInstance;
- }
-
- /**
- * Getter for update instance
- *
- * @return $updateInstance Updateable criteria instance
- */
- public final function getUpdateInstance () {
- return $this->updateInstance;
- }
-
- /**
- * Setter for resolver instance
- *
- * @param $resolverInstance Instance of a command resolver class
- * @return void
- */
- public final function setResolverInstance (Resolver $resolverInstance) {
- $this->resolverInstance = $resolverInstance;
- }
-
- /**
- * Getter for resolver instance
- *
- * @return $resolverInstance Instance of a command resolver class
- */
- public final function getResolverInstance () {
- return $this->resolverInstance;
- }
-
- /**
- * Setter for language instance
- *
- * @param $configInstance The configuration instance which shall
- * be FrameworkConfiguration
- * @return void
- */
- public final function setConfigInstance (FrameworkConfiguration $configInstance) {
- GenericRegistry::getRegistry()->addInstance('config', $configInstance);
- }
-
- /**
- * Getter for configuration instance
- *
- * @return $configInstance Configuration instance
- */
- public final function getConfigInstance () {
- $configInstance = GenericRegistry::getRegistry()->getInstance('config');
- return $configInstance;
+ $this->realClass = $realClass;
}
/**
* @return void
*/
public final function setDebugInstance (DebugMiddleware $debugInstance) {
- GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
+ self::$debugInstance = $debugInstance;
}
/**
* @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
*/
public final function getDebugInstance () {
- // Get debug instance
- $debugInstance = GenericRegistry::getRegistry()->getInstance('debug');
-
- // Return it
- return $debugInstance;
+ return self::$debugInstance;
}
/**
* @return void
*/
public final function setWebOutputInstance (OutputStreamer $webInstance) {
- GenericRegistry::getRegistry()->addInstance('web_output', $webInstance);
+ ObjectRegistry::getRegistry('generic')->addInstance('web_output', $webInstance);
}
/**
* @return $webOutputInstance - Instance to class WebOutput
*/
public final function getWebOutputInstance () {
- $webOutputInstance = GenericRegistry::getRegistry()->getInstance('web_output');
- return $webOutputInstance;
+ return ObjectRegistry::getRegistry('generic')->getInstance('web_output');
}
/**
- * Setter for database instance
+ * Setter for call-back instance
*
- * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
+ * @param $callbackInstance An instance of a FrameworkInterface class
* @return void
*/
- public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
- GenericRegistry::getRegistry()->addInstance('db_instance', $databaseInstance);
+ public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
+ $this->callbackInstance = $callbackInstance;
}
/**
- * Getter for database layer
+ * Getter for call-back instance
*
- * @return $databaseInstance The database layer instance
+ * @return $callbackInstance An instance of a FrameworkInterface class
*/
- public final function getDatabaseInstance () {
- // Get instance
- $databaseInstance = GenericRegistry::getRegistry()->getInstance('db_instance');
-
- // Return instance
- return $databaseInstance;
+ protected final function getCallbackInstance () {
+ return $this->callbackInstance;
}
/**
- * Setter for compressor channel
+ * Checks whether an object equals this object. You should overwrite this
+ * method to implement own equality checks
*
- * @param $compressorInstance An instance of CompressorChannel
- * @return void
+ * @param $objectInstance An instance of a FrameworkInterface object
+ * @return $equals Whether both objects equals
*/
- public final function setCompressorChannel (CompressorChannel $compressorInstance) {
- GenericRegistry::getRegistry()->addInstance('compressor', $compressorInstance);
- }
+ public function equals (FrameworkInterface $objectInstance) {
+ // Now test it
+ $equals = ((
+ $this->__toString() == $objectInstance->__toString()
+ ) && (
+ $this->hashCode() == $objectInstance->hashCode()
+ ));
- /**
- * Getter for compressor channel
- *
- * @return $compressorInstance The compressor channel
- */
- public final function getCompressorChannel () {
- $compressorInstance = GenericRegistry::getRegistry()->getInstance('compressor');
- return $compressorInstance;
+ // Return the result
+ return $equals;
}
/**
- * Private getter for language instance
+ * Generates a generic hash code of this class. You should really overwrite
+ * this method with your own hash code generator code. But keep KISS in mind.
*
- * @return $langInstance An instance to the language sub-system
+ * @return $hashCode A generic hash code respresenting this whole class
*/
- protected final function getLanguageInstance () {
- $langInstance = GenericRegistry::getRegistry()->getInstance('language');
- return $langInstance;
+ public function hashCode () {
+ // Simple hash code
+ return crc32($this->__toString());
}
/**
- * Setter for language instance
+ * Appends a trailing slash to a string
*
- * @param $langInstance An instance to the language sub-system
- * @return void
- * @see LanguageSystem
- */
- public final function setLanguageInstance (ManageableLanguage $langInstance) {
- GenericRegistry::getRegistry()->addInstance('language', $langInstance);
- }
+ * @param $str A string (maybe) without trailing slash
+ * @return $str A string with an auto-appended trailing slash
+ * @throws InvalidArgumentException If a paramter has an invalid value
+ */
+ public final function addMissingTrailingSlash (string $str) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FRAMEWORK-SYSTEM: str=%s - CALLED!', $str));
+ if (empty($str)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "str" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
- /**
- * Private getter for file IO instance
- *
- * @return $fileIoInstance An instance to the file I/O sub-system
- */
- protected final function getFileIoInstance () {
- return $this->fileIoInstance;
- }
+ // Is there a trailing slash?
+ if (substr($str, -1, 1) != '/') {
+ $str .= '/';
+ }
- /**
- * Setter for file I/O instance
- *
- * @param $fileIoInstance An instance to the file I/O sub-system
- * @return void
- */
- public final function setFileIoInstance (IoHandler $fileIoInstance) {
- $this->fileIoInstance = $fileIoInstance;
+ // Return string with trailing slash
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FRAMEWORK-SYSTEM: str=%s - EXIT!', $str));
+ return $str;
}
/**
- * Protected setter for user instance
+ * Debugs this instance by putting out it's full content
*
- * @param $userInstance An instance of a user class
+ * @param $message Optional message to show in debug output
* @return void
+ * @throws InvalidArgumentException If a paramter has an invalid value
*/
- protected final function setUserInstance (ManageableAccount $userInstance) {
- $this->userInstance = $userInstance;
- }
+ public final function debugInstance (string $message = '') {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FRAMEWORK-SYSTEM: message=%s - CALLED!', $message));
+ if (empty($message)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "message" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
- /**
- * Getter for user instance
- *
- * @return $userInstance An instance of a user class
- */
- public final function getUserInstance () {
- return $this->userInstance;
- }
-
- /**
- * Setter for controller instance (this surely breaks a bit the MVC patterm)
- *
- * @param $controllerInstance An instance of the controller
- * @return void
- */
- public final function setControllerInstance (Controller $controllerInstance) {
- $this->controllerInstance = $controllerInstance;
- }
-
- /**
- * Getter for controller instance (this surely breaks a bit the MVC patterm)
- *
- * @return $controllerInstance An instance of the controller
- */
- public final function getControllerInstance () {
- return $this->controllerInstance;
- }
-
- /**
- * Setter for RNG instance
- *
- * @param $rngInstance An instance of a random number generator (RNG)
- * @return void
- */
- protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
- $this->rngInstance = $rngInstance;
- }
-
- /**
- * Getter for RNG instance
- *
- * @return $rngInstance An instance of a random number generator (RNG)
- */
- public final function getRngInstance () {
- return $this->rngInstance;
- }
-
- /**
- * Setter for Cryptable instance
- *
- * @param $cryptoInstance An instance of a Cryptable class
- * @return void
- */
- protected final function setCryptoInstance (Cryptable $cryptoInstance) {
- $this->cryptoInstance = $cryptoInstance;
- }
-
- /**
- * Getter for Cryptable instance
- *
- * @return $cryptoInstance An instance of a Cryptable class
- */
- public final function getCryptoInstance () {
- return $this->cryptoInstance;
- }
-
- /**
- * Setter for the list instance
- *
- * @param $listInstance A list of Listable
- * @return void
- */
- protected final function setListInstance (Listable $listInstance) {
- $this->listInstance = $listInstance;
- }
-
- /**
- * Getter for the list instance
- *
- * @return $listInstance A list of Listable
- */
- protected final function getListInstance () {
- return $this->listInstance;
- }
-
- /**
- * Setter for the menu instance
- *
- * @param $menuInstance A RenderableMenu instance
- * @return void
- */
- protected final function setMenuInstance (RenderableMenu $menuInstance) {
- $this->menuInstance = $menuInstance;
- }
-
- /**
- * Getter for the menu instance
- *
- * @return $menuInstance A RenderableMenu instance
- */
- protected final function getMenuInstance () {
- return $this->menuInstance;
- }
-
- /**
- * Setter for image instance
- *
- * @param $imageInstance An instance of an image
- * @return void
- */
- public final function setImageInstance (BaseImage $imageInstance) {
- $this->imageInstance = $imageInstance;
- }
-
- /**
- * Getter for image instance
- *
- * @return $imageInstance An instance of an image
- */
- public final function getImageInstance () {
- return $this->imageInstance;
- }
-
- /**
- * Setter for stacker instance
- *
- * @param $stackInstance An instance of an stacker
- * @return void
- */
- public final function setStackInstance (Stackable $stackInstance) {
- $this->stackInstance = $stackInstance;
- }
-
- /**
- * Getter for stacker instance
- *
- * @return $stackInstance An instance of an stacker
- */
- public final function getStackInstance () {
- return $this->stackInstance;
- }
-
- /**
- * Setter for compressor instance
- *
- * @param $compressorInstance An instance of an compressor
- * @return void
- */
- public final function setCompressorInstance (Compressor $compressorInstance) {
- $this->compressorInstance = $compressorInstance;
- }
-
- /**
- * Getter for compressor instance
- *
- * @return $compressorInstance An instance of an compressor
- */
- public final function getCompressorInstance () {
- return $this->compressorInstance;
- }
-
- /**
- * Setter for Parseable instance
- *
- * @param $parserInstance An instance of an Parseable
- * @return void
- */
- public final function setParserInstance (Parseable $parserInstance) {
- $this->parserInstance = $parserInstance;
- }
-
- /**
- * Getter for Parseable instance
- *
- * @return $parserInstance An instance of an Parseable
- */
- public final function getParserInstance () {
- return $this->parserInstance;
- }
-
- /**
- * Setter for DatabaseWrapper instance
- *
- * @param $wrapperInstance An instance of an DatabaseWrapper
- * @return void
- */
- public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
- $this->wrapperInstance = $wrapperInstance;
- }
-
- /**
- * Getter for DatabaseWrapper instance
- *
- * @return $wrapperInstance An instance of an DatabaseWrapper
- */
- public final function getWrapperInstance () {
- return $this->wrapperInstance;
- }
-
- /**
- * Setter for socket resource
- *
- * @param $socketResource A valid socket resource
- * @return void
- */
- public final function setSocketResource ($socketResource) {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
- $this->socketResource = $socketResource;
- }
-
- /**
- * Getter for socket resource
- *
- * @return $socketResource A valid socket resource
- */
- public final function getSocketResource () {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
- return $this->socketResource;
- }
-
- /**
- * Setter for helper instance
- *
- * @param $helperInstance An instance of a helper class
- * @return void
- */
- protected final function setHelperInstance (Helper $helperInstance) {
- $this->helperInstance = $helperInstance;
- }
-
- /**
- * Getter for helper instance
- *
- * @return $helperInstance An instance of a helper class
- */
- public final function getHelperInstance () {
- return $this->helperInstance;
- }
-
- /**
- * Getter for a InputStream instance
- *
- * @param $inputStreamInstance The InputStream instance
- */
- protected final function getInputStreamInstance () {
- return $this->inputStreamInstance;
- }
-
- /**
- * Setter for a InputStream instance
- *
- * @param $inputStreamInstance The InputStream instance
- * @return void
- */
- protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
- $this->inputStreamInstance = $inputStreamInstance;
- }
-
- /**
- * Getter for a OutputStream instance
- *
- * @param $outputStreamInstance The OutputStream instance
- */
- protected final function getOutputStreamInstance () {
- return $this->outputStreamInstance;
- }
-
- /**
- * Setter for a OutputStream instance
- *
- * @param $outputStreamInstance The OutputStream instance
- * @return void
- */
- protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
- $this->outputStreamInstance = $outputStreamInstance;
- }
-
- /**
- * Setter for handler instance
- *
- * @param $handlerInstance An instance of a Handleable class
- * @return void
- */
- protected final function setHandlerInstance (Handleable $handlerInstance) {
- $this->handlerInstance = $handlerInstance;
- }
-
- /**
- * Getter for handler instance
- *
- * @return $handlerInstance A Handleable instance
- */
- protected final function getHandlerInstance () {
- return $this->handlerInstance;
- }
-
- /**
- * Setter for visitor instance
- *
- * @param $visitorInstance A Visitor instance
- * @return void
- */
- protected final function setVisitorInstance (Visitor $visitorInstance) {
- $this->visitorInstance = $visitorInstance;
- }
-
- /**
- * Getter for visitor instance
- *
- * @return $visitorInstance A Visitor instance
- */
- protected final function getVisitorInstance () {
- return $this->visitorInstance;
- }
-
- /**
- * Setter for Iterator instance
- *
- * @param $iteratorInstance An instance of an Iterator
- * @return void
- */
- protected final function setIteratorInstance (Iterator $iteratorInstance) {
- $this->iteratorInstance = $iteratorInstance;
- }
-
- /**
- * Getter for Iterator instance
- *
- * @return $iteratorInstance An instance of an Iterator
- */
- public final function getIteratorInstance () {
- return $this->iteratorInstance;
- }
-
- /**
- * Setter for FilePointer instance
- *
- * @param $pointerInstance An instance of an FilePointer class
- * @return void
- */
- protected final function setPointerInstance (FilePointer $pointerInstance) {
- $this->pointerInstance = $pointerInstance;
- }
-
- /**
- * Getter for FilePointer instance
- *
- * @return $pointerInstance An instance of an FilePointer class
- */
- public final function getPointerInstance () {
- return $this->pointerInstance;
- }
-
- /**
- * Unsets pointer instance which triggers a call of __destruct() if the
- * instance is still there. This is surely not fatal on already "closed"
- * file pointer instances.
- *
- * I don't want to mess around with above setter by giving it a default
- * value NULL as setter should always explicitly only set (existing) object
- * instances and NULL is NULL.
- *
- * @return void
- */
- protected final function unsetPointerInstance () {
- // Simply it to NULL
- $this->pointerInstance = NULL;
- }
-
- /**
- * Setter for Indexable instance
- *
- * @param $indexInstance An instance of an Indexable class
- * @return void
- */
- protected final function setIndexInstance (Indexable $indexInstance) {
- $this->indexInstance = $indexInstance;
- }
-
- /**
- * Getter for Indexable instance
- *
- * @return $indexInstance An instance of an Indexable class
- */
- public final function getIndexInstance () {
- return $this->indexInstance;
- }
-
- /**
- * Setter for Block instance
- *
- * @param $blockInstance An instance of an Block class
- * @return void
- */
- protected final function setBlockInstance (Block $blockInstance) {
- $this->blockInstance = $blockInstance;
- }
-
- /**
- * Getter for Block instance
- *
- * @return $blockInstance An instance of an Block class
- */
- public final function getBlockInstance () {
- return $this->blockInstance;
- }
-
- /**
- * Setter for Minable instance
- *
- * @param $minableInstance A Minable instance
- * @return void
- */
- protected final function setMinableInstance (Minable $minableInstance) {
- $this->minableInstance = $minableInstance;
- }
-
- /**
- * Getter for minable instance
- *
- * @return $minableInstance A Minable instance
- */
- protected final function getMinableInstance () {
- return $this->minableInstance;
- }
-
- /**
- * Setter for FrameworkDirectory instance
- *
- * @param $directoryInstance A FrameworkDirectory instance
- * @return void
- */
- protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
- $this->directoryInstance = $directoryInstance;
- }
-
- /**
- * Getter for FrameworkDirectory instance
- *
- * @return $directoryInstance A FrameworkDirectory instance
- */
- protected final function getDirectoryInstance () {
- return $this->directoryInstance;
- }
-
- /**
- * Setter for state instance
- *
- * @param $stateInstance A Stateable instance
- * @return void
- */
- public final function setStateInstance (Stateable $stateInstance) {
- $this->stateInstance = $stateInstance;
- }
-
- /**
- * Getter for state instance
- *
- * @return $stateInstance A Stateable instance
- */
- public final function getStateInstance () {
- return $this->stateInstance;
- }
-
- /**
- * Setter for output instance
- *
- * @param $outputInstance The debug output instance
- * @return void
- */
- public final function setOutputInstance (OutputStreamer $outputInstance) {
- $this->outputInstance = $outputInstance;
- }
-
- /**
- * Getter for output instance
- *
- * @return $outputInstance The debug output instance
- */
- public final function getOutputInstance () {
- return $this->outputInstance;
- }
-
- /**
- * Setter for registry instance
- *
- * @param $registryInstance An instance of a Register class
- * @return void
- */
- protected final function setRegistryInstance (Register $registryInstance) {
- $this->registryInstance = $registryInstance;
- }
-
- /**
- * Getter for registry instance
- *
- * @return $registryInstance The debug registry instance
- */
- public final function getRegistryInstance () {
- return $this->registryInstance;
- }
-
- /**
- * Setter for call-back instance
- *
- * @param $callbackInstance An instance of a FrameworkInterface class
- * @return void
- */
- public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
- $this->callbackInstance = $callbackInstance;
- }
-
- /**
- * Getter for call-back instance
- *
- * @return $callbackInstance An instance of a FrameworkInterface class
- */
- protected final function getCallbackInstance () {
- return $this->callbackInstance;
- }
-
- /**
- * Setter for command name
- *
- * @param $commandName Last validated command name
- * @return void
- */
- protected final function setCommandName ($commandName) {
- $this->commandName = $commandName;
- }
-
- /**
- * Getter for command name
- *
- * @return $commandName Last validated command name
- */
- protected final function getCommandName () {
- return $this->commandName;
- }
-
- /**
- * Setter for controller name
- *
- * @param $controllerName Last validated controller name
- * @return void
- */
- protected final function setControllerName ($controllerName) {
- $this->controllerName = $controllerName;
- }
-
- /**
- * Getter for controller name
- *
- * @return $controllerName Last validated controller name
- */
- protected final function getControllerName () {
- return $this->controllerName;
- }
-
- /**
- * Checks whether an object equals this object. You should overwrite this
- * method to implement own equality checks
- *
- * @param $objectInstance An instance of a FrameworkInterface object
- * @return $equals Whether both objects equals
- */
- public function equals (FrameworkInterface $objectInstance) {
- // Now test it
- $equals = ((
- $this->__toString() == $objectInstance->__toString()
- ) && (
- $this->hashCode() == $objectInstance->hashCode()
- ));
-
- // Return the result
- return $equals;
- }
-
- /**
- * Generates a generic hash code of this class. You should really overwrite
- * this method with your own hash code generator code. But keep KISS in mind.
- *
- * @return $hashCode A generic hash code respresenting this whole class
- */
- public function hashCode () {
- // Simple hash code
- return crc32($this->__toString());
- }
-
- /**
- * Formats computer generated price values into human-understandable formats
- * with thousand and decimal separators.
- *
- * @param $value The in computer format value for a price
- * @param $currency The currency symbol (use HTML-valid characters!)
- * @param $decNum Number of decimals after commata
- * @return $price The for the current language formated price string
- * @throws MissingDecimalsThousandsSeparatorException If decimals or
- * thousands separator
- * is missing
- */
- public function formatCurrency ($value, $currency = '€', $decNum = 2) {
- // Are all required attriutes set?
- if ((!isset($this->decimals)) || (!isset($this->thousands))) {
- // Throw an exception
- throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
- } // END - if
-
- // Cast the number
- $value = (float) $value;
-
- // Reformat the US number
- $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
-
- // Return as string...
- return $price;
- }
-
- /**
- * Appends a trailing slash to a string
- *
- * @param $str A string (maybe) without trailing slash
- * @return $str A string with an auto-appended trailing slash
- */
- public final function addMissingTrailingSlash ($str) {
- // Is there a trailing slash?
- if (substr($str, -1, 1) != '/') {
- $str .= '/';
- } // END - if
-
- // Return string with trailing slash
- return $str;
- }
-
- /**
- * Prepare the template engine (HtmlTemplateEngine by default) for a given
- * application helper instance (ApplicationHelper by default).
- *
- * @param $applicationInstance An application helper instance or
- * null if we shall use the default
- * @return $templateInstance The template engine instance
- * @throws NullPointerException If the discovered application
- * instance is still null
- */
- protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
- // Is the application instance set?
- if (is_null($applicationInstance)) {
- // Get the current instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
-
- // Still null?
- if (is_null($applicationInstance)) {
- // Thrown an exception
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } // END - if
- } // END - if
-
- // Initialize the template engine
- $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
-
- // Return the prepared instance
- return $templateInstance;
- }
-
- /**
- * Debugs this instance by putting out it's full content
- *
- * @param $message Optional message to show in debug output
- * @return void
- */
- public final function debugInstance ($message = '') {
// Restore the error handler to avoid trouble with missing array elements or undeclared variables
restore_error_handler();
$content = sprintf('<div class="debug_message">
Message: %s
</div>' . PHP_EOL, $message);
- } // END - if
+ }
// Generate the output
$content .= sprintf('<pre>%s</pre>',
));
}
- /**
- * Replaces control characters with printable output
- *
- * @param $str String with control characters
- * @return $str Replaced string
- */
- protected function replaceControlCharacters ($str) {
- // Replace them
- $str = str_replace(
- chr(13), '[r]', str_replace(
- chr(10), '[n]', str_replace(
- chr(9) , '[t]',
- $str
- )));
-
- // Return it
- return $str;
- }
-
- /**
- * Output a partial stub message for the caller method
- *
- * @param $message An optional message to display
- * @return void
- */
- protected function partialStub ($message = '') {
- // Init variable
- $stubMessage = 'Partial Stub!';
-
- // Is the extra message given?
- if (!empty($message)) {
- // Then add it as well
- $stubMessage .= ' Message: ' . $message;
- } // END - if
-
- // Debug instance is there?
- if (!is_null($this->getDebugInstance())) {
- // Output stub message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
- } else {
- // Trigger an error
- trigger_error($stubMessage);
- exit;
- }
- }
-
/**
* Outputs a debug backtrace and stops further script execution
*
* @param $message An optional message to output
* @param $doExit Whether exit the program (true is default)
* @return void
+ * @throws InvalidArgumentException If a paramter has an invalid value
*/
- public function debugBackTrace ($message = '', $doExit = true) {
+ public function debugBackTrace (string $message = '', bool $doExit = true) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FRAMEWORK-SYSTEM: message=%s,doExit=%d - CALLED!', $message, intval($doExit)));
+ if (empty($message)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "message" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Sorry, there is no other way getting this nice backtrace
if (!empty($message)) {
// Output message
printf('Message: %s<br />' . PHP_EOL, $message);
- } // END - if
+ }
print('<pre>');
debug_print_backtrace();
// Exit program?
if ($doExit === true) {
- exit();
- } // END - if
+ // Yes, with error code
+ exit(255);
+ }
}
/**
* @param $className Name of the class (currently unsupported)
* @param $lineNumber Line number where the call was made
* @return $debugInstance An instance of a debugger class
+ * @throws InvalidArgumentException If a parameter has an invalid value
* @deprecated Not fully, as the new Logger facilities are not finished yet.
*/
- public final static function createDebugInstance ($className, $lineNumber = NULL) {
- // Is the instance set?
- if (!GenericRegistry::getRegistry()->instanceExists('debug')) {
+ public final static function createDebugInstance (string $className, int $lineNumber = NULL) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ printf('[%s:%d]: className=%s,lineNumber[%s]=%d - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $className, gettype($lineNumber), $lineNumber);
+ if (empty($className)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "className" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Is the debug instance set?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::debugInstance[]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype(self::$debugInstance));
+ if (is_null(self::$debugInstance)) {
// Init debug instance
- $debugInstance = NULL;
+ self::$debugInstance = NULL;
// Try it
try {
// Get a debugger instance
- $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
+ //* NOISY-DEBUG: */ printf('[%s:%d]: className=%s' . PHP_EOL, __METHOD__, __LINE__, $className);
+ self::$debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
} catch (NullPointerException $e) {
// Didn't work, no instance there
- exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
+ exit(sprintf('[%s:%d]: Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, __METHOD__, __LINE__, $e->__toString(), $e->getMessage(), $className, $lineNumber));
}
-
- // Empty string should be ignored and used for testing the middleware
- DebugMiddleware::getSelfInstance()->output('');
-
- // Set it in registry
- GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
- } else {
- // Get instance from registry
- $debugInstance = GenericRegistry::getRegistry()->getDebugInstance();
}
// Return it
- return $debugInstance;
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::debugInstance=%s - EXIT!' . PHP_EOL, __METHOD__, __LINE__, self::$debugInstance->__toString());
+ return self::$debugInstance;
}
/**
*
* @param $message Message to output
* @return void
+ * @throws InvalidArgumentException If a paramter has an invalid value
*/
- public function outputLine ($message) {
- // Simply output it
- print($message . PHP_EOL);
- }
-
- /**
- * Outputs a debug message whether to debug instance (should be set!) or
- * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
- * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
- *
- * @param $message Message we shall send out...
- * @param $doPrint Whether print or die here (default: print)
- * @paran $stripTags Whether to strip tags (default: false)
- * @return void
- */
- public function debugOutput ($message, $doPrint = true, $stripTags = false) {
- // Set debug instance to NULL
- $debugInstance = NULL;
-
- // Get backtrace
- $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
-
- // Is function partialStub/__callStatic ?
- if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
- // Prepend class::function:line from 3rd element
- $message = sprintf('[%s::%s:%d]: %s',
- $backtrace[2]['class'],
- $backtrace[2]['function'],
- (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
- $message
- );
- } else {
- // Prepend class::function:line from 2nd element
- $message = sprintf('[%s::%s:%d]: %s',
- $backtrace[1]['class'],
- $backtrace[1]['function'],
- (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
- $message
- );
- }
-
- // Try it:
- try {
- // Get debug instance
- $debugInstance = $this->getDebugInstance();
- } catch (NullPointerException $e) {
- // The debug instance is not set (yet)
- }
-
- // Is the debug instance there?
- if (is_object($debugInstance)) {
- // Use debug output handler
- $debugInstance->output($message, $stripTags);
-
- if ($doPrint === false) {
- // Die here if not printed
- exit();
- } // END - if
- } else {
- // Are debug times enabled?
- if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
- // Prepent it
- $message = $this->getPrintableExecutionTime() . $message;
- } // END - if
-
- // Put directly out
- if ($doPrint === true) {
- // Print message
- $this->outputLine($message);
- } else {
- // Die here
- exit($message);
- }
+ public function outputLine (string $message) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FRAMEWORK-SYSTEM: message=%s - CALLED!', $message));
+ if (empty($message)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "message" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
}
- }
-
- /**
- * Converts e.g. a command from URL to a valid class by keeping out bad characters
- *
- * @param $str The string, what ever it is needs to be converted
- * @return $className Generated class name
- */
- public static final function convertToClassName ($str) {
- // Init class name
- $className = '';
- // Convert all dashes in underscores
- $str = StringUtils::convertDashesToUnderscores($str);
-
- // Now use that underscores to get classname parts for hungarian style
- foreach (explode('_', $str) as $strPart) {
- // Make the class name part lower case and first upper case
- $className .= ucfirst(strtolower($strPart));
- } // END - foreach
-
- // Return class name
- return $className;
+ // Simply output it
+ print($message . PHP_EOL);
}
/**
*
* @param $phpCode Unmarked PHP code
* @return $markedCode Marked PHP code
- */
- public function markupCode ($phpCode) {
+ * @throws InvalidArgumentException If a paramter has an invalid value
+ */
+ public function markupCode (string $phpCode) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FRAMEWORK-SYSTEM: phpCode=%s - CALLED!', $phpCode));
+ if (empty($phpCode)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "phpCode" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Init marked code
$markedCode = '';
$errorArray['message'],
$errorArray['type']
);
- } // END - if
+ }
// Add line number to the code
foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
($lineNo + 1),
htmlentities($code, ENT_QUOTES)
);
- } // END - foreach
+ }
// Return the code
return $markedCode;
}
- /**
- * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
- * beatiful for web-based front-ends. If null is given a message id
- * null_timestamp will be resolved and returned.
- *
- * @param $timestamp Timestamp to prepare (filter) for display
- * @return $readable A readable timestamp
- */
- public function doFilterFormatTimestamp ($timestamp) {
- // Default value to return
- $readable = '???';
-
- // Is the timestamp null?
- if (is_null($timestamp)) {
- // Get a message string
- $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
- } else {
- switch ($this->getLanguageInstance()->getLanguageCode()) {
- case 'de': // German format is a bit different to default
- // Split the GMT stamp up
- $dateTime = explode(' ', $timestamp );
- $dateArray = explode('-', $dateTime[0]);
- $timeArray = explode(':', $dateTime[1]);
-
- // Construct the timestamp
- $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
- $dateArray[0],
- $dateArray[1],
- $dateArray[2],
- $timeArray[0],
- $timeArray[1],
- $timeArray[2]
- );
- break;
-
- default: // Default is pass-through
- $readable = $timestamp;
- break;
- } // END - switch
- }
-
- // Return the stamp
- return $readable;
- }
-
- /**
- * Filter a given number into a localized number
- *
- * @param $value The raw value from e.g. database
- * @return $localized Localized value
- */
- public function doFilterFormatNumber ($value) {
- // Generate it from config and localize dependencies
- switch ($this->getLanguageInstance()->getLanguageCode()) {
- case 'de': // German format is a bit different to default
- $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
- break;
-
- default: // US, etc.
- $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
- break;
- } // END - switch
-
- // Return it
- return $localized;
- }
-
/**
* "Getter" for databse entry
*
* @return $entry An array with database entries
* @throws NullPointerException If the database result is not found
* @throws InvalidDatabaseResultException If the database result is invalid
+ * @deprecated Monolithic method, should be moved to proper classes
*/
protected final function getDatabaseEntry () {
+ // This method is deprecated
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: CALLED!');
+ $this->deprecationWarning('Monolithic method, should be moved to proper classes');
+
// Is there an instance?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FRAMEWORK-SYSTEM: this->resultInstance[]=%s', gettype($this->getResultInstance())));
if (!$this->getResultInstance() instanceof SearchableResult) {
// Throw an exception here
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } // END - if
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
+ }
// Rewind it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: Invoking this->resultInstance->rewind() ...');
$this->getResultInstance()->rewind();
// Do we have an entry?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FRAMEWORK-SYSTEM: this->resultInstance->isValid()=%d', intval($this->getResultInstance()->isValid())));
if ($this->getResultInstance()->valid() === false) {
// @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
- } // END - if
+ }
// Get next entry
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: Invoking this->resultInstance->next() ...');
$this->getResultInstance()->next();
// Fetch it
$entry = $this->getResultInstance()->current();
// And return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: entry[]=%s - EXIT!', gettype($entry)));
return $entry;
}
* @param $fieldName Field name which we shall get
* @return $fieldValue Field value from the user
* @throws NullPointerException If the result instance is null
- */
- public final function getField ($fieldName) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @deprecated Monolithic method, should be moved to proper classes
+ */
+ public final function getField (string $fieldName) {
+ // Check parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: fieldName=%s - CALLED!', $fieldName));
+ if (empty($fieldName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "fieldName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // This method is deprecated
+ $this->deprecationWarning('Monolithic method, should be moved to proper classes');
+
// Default field value
$fieldValue = NULL;
$resultInstance = $this->getResultInstance();
// Is this instance null?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FRAMEWORK-SYSTEM: resultInstance[]=%s', gettype($resultInstance)));
if (is_null($resultInstance)) {
// Then the user instance is no longer valid (expired cookies?)
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } // END - if
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
+ }
// Get current array
$fieldArray = $resultInstance->current();
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
// Convert dashes to underscore
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FRAMEWORK-SYSTEM: fieldArray()=%d', count($fieldArray)));
$fieldName2 = StringUtils::convertDashesToUnderscores($fieldName);
// Does the field exist?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FRAMEWORK-SYSTEM: fieldName2=%s', $fieldName2));
if ($this->isFieldSet($fieldName)) {
// Get it
$fieldValue = $fieldArray[$fieldName2];
- } elseif (defined('DEVELOPER')) {
+ } elseif (FrameworkBootstrap::getConfigurationInstance()->isEnabled('developer_mode')) {
// Missing field entry, may require debugging
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
+ self::createDebugInstance(__CLASS__, __LINE__)->warningMessage('BASE-FRAMEWORK-SYSTEM: fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
} else {
// Missing field entry, may require debugging
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
+ self::createDebugInstance(__CLASS__, __LINE__)->warningMessage('BASE-FRAMEWORK-SYSTEM: fieldName=' . $fieldName . ' not found!');
}
// Return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: fieldValue[]=%s - EXIT!', gettype($fieldValue)));
return $fieldValue;
}
* @param $fieldName Field name to check
* @return $isSet Whether the given field name is set
* @throws NullPointerException If the result instance is null
- */
- public function isFieldSet ($fieldName) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ public function isFieldSet (string $fieldName) {
+ // Check parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: fieldName=%s - CALLED!', $fieldName));
+ if (empty($fieldName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "fieldName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get result instance
$resultInstance = $this->getResultInstance();
// Is this instance null?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FRAMEWORK-SYSTEM: resultInstance[]=%s', gettype($resultInstance)));
if (is_null($resultInstance)) {
// Then the user instance is no longer valid (expired cookies?)
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } // END - if
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
+ }
// Get current array
$fieldArray = $resultInstance->current();
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
// Convert dashes to underscore
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FRAMEWORK-SYSTEM: fieldArray()=%d,fieldName=%s - BEFORE!', count($fieldArray), $fieldName));
$fieldName = StringUtils::convertDashesToUnderscores($fieldName);
// Determine it
- $isSet = isset($fieldArray[$fieldName]);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FRAMEWORK-SYSTEM: fieldName=%s - AFTER!', $fieldName));
+ $isset = isset($fieldArray[$fieldName]);
// Return result
- return $isSet;
- }
-
- /**
- * Flushs all pending updates to the database layer
- *
- * @return void
- */
- public function flushPendingUpdates () {
- // Get result instance
- $resultInstance = $this->getResultInstance();
-
- // Do we have data to update?
- if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
- // Get wrapper class name config entry
- $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
-
- // Create object instance
- $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
-
- // Yes, then send the whole result to the database layer
- $wrapperInstance->doUpdateByResult($this->getResultInstance());
- } // END - if
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: isset=%d - EXIT!', intval($isset)));
+ return $isset;
}
/**
*
* @param $message The message we shall output to the developer
* @return void
+ * @throws InvalidArgumentException If a paramter has an invalid value
* @todo Write a logging mechanism for productive mode
*/
- public function deprecationWarning ($message) {
+ public function deprecationWarning (string $message) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: message=%s - CALLED!', $message));
+ if (empty($message)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "message" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Is developer mode active?
- if (defined('DEVELOPER')) {
+ if (FrameworkBootstrap::getConfigurationInstance()->isEnabled('developer_mode')) {
// Debug instance is there?
if (!is_null($this->getDebugInstance())) {
// Output stub message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
+ self::createDebugInstance(__CLASS__, __LINE__)->warningMessage($message);
} else {
// Trigger an error
trigger_error($message . "<br />\n");
- exit;
+ exit(255);
}
} else {
// @TODO Finish this part!
- $this->partialStub('Developer mode inactive. Message:' . $message);
+ DebugMiddleware::getSelfInstance()->partialStub('Developer mode inactive. Message:' . $message);
}
+
+ // Trace mesage
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: EXIT!');
}
/**
*
* @param $phpExtension The PHP extension we shall check
* @return $isLoaded Whether the PHP extension is loaded
- */
- public final function isPhpExtensionLoaded ($phpExtension) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ public final function isPhpExtensionLoaded (string $phpExtension) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: phpExtension=%s - CALLED!', $phpExtension));
+ if (empty($phpExtension)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "phpExtension" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Is it loaded?
$isLoaded = in_array($phpExtension, get_loaded_extensions());
// Return result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: isLoaded=%d - EXIT!', intval($isLoaded)));
return $isLoaded;
}
*/
public function getMilliTime () {
// Get the time of day as float
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: CALLED!');
$milliTime = gettimeofday(true);
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: milliTime=%s - EXIT!', $milliTime));
return $milliTime;
}
* Idles (sleeps) for given milliseconds
*
* @return $hasSlept Whether it goes fine
- */
- public function idle ($milliSeconds) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ public function idle (int $milliSeconds) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: milliSeconds=%s - CALLED!', $milliSeconds));
+ if ($milliSeconds < 1) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('milliSeconds=%d are not a reasonable value to idle', $milliSeconds));
+ }
+
// Sleep is fine by default
$hasSlept = true;
}
// Return result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: hasSlept=%d - EXIT!', intval($hasSlept)));
return $hasSlept;
}
- /**
- * Converts a hexadecimal string, even with negative sign as first string to
- * a decimal number using BC functions.
- *
- * This work is based on comment #86673 on php.net documentation page at:
- * <http://de.php.net/manual/en/function.dechex.php#86673>
- *
- * @param $hex Hexadecimal string
- * @return $dec Decimal number
- */
- protected function hex2dec ($hex) {
- // Convert to all lower-case
- $hex = strtolower($hex);
-
- // Detect sign (negative/positive numbers)
- $sign = '';
- if (substr($hex, 0, 1) == '-') {
- $sign = '-';
- $hex = substr($hex, 1);
- } // END - if
-
- // Decode the hexadecimal string into a decimal number
- $dec = 0;
- for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
- $factor = self::$hexdec[substr($hex, $i, 1)];
- $dec = bcadd($dec, bcmul($factor, $e));
- } // END - for
-
- // Return the decimal number
- return $sign . $dec;
- }
-
- /**
- * Converts even very large decimal numbers, also signed, to a hexadecimal
- * string.
- *
- * This work is based on comment #97756 on php.net documentation page at:
- * <http://de.php.net/manual/en/function.hexdec.php#97756>
- *
- * @param $dec Decimal number, even with negative sign
- * @param $maxLength Optional maximum length of the string
- * @return $hex Hexadecimal string
- */
- protected function dec2hex ($dec, $maxLength = 0) {
- // maxLength can be zero or devideable by 2
- assert(($maxLength == 0) || (($maxLength % 2) == 0));
-
- // Detect sign (negative/positive numbers)
- $sign = '';
- if ($dec < 0) {
- $sign = '-';
- $dec = abs($dec);
- } // END - if
-
- // Encode the decimal number into a hexadecimal string
- $hex = '';
- do {
- $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
- $dec /= (2 ^ 4);
- } while ($dec >= 1);
-
- /*
- * Leading zeros are required for hex-decimal "numbers". In some
- * situations more leading zeros are wanted, so check for both
- * conditions.
- */
- if ($maxLength > 0) {
- // Prepend more zeros
- $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
- } elseif ((strlen($hex) % 2) != 0) {
- // Only make string's length dividable by 2
- $hex = '0' . $hex;
- }
-
- // Return the hexadecimal string
- return $sign . $hex;
- }
-
- /**
- * Converts a ASCII string (0 to 255) into a decimal number.
- *
- * @param $asc The ASCII string to be converted
- * @return $dec Decimal number
- */
- protected function asc2dec ($asc) {
- // Convert it into a hexadecimal number
- $hex = bin2hex($asc);
-
- // And back into a decimal number
- $dec = $this->hex2dec($hex);
-
- // Return it
- return $dec;
- }
-
- /**
- * Converts a decimal number into an ASCII string.
- *
- * @param $dec Decimal number
- * @return $asc An ASCII string
- */
- protected function dec2asc ($dec) {
- // First convert the number into a hexadecimal string
- $hex = $this->dec2hex($dec);
-
- // Then convert it into the ASCII string
- $asc = $this->hex2asc($hex);
-
- // Return it
- return $asc;
- }
-
- /**
- * Converts a hexadecimal number into an ASCII string. Negative numbers
- * are not allowed.
- *
- * @param $hex Hexadecimal string
- * @return $asc An ASCII string
- */
- protected function hex2asc ($hex) {
- // Check for length, it must be devideable by 2
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
- assert((strlen($hex) % 2) == 0);
-
- // Walk the string
- $asc = '';
- for ($idx = 0; $idx < strlen($hex); $idx+=2) {
- // Get the decimal number of the chunk
- $part = hexdec(substr($hex, $idx, 2));
-
- // Add it to the final string
- $asc .= chr($part);
- } // END - for
-
- // Return the final string
- return $asc;
- }
/**
* Checks whether the given encoded data was encoded with Base64
*
* @param $encodedData Encoded data we shall check
* @return $isBase64 Whether the encoded data is Base64
- */
- protected function isBase64Encoded ($encodedData) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ protected function isBase64Encoded (string $encodedData) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: encodedData=%s - CALLED!', $encodedData));
+ if (empty($encodedData)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "encodedData" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Determine it
$isBase64 = (@base64_decode($encodedData, true) !== false);
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: isBase64=%d - EXIT!', intval($isBase64)));
return $isBase64;
}
- /**
- * Gets a cache key from Criteria instance
- *
- * @param $criteriaInstance An instance of a Criteria class
- * @param $onlyKeys Only use these keys for a cache key
- * @return $cacheKey A cache key suitable for lookup/storage purposes
- */
- protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
- // Generate it
- $cacheKey = sprintf('%s@%s',
- $this->__toString(),
- $criteriaInstance->getCacheKey($onlyKeys)
- );
-
- // And return it
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
- return $cacheKey;
- }
-
/**
* Getter for startup time in miliseconds
*
* @return $executionTime Current execution time in nice braces
*/
protected function getPrintableExecutionTime () {
- // Caculate the execution time
- $executionTime = microtime(true) - $this->getStartupTime();
-
- // Pack it in nice braces
- $executionTime = sprintf('[ %01.5f ] ', $executionTime);
+ // Calculate execution time and pack it in nice braces
+ $executionTime = sprintf('[ %01.5f ] ', (microtime(true) - $this->getStartupTime()));
// And return it
return $executionTime;
}
- /**
- * Hashes a given string with a simple but stronger hash function (no salt)
- * and hex-encode it.
- *
- * @param $str The string to be hashed
- * @return $hash The hash from string $str
- */
- public static final function hash ($str) {
- // Hash given string with (better secure) hasher
- $hash = bin2hex(mhash(MHASH_SHA256, $str));
-
- // Return it
- return $hash;
- }
-
- /**
- * "Getter" for length of hash() output. This will be "cached" to speed up
- * things.
- *
- * @return $length Length of hash() output
- */
- public static final function getHashLength () {
- // Is it cashed?
- if (is_null(self::$hashLength)) {
- // No, then hash a string and save its length.
- self::$hashLength = strlen(self::hash('abc123'));
- } // END - if
-
- // Return it
- return self::$hashLength;
- }
-
- /**
- * Checks whether the given number is really a number (only chars 0-9).
- *
- * @param $num A string consisting only chars between 0 and 9
- * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
- * @param $assertMismatch Whether to assert mismatches
- * @return $ret The (hopefully) secured numbered value
- */
- public function bigintval ($num, $castValue = true, $assertMismatch = false) {
- // Filter all numbers out
- $ret = preg_replace('/[^0123456789]/', '', $num);
-
- // Shall we cast?
- if ($castValue === true) {
- // Cast to biggest numeric type
- $ret = (double) $ret;
- } // END - if
-
- // Assert only if requested
- if ($assertMismatch === true) {
- // Has the whole value changed?
- assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
- } // END - if
-
- // Return result
- return $ret;
- }
-
- /**
- * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
- *
- * @param $num A string consisting only chars between 0 and 9
- * @param $assertMismatch Whether to assert mismatches
- * @return $ret The (hopefully) secured hext-numbered value
- */
- public function hexval ($num, $assertMismatch = false) {
- // Filter all numbers out
- $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
-
- // Assert only if requested
- if ($assertMismatch === true) {
- // Has the whole value changed?
- assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
- } // END - if
-
- // Return result
- return $ret;
- }
-
/**
* Determines if an element is set in the generic array
*
* @param $key Key to check
* @param $element Element to check
* @return $isset Whether the given key is set
- */
- protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ protected final function isGenericArrayElementSet (string $keyGroup, string $subGroup, string $key, string $element) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s,element=%s - CALLED!', $keyGroup, $subGroup, $key, $element));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($element === '') {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "element" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Is it there?
$isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: isset=%d - EXIT!', intval($isset)));
return $isset;
}
/**
* @param $subGroup Sub group for the key
* @param $key Key to check
* @return $isset Whether the given key is set
- */
- protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ protected final function isGenericArrayKeySet (string $keyGroup, string $subGroup, string $key) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s - CALLED!', $keyGroup, $subGroup, $key));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Is it there?
$isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: isset=%d - EXIT!', intval($isset)));
return $isset;
}
-
/**
* Determines if a group is set in the generic array
*
* @param $keyGroup Main group
* @param $subGroup Sub group
* @return $isset Whether the given group is set
- */
- protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ protected final function isGenericArrayGroupSet (string $keyGroup, string $subGroup) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s - CALLED!', $keyGroup, $subGroup));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Is it there?
$isset = isset($this->genericArray[$keyGroup][$subGroup]);
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: isset=%d - EXIT!', intval($isset)));
return $isset;
}
* @param $keyGroup Main key group
* @param $subGroup Sub key group
* @return $array An array with all array elements
- */
- protected final function getGenericSubArray ($keyGroup, $subGroup) {
- // Is it there?
- if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If key/sub group isn't there but this method is invoked
+ */
+ protected final function getGenericSubArray (string $keyGroup, string $subGroup) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s - CALLED!', $keyGroup, $subGroup));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
// No, then abort here
- trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
- exit;
- } // END - if
-
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
+ throw new BadMethodCallException(sprintf('keyGroup=%s,subGroup=%s not found.', $keyGroup, $subGroup), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: this->genericArray[%s][%s][]=%s - EXIT!', $keyGroup, $subGroup, gettype($this->genericArray[$keyGroup][$subGroup])));
return $this->genericArray[$keyGroup][$subGroup];
}
* @param $subGroup Sub group for the key
* @param $key Key to unset
* @return void
- */
- protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ protected final function unsetGenericArrayKey (string $keyGroup, string $subGroup, string $key) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s - CALLED!', $keyGroup, $subGroup, $key));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Remove it
unset($this->genericArray[$keyGroup][$subGroup][$key]);
+
+ // Trace mesage
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: EXIT!');
}
/**
* @param $key Key to unset
* @param $element Element to unset
* @return void
- */
- protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ protected final function unsetGenericArrayElement (string $keyGroup, string $subGroup, string $key, string $element) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s,element=%s - CALLED!', $keyGroup, $subGroup, $key, $element));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($element === '') {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "element" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Remove it
unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
+
+ // Trace mesage
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: EXIT!');
}
/**
* @param $key Key to unset
* @param $value Value to add/append
* @return void
- */
- protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
- // Debug message
- //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true) . ',appendGlue=' . $appendGlue);
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ protected final function appendStringToGenericArrayKey (string $keyGroup, string $subGroup, string $key, string $value, string $appendGlue = '') {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s,value=%s,appendGlue=%s - CALLED!', $keyGroup, $subGroup, $key, $value, $appendGlue));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Is it already there?
if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
// Append it
- $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
+ $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . $value;
} else {
// Add it
- $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
+ $this->genericArray[$keyGroup][$subGroup][$key] = $value;
}
+
+ // Trace mesage
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: EXIT!');
}
/**
* @param $element Element to check
* @param $value Value to add/append
* @return void
- */
- protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
- // Debug message
- //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, true) . ',appendGlue=' . $appendGlue);
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ protected final function appendStringToGenericArrayElement (string $keyGroup, string $subGroup, string $key, string $element, string $value, string $appendGlue = '') {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s,element=%s,value=%s,appendGlue=%s - CALLED!', $keyGroup, $subGroup, $key, $element, $value, $appendGlue));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($element === '') {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "element" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Is it already there?
if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
// Append it
- $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
+ $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . $value;
} else {
// Add it
- $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
+ $this->setGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
}
- }
-
- /**
- * Sets a string in a given generic array element
- *
- * @param $keyGroup Main group for the key
- * @param $subGroup Sub group for the key
- * @param $key Key to unset
- * @param $element Element to check
- * @param $value Value to add/append
- * @return void
- */
- protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
- // Debug message
- //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, true) . ',appendGlue=' . $appendGlue);
- // Set it
- $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
+ // Trace mesage
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: EXIT!');
}
/**
* @param $key Key to use
* @param $forceInit Optionally force initialization
* @return void
- */
- protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
-
- // Is it already set?
- if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If key/sub group has already been initialized
+ */
+ protected final function initGenericArrayGroup (string $keyGroup, string $subGroup, bool $forceInit = false) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,forceInit=%d - CALLED!', $keyGroup, $subGroup, intval($forceInit)));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
// Already initialized
- trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
- exit;
- } // END - if
+ throw new BadMethodCallException(sprintf('keyGroup=%s,subGroup=%s already initialized.', $keyGroup, $subGroup), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Initialize it
- $this->genericArray[$keyGroup][$subGroup] = array();
+ $this->genericArray[$keyGroup][$subGroup] = [];
+
+ // Trace mesage
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: EXIT!');
}
/**
* @param $key Key to use
* @param $forceInit Optionally force initialization
* @return void
- */
- protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
-
- // Is it already set?
- if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If key/sub group has already been initialized
+ */
+ protected final function initGenericArrayKey (string $keyGroup, string $subGroup, string $key, bool $forceInit = false) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s,forceInit=%d - CALLED!', $keyGroup, $subGroup, $key, intval($forceInit)));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
// Already initialized
- trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
- exit;
- } // END - if
+ throw new BadMethodCallException(sprintf('keyGroup=%s,subGroup=%s,key[%s]=%s already initialized.', $keyGroup, $subGroup, gettype($key), $key), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Initialize it
- $this->genericArray[$keyGroup][$subGroup][$key] = array();
+ $this->genericArray[$keyGroup][$subGroup][$key] = [];
+
+ // Trace mesage
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: EXIT!');
}
/**
* @param $element Element to use
* @param $forceInit Optionally force initialization
* @return void
- */
- protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
-
- // Is it already set?
- if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If key/sub group isn't there but this method is invoked
+ */
+ protected final function initGenericArrayElement (string $keyGroup, string $subGroup, string $key, string $element, bool $forceInit = false) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s,element=%s,forceInit=%d - CALLED!', $keyGroup, $subGroup, $key, $element, intval($forceInit)));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($element === '') {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "element" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
// Already initialized
- trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
- exit;
- } // END - if
+ throw new BadMethodCallException(sprintf('keyGroup=%s,subGroup=%s,key[%s]=%s,element[%s]=%s already initialized.', $keyGroup, $subGroup, gettype($key), $key, gettype($element), $element), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Initialize it
- $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
+ $this->genericArray[$keyGroup][$subGroup][$key][$element] = [];
+
+ // Trace mesage
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: EXIT!');
}
/**
- * Pushes an element to a generic key
+ * Pushes an element to a generic key. If the key isn't found, it will be initialized.
*
* @param $keyGroup Main group for the key
* @param $subGroup Sub group for the key
* @param $key Key to use
* @param $value Value to add/append
* @return $count Number of array elements
- */
- protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
- // Debug message
- //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
-
- // Is it set?
- if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ protected final function pushValueToGenericArrayKey (string $keyGroup, string $subGroup, string $key, $value) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s,value[]=%s - CALLED!', $keyGroup, $subGroup, $key, gettype($value)));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
// Initialize array
$this->initGenericArrayKey($keyGroup, $subGroup, $key);
- } // END - if
+ }
// Then push it
$count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
// Return count
//* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
- //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: count=%d - EXIT!', $count));
return $count;
}
/**
- * Pushes an element to a generic array element
+ * Pushes an element to a generic array element. If the key isn't found, it will be initialized.
*
* @param $keyGroup Main group for the key
* @param $subGroup Sub group for the key
* @param $element Element to check
* @param $value Value to add/append
* @return $count Number of array elements
- */
- protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
- // Debug message
- //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, true));
-
- // Is it set?
- if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ protected final function pushValueToGenericArrayElement (string $keyGroup, string $subGroup, string $key, string $element, $value) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s,element=%s,value[]=%s - CALLED!', $keyGroup, $subGroup, $key, $element, gettype($value)));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($element === '') {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "element" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
// Initialize array
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: Invoking this->initGenericArrayElement(%s,%s,%s,%s) ...', $keyGroup, $subGroup, $key, $element));
$this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
- } // END - if
+ }
// Then push it
$count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
// Return count
//* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
- //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: count=%d - EXIT!', $count));
return $count;
}
* @param $subGroup Sub group for the key
* @param $key Key to unset
* @return $value Last "popped" value
- */
- protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
-
- // Is it set?
- if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If key/sub group isn't there but this method is invoked
+ */
+ protected final function popGenericArrayElement (string $keyGroup, string $subGroup, string $key) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s - CALLED!', $keyGroup, $subGroup, $key));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
// Not found
- trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
- exit;
- } // END - if
+ throw new BadMethodCallException(sprintf('keyGroup=%s,subGroup=%s,key[%s]=%s not found.', $keyGroup, $subGroup, gettype($key), $key), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Then "pop" it
$value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
// Return value
//* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
- //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: value[]=%s - EXIT!', gettype($value)));
return $value;
}
* @param $keyGroup Main group for the key
* @param $subGroup Sub group for the key
* @param $key Key to unset
- * @return $value Last "popped" value
- */
- protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
-
- // Is it set?
- if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
+ * @return $value Last "shifted" value
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If key/sub group isn't there but this method is invoked
+ */
+ protected final function shiftGenericArrayElement (string $keyGroup, string $subGroup, string $key) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s - CALLED!', $keyGroup, $subGroup, $key));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
// Not found
- trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
- exit;
- } // END - if
+ throw new BadMethodCallException(sprintf('keyGroup=%s,subGroup=%s,key[%s]=%s not found.', $keyGroup, $subGroup, gettype($key), $key), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Then "shift" it
$value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
// Return value
//* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
- //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: value[]=%s - EXIT!', gettype($value)));
return $value;
}
*
* @param $keyGroup Main group for the key
* @return $count Count of given group
- */
- protected final function countGenericArray ($keyGroup) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
-
- // Is it there?
- if (!isset($this->genericArray[$keyGroup])) {
- // Abort here
- trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
- exit;
- } // END - if
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If key group isn't there but this method is invoked
+ */
+ protected final function countGenericArray (string $keyGroup) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s - CALLED!', $keyGroup));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!isset($this->genericArray[$keyGroup])) {
+ // Not found
+ throw new BadMethodCallException(sprintf('keyGroup=%s not found.', $keyGroup), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Then count it
$count = count($this->genericArray[$keyGroup]);
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
-
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: count=%d - EXIT!', $count));
return $count;
}
* @param $keyGroup Main group for the key
* @param $subGroup Sub group for the key
* @return $count Count of given group
- */
- protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
-
- // Is it there?
- if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If key/sub group isn't there but this method is invoked
+ */
+ protected final function countGenericArrayGroup (string $keyGroup, string $subGroup) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s - CALLED!', $keyGroup, $subGroup));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
// Abort here
- trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
- exit;
- } // END - if
+ throw new BadMethodCallException(sprintf('keyGroup=%s,subGroup=%s not found.', $keyGroup, $subGroup), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Then count it
$count = count($this->genericArray[$keyGroup][$subGroup]);
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
-
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: count=%d - EXIT!', $count));
return $count;
}
*
* @param $keyGroup Main group for the key
* @param $subGroup Sub group for the key
- * @para $key Key to count
+ * @param $key Key to count
* @return $count Count of given key
- */
- protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
-
- // Is it there?
- if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If key/sub group isn't there but this method is invoked
+ */
+ protected final function countGenericArrayElements (string $keyGroup, string $subGroup, string $key) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s - CALLED!', $keyGroup, $subGroup, $key));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
// Abort here
- trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
- exit;
+ throw new BadMethodCallException(sprintf('keyGroup=%s,subGroup=%s,key[%s]=%s not found.', $keyGroup, $subGroup, gettype($key), $key), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
} elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
// Not valid
- trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
- exit;
+ throw new BadMethodCallException(sprintf('keyGroup=%s,subGroup=%s is not a valid key/sub group.', $keyGroup, $subGroup), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
}
// Then count it
$count = count($this->genericArray[$keyGroup][$subGroup][$key]);
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
-
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: count=%d - EXIT!', $count));
return $count;
}
*
* @param $keyGroup Key group to get
* @return $array Whole generic array group
- */
- protected final function getGenericArray ($keyGroup) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
-
- // Is it there?
- if (!isset($this->genericArray[$keyGroup])) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If key/sub group isn't there but this method is invoked
+ */
+ protected final function getGenericArray (string $keyGroup) {
+ // Check parameters
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s - CALLED!', $keyGroup));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!isset($this->genericArray[$keyGroup])) {
// Then abort here
- trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
- exit;
- } // END - if
+ throw new BadMethodCallException(sprintf('keyGroup=%s not found', $keyGroup), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: this->genericArray[%s][]=%s - EXIT!', $keyGroup, gettype($this->genericArray[$keyGroup])));
return $this->genericArray[$keyGroup];
}
* @param $key Key to unset
* @param $value Mixed value from generic array element
* @return void
- */
- protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
- // Debug message
- //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If key/sub group isn't there but this method is invoked
+ */
+ protected final function setGenericArrayKey (string $keyGroup, string $subGroup, string $key, $value) {
+ // Check parameters
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s,value[]=%s - CALLED!', $keyGroup, $subGroup, $key, gettype($value)));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
+ // Then abort here
+ throw new BadMethodCallException(sprintf('keyGroup=%s,subGroup=%s not found', $keyGroup), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Set value here
$this->genericArray[$keyGroup][$subGroup][$key] = $value;
+
+ // Trace mesage
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: EXIT!');
}
/**
* @param $subGroup Sub group for the key
* @param $key Key to unset
* @return $value Mixed value from generic array element
- */
- protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
-
- // Is it there?
- if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If key/sub group isn't there but this method is invoked
+ */
+ protected final function getGenericArrayKey (string $keyGroup, string $subGroup, string $key) {
+ // Check parameters
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s - CALLED!', $keyGroup, $subGroup, $key));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
// Then abort here
- trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
- exit;
- } // END - if
+ throw new BadMethodCallException(sprintf('keyGroup=%s,subGroup=%s,key[%s]=%s not found.', $keyGroup, $subGroup, gettype($key), $key), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: this->genericArray[%s][%s][%s][]=%s - EXIT!', $keyGroup, $subGroup, $key, gettype($this->genericArray[$keyGroup][$subGroup][$key])));
return $this->genericArray[$keyGroup][$subGroup][$key];
}
* @param $element Element to set
* @param $value Value to set
* @return void
- */
- protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
- // Debug message
- //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, true));
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ protected final function setGenericArrayElement (string $keyGroup, string $subGroup, string $key, string $element, $value) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s,element=%s,value[]=%s - CALLED!', $keyGroup, $subGroup, $key, $element, gettype($value)));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($element === '') {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "element" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
+ // Initialize array
+ $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
+ }
// Then set it
$this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
+
+ // Trace mesage
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: EXIT!');
}
/**
* @param $key Key to look for
* @param $element Element to look for
* @return $value Mixed value from generic array element
- */
- protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
-
- // Is it there?
- if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If key/sub group isn't there but this method is invoked
+ */
+ protected final function getGenericArrayElement (string $keyGroup, string $subGroup, string $key, string $element) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s,element=%s - CALLED!', $keyGroup, $subGroup, $key, $element));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($element === '') {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "element" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
// Then abort here
- trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
- exit;
- } // END - if
+ throw new BadMethodCallException(sprintf('keyGroup=%s,subGroup=%s,key[%s]=%s,element[%s]=%s not found.', $keyGroup, $subGroup, gettype($key), $key, gettype($element), $element), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: this->genericArray[%s][%s][%s][%s][]=%s - EXIT!', $keyGroup, $subGroup, $key, gettype($this->genericArray[$keyGroup][$subGroup][$key][$element])));
return $this->genericArray[$keyGroup][$subGroup][$key][$element];
}
* @param $keyGroup Key group to get
* @param $subGroup Sub group for the key
* @return $isValid Whether given sub group is valid
- */
- protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ protected final function isValidGenericArrayGroup (string $keyGroup, string $subGroup) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s - CALLED!', $keyGroup, $subGroup));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Determine it
$isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: isValid=%d - EXIT!', intval($isValid)));
return $isValid;
}
* @param $key Key to check
* @return $isValid Whether given sub group is valid
*/
- protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
- // Debug message
- //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
+ protected final function isValidGenericArrayKey (string $keyGroup, string $subGroup, string $key) {
+ // Check parameters
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: keyGroup=%s,subGroup=%s,key=%s - CALLED!', $keyGroup, $subGroup, $key));
+ if (empty($keyGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "keyGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Determine it
$isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: isValid=%d - EXIT!', intval($isValid)));
return $isValid;
}
* @return void
*/
protected function initWebOutputInstance () {
- // Get application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
-
// Init web output instance
- $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: CALLED!');
+ $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class');
// Set it locally
$this->setWebOutputInstance($outputInstance);
+
+ // Trace mesage
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: EXIT!');
}
/**
* @param $boolean Boolean value
* @return $translated Translated boolean value
*/
- public static final function translateBooleanToYesNo ($boolean) {
- // Make sure it is really boolean
- assert(is_bool($boolean));
-
+ public static final function translateBooleanToYesNo (bool $boolean) {
// "Translate" it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: boolean=%d - CALLED!', intval($boolean)));
$translated = ($boolean === true) ? 'Y' : 'N';
// ... and return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: translated=%s - EXIT!', $translated));
return $translated;
}
- /**
- * Encodes raw data (almost any type) by "serializing" it and then pack it
- * into a "binary format".
- *
- * @param $rawData Raw data (almost any type)
- * @return $encoded Encoded data
- */
- protected function encodeData ($rawData) {
- // Make sure no objects or resources pass through
- assert(!is_object($rawData));
- assert(!is_resource($rawData));
-
- // First "serialize" it (json_encode() is faster than serialize())
- $encoded = $this->packString(json_encode($rawData));
-
- // And return it
- return $encoded;
- }
-
- /**
- * Pack a string into a "binary format". Please execuse me that this is
- * widely undocumented. :-(
- *
- * @param $str Unpacked string
- * @return $packed Packed string
- * @todo Improve documentation
- */
- protected function packString ($str) {
- // Debug message
- //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
-
- // First compress the string (gzcompress is okay)
- $str = gzcompress($str);
-
- // Init variable
- $packed = '';
-
- // And start the "encoding" loop
- for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
- $big = 0;
- for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
- $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
-
- if (($idx + $i) <= strlen($str)) {
- $ord = ord(substr($str, ($idx + $i), 1));
-
- $add = $ord * pow(256, $factor);
-
- $big += $add;
-
- //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
- } // END - if
- } // END - for
-
- $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
- $r = $big & $this->packingData[$this->archArrayElement]['right'];
-
- $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
- //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
-
- $packed .= $chunk;
- } // END - for
-
- // Return it
- //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
- return $packed;
- }
-
/**
* Creates a full-qualified file name (FQFN) for given file name by adding
* a configured temporary file path to it.
*
* @param $infoInstance An instance of a SplFileInfo class
- * @return $tempInstance An instance of a SplFileInfo class (temporary file)
+ * @return $fileInfoInstance An instance of a SplFileInfo class (temporary file)
* @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
* @throws FileIoException If the file cannot be written
*/
protected static function createTempPathForFile (SplFileInfo $infoInstance) {
// Get config entry
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: infoInstance=%s - CALLED!', $infoInstance->__toString()));
$basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
// Is the path writeable?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: basePath=%s', $basePath));
if (!is_writable($basePath)) {
// Path is write-protected
throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
- } // END - if
+ }
// Add it
- $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
+ $fileInfoInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
// Is it reachable?
- if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
+ if (!FrameworkBootstrap::isReachableFilePath($fileInfoInstance)) {
// Not reachable
- throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
- } // END - if
+ throw new FileIoException($fileInfoInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
+ }
// Return it
- return $tempInstance;
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: fileInfoInstance=%s - EXIT!', $fileInfoInstance->__toString()));
+ return $fileInfoInstance;
}
/**
* "Getter" for a printable state name
*
* @return $stateName Name of the node's state in a printable format
+ * @throws BadMethodCallException If this instance doesn't have a callable getter for stateInstance
+ * @todo Move this class away from this monolithic place (not whole class is monolithic)
*/
public final function getPrintableState () {
+ // Check if getter is there
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: CALLED!');
+ if (!is_callable($this, 'getStateInstance')) {
+ // Throw BMCE
+ throw new BadMethodCallException(sprintf('this=%s has no callable getter for stateInstance', $this->__toString()), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
+
// Default is 'null'
$stateName = 'null';
$stateInstance = $this->getStateInstance();
// Is it an instance of Stateable?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: stateInstance[]=%s', gettype($stateInstance)));
if ($stateInstance instanceof Stateable) {
// Then use that state name
$stateName = $stateInstance->getStateName();
- } // END - if
+ }
// Return result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FRAMEWORK-SYSTEM: stateName=%s - EXIT!', $stateName));
return $stateName;
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @param $className Real class name
*/
- public function __construct ($className) {
- $this->realClass = (string) $className;
+ public function __construct (string $className) {
+ $this->realClass = $className;
}
/**
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
namespace Org\Mxchange\CoreFramework\Client\Http;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Client\BaseClient;
use Org\Mxchange\CoreFramework\Client\Client;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+use \UnexpectedValueException;
/**
* A HTTP client class
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Set default user agent string (to allow other classes to override this)
$this->setUserAgent(self::HTTP_USER_AGENT);
*/
public final static function createHttpClient ($socketResouce = FALSE) {
// Get a new instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HTTP-CLIENT: socketResource[%s]=%s - CALLED!', gettype($socketResource), $socketResource));
$clientInstance = new HttpClient();
// Set socket resource
$clientInstance->setSocketResource($socketResource);
// Return the prepared instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HTTP-CLIENT: clientInstance=%s - EXIT!', $clientInstance->__toString()));
return $clientInstance;
}
*/
protected function isProxyUsed () {
// Do we have cache?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HTTP-CLIENT: CALLED!');
if (!isset($GLOBALS[__METHOD__])) {
// Determine it
- $GLOBALS[__METHOD__] = (($this->getConfigInstance()->getConfigEntry('proxy_host') != '') && ($this->getConfigInstance()->getConfigEntry('proxy_port') > 0));
- } // END - if
+ $GLOBALS[__METHOD__] = ((FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_host') != '') && (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_port') > 0));
+ }
// Return cache
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HTTP-CLIENT: isProxyUsed=%d - EXIT!', $GLOBALS[__METHOD__]));
return $GLOBALS[__METHOD__];
}
* @param $host Host to connect to
* @param $port Port number to connect to
* @return $response Response array
+ * @throws InvalidArgumentException If a paramter has an invalid value
+ * @throws UnexpectedValueException If an unexpected value was found
*/
- protected function setupProxyTunnel ($host, $port) {
+ protected function setupProxyTunnel (string $host, int $port) {
+ // Check paramters
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HTTP-CLIENT: host=%s,port=%d - CALLED!', $host, $port));
+ if (empty($host)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "host" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($port < 1) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('port=%d is not a valid port number', $port), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Initialize array
- $response = array('', '', '');
+ $response = ['', '', ''];
// Do the connect
- $respArray = $this->doConnectRequest($host, $port);
+ $responseArray = $this->doConnectRequest($host, $port);
+
+ // Check array
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HTTP-CLIENT: responseArray()=%d', count($responseArray)));
+ if (count($responseArray) < 2) {
+ // Not expected count
+ throw new UnexpectedValueException(sprintf('responseArray()=%d must have at least two elements', count($responseArray)), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// Analyze first header line
- if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
+ if (((strtolower($responseArray[0]) !== 'http/1.0') && (strtolower($responseArray[0]) !== 'http/1.1')) || ($responseArray[1] != '200')) {
// Response code is not 200
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HTTP-CLIENT: Returning empty response array - EXIT!');
return $response;
- } // END - if
+ }
// All fine!
- return $respArray;
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HTTP-CLIENT: responseArray()=%d - EXIT!', count($responseArray)));
+ return $responseArray;
}
/**
* @param $port Port number to connect to
* @return $responseArray Array with raw response
*/
- private function sendRawHttpRequest ($method, $host, $port, array $header = array()) {
+ private function sendRawHttpRequest (string $method, string $host, int $port, array $header = []) {
// Minimum raw HTTP/1.1 request
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HTTP-CLIENT: method=%s,host=%s,port=%d,header()=%d - CALLED!', $method, $host, $port, count($header)));
$rawRequest = $method . ' ' . $host . ':' . $port . ' HTTP/1.1' . self::HTTP_EOL;
$rawRequest .= 'Host: ' . $host . ':' . $port . self::HTTP_EOL;
// Use login data to proxy? (username at least)
- if ($this->getConfigInstance()->getConfigEntry('proxy_username') != '') {
+ if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_username') != '') {
// Add it as well
- $encodedAuth = base64_encode($this->getConfigInstance()->getConfigEntry('proxy_username') . ':' . $this->getConfigInstance()->getConfigEntry('proxy_password'));
+ $encodedAuth = base64_encode(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_username') . ':' . FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_password'));
$rawRequest .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
- } // END - if
+ }
// Add last new-line
$rawRequest .= self::HTTP_EOL;
- //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('HTTP-CLIENT[' . __METHOD__ . ':' . __LINE__ . ']: rawRequest=' . $rawRequest);
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HTTP-CLIENT: rawRequest=' . $rawRequest);
// Write request
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HTTP-CLIENT: Sending %d bytes to this->socketResource=%s ...', strlen($rawRequest), $this->getSocketResource()));
fwrite($this->getSocketResource(), $rawRequest);
// Got response?
- if (feof($this->getSocketResource())) {
+ $feof = feof($this->getSocketResource());
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HTTP-CLIENT: this->socketResource=%s,feof=%d', $this->getSocketResource(), intval($feof)));
+ if ($feof) {
// No response received
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HTTP-CLIENT: this->socketResource=%s has reached EOF - EXIT!', $this->getSocketResource()));
return $response;
- } // END - if
+ }
// Read the first line
- $resp = trim(fgets($this->getSocketResource(), 10240));
+ $rawResponse = trim(fgets($this->getSocketResource(), 10240));
// "Explode" the string to an array
- $responseArray = explode(' ', $resp);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HTTP-CLIENT: Received %d bytes back from this->socketResource=%s ...', strlen($rawResponse), $this->getSocketResource()));
+ $responseArray = explode(' ', $rawResponse);
// And return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HTTP-CLIENT: responseArray()=%d - EXIT!', count($responseArray)));
return $responseArray;
}
* @param $host Host to connect to
* @param $port Port number to connect to
* @return $responseArray An array with the read response
+ * @throws InvalidArgumentException If a paramter has an invalid value
*/
- public function doConnectRequest ($host, $port) {
+ public function doConnectRequest (string $host, int $port) {
+ // Check paramters
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HTTP-CLIENT: host=%s,port=%d - CALLED!', $host, $port));
+ if (empty($host)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "host" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($port < 1) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('port=%d is not a valid port number', $port), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Prepare extra header(s)
- $headers = array(
+ $headers = [
'Proxy-Connection' => 'Keep-Alive'
- );
+ ];
// Prepare raw request
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HTTP-CLIENT: Invoking this->sendRawHttpRequest(CONNECT,%s,%d,headers()=%d) ...', $host, $port, count($headers)));
$responseArray = $this->sendRawHttpRequest('CONNECT', $host, $port, $headers);
// Return response array
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('HTTP-CLIENT: responseArray()=%d - EXIT!', count($responseArray)));
return $responseArray;
}
<?php
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+
/**
*
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @return void
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
- $this->partialStub('Unfinished!');
+ DebugMiddleware::getSelfInstance()->partialStub('Unfinished!');
}
/**
* @return void
*/
public function addExtraFilters (Controller $controllerInstance, Requestable $requestInstance) {
- $this->partialStub('Unfinished!');
+ DebugMiddleware::getSelfInstance()->partialStub('Unfinished!');
}
}
namespace Org\Mxchange\CoreFramework\Command;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
+use Org\Mxchange\CoreFramework\Traits\Resolver\ResolverTrait;
+use Org\Mxchange\CoreFramework\Traits\Template\CompileableTemplateTrait;
+
+// Import SPL stuff
+use \BadMethodCallException;
+use \InvalidArgumentException;
/**
* A general (base) command
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseCommand extends BaseFrameworkSystem {
+ // Load traits
+ use CompileableTemplateTrait;
+ use ResolverTrait;
+
/**
* Protected constructor
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
+ /**
+ * Initializes the template engine
+ *
+ * @param $templateType Type of template, e.g. 'html', 'image', 'console' ...
+ * @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ */
+ public final function initTemplateEngine (string $templateType) {
+ // Check paramter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-COMMAND: templateType=%s - CALLED!', $templateType));
+ if (empty($templateType)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "templateType" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Prepare a template instance
+ $templateInstance = ObjectFactory::createObjectByConfiguredName(sprintf('%s_template_class', $templateType));
+
+ // Set it here
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-COMMAND: templateInstance=%s', $templateInstance->__toString()));
+ $this->setTemplateInstance($templateInstance);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-COMMAND: EXIT!');
+ }
+
/**
* Sends a generic HTTP response with header, menu, content and footer
*
* @param $responseInstance An instance of a class with an Responseable interface
* @param $suffix Optional template suffix, e.g. '_form' for forms
* @return void
+ * @throws BadMethodCallException If a POST request ended here
*/
- protected function sendGenericGetResponse (Requestable $requestInstance, Responseable $responseInstance, $suffix = '') {
- // This command doesn't handle any POST requests, so only handle get request
- assert(!$requestInstance->isPostRequestMethod());
-
- // Get the application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
-
- // Prepare a template instance
- $templateInstance = $this->prepareTemplateInstance($applicationInstance);
+ protected function sendGenericGetResponse (Requestable $requestInstance, Responseable $responseInstance, string $suffix = '') {
+ // Check conditions
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-COMMAND: requestInstance=%s,responseInstance=%s,suffix=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString(), $suffix));
+ if ($requestInstance->isPostRequestMethod()) {
+ // POST request isn't handled here
+ throw new BadMethodCallException('This method does only handle GET/HEAD requests', FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Transfer application data
- $templateInstance->assignApplicationData();
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-COMMAND: Invoking this->templateInstance->assignApplicationData() ...');
+ $this->getTemplateInstance()->assignApplicationData();
// Assign base URL
- $templateInstance->assignConfigVariable('base_url');
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-COMMAND: Invoking this->templateInstance->assignConfigVariable(base_url) ...');
+ $this->getTemplateInstance()->assignConfigVariable('base_url');
+
+ // Get the application instance
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Load the master template
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-COMMAND: applicationInstance=%s', $applicationInstance->__toString()));
$masterTemplate = $applicationInstance->buildMasterTemplateName();
// Load header template
- $templateInstance->loadCodeTemplate('header');
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-COMMAND: masterTemplate=%s', $masterTemplate));
+ $this->getTemplateInstance()->loadCodeTemplate('header');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('header', 'header');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('header', 'header');
// Load footer template
- $templateInstance->loadCodeTemplate('footer');
+ $this->getTemplateInstance()->loadCodeTemplate('footer');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('footer', 'footer');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('footer', 'footer');
// Load the content template
- $templateInstance->loadCodeTemplate($this->getResolverInstance()->getCommandName() . $suffix);
+ $this->getTemplateInstance()->loadCodeTemplate($this->getResolverInstance()->getCommandName() . $suffix);
// Assign the content template with the master template as a content ... ;)
- $templateInstance->assignTemplateWithVariable($applicationInstance->getAppShortName() . '_' . $this->getResolverInstance()->getCommandName(), 'main_content');
+ $this->getTemplateInstance()->assignTemplateWithVariable($applicationInstance->getAppShortName() . '_' . $this->getResolverInstance()->getCommandName(), 'main_content');
// Load the master template
- $templateInstance->loadCodeTemplate($masterTemplate);
+ $this->getTemplateInstance()->loadCodeTemplate($masterTemplate);
// Set title
- $templateInstance->assignVariable('title', $this->getLanguageInstance()->getMessage('page_' . $applicationInstance->getAppShortName() . '_' . $this->getResolverInstance()->getCommandName() . '_title'));
+ $this->getTemplateInstance()->assignVariable('title', FrameworkBootstrap::getLanguageInstance()->getMessage('page_' . $applicationInstance->getAppShortName() . '_' . $this->getResolverInstance()->getCommandName() . '_title'));
- // Construct the menu in every command. We could do this in BaseCommand class. But this means
- // *every* command has a navigation system and that is want we don't want.
- $menuInstance = ObjectFactory::createObjectByConfiguredName($applicationInstance->getAppShortName() . '_' . $this->getResolverInstance()->getCommandName() . '_menu_class', array($applicationInstance));
+ /*
+ * Construct the menu in every command. We could do this in BaseCommand
+ * class. But this means *every* command has a navigation system and
+ * that is want we don't want.
+ */
+ $menuInstance = ObjectFactory::createObjectByConfiguredName($applicationInstance->getAppShortName() . '_' . $this->getResolverInstance()->getCommandName() . '_menu_class');
// Render the menu
$menuInstance->renderMenu();
// Transfer it to the template engine instance
- $menuInstance->transferContentToTemplateEngine($templateInstance);
+ $menuInstance->transferContentToTemplateEngine($this->getTemplateInstance());
/*
* ... and all variables. This should be merged together in a pattern
* to make things easier. A cache mechanism should be added between
* these two calls to cache compiled templates.
*/
- $templateInstance->compileVariables();
+ $this->getTemplateInstance()->compileVariables();
// Get the content back from the template engine and put it in response class
- $templateInstance->transferToResponse($responseInstance);
+ $this->getTemplateInstance()->transferToResponse($responseInstance);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-COMMAND: EXIT!');
}
}
<?php
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+
/**
* A ??? console command
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @return void
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
- $this->partialStub('Unfinished!');
+ DebugMiddleware::getSelfInstance()->partialStub('Unfinished!');
}
/**
* @return void
*/
public function addExtraFilters (Controller $controllerInstance, Requestable $requestInstance) {
- $this->partialStub('Unfinished!');
+ DebugMiddleware::getSelfInstance()->partialStub('Unfinished!');
}
}
use Org\Mxchange\CoreFramework\Command\Commandable;
use Org\Mxchange\CoreFramework\Controller\Controller;
use Org\Mxchange\CoreFramework\Feature\FrameworkFeature;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Abort here
return;
- } // END - if
+ }
// @TODO Unfinished
- $this->partialStub('Still unfinished! ;-)');
+ DebugMiddleware::getSelfInstance()->partialStub('Still unfinished! ;-)');
}
/**
<?php
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+
/**
* A command for ??? page
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @todo 0% done
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
- $this->partialStub('Unfinished method.');
+ DebugMiddleware::getSelfInstance()->partialStub('Unfinished method.');
}
/**
namespace Org\Mxchange\CoreFramework\Command\Guest;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Command\BaseCommand;
use Org\Mxchange\CoreFramework\Command\Commandable;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseWrapper;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseFrontend;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Get the application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
-
- // Prepare a template instance
- $templateInstance = $this->prepareTemplateInstance($applicationInstance);
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Assign application data with template engine
- $templateInstance->assignApplicationData();
+ $this->getTemplateInstance()->assignApplicationData();
// Assign base URL
- $templateInstance->assignConfigVariable('base_url');
+ $this->getTemplateInstance()->assignConfigVariable('base_url');
// Load the master template
$masterTemplate = $applicationInstance->buildMasterTemplateName();
// Load header template
- $templateInstance->loadCodeTemplate('header');
+ $this->getTemplateInstance()->loadCodeTemplate('header');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('header', 'header');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('header', 'header');
// Load footer template
- $templateInstance->loadCodeTemplate('footer');
+ $this->getTemplateInstance()->loadCodeTemplate('footer');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('footer', 'footer');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('footer', 'footer');
// Load the home template
- $templateInstance->loadCodeTemplate('confirm_link');
+ $this->getTemplateInstance()->loadCodeTemplate('confirm_link');
// Assign the home template with the master template as a content ... ;)
- $templateInstance->assignTemplateWithVariable('confirm_link', 'main_content');
+ $this->getTemplateInstance()->assignTemplateWithVariable('confirm_link', 'main_content');
// Load the master template
- $templateInstance->loadCodeTemplate($masterTemplate);
+ $this->getTemplateInstance()->loadCodeTemplate($masterTemplate);
// Set title
- $templateInstance->assignVariable('title', $this->getLanguageInstance()->getMessage('page_confirm_link_title'));
+ $this->getTemplateInstance()->assignVariable('title', FrameworkBootstrap::getLanguageInstance()->getMessage('page_confirm_link_title'));
// Get user instance
try {
- $userInstance = GenericRegistry::getRegistry()->getInstance('user');
+ $userInstance = ObjectRegistry::getRegistry('generic')->getInstance('user');
} catch (NullPointerException $e) {
// Not found user, e.g. when the user is somehow invalid
$responseInstance->redirectToConfiguredUrl('html_cmd_user_is_null');
}
// Set username
- $templateInstance->assignVariable('username', $userInstance->getField(UserDatabaseWrapper::DB_COLUMN_USERNAME));
+ $this->getTemplateInstance()->assignVariable('username', $userInstance->getField(UserDatabaseFrontend::DB_COLUMN_USERNAME));
// Construct the menu in every command. We could do this in BaseCommand class. But this means
// *every* command has a navigation system and that is want we don't want.
- $menuInstance = ObjectFactory::createObjectByConfiguredName('confirm_menu_class', array($applicationInstance));
+ $menuInstance = ObjectFactory::createObjectByConfiguredName('confirm_menu_class');
// Render the menu
$menuInstance->renderMenu();
// Transfer it to the template engine instance
- $menuInstance->transferContentToTemplateEngine($templateInstance);
+ $menuInstance->transferContentToTemplateEngine($this->getTemplateInstance());
/*
* ... and all variables. This should be merged together in a pattern
* to make things easier. A cache mechanism should be added between
* these two calls to cache compiled templates.
*/
- $templateInstance->compileVariables();
+ $this->getTemplateInstance()->compileVariables();
// Get the content back from the template engine and put it in response class
- $templateInstance->transferToResponse($responseInstance);
+ $this->getTemplateInstance()->transferToResponse($responseInstance);
}
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
namespace Org\Mxchange\CoreFramework\Command\Guest;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Command\BaseCommand;
use Org\Mxchange\CoreFramework\Command\Commandable;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Get the application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Prepare a template instance
- $templateInstance = $this->prepareTemplateInstance($applicationInstance);
-
// Transfer application data
- $templateInstance->assignApplicationData();
+ $this->getTemplateInstance()->assignApplicationData();
// Load the master template
$masterTemplate = $applicationInstance->buildMasterTemplateName();
// Load header template
- $templateInstance->loadCodeTemplate('header');
+ $this->getTemplateInstance()->loadCodeTemplate('header');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('header', 'header');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('header', 'header');
// Load footer template
- $templateInstance->loadCodeTemplate('footer');
+ $this->getTemplateInstance()->loadCodeTemplate('footer');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('footer', 'footer');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('footer', 'footer');
// Load the home template
- $templateInstance->loadCodeTemplate('home');
+ $this->getTemplateInstance()->loadCodeTemplate('home');
// Assign the home template with the master template as a content ... ;)
- $templateInstance->assignTemplateWithVariable('home', 'main_content');
+ $this->getTemplateInstance()->assignTemplateWithVariable('home', 'main_content');
// Load the master template
- $templateInstance->loadCodeTemplate($masterTemplate);
+ $this->getTemplateInstance()->loadCodeTemplate($masterTemplate);
// Set title
- $templateInstance->assignVariable('title', $this->getLanguageInstance()->getMessage('page_home_title'));
+ $this->getTemplateInstance()->assignVariable('title', FrameworkBootstrap::getLanguageInstance()->getMessage('page_home_title'));
// Construct the menu in every command. We could do this in BaseCommand class. But this means
// *every* command has a navigation system and that is want we don't want.
- $menuInstance = ObjectFactory::createObjectByConfiguredName('home_menu_class', array($applicationInstance));
+ $menuInstance = ObjectFactory::createObjectByConfiguredName('home_menu_class');
// Render the menu
$menuInstance->renderMenu();
// Transfer it to the template engine instance
- $menuInstance->transferContentToTemplateEngine($templateInstance);
+ $menuInstance->transferContentToTemplateEngine($this->getTemplateInstance());
/*
* ... and all variables. This should be merged together in a pattern
* to make things easier. A cache mechanism should be added between
* these two calls to cache compiled templates.
*/
- $templateInstance->compileVariables();
+ $this->getTemplateInstance()->compileVariables();
// Get the content back from the template engine and put it in response class
- $templateInstance->transferToResponse($responseInstance);
+ $this->getTemplateInstance()->transferToResponse($responseInstance);
}
/**
// Import framework stuff
use Org\Mxchange\CoreFramework\Action\PerformableAction;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Command\BaseCommand;
use Org\Mxchange\CoreFramework\Command\Commandable;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
-use Org\Mxchange\CoreFramework\String\Utils\StringUtils;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
/**
* A command for the login area (member/gamer area)
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Get the action instance from registry
- $actionInstance = GenericRegistry::getRegistry()->getInstance('action');
+ $actionInstance = ObjectRegistry::getRegistry('generic')->getInstance('action');
// Do we have an action here?
if ($actionInstance instanceof PerformableAction) {
// Execute the action (shall not output anything, see below why)
$actionInstance->execute($requestInstance, $responseInstance);
- } // END - if
+ }
// Get the application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
-
- // Prepare a template instance
- $templateInstance = $this->prepareTemplateInstance($applicationInstance);
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Assign base URL
- $templateInstance->assignConfigVariable('base_url');
+ $this->getTemplateInstance()->assignConfigVariable('base_url');
// Assign all the application's data with template variables
- $templateInstance->assignApplicationData();
+ $this->getTemplateInstance()->assignApplicationData();
// Load the master template
$masterTemplate = $applicationInstance->buildMasterTemplateName();
// Load header template
- $templateInstance->loadCodeTemplate('header');
+ $this->getTemplateInstance()->loadCodeTemplate('header');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('header', 'header');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('header', 'header');
// Load footer template
- $templateInstance->loadCodeTemplate('footer');
+ $this->getTemplateInstance()->loadCodeTemplate('footer');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('footer', 'footer');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('footer', 'footer');
// Load the matching template
- $templateInstance->loadCodeTemplate('action_' . $this->actionName);
+ $this->getTemplateInstance()->loadCodeTemplate('action_' . $this->actionName);
// Assign the template with the master template as a content ... ;)
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('action_' . $this->actionName, 'login_content');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('action_' . $this->actionName, 'login_content');
// Load main template
- $templateInstance->loadCodeTemplate('login_main');
+ $this->getTemplateInstance()->loadCodeTemplate('login_main');
// Assign the main template with the master template as a content ... ;)
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('login_main', 'main_content');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('login_main', 'main_content');
// Load the master template
- $templateInstance->loadCodeTemplate($masterTemplate);
+ $this->getTemplateInstance()->loadCodeTemplate($masterTemplate);
// Set title
- $templateInstance->assignVariable('title', $this->getLanguageInstance()->getMessage($this->actionName . '_title'));
+ $this->getTemplateInstance()->assignVariable('title', FrameworkBootstrap::getLanguageInstance()->getMessage($this->actionName . '_title'));
// Construct the menu in every command. We could do this in BaseCommand class. But this means
// *every* command has a navigation system and that is want we don't want.
- $menuInstance = ObjectFactory::createObjectByConfiguredName('login_area_menu_class', array($applicationInstance));
+ $menuInstance = ObjectFactory::createObjectByConfiguredName('login_area_menu_class');
// Render the menu
$menuInstance->renderMenu();
// Transfer it to the template engine instance
- $menuInstance->transferContentToTemplateEngine($templateInstance);
+ $menuInstance->transferContentToTemplateEngine($this->getTemplateInstance());
/*
* ... and all variables. This should be merged together in a pattern
* to make things easier. A cache mechanism should be added between
* these two calls to cache compiled templates.
*/
- $templateInstance->compileVariables();
+ $this->getTemplateInstance()->compileVariables();
// Get the content back from the template engine and put it in response class
- $templateInstance->transferToResponse($responseInstance);
+ $this->getTemplateInstance()->transferToResponse($responseInstance);
}
/**
* @return void
*/
public function addExtraFilters (Controller $controllerInstance, Requestable $requestInstance) {
- // Default is no action
- $actionInstance = NULL;
-
- // Get registry
- $registryInstance = GenericRegistry::getRegistry();
-
// Get our application instance from the registry
- $applicationInstance = $registryInstance->getInstance('application');
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Default action is the one from configuration
- $this->actionName = StringUtils::convertDashesToUnderscores($applicationInstance->getAppShortName()) . '_login_' . $this->getConfigInstance()->getConfigEntry('login_default_action');
+ $this->actionName = StringUtils::convertDashesToUnderscores($applicationInstance->getAppShortName()) . '_login_' . FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('login_default_action');
// Get "action" from request
$actReq = $requestInstance->getRequestElement('action');
// Do we have a "action" parameter set?
- if ((is_string($actReq)) && (!empty($actReq))) {
+ if (!empty($actReq)) {
// Then use it with prefix
$this->actionName = StringUtils::convertDashesToUnderscores($applicationInstance->getAppShortName()) . '_login_' . $actReq;
- } // END - if
+ }
// Get a resolver
$actionResolver = HtmlActionResolver::createHtmlActionResolver($this->actionName);
$actionInstance->addExtraFilters($controllerInstance, $requestInstance);
// Remember this action in registry
- GenericRegistry::getRegistry()->addInstance('action', $actionInstance);
+ ObjectRegistry::getRegistry('generic')->addInstance('action', $actionInstance);
}
}
namespace Org\Mxchange\CoreFramework\Command\Login;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Command\BaseCommand;
use Org\Mxchange\CoreFramework\Command\Commandable;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Set request instance as extra instance
- GenericRegistry::getRegistry()->addInstance('extra', $this);
+ ObjectRegistry::getRegistry('generic')->addInstance('extra', $this);
// Get the application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
-
- // Prepare a template instance
- $templateInstance = $this->prepareTemplateInstance($applicationInstance);
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Assign application data with template engine
- $templateInstance->assignApplicationData();
+ $this->getTemplateInstance()->assignApplicationData();
// Assign base URL
- $templateInstance->assignConfigVariable('base_url');
+ $this->getTemplateInstance()->assignConfigVariable('base_url');
// Load the master template
$masterTemplate = $applicationInstance->buildMasterTemplateName();
// Load header template
- $templateInstance->loadCodeTemplate('header');
+ $this->getTemplateInstance()->loadCodeTemplate('header');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('header', 'header');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('header', 'header');
// Load footer template
- $templateInstance->loadCodeTemplate('footer');
+ $this->getTemplateInstance()->loadCodeTemplate('footer');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('footer', 'footer');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('footer', 'footer');
// Load the home template
- $templateInstance->loadCodeTemplate('login_form');
+ $this->getTemplateInstance()->loadCodeTemplate('login_form');
// Assign the home template with the master template as a content ... ;)
- $templateInstance->assignTemplateWithVariable('login_form', 'main_content');
+ $this->getTemplateInstance()->assignTemplateWithVariable('login_form', 'main_content');
// Load the master template
- $templateInstance->loadCodeTemplate($masterTemplate);
+ $this->getTemplateInstance()->loadCodeTemplate($masterTemplate);
// Set title
- $templateInstance->assignVariable('title', $this->getLanguageInstance()->getMessage('page_login_title'));
+ $this->getTemplateInstance()->assignVariable('title', FrameworkBootstrap::getLanguageInstance()->getMessage('page_login_title'));
// Construct the menu in every command. We could do this in BaseCommand class. But this means
// *every* command has a navigation system and that is want we don't want.
- $menuInstance = ObjectFactory::createObjectByConfiguredName('login_menu_class', array($applicationInstance));
+ $menuInstance = ObjectFactory::createObjectByConfiguredName('login_menu_class');
// Render the menu
$menuInstance->renderMenu();
// Transfer it to the template engine instance
- $menuInstance->transferContentToTemplateEngine($templateInstance);
+ $menuInstance->transferContentToTemplateEngine($this->getTemplateInstance());
/*
* ... and all variables. This should be merged together in a pattern
* to make things easier. A cache mechanism should be added between
* these two calls to cache compiled templates.
*/
- $templateInstance->compileVariables();
+ $this->getTemplateInstance()->compileVariables();
// Get the content back from the template engine and put it in response class
- $templateInstance->transferToResponse($responseInstance);
+ $this->getTemplateInstance()->transferToResponse($responseInstance);
}
/**
namespace Org\Mxchange\CoreFramework\Command\Failed;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Command\BaseCommand;
use Org\Mxchange\CoreFramework\Command\Commandable;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Get the application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
-
- // Prepare a template instance
- $templateInstance = $this->prepareTemplateInstance($applicationInstance);
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Assign application data with template engine
- $templateInstance->assignApplicationData();
+ $this->getTemplateInstance()->assignApplicationData();
// Load the master template
$masterTemplate = $applicationInstance->buildMasterTemplateName();
// Load header template
- $templateInstance->loadCodeTemplate('header');
+ $this->getTemplateInstance()->loadCodeTemplate('header');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('header', 'header');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('header', 'header');
// Load footer template
- $templateInstance->loadCodeTemplate('footer');
+ $this->getTemplateInstance()->loadCodeTemplate('footer');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('footer', 'footer');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('footer', 'footer');
// Load the login_failed template
- $templateInstance->loadCodeTemplate('login_failed');
+ $this->getTemplateInstance()->loadCodeTemplate('login_failed');
// Assign the login_failed template with the master template as a content ... ;)
- $templateInstance->assignTemplateWithVariable('login_failed', 'main_content');
+ $this->getTemplateInstance()->assignTemplateWithVariable('login_failed', 'main_content');
// Load the master template
- $templateInstance->loadCodeTemplate($masterTemplate);
+ $this->getTemplateInstance()->loadCodeTemplate($masterTemplate);
// Set title
- $templateInstance->assignVariable('title', $this->getLanguageInstance()->getMessage('login_failed_title'));
+ $this->getTemplateInstance()->assignVariable('title', FrameworkBootstrap::getLanguageInstance()->getMessage('login_failed_title'));
// Assign base URL
- $templateInstance->assignConfigVariable('base_url');
+ $this->getTemplateInstance()->assignConfigVariable('base_url');
// Construct the menu in every command. We could do this in BaseCommand class. But this means
// *every* command has a navigation system and that is want we don't want.
- $menuInstance = ObjectFactory::createObjectByConfiguredName('login_failed_menu_class', array($applicationInstance));
+ $menuInstance = ObjectFactory::createObjectByConfiguredName('login_failed_menu_class');
// Render the menu
$menuInstance->renderMenu();
// Transfer it to the template engine instance
- $menuInstance->transferContentToTemplateEngine($templateInstance);
+ $menuInstance->transferContentToTemplateEngine($this->getTemplateInstance());
/*
* ... and all variables. This should be merged together in a pattern
* to make things easier. A cache mechanism should be added between
* these two calls to cache compiled templates.
*/
- $templateInstance->compileVariables();
+ $this->getTemplateInstance()->compileVariables();
// Get the content back from the template engine and put it in response class
- $templateInstance->transferToResponse($responseInstance);
+ $this->getTemplateInstance()->transferToResponse($responseInstance);
}
/**
use Org\Mxchange\CoreFramework\Command\BaseCommand;
use Org\Mxchange\CoreFramework\Command\Commandable;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
namespace Org\Mxchange\CoreFramework\Command\Logout;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Command\BaseCommand;
use Org\Mxchange\CoreFramework\Command\Commandable;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Get the application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
-
- // Prepare a template instance
- $templateInstance = $this->prepareTemplateInstance($applicationInstance);
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Assign application data
- $templateInstance->assignApplicationData();
+ $this->getTemplateInstance()->assignApplicationData();
// Load the master template
$masterTemplate = $applicationInstance->buildMasterTemplateName();
// Load header template
- $templateInstance->loadCodeTemplate('header');
+ $this->getTemplateInstance()->loadCodeTemplate('header');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('header', 'header');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('header', 'header');
// Load footer template
- $templateInstance->loadCodeTemplate('footer');
+ $this->getTemplateInstance()->loadCodeTemplate('footer');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('footer', 'footer');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('footer', 'footer');
// Load the logout_done template
- $templateInstance->loadCodeTemplate('logout_done');
+ $this->getTemplateInstance()->loadCodeTemplate('logout_done');
// Assign the logout_done template with the master template as a content ... ;)
- $templateInstance->assignTemplateWithVariable('logout_done', 'main_content');
+ $this->getTemplateInstance()->assignTemplateWithVariable('logout_done', 'main_content');
// Load the master template
- $templateInstance->loadCodeTemplate($masterTemplate);
+ $this->getTemplateInstance()->loadCodeTemplate($masterTemplate);
// Set title
- $templateInstance->assignVariable('title', $this->getLanguageInstance()->getMessage('logout_done_title'));
+ $this->getTemplateInstance()->assignVariable('title', FrameworkBootstrap::getLanguageInstance()->getMessage('logout_done_title'));
// Assign base URL
- $templateInstance->assignConfigVariable('base_url');
+ $this->getTemplateInstance()->assignConfigVariable('base_url');
// Construct the menu in every command. We could do this in BaseCommand class. But this means
// *every* command has a navigation system and that is want we don't want.
- $menuInstance = ObjectFactory::createObjectByConfiguredName('logout_menu_class', array($applicationInstance));
+ $menuInstance = ObjectFactory::createObjectByConfiguredName('logout_menu_class');
// Render the menu
$menuInstance->renderMenu();
// Transfer it to the template engine instance
- $menuInstance->transferContentToTemplateEngine($templateInstance);
+ $menuInstance->transferContentToTemplateEngine($this->getTemplateInstance());
/*
* ... and all variables. This should be merged together in a pattern
* to make things easier. A cache mechanism should be added between
* these two calls to cache compiled templates.
*/
- $templateInstance->compileVariables();
+ $this->getTemplateInstance()->compileVariables();
// Get the content back from the template engine and put it in response class
- $templateInstance->transferToResponse($responseInstance);
+ $this->getTemplateInstance()->transferToResponse($responseInstance);
}
/**
use Org\Mxchange\CoreFramework\Command\BaseCommand;
use Org\Mxchange\CoreFramework\Command\Commandable;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @todo 0% done
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
- $this->partialStub('Unfinished method.');
+ DebugMiddleware::getSelfInstance()->partialStub('Unfinished method.');
}
/**
namespace Org\Mxchange\CoreFramework\Command\Register;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Command\BaseCommand;
use Org\Mxchange\CoreFramework\Command\Commandable;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Set request instance as extra instance
- GenericRegistry::getRegistry()->addInstance('extra', $this);
+ ObjectRegistry::getRegistry('generic')->addInstance('extra', $this);
// Get the application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
-
- // Prepare a template instance
- $templateInstance = $this->prepareTemplateInstance($applicationInstance);
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Assign all the application's data with template variables
- $templateInstance->assignApplicationData();
+ $this->getTemplateInstance()->assignApplicationData();
// Assign base URL
- $templateInstance->assignConfigVariable('base_url');
+ $this->getTemplateInstance()->assignConfigVariable('base_url');
// Load the master template
$masterTemplate = $applicationInstance->buildMasterTemplateName();
// Load header template
- $templateInstance->loadCodeTemplate('header');
+ $this->getTemplateInstance()->loadCodeTemplate('header');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('header', 'header');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('header', 'header');
// Load footer template
- $templateInstance->loadCodeTemplate('footer');
+ $this->getTemplateInstance()->loadCodeTemplate('footer');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('footer', 'footer');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('footer', 'footer');
// Load the register template
- $templateInstance->loadCodeTemplate('register_form');
+ $this->getTemplateInstance()->loadCodeTemplate('register_form');
// Assign the register template with the master template as a content ... ;)
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('register_form', 'main_content');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('register_form', 'main_content');
// Load the master template
- $templateInstance->loadCodeTemplate($masterTemplate);
+ $this->getTemplateInstance()->loadCodeTemplate($masterTemplate);
// Set title
- $templateInstance->assignVariable('title', $this->getLanguageInstance()->getMessage('page_register_title'));
+ $this->getTemplateInstance()->assignVariable('title', FrameworkBootstrap::getLanguageInstance()->getMessage('page_register_title'));
// Construct the menu in every command. We could do this in BaseCommand class. But this means
// *every* command has a navigation system and that is want we don't want.
- $menuInstance = ObjectFactory::createObjectByConfiguredName('register_menu_class', array($applicationInstance));
+ $menuInstance = ObjectFactory::createObjectByConfiguredName('register_menu_class');
// Render the menu
$menuInstance->renderMenu();
// Transfer it to the template engine instance
- $menuInstance->transferContentToTemplateEngine($templateInstance);
+ $menuInstance->transferContentToTemplateEngine($this->getTemplateInstance());
/*
* ... and all variables. This should be merged together in a pattern
* to make things easier. A cache mechanism should be added between
* these two calls to cache compiled templates.
*/
- $templateInstance->compileVariables();
+ $this->getTemplateInstance()->compileVariables();
// Get the content back from the template engine and put it in response class
- $templateInstance->transferToResponse($responseInstance);
+ $this->getTemplateInstance()->transferToResponse($responseInstance);
}
/**
namespace Org\Mxchange\CoreFramework\Command\Guest;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Command\BaseCommand;
use Org\Mxchange\CoreFramework\Command\Commandable;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseWrapper;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseFrontend;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
+use Org\Mxchange\CoreFramework\Helper\Crypto\CryptoHelper;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Get user instance from registry
- $userInstance = GenericRegistry::getRegistry()->getInstance('user');
+ $userInstance = ObjectRegistry::getRegistry('generic')->getInstance('user');
// Get an application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Get a RNG instance (Random Number Generator)
$rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
$randomString = $rngInstance->randomString(255);
// Get a crypto instance
- $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
+ $cryptoInstance = CryptoHelper::getSelfInstance();
// Hash and encrypt the string
$hashedString = $cryptoInstance->hashString($cryptoInstance->encryptString($randomString));
// Update the user class
- $userInstance->updateDatabaseField(UserDatabaseWrapper::DB_COLUMN_CONFIRM_HASH, $hashedString);
+ $userInstance->updateDatabaseField(UserDatabaseFrontend::DB_COLUMN_CONFIRM_HASH, $hashedString);
// Re-set config entry to mailer engine
- $this->getConfigInstance()->setConfigEntry('html_template_class', $this->getConfigInstance()->getConfigEntry('mail_template_class'));
-
- // Prepare the template engine
- $templateInstance = $this->prepareTemplateInstance($applicationInstance);
+ FrameworkBootstrap::getConfigurationInstance()->setConfigEntry('html_template_class', FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('mail_template_class'));
// Assign the application data with the template engine
- $templateInstance->assignApplicationData();
+ $this->getTemplateInstance()->assignApplicationData();
// Get a mailer class
- $mailerInstance = ObjectFactory::createObjectByConfiguredName('mailer_class', array($templateInstance, 'resend_link'));
+ $mailerInstance = ObjectFactory::createObjectByConfiguredName('mailer_class', array($this->getTemplateInstance(), 'resend_link'));
// Set this mailer in our template engine
- $templateInstance->setMailerInstance($mailerInstance);
+ $this->getTemplateInstance()->setMailerInstance($mailerInstance);
// Add template variables we shall get
$mailerInstance->addConfigTemplateVariable('base_url');
namespace Org\Mxchange\CoreFramework\Command\Status;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Command\BaseCommand;
use Org\Mxchange\CoreFramework\Command\Commandable;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Get the application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
-
- // Prepare a template instance
- $templateInstance = $this->prepareTemplateInstance($applicationInstance);
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Transfer application data
- $templateInstance->assignApplicationData();
+ $this->getTemplateInstance()->assignApplicationData();
// Load the master template
$masterTemplate = $applicationInstance->buildMasterTemplateName();
// Load header template
- $templateInstance->loadCodeTemplate('header');
+ $this->getTemplateInstance()->loadCodeTemplate('header');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('header', 'header');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('header', 'header');
// Load footer template
- $templateInstance->loadCodeTemplate('footer');
+ $this->getTemplateInstance()->loadCodeTemplate('footer');
// Compile and assign it with a variable
- $templateInstance->compileTemplate();
- $templateInstance->assignTemplateWithVariable('footer', 'footer');
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->assignTemplateWithVariable('footer', 'footer');
// Load the status template
- $templateInstance->loadCodeTemplate('status');
+ $this->getTemplateInstance()->loadCodeTemplate('status');
// Assign the status template with the master template as a content ... ;)
- $templateInstance->assignTemplateWithVariable('status', 'main_content');
+ $this->getTemplateInstance()->assignTemplateWithVariable('status', 'main_content');
// Load the master template
- $templateInstance->loadCodeTemplate($masterTemplate);
+ $this->getTemplateInstance()->loadCodeTemplate($masterTemplate);
// Set title
- $templateInstance->assignVariable('title', $this->getLanguageInstance()->getMessage('page_status_title'));
+ $this->getTemplateInstance()->assignVariable('title', FrameworkBootstrap::getLanguageInstance()->getMessage('page_status_title'));
// Construct the menu in every command. We could do this in BaseCommand class. But this means
// *every* command has a navigation system and that is want we don't want.
- $menuInstance = ObjectFactory::createObjectByConfiguredName('status_menu_class', array($applicationInstance));
+ $menuInstance = ObjectFactory::createObjectByConfiguredName('status_menu_class');
// Render the menu
$menuInstance->renderMenu();
// Transfer it to the template engine instance
- $menuInstance->transferContentToTemplateEngine($templateInstance);
+ $menuInstance->transferContentToTemplateEngine($this->getTemplateInstance());
/*
* ... and all variables. This should be merged together in a pattern
* to make things easier. A cache mechanism should be added between
* these two calls to cache compiled templates.
*/
- $templateInstance->compileVariables();
+ $this->getTemplateInstance()->compileVariables();
// Get the content back from the template engine and put it in response class
- $templateInstance->transferToResponse($responseInstance);
+ $this->getTemplateInstance()->transferToResponse($responseInstance);
}
/**
use Org\Mxchange\CoreFramework\Command\BaseCommand;
use Org\Mxchange\CoreFramework\Command\Commandable;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$decryptedCode = $requestInstance->getRequestElement('decrypted');
// Get the application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
-
- // Prepare a template instance
- $templateInstance = $this->prepareTemplateInstance($applicationInstance);
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Assign variable
- $templateInstance->assignVariable('decrypted_code', $decryptedCode);
+ $this->getTemplateInstance()->assignVariable('decrypted_code', $decryptedCode);
// Load the code (pardon, image...) template
- $templateInstance->loadCodeTemplate('code_captcha');
+ $this->getTemplateInstance()->loadCodeTemplate('code_captcha');
// Compile the template
- $templateInstance->compileTemplate();
+ $this->getTemplateInstance()->compileTemplate();
// Compile all variables
- $templateInstance->compileVariables();
+ $this->getTemplateInstance()->compileVariables();
// Transfer it to the response
- $templateInstance->transferToResponse($responseInstance);
+ $this->getTemplateInstance()->transferToResponse($responseInstance);
}
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor!
parent::__construct(__CLASS__);
}
$compressorInstance = NULL;
// Get new instance
- if ((function_exists('bzcompress')) && (function_exists('bzdecompress'))) {
+ if (extension_loaded('bzip2')) {
// Compressor can maybe be used
$compressorInstance = new Bzip2Compressor();
- } // END - if
+ }
// Return the compressor instance
return $compressorInstance;
*
* @param $streamData Mixed non-object stream data
* @return $streamData The compressed stream data
- * @throws InvalidObjectException If the stream is an object
*/
- public function compressStream ($streamData) {
- if (is_object($streamData)) {
- // Throw an exception
- throw new InvalidObjectException($streamData, self::EXCEPTION_UNEXPECTED_OBJECT);
- } // END - if
+ public function compressStream (string $streamData) {
+ // Compress it
+ $streamData = bzcompress($streamData, 1);
// Return the compressed stream
- return bzcompress($streamData, 1);
+ return $streamData;
}
/**
*
* @param $streamData Mixed non-object stream data
* @return $streamData The decompressed stream data
- * @throws InvalidObjectException If the stream is an object
*/
- public function decompressStream ($streamData) {
- if (is_object($streamData)) {
- // Throw an exception
- throw new InvalidObjectException($streamData, self::EXCEPTION_UNEXPECTED_OBJECT);
- } // END - if
-
+ public function decompressStream (string $streamData) {
// Decompress it
$streamData = bzdecompress($streamData, true);
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor!
parent::__construct(__CLASS__);
}
if ((function_exists('gzencode')) && (function_exists('gzdecode'))) {
// Compressor can maybe be used
$compressorInstance = new GzipCompressor();
- } // END - if
+ }
// Return the compressor instance
return $compressorInstance;
*
* @param $streamData Mixed non-object stream data
* @return $streamData The compressed stream data
- * @throws InvalidObjectException If the stream is an object
*/
- public function compressStream ($streamData) {
- if (is_object($streamData)) {
- // Throw an exception
- throw new InvalidObjectException($streamData, self::EXCEPTION_UNEXPECTED_OBJECT);
- } // END - if
+ public function compressStream (string $streamData) {
+ // Compress stream
+ $streamData = gzencode($streamData, 1);
- // Return the compressed stream
- return gzencode($streamData, 1);
+ // Return it
+ return $streamData;
}
/**
*
* @param $streamData Mixed non-object stream data
* @return $streamData The decompressed stream data
- * @throws InvalidObjectException If the stream is an object
*/
- public function decompressStream ($streamData) {
- if (is_object($streamData)) {
- // Throw an exception
- throw new InvalidObjectException($streamData, self::EXCEPTION_UNEXPECTED_OBJECT);
- } // END - if
+ public function decompressStream (string $streamData) {
+ // Decompress string
+ $streamData = gzdecode($streamData);
- // Return the decompressed stream
- return gzdecode($streamData);
+ // Return it
+ return $streamData;
}
/**
use Org\Mxchange\CoreFramework\Compressor\Compressor;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+// Load SPL stuff
+use \InvalidArgumentException;
+
/**
* Null compression and decompression class
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor!
parent::__construct(__CLASS__);
}
*
* @param $streamData Mixed non-object stream data
* @return $streamData The compressed stream data
- * @throws InvalidObjectException If the stream is an object
+ * @throws InvalidArgumentException If the stream is not compressable or decompressable
*/
- public function compressStream ($streamData) {
- if (is_object($streamData)) {
+ public function compressStream (string $streamData) {
+ // Validate parameter
+ if (is_object($streamData) || is_resource($streamData)) {
// Throw an exception
- throw new InvalidObjectException($streamData, self::EXCEPTION_UNEXPECTED_OBJECT);
- } // END - if
+ throw new InvalidArgumentException(sprintf('streamData[]=%s cannot be compressed/decompressed', gettype($streamData)));
+ }
// Return the compressed stream
return $streamData;
*
* @param $streamData Mixed non-object stream data
* @return $streamData The decompressed stream data
- * @throws InvalidObjectException If the stream is an object
+ * @throws InvalidArgumentException If the stream is not compressable or decompressable
*/
- public function decompressStream ($streamData) {
- if (is_object($streamData)) {
+ public function decompressStream (string $streamData) {
+ // Validate parameter
+ if (is_object($streamData) || is_resource($streamData)) {
// Throw an exception
- throw new InvalidObjectException($streamData, self::EXCEPTION_UNEXPECTED_OBJECT);
- } // END - if
+ throw new InvalidArgumentException(sprintf('streamData[]=%s cannot be compressed/decompressed', gettype($streamData)));
+ }
// Return the decompressed stream
return $streamData;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor!
parent::__construct(__CLASS__);
}
if ((function_exists('gzcompress')) && (function_exists('gzuncompress'))) {
// Compressor can maybe be used
$compressorInstance = new ZlibCompressor();
- } // END - if
+ }
// Return the compressor instance
return $compressorInstance;
*
* @param $streamData Mixed non-object stream data
* @return $streamData The compressed stream data
- * @throws InvalidObjectException If the stream is an object
*/
- public function compressStream ($streamData) {
- if (is_object($streamData)) {
- // Throw an exception
- throw new InvalidObjectException($streamData, self::EXCEPTION_UNEXPECTED_OBJECT);
- } // END - if
+ public function compressStream (string $streamData) {
+ // Compress string
+ $streamData = gzcompress($streamData, 1);
- // Return the compressed stream
- return gzcompress($streamData, 1);
+ // Return it
+ return $streamData;
}
/**
*
* @param $streamData Mixed non-object stream data
* @return $streamData The decompressed stream data
- * @throws InvalidObjectException If the stream is an object
*/
- public function decompressStream ($streamData) {
- if (is_object($streamData)) {
- // Throw an exception
- throw new InvalidObjectException($streamData, self::EXCEPTION_UNEXPECTED_OBJECT);
- } // END - if
-
+ public function decompressStream (string $streamData) {
// Return the decompressed stream
- return gzuncompress($streamData);
+ $streamData = gzuncompress($streamData);
+
+ // Return it
+ return $streamData;
}
/**
<?php
// Own namespace
-namespace CoreFramework\Container\;
+namespace Org\Mxchange\CoreFramework\Container\;
// Import framework stuff
use Org\Mxchange\CoreFramework\Container\BaseContainer;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
namespace Org\Mxchange\CoreFramework\Controller;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Chain\Filter\InvalidFilterChainException;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filter\Filterable;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Registry\Registerable;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
+use Org\Mxchange\CoreFramework\Traits\Resolver\ResolverTrait;
+
+// Import SPL stuff
+use \BadMethodCallException;
+use \InvalidArgumentException;
/**
* A generic controller class. You should extend this base class if you want to
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseController extends BaseFrameworkSystem implements Registerable {
+ // Load traits
+ use ResolverTrait;
+
// Exception constants
const EXCEPTION_FILTER_CHAIN_INVALID = 0xf10;
// Names of controller's own filter chains
const FILTER_CHAIN_PRE_COMMAND = 'controller_pre_command';
const FILTER_CHAIN_POST_COMMAND = 'controller_post_command';
+ const FILTER_CHAIN_SHUTDOWN = 'shutdown';
/**
* Generic filter chains
*/
- private $filterChains = array();
+ private $filterChains = [];
/**
* Protected constructor
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CONTROLLER: className=%s - CONSTRUCTED!', $className));
parent::__construct($className);
// Initialize both filter chains
- $this->initFilterChain(self::FILTER_CHAIN_PRE_COMMAND);
- $this->initFilterChain(self::FILTER_CHAIN_POST_COMMAND);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('BASE-CONTROLLER: Initializing filter chains ...');
+ foreach([self::FILTER_CHAIN_PRE_COMMAND, self::FILTER_CHAIN_POST_COMMAND] as $filterChain) {
+ // Init it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CONTROLLER: Invoking this->initFilterChain(=%s) ...', $filterChain));
+ $this->initFilterChain($filterChain);
+ }
// Add this controller to the registry
- GenericRegistry::getRegistry()->addInstance('controller', $this);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-CONTROLLER: Registering this=%s ...', $this->__toString()));
+ ObjectRegistry::getRegistry('generic')->addInstance('controller', $this);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CONTROLLER: EXIT!');
}
/**
*/
public function executeGenericPrePostCommand (Requestable $requestInstance, Responseable $responseInstance) {
// Get the command instance from the resolver by sending a request instance to the resolver
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CONTROLLER: requestInstance=%s,responseInstance=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString()));
$commandInstance = $this->getResolverInstance()->resolveCommandByRequest($requestInstance);
// Add more filters by the command
$this->executePreFilters($requestInstance, $responseInstance);
// This request was valid! :-D
- $requestInstance->requestIsValid();
+ $requestInstance->setIsRequestValid(TRUE);
// Execute the command
$commandInstance->execute($requestInstance, $responseInstance);
// Flush the response out
$responseInstance->flushBuffer();
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CONTROLLER: EXIT!');
}
/**
*/
public function genericHanleRequestLoginFailedRedirect (Requestable $requestInstance, Responseable $responseInstance) {
// Get the "form action"
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CONTROLLER: requestInstance=%s,responseInstance=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString()));
$formAction = $requestInstance->getRequestElement('form');
// Get command instance from resolver
- $commandInstance = $this->getResolverInstance()->resolveCommand($formAction);
+ $commandInstance = $this->getResolverInstance()->resolveCommand('Org\Mxchange\CoreFramework\Command\Failed', $formAction);
// Add more filters by the command
$commandInstance->addExtraFilters($this, $requestInstance);
$responseInstance->redirectToConfiguredUrl('login_failed');
// Exit here
- exit();
+ exit;
}
/*
// Execute *very* generic post filters
$this->executePostFilters($requestInstance, $responseInstance);
- } // END - if
+ }
// Flush the buffer out
$responseInstance->flushBuffer();
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CONTROLLER: EXIT!');
}
/**
*/
public function genericHanleRequestLoginAreaFailedRedirect (Requestable $requestInstance, Responseable $responseInstance) {
// Get the command instance from the resolver by sending a request instance to the resolver
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CONTROLLER: requestInstance=%s,responseInstance=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString()));
$commandInstance = $this->getResolverInstance()->resolveCommandByRequest($requestInstance);
// Add more filters by the command
$responseInstance->redirectToConfiguredUrl('login_failed');
// Exit here
- exit();
+ exit;
}
// This request was valid! :-D
- $requestInstance->requestIsValid();
+ $requestInstance->setIsRequestValid(TRUE);
// Execute the command
$commandInstance->execute($requestInstance, $responseInstance);
// Flush the response out
$responseInstance->flushBuffer();
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CONTROLLER: EXIT!');
}
/**
*
* @param $filterChain Name of the filter chain
* @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ * @throws BadMethodCallException If the given filter chain is already initialized
*/
- protected function initFilterChain ($filterChain) {
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONTROLLER: ' . $filterChain . ' init: START');
+ protected function initFilterChain (string $filterChain) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CONTROLLER: filterChain=%s - CALLED!', $filterChain));
+ if (empty($filterChain)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "filterChain" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (isset($this->filterChains[$filterChain])) {
+ // Throw BMCE
+ throw new BadMethodCallException(sprintf('filterChain=%s is already initialized', $filterChain), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
+
+ // Initialize filter chain
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-CONTROLLER: Initializing filterChain=%s ...', $filterChain));
$this->filterChains[$filterChain] = ObjectFactory::createObjectByConfiguredName('filter_chain_class');
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONTROLLER: ' . $filterChain . ' init: FINISHED');
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CONTROLLER: EXIT!');
}
/**
* @param $filterChain Chain of the filter
* @param $filterInstance An instance of a filter
* @return void
- * @throws InvalidFilterChainException If the filter chain is invalid
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ * @throws BadMethodCallException If the given filter chain is not yet initialized
*/
- protected function addFilter ($filterChain, Filterable $filterInstance) {
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONTROLLER: ' . $filterChain . ',' . $filterInstance->__toString(). ' add: START');
-
- // Test if the filter is there
- if (!isset($this->filterChains[$filterChain])) {
- // Throw an exception here
- throw new InvalidFilterChainException(array($this, $filterChain), self::EXCEPTION_FILTER_CHAIN_INVALID);
- } // END - if
+ protected function addFilter (string $filterChain, Filterable $filterInstance) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CONTROLLER: filterChain=%s,filterInstance=%s - CALLED!', $filterChain, $filterInstance->__toString()));
+ if (empty($filterChain)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "filterChain" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!isset($this->filterChains[$filterChain])) {
+ // Throw IAE
+ throw new BadMethodCallException(sprintf('filterChain=%s is not a valid chain', $filterChain), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Add the filter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-CONTROLLER: Adding filterInstance=%s to filterChain=%s ...', $filterInstance->__toString(), $filterChain));
$this->filterChains[$filterChain]->addFilter($filterInstance);
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONTROLLER: ' . $filterChain . ',' . $filterInstance->__toString(). ' add: FINISH');
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CONTROLLER: EXIT!');
}
/**
*/
public function addPreFilter (Filterable $filterInstance) {
// Add the pre filter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CONTROLLER: filterInstance=%s - CALLED!', $filterInstance->__toString()));
$this->addFilter(self::FILTER_CHAIN_PRE_COMMAND, $filterInstance);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CONTROLLER: EXIT!');
}
/**
* @return void
*/
public function addPostFilter (Filterable $filterInstance) {
- // Add the post filter
+ // Add post filter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CONTROLLER: filterInstance=%s - CALLED!', $filterInstance->__toString()));
$this->addFilter(self::FILTER_CHAIN_POST_COMMAND, $filterInstance);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CONTROLLER: EXIT!');
}
/**
* @return void
*/
public function addShutdownFilter (Filterable $filterInstance) {
- $this->addFilter('shutdown', $filterInstance);
+ // Add shutdown filter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CONTROLLER: filterInstance=%s - CALLED!', $filterInstance->__toString()));
+ $this->addFilter(self::FILTER_CHAIN_SHUTDOWN, $filterInstance);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CONTROLLER: EXIT!');
}
/**
* @param $requestInstance An instance of a Requestable class
* @param $responseInstance An instance of a Responseable class
* @return void
- * @throws InvalidFilterChainException If the filter chain is invalid
+ * @throws InvalidArgumentException If the filter chain is invalid
*/
- protected function executeFilters ($filterChain, Requestable $requestInstance, Responseable $responseInstance) {
- // Test if the filter is there
- if (!isset($this->filterChains[$filterChain])) {
+ protected function executeFilters (string $filterChain, Requestable $requestInstance, Responseable $responseInstance) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CONTROLLER: filterChain=%s,requestInstance=%s,responseInstance=%s - CALLED!', $filterChain, $requestInstance->__toString(), $responseInstance->__toString()));
+ if (empty($filterChain)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "filterChain" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!isset($this->filterChains[$filterChain])) {
// Throw an exception here
- throw new InvalidFilterChainException(array($this, $filterChain), self::EXCEPTION_FILTER_CHAIN_INVALID);
- } // END - if
+ throw new BadMethodCallException(sprintf('filterChain=%s is not a valid chain', $filterChain), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Run all filters
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-CONTROLLER: Processing filterChain=%s...', $filterChain));
$this->filterChains[$filterChain]->processFilters($requestInstance, $responseInstance);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CONTROLLER: EXIT!');
}
/**
*/
protected function executePreFilters (Requestable $requestInstance, Responseable $responseInstance) {
// Execute all pre filters
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CONTROLLER: requestInstance=%s,responseInstance=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString()));
$this->executeFilters(self::FILTER_CHAIN_PRE_COMMAND, $requestInstance, $responseInstance);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CONTROLLER: EXIT!');
}
/**
*/
protected function executePostFilters (Requestable $requestInstance, Responseable $responseInstance) {
// Execute all post filters
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CONTROLLER: requestInstance=%s,responseInstance=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString()));
$this->executeFilters(self::FILTER_CHAIN_POST_COMMAND, $requestInstance, $responseInstance);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CONTROLLER: EXIT!');
}
/**
* @return void
*/
public function executeShutdownFilters (Requestable $requestInstance, Responseable $responseInstance) {
- $this->executeFilters('shutdown', $requestInstance, $responseInstance);
+ // Execute all shutdown filter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CONTROLLER: requestInstance=%s,responseInstance=%s - CALLED!', $requestInstance->__toString(), $responseInstance->__toString()));
+ $this->executeFilters(self::FILTER_CHAIN_SHUTDOWN, $requestInstance, $responseInstance);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CONTROLLER: EXIT!');
}
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @todo This controller shall still provide some headlines for sidebars
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$commandInstance = $this->getResolverInstance()->resolveCommandByRequest($requestInstance);
// This request was valid! :-D
- $requestInstance->requestIsValid();
+ $requestInstance->setIsRequestValid(TRUE);
// Execute the command
$commandInstance->execute($requestInstance, $responseInstance);
// Import framework stuff
use Org\Mxchange\CoreFramework\Controller\BaseController;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
<?php
// Own namespace
-namespace CoreFramework\Controller\!!!;
+namespace Org\Mxchange\CoreFramework\Controller\!!!;
// Import framework stuff
use Org\Mxchange\CoreFramework\Controller\BaseController;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Controller\BaseController;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @todo This controller shall still provide some headlines for sidebars
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$commandInstance = $this->getResolverInstance()->resolveCommandByRequest($requestInstance);
// This request was valid! :-D
- $requestInstance->requestIsValid();
+ $requestInstance->setIsRequestValid(TRUE);
// Execute the command
$commandInstance->execute($requestInstance, $responseInstance);
// Import framework stuff
use Org\Mxchange\CoreFramework\Controller\BaseController;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$commandInstance = $this->getResolverInstance()->resolveCommandByRequest($requestInstance);
// This request was valid! :-D
- $requestInstance->requestIsValid();
+ $requestInstance->setIsRequestValid(TRUE);
// Execute the command
$commandInstance->execute($requestInstance, $responseInstance);
// Import framework stuff
use Org\Mxchange\CoreFramework\Controller\BaseController;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @todo This controller shall still provide some headlines for sidebars
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$commandInstance = $this->getResolverInstance()->resolveCommandByRequest($requestInstance);
// This request was valid! :-D
- $requestInstance->requestIsValid();
+ $requestInstance->setIsRequestValid(TRUE);
// Execute the command
$commandInstance->execute($requestInstance, $responseInstance);
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @todo This controller shall still provide some headlines for sidebars
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$commandInstance = $this->getResolverInstance()->resolveCommandByRequest($requestInstance);
// This request was valid! :-D
- $requestInstance->requestIsValid();
+ $requestInstance->setIsRequestValid(TRUE);
// Execute the command
$commandInstance->execute($requestInstance, $responseInstance);
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Set resolver instance
$controllerInstance->setResolverInstance($resolverInstance);
- // We need the controller instance in resolver class so set it here
- $resolverInstance->setControllerInstance($controllerInstance);
-
// Return the prepared instance
return $controllerInstance;
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Controller\BaseController;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Controller\BaseController;
use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$commandInstance = $this->getResolverInstance()->resolveCommandByRequest($requestInstance);
// This request was valid! :-D
- $requestInstance->requestIsValid();
+ $requestInstance->setIsRequestValid(TRUE);
// Execute the command
$commandInstance->execute($requestInstance, $responseInstance);
namespace Org\Mxchange\CoreFramework\Criteria;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Criteria\Search\SearchCriteria;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
-use Org\Mxchange\CoreFramework\String\Utils\StringUtils;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
+
+// Import SPL stuff
+use \BadMethodCallException;
+use \InvalidArgumentException;
+use \UnexpectedValueException;
/**
* A general crtieria class
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*/
abstract class BaseCriteria extends BaseFrameworkSystem implements Criteria {
/**
- * Wrapper class name stored in config entry
+ * Frontend class name stored in config entry
+ */
+ private $frontendConfigEntry = '';
+
+ /**
+ * All supported criteria types
*/
- private $wrapperConfigEntry = '';
+ private static $CRITERIA_TYPES = [];
/**
* Protected constructor
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: className=%s - CONSTRUCTED!', $className));
parent::__construct($className);
+ // Initialize valid criteria types array
+ self::$CRITERIA_TYPES = [Criteria::CRITERIA_TYPE_DEFAULT, Criteria::CRITERIA_TYPE_CHOICE, Criteria::CRITERIA_TYPE_EXCLUDE];
+
// Initialize all criteria arrays
- foreach (array('default', 'choice', 'exclude') as $criteriaType) {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-CRITERIA: self::CRITERIA_TYPES()=%d', count(self::$CRITERIA_TYPES)));
+ foreach (self::$CRITERIA_TYPES as $criteriaType) {
// Init it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: Invoking this->initGenericArrayKey(criteria,%s,entries) ...', $criteriaType));
$this->initGenericArrayKey('criteria', $criteriaType, 'entries');
- } // END - foreach
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CRITERIA: EXIT!');
+ }
+
+ /**
+ * Count the criteria, e.g. useful to find out if a database query has no
+ * limitation (search criteria).
+ *
+ * @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
+ * @return $count Count of all criteria entries
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ protected final function count (string $criteriaType = Criteria::CRITERIA_TYPE_DEFAULT) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: criteriaType=%s - CALLED!', strtoupper($criteriaType), $criteriaType));
+ if (empty($criteriaType)) {
+ // Throw it again
+ throw new InvalidArgumentException('Parameter "criteriaType" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!in_array($criteriaType, self::$CRITERIA_TYPES)) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('criteriaType=%s is not supported', $criteriaType));
+ }
+
+ // Invoke inner method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: Invoking this->countGenericArrayGroup(criteria, %s) ... - EXIT!', strtoupper($criteriaType), $criteriaType));
+ return $this->countGenericArrayGroup('criteria', $criteriaType);
}
/**
*
* @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
* @param $criteriaKey Criteria key
- * @return $isSet Whether key is set
+ * @return $isset Whether key is set
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws UnexpectedValueException If a parameter contains an unexpected/unsupported value
*/
- public function isKeySet ($criteriaType, $criteriaKey) {
- // Make sure no 'my-' or 'my_' passes this point
- assert((strpos($criteriaKey, 'my-') === false) && (strpos($criteriaKey, 'my_') === false));
+ public function isKeySet (string $criteriaType, string $criteriaKey) {
+ // Check parameters
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: criteriaType=%s,criteriaKey=%s - CALLED!', strtoupper($criteriaType), $criteriaType, $criteriaKey));
+ if (empty($criteriaType)) {
+ // Throw it again
+ throw new InvalidArgumentException('Parameter "criteriaType" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!in_array($criteriaType, self::$CRITERIA_TYPES)) {
+ // Throw it again
+ throw new UnexpectedValueException(sprintf('criteriaType=%s is not supported', $criteriaType), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ } elseif (empty($criteriaKey)) {
+ // Throw it again
+ throw new InvalidArgumentException('Parameter "criteriaKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ((strpos($criteriaKey, 'my-') !== false) || (strpos($criteriaKey, 'my_') !== false)) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('criteriaKey=%s has illegal prefix "my"', $criteriaKey));
+ }
// Determine it
- $isSet = $this->isGenericArrayElementSet('criteria', $criteriaType, 'entries', $criteriaKey);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-CRITERIA: Invoking this->isGenericArrayElementSet(criteria,%s,entries,%s) ...', strtoupper($criteriaType), $criteriaType, $criteriaKey));
+ $isset = $this->isGenericArrayElementSet('criteria', $criteriaType, 'entries', $criteriaKey);
// Return it
- return $isSet;
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: isset=%d - EXIT!', strtoupper($criteriaType), intval($isset)));
+ return $isset;
}
/**
* Checks whether given key is set for 'choice' type
*
* @param $criteriaKey Criteria key
- * @return $isSet Whether key is set
+ * @return $isset Whether key is set
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- public function isChoiceKeySet ($criteriaKey) {
- // Call inner method
- return $this->isKeySet('choice', $criteriaKey);
+ public function isChoiceKeySet (string $criteriaKey) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: criteriaKey=%s - CALLED!', $criteriaKey));
+ if (empty($criteriaKey)) {
+ // Throw it again
+ throw new InvalidArgumentException('Parameter "criteriaKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Invoke inner method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: Invoking this->isKeySet(%s,%s) ...', Criteria::CRITERIA_TYPE_CHOICE, $criteriaKey));
+ return $this->isKeySet(Criteria::CRITERIA_TYPE_CHOICE, $criteriaKey);
}
/**
* Checks whether given key is set for 'exclude' type
*
* @param $criteriaKey Criteria key
- * @return $isSet Whether key is set
+ * @return $isset Whether key is set
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- public function isExcludeKeySet ($criteriaKey) {
- // Call inner method
- return $this->isKeySet('exclude', $criteriaKey);
+ public function isExcludeKeySet (string $criteriaKey) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: criteriaKey=%s - CALLED!', $criteriaKey));
+ if (empty($criteriaKey)) {
+ // Throw it again
+ throw new InvalidArgumentException('Parameter "criteriaKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Invoke inner method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: Invoking this->isKeySet(%s,%s) ... - EXIT!', Criteria::CRITERIA_TYPE_EXCLUDE, $criteriaKey));
+ return $this->isKeySet(Criteria::CRITERIA_TYPE_EXCLUDE, $criteriaKey);
}
/**
- * Setter for wrapper class name
+ * Setter for frontend class name
*
- * @param $wrapperConfigEntry Configuration entry which hold the wrapper class' name
+ * @param $frontendConfigEntry Configuration entry which hold the frontend class' name
* @return void
*/
- public final function setWrapperConfigEntry ($wrapperConfigEntry) {
- $this->wrapperConfigEntry = (string) $wrapperConfigEntry;
+ public final function setFrontendConfigEntry (string $frontendConfigEntry) {
+ $this->frontendConfigEntry = $frontendConfigEntry;
}
/**
- * Getter for wrapper class name
+ * Getter for frontend class name
*
- * @return $wrapperConfigEntry Configuration entry which hold the wrapper class' name
+ * @return $frontendConfigEntry Configuration entry which hold the frontend class' name
*/
- public final function getWrapperConfigEntry () {
- return $this->wrapperConfigEntry;
+ public final function getFrontendConfigEntry () {
+ return $this->frontendConfigEntry;
}
/**
*
* @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
* @return $criteria
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws UnexpectedValueException If a parameter contains an unexpected/unsupported value
*/
- public final function getCriteriaArray ($criteriaType = 'default') {
+ public final function getCriteriaArray (string $criteriaType = Criteria::CRITERIA_TYPE_DEFAULT) {
+ // Check parameters
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: criteriaType=%s - CALLED!', strtoupper($criteriaType), $criteriaType));
+ if (empty($criteriaType)) {
+ // Throw it again
+ throw new InvalidArgumentException('Parameter "criteriaType" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!in_array($criteriaType, self::$CRITERIA_TYPES)) {
+ // Throw it again
+ throw new UnexpectedValueException(sprintf('criteriaType=%s is not supported', $criteriaType), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
+
+ // Invoke inner method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: Invoking this->getGenericArrayKey(criteria,%s,entries) ... - EXIT!', strtoupper($criteriaType), $criteriaType));
return $this->getGenericArrayKey('criteria', $criteriaType, 'entries');
}
* @return $criteria
*/
public final function getCriteriaChoiceArray () {
- return $this->getCriteriaArray('choice');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: CALLED!', strtoupper($criteriaType)));
+ return $this->getCriteriaArray(Criteria::CRITERIA_TYPE_CHOICE);
}
/**
* @return $criteria
*/
public final function getCriteriaExcludeArray () {
- return $this->getCriteriaArray('exclude');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CRITERIA: CALLED!');
+ return $this->getCriteriaArray(Criteria::CRITERIA_TYPE_EXCLUDE);
}
/**
* @param $criteriaKey Criteria key to unset
* @return void
*/
- public final function unsetCriteria ($criteriaKey) {
- // Make sure no 'my-' or 'my_' passes this point
- assert((strpos($criteriaKey, 'my-') === false) && (strpos($criteriaKey, 'my_') === false));
+ public final function unsetCriteria (string $criteriaKey) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: criteriaKey=%s - CALLED!', $criteriaKey));
+ if (empty($criteriaKey)) {
+ // Throw it again
+ throw new InvalidArgumentException('Parameter "criteriaKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ((strpos($criteriaKey, 'my-') !== false) || (strpos($criteriaKey, 'my_') !== false)) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('criteriaKey=%s has illegal prefix "my"', $criteriaKey));
+ }
// Convert dashes to underscore
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: Invoking StringUtils::convertDashesToUnderscores(%s) ...', strtoupper($criteriaType), $criteriaKey));
$criteriaKey = StringUtils::convertDashesToUnderscores($criteriaKey);
// "Walk" through all criterias
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-CRITERIA: criteriaKey=%s', strtoupper($criteriaType), $criteriaKey));
foreach ($this->getGenericArray('criteria') as $criteriaType => $dummy) {
// Remove it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: Removing criteriaType=%s,criteriaKey=%s ...', strtoupper($criteriaType), $criteriaType, $criteriaKey));
$this->unsetGenericArrayElement('criteria', $criteriaType, 'entries', $criteriaKey);
- } // END - foreach
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CRITERIA: EXIT!');
}
/**
* @param $criteriaValue Criteria value
* @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
* @return void
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws UnexpectedValueException If a parameter contains an unexpected/unsupported value
*/
- public final function addCriteria ($criteriaKey, $criteriaValue, $criteriaType = 'default') {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($criteriaType) . '-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: criteriaKey=' . $criteriaKey . ',criteriaValue=' . $criteriaValue . ',criteriaType=' . $criteriaType . ' - CALLED!');
-
- // Make sure no 'my-' or 'my_' passes this point
- assert((strpos($criteriaKey, 'my-') === false) && (strpos($criteriaKey, 'my_') === false) && (!is_bool($criteriaValue)));
+ public final function addCriteria (string $criteriaKey, $criteriaValue, string $criteriaType = Criteria::CRITERIA_TYPE_DEFAULT) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: criteriaKey=%s,criteriaValue[]=%s,criteriaType=%s - CALLED!', strtoupper($criteriaType), $criteriaKey, gettype($criteriaValue), $criteriaType));
+ if (empty($criteriaKey)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "criteriaKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ((strpos($criteriaKey, 'my-') !== false) || (strpos($criteriaKey, 'my_') !== false)) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('criteriaKey=%s has illegal prefix "my"', $criteriaKey));
+ } elseif (is_array($criteriaValue) || is_bool($criteriaValue) || is_object($criteriaValue) || is_resource($criteriaValue)) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('value[]=%s is not supported', gettype($criteriaValue)));
+ } elseif (empty($criteriaType)) {
+ // Throw it again
+ throw new InvalidArgumentException('Parameter "criteriaType" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!in_array($criteriaType, self::$CRITERIA_TYPES)) {
+ // Throw it again
+ throw new UnexpectedValueException(sprintf('criteriaType=%s is not supported', $criteriaType), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// Convert dashes to underscore
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: Invoking StringUtils::convertDashesToUnderscores(%s) ...', strtoupper($criteriaType), $criteriaKey));
$criteriaKey = StringUtils::convertDashesToUnderscores($criteriaKey);
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($criteriaType) . '(' . $this->__toString() . ')-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: criteriaKey=' . $criteriaKey);
+ // Set it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: Invoking this->setGenericArrayElement(criteria,%s,entries,%s,criteriaValue[]=%s) ...', strtoupper($criteriaType), $criteriaType, $criteriaKey, gettype($criteriaValue)));
+ $this->setGenericArrayElement('criteria', $criteriaType, 'entries', $criteriaKey, $criteriaValue);
- // Append it
- $this->appendStringToGenericArrayElement('criteria', $criteriaType, 'entries', $criteriaKey, $criteriaValue);
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: EXIT!', strtoupper($criteriaType)));
}
/**
* @param $criteriaValue Criteria value
* @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
* @return void
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws UnexpectedValueException If a parameter contains an unexpected/unsupported value
*/
- public final function setCriteria ($criteriaKey, $criteriaValue, $criteriaType = 'default') {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($criteriaType) . '-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: criteriaKey=' . $criteriaKey . ',criteriaValue=' . $criteriaValue . ',criteriaType=' . $criteriaType . ' - CALLED!');
-
- // Make sure no 'my-' or 'my_' passes this point
- assert((strpos($criteriaKey, 'my-') === false) && (strpos($criteriaKey, 'my_') === false) && (!is_bool($criteriaValue)));
+ public final function setCriteria (string $criteriaKey, $criteriaValue, string $criteriaType = Criteria::CRITERIA_TYPE_DEFAULT) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: criteriaKey=%s,criteriaValue[]=%s$criteriaValue,criteriaType=%s - CALLED!', strtoupper($criteriaType), $criteriaKey, gettype($criteriaValue), $criteriaType));
+ if (empty($criteriaKey)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "criteriaKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ((strpos($criteriaKey, 'my-') !== false) || (strpos($criteriaKey, 'my_') !== false)) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('criteriaKey=%s has illegal prefix "my"', $criteriaKey));
+ } elseif (is_array($criteriaValue) || is_bool($criteriaValue) || is_object($criteriaValue) || is_resource($criteriaValue)) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('value[]=%s is not supported', gettype($criteriaValue)));
+ } elseif (empty($criteriaType)) {
+ // Throw it again
+ throw new InvalidArgumentException('Parameter "criteriaType" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!in_array($criteriaType, self::$CRITERIA_TYPES)) {
+ // Throw it again
+ throw new UnexpectedValueException(sprintf('criteriaType=%s is not supported', $criteriaType), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// Convert dashes to underscore
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: Invoking StringUtils::convertDashesToUnderscores(%s) ...', strtoupper($criteriaType), $criteriaKey));
$criteriaKey = StringUtils::convertDashesToUnderscores($criteriaKey);
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($criteriaType) . '(' . $this->__toString() . ')-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: criteriaKey=' . $criteriaKey);
-
// Set it
- $this->setStringGenericArrayElement('criteria', $criteriaType, 'entries', $criteriaKey, $criteriaValue);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: Invoking this->setGenericArrayElement(criteria,%s,entries,%s,criteriaValue[]=%s) ...', strtoupper($criteriaType), $criteriaKey, gettype($criteriaValue)));
+ $this->setGenericArrayElement('criteria', $criteriaType, 'entries', $criteriaKey, $criteriaValue);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CRITERIA: EXIT!');
}
/**
* @param $criteriaKey Criteria key
* @param $criteriaValue Criteria value
* @return void
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws UnexpectedValueException If $criteriaValue has an unexpected type
*/
- public final function addChoiceCriteria ($criteriaKey, $criteriaValue) {
- // Make sure no 'my-' or 'my_' passes this point
- assert((strpos($criteriaKey, 'my-') === false) && (strpos($criteriaKey, 'my_') === false) && (!is_bool($criteriaValue)));
+ public final function addChoiceCriteria (string $criteriaKey, $criteriaValue) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: criteriaKey=%s,criteriaValue[]=%s - CALLED!', $criteriaKey, gettype($criteriaValue)));
+ if (empty($criteriaKey)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "criteriaKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ((strpos($criteriaKey, 'my-') !== false) || (strpos($criteriaKey, 'my_') !== false)) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('criteriaKey=%s has illegal prefix "my"', $criteriaKey));
+ } elseif (is_array($criteriaValue) || is_bool($criteriaValue) || is_object($criteriaValue) || is_resource($criteriaValue)) {
+ // Throw UAE
+ throw new UnexpectedValueException(sprintf('criteriaValue[]=%s is not accepted', gettype($criteriaValue)), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($criteriaType) . '(' . $this->__toString() . ')-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: criteriaKey=' . $criteriaKey . ',criteriaValue=' . $criteriaValue);
+ // Convert dashes to underscore
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: Invoking StringUtils::convertDashesToUnderscores(%s) ...', $criteriaKey));
+ $criteriaKey = StringUtils::convertDashesToUnderscores($criteriaKey);
// Add it
- $this->pushValueToGenericArrayElement('criteria', 'choice', 'entries', StringUtils::convertDashesToUnderscores($criteriaKey), (string) $criteriaValue);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: Invoking this->pushValueToGenericArrayElement(criteria,%s,entries,%s,criteriaValue[]=%s) ...', Criteria::CRITERIA_TYPE_CHOICE, $criteriaKey, gettype($criteriaValue)));
+ $this->pushValueToGenericArrayElement('criteria', Criteria::CRITERIA_TYPE_CHOICE, 'entries', $criteriaKey, $criteriaValue);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CRITERIA: EXIT!');
}
/**
* @param $criteriaKey Criteria key
* @param $criteriaValue Criteria value
* @return void
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws UnexpectedValueException If $criteriaValue has an unexpected type
*/
- public final function addExcludeCriteria ($criteriaKey, $criteriaValue) {
+ public final function addExcludeCriteria (string $criteriaKey, $criteriaValue) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: criteriaKey=%s,criteriaValue[%s]=%s - CALLED!', $criteriaKey, gettype($criteriaValue), $criteriaValue));
+ if (empty($criteriaKey)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "criteriaKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ((strpos($criteriaKey, 'my-') !== false) || (strpos($criteriaKey, 'my_') !== false)) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('criteriaKey=%s has illegal prefix "my"', $criteriaKey));
+ } elseif (is_array($criteriaValue) || is_bool($criteriaValue) || is_object($criteriaValue) || is_resource($criteriaValue)) {
+ // Throw UAE
+ throw new UnexpectedValueException(sprintf('criteriaValue[]=%s is not accepted', gettype($criteriaValue)), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
+
// Add it with generic method
- $this->addCriteria($criteriaKey, $criteriaValue, 'exclude');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: Invoking this->addCriteria(%s,criteriaValue[]=%s,%s) ...', $criteriaKey, gettype($criteriaValue), Criteria::CRITERIA_TYPE_EXCLUDE));
+ $this->addCriteria($criteriaKey, $criteriaValue, Criteria::CRITERIA_TYPE_EXCLUDE);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CRITERIA: EXIT!');
}
/**
* @param $configEntry Configuration entry
* @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
* @return void
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws UnexpectedValueException If a parameter contains an unexpected/unsupported value
*/
- public final function addConfiguredCriteria ($criteriaKey, $configEntry, $criteriaType = 'default') {
+ public final function addConfiguredCriteria (string $criteriaKey, string $configEntry, string $criteriaType = Criteria::CRITERIA_TYPE_DEFAULT) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: criteriaKey=%s,configEntry=%s,criteriaType=%s - CALLED!', strtoupper($criteriaType), $criteriaKey, $configEntry, $criteriaType));
+ if (empty($criteriaKey)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "criteriaKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ((strpos($criteriaKey, 'my-') !== false) || (strpos($criteriaKey, 'my_') !== false)) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('criteriaKey=%s has illegal prefix "my"', $criteriaKey));
+ } elseif (empty($configEntry)) {
+ // Throw it again
+ throw new InvalidArgumentException('Parameter "configEntry" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($criteriaType)) {
+ // Throw it again
+ throw new InvalidArgumentException('Parameter "criteriaType" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!in_array($criteriaType, self::$CRITERIA_TYPES)) {
+ // Throw it again
+ throw new UnexpectedValueException(sprintf('criteriaType=%s is not supported', $criteriaType), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
+
// Add the configuration entry as a criteria
- $value = $this->getConfigInstance()->getConfigEntry($configEntry);
+ $value = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($configEntry);
+
+ // Invoke inner method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: Invoking this->addCriteria(%s,value[%s]=%s,%s) ...', strtoupper($criteriaType), $criteriaKey, gettype($value), $value, $criteriaType));
$this->addCriteria($criteriaKey, $value, $criteriaType);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: EXIT!', strtoupper($criteriaType)));
}
/**
* @param $criteriaKey The requested criteria key
* @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
* @return $value Whether the value of the critera or false
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws UnexpectedValueException If a parameter contains an unexpected/unsupported value
*/
- public function getCriteriaElemnent ($criteriaKey, $criteriaType = 'default') {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($criteriaType) . '-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: criteriaKey=' . $criteriaKey . ',criteriaType=' . $criteriaType . ' - CALLED!');
-
- // Make sure no 'my-' or 'my_' passes this point
- assert((strpos($criteriaKey, 'my-') === false) && (strpos($criteriaKey, 'my_') === false));
+ public function getCriteriaElemnent (string $criteriaKey, string $criteriaType = Criteria::CRITERIA_TYPE_DEFAULT) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: criteriaKey=%s,criteriaType=%s - CALLED!', strtoupper($criteriaType), $criteriaKey, $criteriaType));
+ if (empty($criteriaKey)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "criteriaKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ((strpos($criteriaKey, 'my-') !== false) || (strpos($criteriaKey, 'my_') !== false)) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('criteriaKey=%s has illegal prefix "my"', $criteriaKey));
+ } elseif (empty($criteriaType)) {
+ // Throw it again
+ throw new InvalidArgumentException('Parameter "criteriaType" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!in_array($criteriaType, self::$CRITERIA_TYPES)) {
+ // Throw it again
+ throw new UnexpectedValueException(sprintf('criteriaType=%s is not supported', $criteriaType), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// Convert dashes to underscore
$criteriaKey = StringUtils::convertDashesToUnderscores($criteriaKey);
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($criteriaType) . '-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: criteriaKey=' . $criteriaKey . ',criteria()=' . $this->countGenericArrayGroup('criteria', $criteriaType));
-
// Default is not found
$value = false;
// Is the criteria there?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-CRITERIA: criteriaKey=%s,criteria()=%d', strtoupper($criteriaType), $criteriaKey, $this->countGenericArrayGroup('criteria', $criteriaType)));
if ($this->isKeySet($criteriaType, $criteriaKey)) {
// Then use it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: Invoking this->getGenericArrayElement(criteria,%s,entries,%s) ...', strtoupper($criteriaType), $criteriaType, $criteriaKey));
$value = $this->getGenericArrayElement('criteria', $criteriaType, 'entries', $criteriaKey);
- } // END - if
-
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($criteriaType) . '-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: value=' . $value . ' - EXIT!');
+ }
// Return the value
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: value[]=%s - EXIT!', strtoupper($criteriaType), gettype($value)));
return $value;
}
*
* @param $criteriaKey The requested criteria key
* @return $value Whether the value of the critera or false
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- public function getCriteriaChoiceElemnent ($criteriaKey) {
- // Call inner method
- return $this->getCriteriaElemnent($criteriaKey, 'choice');
+ public function getCriteriaChoiceElemnent (string $criteriaKey) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: criteriaKey=%s - CALLED!', $criteriaKey));
+ if (empty($criteriaKey)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "criteriaKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ((strpos($criteriaKey, 'my-') !== false) || (strpos($criteriaKey, 'my_') !== false)) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('criteriaKey=%s has illegal prefix "my"', $criteriaKey));
+ }
+
+ // Invoke inner method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: Invoking this->getCriteriaElemnent(%s,%s) ...', $criteriaKey, Criteria::CRITERIA_TYPE_CHOICE));
+ return $this->getCriteriaElemnent($criteriaKey, Criteria::CRITERIA_TYPE_CHOICE);
}
/**
*
* @param $criteriaKey The requested criteria key
* @return $value Whether the value of the critera or false
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- public function getCriteriaExcludeElemnent ($criteriaKey) {
- // Call inner method
- return $this->getCriteriaElemnent($criteriaKey, 'exclude');
+ public function getCriteriaExcludeElemnent (string $criteriaKey) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: criteriaKey=%s - CALLED!', $criteriaKey));
+ if (empty($criteriaKey)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "criteriaKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ((strpos($criteriaKey, 'my-') !== false) || (strpos($criteriaKey, 'my_') !== false)) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('criteriaKey=%s has illegal prefix "my"', $criteriaKey));
+ }
+
+ // Invoke inner method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: Invoking this->getCriteriaElemnent(%s,%s) ...', $criteriaKey, Criteria::CRITERIA_TYPE_EXCLUDE));
+ return $this->getCriteriaElemnent($criteriaKey, Criteria::CRITERIA_TYPE_EXCLUDE);
}
/**
* @param $entryArray Array with the entries to find
* @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
* @return $matches Whether the entry matches or not
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws UnexpectedValueException If a parameter contains an unexpected/unsupported value
*/
- public function ifEntryMatches (array $entryArray, $criteriaType = 'default') {
+ public function ifEntryMatches (array $entryArray, string $criteriaType = Criteria::CRITERIA_TYPE_DEFAULT) {
+ // Check parameters
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: entryArray()=%d,criteriaType=%s - CALLED!', strtoupper($criteriaType), count($entryArray), $criteriaType));
+ if (count($entryArray) == 0) {
+ // Throw IAE
+ throw new InvalidArgumentException('entryArray cannot be an empty array');
+ } elseif (empty($criteriaType)) {
+ // Throw it again
+ throw new InvalidArgumentException('Parameter "criteriaType" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!in_array($criteriaType, self::$CRITERIA_TYPES)) {
+ // Throw it again
+ throw new UnexpectedValueException(sprintf('criteriaType=%s is not supported', $criteriaType), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
+
// First nothing matches and nothing is counted
$matches = false;
$counted = 0;
// Walk through all entries
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-CRITERIA: Walking over entryArray()=%d ...', strtoupper($criteriaType), count($entryArray)));
foreach ($entryArray as $key => $entry) {
// Make sure no 'my-' or 'my_' passes this point
- assert((strpos($key, 'my-') === false) && (strpos($key, 'my_') === false));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-CRITERIA: key=%s,entry[%s]=%s', strtoupper($criteriaType), $key, gettype($entry), $entry));
+ if ((strpos($key, 'my-') !== false) || (strpos($key, 'my_') !== false)) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('key=%s has illegal prefix "my"', $key));
+ }
// Convert dashes to underscore
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: Invoking StringUtils::convertDashesToUnderscores(%s) ...', strtoupper($criteriaType), $key));
$key = StringUtils::convertDashesToUnderscores($key);
// Then walk through all search criteria
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-CRITERIA: key=%s - AFTER!', strtoupper($criteriaType), $key));
foreach ($this->getGenericArrayKey('criteria', $criteriaType, 'entries') as $criteriaKey => $criteriaValue) {
// Make sure no 'my-' or 'my_' passes this point
- assert((strpos($criteriaKey, 'my-') === false) && (strpos($criteriaKey, 'my_') === false) && (!is_bool($criteriaValue)));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-CRITERIA: criteriaKey=%s,criteriaValue[%s]=%s', strtoupper($criteriaType), $criteriaKey, gettype($criteriaValue), $criteriaValue));
+ if ((strpos($criteriaKey, 'my-') !== false) || (strpos($criteriaKey, 'my_') !== false)) {
+ // Throw it again
+ throw new UnexpectedValueException(sprintf('criteriaKey=%s has illegal prefix "my"', $criteriaKey), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// Convert dashes to underscore
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: Invoking StringUtils::convertDashesToUnderscores(%s) ...', strtoupper($criteriaType), $criteriaKey));
$criteriaKey = StringUtils::convertDashesToUnderscores($criteriaKey);
// Is the element found and does it match?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-CRITERIA: key=%s,criteriaKey=%s', strtoupper($criteriaType), $key, $criteriaKey));
if (($key == $criteriaKey) && ($criteriaValue == $entry)) {
// Then count this one up
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-CRITERIA: MATCHES!', strtoupper($criteriaType)));
$counted++;
- } // END - if
- } // END - foreach
- } // END - foreach
+ }
+ }
+ }
// Now check if expected criteria counts match
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-CRITERIA: counted=%d', strtoupper($criteriaType), $counted));
$matches = ($counted == $this->countGenericArrayGroup('criteria', $criteriaType));
// Return the result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: matches=%d - EXIT!', strtoupper($criteriaType), intval($matches)));
return $matches;
}
*
* @param $entryArray Array with the entries to find
* @return $matches Whether the entry matches or not
+ * @throws InvalidArgumentException If a parameter is not valid
*/
public function ifChoiceMatches (array $entryArray) {
- // Call inner method
- return $this->ifEntryMatches($entryArray, 'choice');
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: entryArray()=%d - CALLED!', count($entryArray)));
+ if (count($entryArray) == 0) {
+ // Throw IAE
+ throw new InvalidArgumentException('entryArray cannot be an empty array');
+ }
+
+ // Invoke inner method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: Invoking this->ifEntryMatches(%d,%s) ...', count($entryArray), Criteria::CRITERIA_TYPE_CHOICE));
+ return $this->ifEntryMatches($entryArray, Criteria::CRITERIA_TYPE_CHOICE);
}
/**
*
* @param $entryArray Array with the entries to find
* @return $matches Whether the entry matches or not
+ * @throws InvalidArgumentException If a parameter is not valid
*/
public function ifExcludeMatches (array $entryArray) {
- // Call inner method
- return $this->ifEntryMatches($entryArray, 'exclude');
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: entryArray()=%d - CALLED!', count($entryArray)));
+ if (count($entryArray) == 0) {
+ // Throw IAE
+ throw new InvalidArgumentException('entryArray cannot be an empty array');
+ }
+
+ // Invoke inner method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: Invoking this->ifEntryMatches(%d,%s) ...', count($entryArray), Criteria::CRITERIA_TYPE_EXCLUDE));
+ return $this->ifEntryMatches($entryArray, Criteria::CRITERIA_TYPE_EXCLUDE);
}
/**
* @param $onlyKeys Only use these keys for a cache key
* @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
* @return $cacheKey The key suitable for the cache system
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws UnexpectedValueException If a parameter contains an unexpected/unsupported value
+ * @throws BadMethodCallException If this method is invoked before $criteriaType has been initialized
*/
- public function getCacheKey ($onlyKeys = array(), $criteriaType = 'default') {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': criteriaType=' . $criteriaType . ',count()=' . $this->countGenericArray('criteria')));
-
- // Make sure the criteria is there
- assert($this->isValidGenericArrayGroup('criteria', $criteriaType));
+ public function getCacheKey (array $onlyKeys = [], string $criteriaType = Criteria::CRITERIA_TYPE_DEFAULT) {
+ // Check parameters
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: onlyKeys()=%d,criteriaType=%s - CALLED!', strtoupper($criteriaType), count($onlyKeys), $criteriaType));
+ if (empty($criteriaType)) {
+ // Throw it again
+ throw new InvalidArgumentException('Parameter "criteriaType" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!in_array($criteriaType, self::$CRITERIA_TYPES)) {
+ // Throw it again
+ throw new UnexpectedValueException(sprintf('criteriaType=%s is not supported', $criteriaType), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ } elseif (!$this->isValidGenericArrayGroup('criteria', $criteriaType)) {
+ // Not intialized yet
+ throw new BadMethodCallException(sprintf('Method cannot be invoked before criteriaType=%s is initialized!', $criteriaType), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Initialize the key
$cacheKey = '';
// Now walk through all criterias
foreach ($this->getGenericArrayKey('criteria', $criteriaType, 'entries') as $criteriaKey => $criteriaValue) {
// Make sure no 'my-' or 'my_' passes this point
- assert((strpos($criteriaKey, 'my-') === false) && (strpos($criteriaKey, 'my_') === false) && (!is_bool($criteriaValue)));
-
- // $criteriaValue cannot be an array
- assert(!is_array($criteriaValue));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-CRITERIA: criteriaKey=%s,criteriaValue[%s]=%s', strtoupper($criteriaType), $criteriaKey, gettype($criteriaValue), $criteriaValue));
+ if ((strpos($criteriaKey, 'my-') !== false) || (strpos($criteriaKey, 'my_') !== false)) {
+ // Throw UAE
+ throw new UnexpectedValueException(sprintf('criteriaKey=%s has illegal prefix "my"', $criteriaKey), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ } elseif (is_array($criteriaValue) || is_bool($criteriaValue) || is_object($criteriaValue) || is_resource($criteriaValue)) {
+ // Throw it again
+ throw new UnexpectedValueException(sprintf('criteriaValue[]=%s is not supported', gettype($criteriaValue)), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// Convert dashes to underscore
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: Invoking StringUtils::convertDashesToUnderscores(%s) ...', strtoupper($criteriaType), $criteriaKey));
$criteriaKey = StringUtils::convertDashesToUnderscores($criteriaKey);
// Is the value in array or is $onlyKeys empty?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-CRITERIA: criteriaKey=%s', strtoupper($criteriaType), $criteriaKey));
if ((isset($onlyKeys[$criteriaKey])) || (count($onlyKeys) == 0)) {
// Add the value URL encoded to avoid any trouble with special characters
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-CRITERIA: Adding criteriaKey=%s,criteriaValue[%s]=%s to cache key ...', strtoupper($criteriaType), $criteriaKey, gettype($criteriaValue), $criteriaValue));
$cacheKey .= sprintf('%s=%s;',
$criteriaKey,
urlencode($criteriaValue)
);
- } // END - if
- } // END - foreach
+ }
+ }
// Remove last semicolon
$cacheKey = substr($cacheKey, 0, -1);
// Is the instance SearchCriteria?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-CRITERIA: cacheKey=%s,this=%s', strtoupper($criteriaType), $cacheKey, $this->__toString()));
if ($this instanceof SearchCriteria) {
// Check if 'limit' and 'skip' are in
if (((isset($onlyKeys['limit'])) && (isset($onlyKeys['skip']))) || (count($onlyKeys) == 0)) {
// Add limit and skip values
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('%s-CRITERIA: Adding this->limit=%d,this->skip=%d to cache key ...', strtoupper($criteriaType), $this->getLimit(), $this->getSkip()));
$cacheKey .= sprintf(';%%limit%%=%s;%%skip%%=%s',
$this->getLimit(),
$this->getSkip()
);
- } // END - if
- } // END - if
+ }
+ }
// Return the cache key
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('%s-CRITERIA: cacheKey=%s - EXIT!', strtoupper($criteriaType), $cacheKey));
return $cacheKey;
}
* @param $onlyKeys Only use these keys for a cache key
* @return $cacheKey The key suitable for the cache system
*/
- public function getCacheKeyChoice ($onlyKeys = array()) {
- // Call inner method
- return $this->getCacheKey($onlyKeys, 'choice');
+ public function getCacheKeyChoice (array $onlyKeys = []) {
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: onlyKeys()=%d - CALLED!', count($onlyKeys)));
+
+ // Invoke inner method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: Invoking this->getCacheKey(onlyKeys()=%d,%s) ...', count($onlyKeys),Criteria::CRITERIA_TYPE_CHOICE));
+ return $this->getCacheKey($onlyKeys, Criteria::CRITERIA_TYPE_CHOICE);
}
/**
* @param $onlyKeys Only use these keys for a cache key
* @return $cacheKey The key suitable for the cache system
*/
- public function getCacheKeyExclude ($onlyKeys = array()) {
- // Call inner method
- return $this->getCacheKey($onlyKeys, 'exclude');
- }
+ public function getCacheKeyExclude (array $onlyKeys = []) {
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: onlyKeys()=%d - CALLED!', count($onlyKeys)));
- /**
- * Count the criteria, e.g. useful to find out if a database query has no
- * limitation (search criteria).
- *
- * @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
- * @return $count Count of all criteria entries
- */
- public final function count ($criteriaType = 'default') {
- // Return it
- return $this->countGenericArrayGroup('criteria', $criteriaType);
+ // Invoke inner method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-CRITERIA: Invoking this->getCacheKey(onlyKeys()=%d,%s) ...', count($onlyKeys),Criteria::CRITERIA_TYPE_EXCLUDE));
+ return $this->getCacheKey($onlyKeys, Criteria::CRITERIA_TYPE_EXCLUDE);
}
/**
* @return $count Count of all criteria entries
*/
public final function countChoice () {
- return $this->count('choice');
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CRITERIA: CALLED!');
+ return $this->count(Criteria::CRITERIA_TYPE_CHOICE);
}
/**
* @return $count Count of all criteria entries
*/
public final function countExclude () {
- return $this->count('exclude');
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-CRITERIA: CALLED!');
+ return $this->count(Criteria::CRITERIA_TYPE_EXCLUDE);
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Criteria\BaseCriteria;
+use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
-use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+
+// Import SPL stuff
+use \BadMethodCallException;
+use \InvalidArgumentException;
/**
* A set of data storeable in databases
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* Primary keys
*/
- private $primaryKeys = array();
+ private $primaryKeys = [];
+
+ /**
+ * Search criteria instance
+ */
+ private $searchInstance = NULL;
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*
* @param $tableName Name of the table
* @return $criteriaInstance An instance of this criteria
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- public static final function createDataSetCriteria ($tableName) {
+ public static final function createDataSetCriteria (string $tableName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATA-SET-CRITERIA: tableName=%s - CALLED!', $tableName));
+ if (empty($tableName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "tableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get a new instance
$criteriaInstance = new DataSetCriteria();
$criteriaInstance->setTableName($tableName);
// Return the instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATA-SET-CRITERIA: criteriaInstance=%s - EXIT!', $criteriaInstance->__toString()));
return $criteriaInstance;
}
* @param $tableName Name of the table to set
* @return void
*/
- public final function setTableName ($tableName) {
- $this->tableName = (string) $tableName;
+ public final function setTableName (string $tableName) {
+ $this->tableName = $tableName;
}
/**
* @param $uniqueKey Column to use as unique key
* @return void
*/
- public final function setUniqueKey ($uniqueKey) {
- $this->uniqueKey = (string) $uniqueKey;
+ public final function setUniqueKey (string $uniqueKey) {
+ $this->uniqueKey = $uniqueKey;
}
/**
return $this->uniqueKey;
}
+ /**
+ * Setter for primary key
+ *
+ * @param $primaryKey Primary key to set
+ * @return void
+ */
+ public final function setPrimaryKey (string $primaryKey) {
+ $this->primaryKey = $primaryKey;
+ }
+
+ /**
+ * Setter for primary key array
+ *
+ * @param $primaryKeys Primary key array to set
+ * @return void
+ */
+ public function setPrimaryKeyCombined (array $primaryKeys) {
+ $this->primaryKeys = $primaryKeys;
+ }
+
+ /**
+ * Getter for primary keys
+ *
+ * @return $primaryKeys Primary key array
+ */
+ public final function getPrimaryKeys () {
+ // Return it
+ return $this->primaryKeys;
+ }
+
+ /**
+ * Setter for search instance
+ *
+ * @param $searchInstance Searchable criteria instance
+ * @return void
+ */
+ public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
+ $this->searchInstance = $searchInstance;
+ }
+
+ /**
+ * Getter for search instance
+ *
+ * @return $searchInstance Searchable criteria instance
+ */
+ public final function getSearchInstance () {
+ return $this->searchInstance;
+ }
+
/**
* Getter for unique key value
*
* @return $uniqueValue Value of the unique key
+ * @throws BadMethodCallException If no primary and no unique key was found
*/
public final function getUniqueValue () {
// Get primary key(s) first
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('DATA-SET-CRITERIA: CALLED!');
$primaryKey = trim($this->getCriteriaElemnent($this->getPrimaryKey()));
$primaryKeys = $this->getPrimaryKeys();
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: tableName=' . $this->getTableName() . ',primaryKey=' . $primaryKey . ',primaryKeys()=' . count($primaryKeys));
-
/*
* If this is not set, this could mean a badly written frontend as
* tables should always have a primary key.
*/
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('DATA-SET-CRITERIA: this->tableName=%s,primaryKey=%s,primaryKeys()=%d', $this->getTableName(), $primaryKey, count($primaryKeys)));
if (count($primaryKeys) > 0) {
/*
* Init return value, this can be put all together without any
$return = '';
// Combination set, so get all
- foreach ($primaryKeys as $primaryKey) {
+ foreach ($primaryKeys as $primaryKeyPart) {
// Add it
- $return .= trim($this->getCriteriaElemnent($primaryKey));
- } // END - foreach
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('DATA-SET-CRITERIA: primaryKeyPart=%s', $primaryKeyPart));
+ $return .= trim($this->getCriteriaElemnent($primaryKeyPart));
+ }
// Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: tableName=' . $this->getTableName() . ',return=' . $return . ' - EXIT!');
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATA-SET-CRITERIA: return=%s - EXIT!', $return));
return $return;
} elseif (!empty($primaryKey)) {
// Return primary key
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATA-SET-CRITERIA: primaryKey=%s - EXIT!', $primaryKey));
return $primaryKey;
} else {
- // @TODO Issue a warning
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: Primary key not set for table ' . $this->getTableName() . ', please fix your table. Falling back to unique key ...');
+ // Issue a warning
+ self::createDebugInstance(__CLASS__, __LINE__)->warningMessage('DATA-SET-CRITERIA: Primary key not set for table ' . $this->getTableName() . ', please fix your table. Falling back to unique key ...');
// Get unique key
$uniqueKey = trim($this->getCriteriaElemnent($this->getUniqueKey()));
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: tableName=' . $this->getTableName() . ',uniqueKey=' . $uniqueKey);
-
// Is it empty, too?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('DATA-SET-CRITERIA: uniqueKey=%s', $uniqueKey));
if (empty($uniqueKey)) {
// Bad news, nothing is "unique" by design for this table
- ApplicationEntryPoint::exitApplication('Table ' . $this->getTableName() . ' has both no primary and unique key, but ' . __METHOD__ . ' was called. Please fix your table.');
- } else {
- // Return unique key
- return $uniqueKey;
+ throw new BadMethodCallException(sprintf('Table %s has both no primary and unique key, but %s was called. Please fix your table.', $this->getTableName(), __METHOD__), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
}
+
+ // Return unique key
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATA-SET-CRITERIA: uniqueKey=%s - EXIT!', $uniqueKey));
+ return $uniqueKey;
}
}
*/
public final function getPrimaryKey () {
// Get primary key by default
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('DATA-SET-CRITERIA: CALLED!');
$primaryKey = $this->primaryKey;
+ // Is it still empty?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('DATA-SET-CRITERIA: primaryKey=%s', $primaryKey));
if (empty($primaryKey)) {
// Get uniqueKey
$primaryKey = $this->getUniqueKey();
- } // END - if
+ }
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATA-SET-CRITERIA: primaryKey=%s - EXIT!', $primaryKey));
return $primaryKey;
}
- /**
- * Setter for primary key
- *
- * @param $primaryKey Primary key to set
- * @return void
- */
- public final function setPrimaryKey ($primaryKey) {
- $this->primaryKey = (string) $primaryKey;
- }
-
- /**
- * Setter for primary key array
- *
- * @param $primaryKeys Primary key array to set
- * @return void
- */
- public function setPrimaryKeyCombined (array $primaryKeys) {
- $this->primaryKeys = $primaryKeys;
- }
-
- /**
- * Getter for primary keys
- *
- * @return $primaryKeys Primary key array
- */
- public final function getPrimaryKeys () {
- // Return it
- return $this->primaryKeys;
- }
-
}
namespace Org\Mxchange\CoreFramework\Criteria\Search;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Criteria\BaseCriteria;
use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+use \UnexpectedValueException;
/**
* Search criteria for e.g. searching in databases. Do not use this class if
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* Criteria to handle
*/
- private $criteria = array();
+ private $criteria = [];
/**
* Limitation for the search
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public static final function createSearchCriteria () {
// Get a new instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('SEARCH-CRITERIA: CALLED!');
$criteriaInstance = new SearchCriteria();
// Return this instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SEARCH-CRITERIA: criteriaInstance=%s - EXIT!', $criteriaInstance->__toString()));
return $criteriaInstance;
}
* @return void
* @todo Find a nice casting here. (int) allows until and including 32766.
*/
- public final function setLimit ($limit) {
+ public final function setLimit (int $limit) {
$this->limit = $limit;
}
/**
* "Setter" for limit from a configuration entry
*
- * @param $configEntry The configuration entry which hold a number as limit
+ * @param $configKey The configuration entry which hold a number as limit
* @return void
+ * @throws InvalidArgumentException If a paramter has an invalid value
*/
- public final function setConfiguredLimit ($configEntry) {
- // Get the limit from config entry and set it
- $limit = $this->getConfigInstance()->getConfigEntry($configEntry);
+ public final function setConfiguredLimit (string $configKey) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SEARCH-CRITERIA: configKey=%s - CALLED!', $configKey));
+ if (empty($configKey)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "configKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Get the limit from config entry
+ $limit = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($configKey);
+
+ // And set it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SEARCH-CRITERIA: limit=%d', $limit));
$this->setLimit($limit);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('SEARCH-CRITERIA: EXIT!');
}
/**
* @return void
* @todo Find a nice casting here. (int) allows until and including 32766.
*/
- public final function setSkip ($skip) {
+ public final function setSkip (int $skip) {
$this->skip = $skip;
}
* @param $value Value to check
* @param $separator Separator for "exploding" $value (default: ',')
* @return $isMatching Whether the key/value is matching or excluded
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws UnexpectedValueException If $searchChoice is not an array
*/
- public function isCriteriaMatching ($key, $value, $separator = ',') {
+ public function isCriteriaMatching (string $key, $value, string $separator = ',') {
// $key/$value cannot be array/NULL/bool, value can be NULL but then NULL must be loocked for
- assert((!is_array($value)) && (!is_bool($value)) && (!is_array($key)) && (!is_null($key)) && (!is_bool($key)));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SEARCH-CRITERIA: key=%s,value[]=%s,separator=%s - CALLED!', $key, gettype($value), $separator));
+ if (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (is_array($value) || is_bool($value) || is_object($value) || is_resource($value)) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('value[]=%s is not supported/valid', gettype($value)));
+ } elseif (empty($separator)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "separator" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// "Explode" value
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SEARCH-CRITERIA: Invoking explode("%s",value[]=%s) ...', $separator, gettype($value)));
$valueArray = explode($separator, $value);
-
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SEARCH-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: key=' . $key . ',value[' . gettype($value) . ']=' . $value . ' - CALLED!');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SEARCH-CRITERIA: valueArray()=%d', count($valueArray)));
// Get 'default' search value
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SEARCH-CRITERIA: Invoking this->getCriteriaElemnent(%s) ...', $key));
$searchDefault = $this->getCriteriaElemnent($key);
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SEARCH-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: getCriteriaElement(' . $key . ')[' . gettype($searchDefault) . ']=' . $searchDefault);
-
// 'default' check
- $isMatching = (((($searchDefault !== false) && ($searchDefault == $value)) || ((is_null($searchDefault)) && (is_null($value)))) || ($searchDefault === false));
-
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SEARCH-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: getCriteriaElement(' . $key . ')[' . gettype($searchDefault) . ']=' . $searchDefault . ',isMatching=' . intval($isMatching));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SEARCH-CRITERIA: searchDefault[%s]=%s', gettype($searchDefault), $searchDefault));
+ $isMatching = (
+ (
+ (
+ ($searchDefault !== false) &&
+ ($searchDefault == $value)
+ ) || (
+ is_null($searchDefault) &&
+ is_null($value)
+ )
+ ) || (
+ $searchDefault === false
+ )
+ );
// Get 'choice' search value (can be NULL or $separator-separated string)
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SEARCH-CRITERIA: isMatching=%d', intval($isMatching)));
$searchChoice = $this->getCriteriaChoiceElemnent($key);
- // May be false or array
- assert(($searchChoice === false) || (is_array($searchChoice)));
-
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SEARCH-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: getCriteriaChoiceElement(' . $key . ')[' . gettype($searchChoice) . ']=' . print_r($searchChoice, true));
+ // Is an array returned?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SEARCH-CRITERIA: searchChoice[]=%s', gettype($searchChoice)));
+ if (!is_array($searchChoice) && !is_bool($searchChoice)) {
+ // Should not happen
+ throw new UnexpectedValueException(sprintf('searchChoice[]=%s is unexpected', gettype($searchChoice)), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// 'choice' check
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SEARCH-CRITERIA: searchChoice[]=%s', gettype($searchChoice)));
if ((is_array($searchChoice)) && (count($valueArray) == 1)) {
- // $value is a single-search value, so use in_array()
+ // $value is a single-search value, so use in_[]
$isMatching = ((($isMatching === true) || (($searchDefault === false) && (!is_null($value)))) && (in_array($value, $searchChoice)));
// Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SEARCH-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: getCriteriaChoiceElement(' . $key . ')[]=' . gettype($searchChoice) . ',value[' . gettype($value) . ']=' . $value . ',isMatching=' . intval($isMatching) . ' - SINGLE-MATCH');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SEARCH-CRITERIA: isMatching=%d - SINGLE-MATCH', intval($isMatching)));
} elseif ((is_array($searchChoice)) && (count($valueArray) > 1)) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SEARCH-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: getCriteriaChoiceElement(' . $key . ')[]=' . gettype($searchChoice) . ',valueArray()=' . count($valueArray) . ',isMatching=' . intval($isMatching));
-
// $value is choice-search value, so check all entries
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SEARCH-CRITERIA: searchChoice()=%d,valueArray()=%d - MULTI-MATCH', count($searchChoice), count($valueArray)));
$isMatching = (($isMatching === true) || (($searchDefault === false) && (!is_null($value))));
- $idx = 0;
- foreach ($valueArray as $idx => $match) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SEARCH-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: match=' . $match . ',count(searchChoice)=' . count($searchChoice));
+ // Loop through all values
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SEARCH-CRITERIA: isMatching=%d - BEFORE!', intval($isMatching)));
+ foreach ($valueArray as $idx => $match) {
// Is it found? (one is okay)
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SEARCH-CRITERIA: idx=%d,match=%s', $idx, $match));
$isMatching = (($isMatching === true) && (in_array($match, $searchChoice)));
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SEARCH-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: match=' . $match . ',isMatching=' . intval($isMatching));
- } // END - foreach
+ // No longer matching?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SEARCH-CRITERIA: isMatching=%d - LOOP!', intval($isMatching)));
+ if (!$isMatching) {
+ // Skip further iterations
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('SEARCH-CRITERIA: BREAK!');
+ break;
+ }
+ }
// Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SEARCH-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: getCriteriaChoiceElement(' . $key . ')[]=' . gettype($searchChoice) . ',valueArray()=' . count($valueArray) . ',idx=' . $idx . ',isMatching=' . intval($isMatching) . ' - CHOICE-MATCH');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SEARCH-CRITERIA: isMatching=%d - AFTER!', intval($isMatching)));
} else {
// Choice-match is false
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SEARCH-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: getCriteriaChoiceElement(' . $key . ')[]=' . gettype($searchChoice) . ',value[' . gettype($value) . ']=' . $value . ',isMatching=' . intval($isMatching) . ' - false-MATCH');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SEARCH-CRITERIA: key=%s[],searchChoice[]=%s,value[%s]=%s,isMatching=%d - FALSE-MATCH', $key, gettype($searchChoice), gettype($value), $value, intval($isMatching)));
}
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SEARCH-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: getCriteriaChoiceElement(' . $key . ')[]=' . gettype($searchChoice) . ',isMatching=' . intval($isMatching));
-
// Get 'exclude' search value
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SEARCH-CRITERIA: Invoking this->getCriteriaExcludeElemnent(%s) ...', $key));
$searchExclude = $this->getCriteriaExcludeElemnent($key);
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SEARCH-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: getCriteriaExcludeElement(' . $key . ')[' . gettype($searchExclude) . ']=' . $searchExclude);
-
// 'exclude' check
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('SEARCH-CRITERIA: searchExclude[%s]=%s', gettype($searchExclude), $searchExclude));
$isMatching = (
(
(
);
// Return result
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SEARCH-CRITERIA[' . __METHOD__ . ':' . __LINE__ . ']: key=' . $key . ',value[' . gettype($value) . ']=' . $value . ',isMatching=' . intval($isMatching) . ' - EXIT!');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SEARCH-CRITERIA: isMatching=%d - EXIT!', intval($isMatching)));
return $isMatching;
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Criteria\BaseCriteria;
+use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
use Org\Mxchange\CoreFramework\Criteria\Local\LocalUpdateCriteria;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class UpdateCriteria extends BaseCriteria implements LocalUpdateCriteria {
+ /**
+ * Search criteria instance
+ */
+ private $searchInstance = NULL;
+
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public static final function createUpdateCriteria () {
// Get a new instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('UPDATE-CRITERIA: CALLED!');
$criteriaInstance = new UpdateCriteria();
// Return this instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('SEARCH-CRITERIA: criteriaInstance=%s - EXIT!', $criteriaInstance->__toString()));
return $criteriaInstance;
}
return $this->getCriteriaArray();
}
+ /**
+ * Setter for search instance
+ *
+ * @param $searchInstance Searchable criteria instance
+ * @return void
+ */
+ public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
+ $this->searchInstance = $searchInstance;
+ }
+
+ /**
+ * Getter for search instance
+ *
+ * @return $searchInstance Searchable criteria instance
+ */
+ public final function getSearchInstance () {
+ return $this->searchInstance;
+ }
+
}
namespace Org\Mxchange\CoreFramework\Helper\Crypto;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Crypto\Cryptable;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*/
private $salt = '';
+ /**
+ * Instance of a RNG
+ */
+ private $rngInstance = NULL;
+
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public static final function createCryptoHelper () {
// Get a new instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CRYPTO-HELPER: CALLED!');
$cryptoInstance = new CryptoHelper();
// Initialize the hasher
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CRYPTO-HELPER: Invoking cryptoInstance->initHasher() ...');
$cryptoInstance->initHasher();
// Attach a crypto stream
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CRYPTO-HELPER: Invoking cryptoInstance->attachCryptoStream() ...');
$cryptoInstance->attachCryptoStream();
// Return the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CRYPTO-HELPER: cryptoInstance=%s - EXIT!', $cryptoInstance->__toString()));
return $cryptoInstance;
}
*/
public static final function getSelfInstance () {
// Is no instance there?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CRYPTO-HELPER: self::selfInstance[]=%s - CALLED!', gettype(self::$selfInstance)));
if (is_null(self::$selfInstance)) {
// Then get a new one
self::$selfInstance = self::createCryptoHelper();
- } // END - if
+ }
// Return the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CRYPTO-HELPER: self::selfInstance=%s - EXIT!', self::$selfInstance->__toString()));
return self::$selfInstance;
}
+ /**
+ * Setter for RNG instance
+ *
+ * @param $rngInstance An instance of a random number generator (RNG)
+ * @return void
+ */
+ protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
+ $this->rngInstance = $rngInstance;
+ }
+
+ /**
+ * Getter for RNG instance
+ *
+ * @return $rngInstance An instance of a random number generator (RNG)
+ */
+ public final function getRngInstance () {
+ return $this->rngInstance;
+ }
+
/**
* Attaches a crypto stream to this crypto helper by detecting loaded
* modules.
*/
protected function attachCryptoStream () {
// @TODO Maybe rewrite this with DirectoryIterator, similar to Compressor thing?
- // Do we have openssl/mcrypt loaded?
- if ($this->isPhpExtensionLoaded('mcrypt')) {
+ // Do we have openssl loaded?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CRYPTO-HELPER: CALLED!');
+ if ($this->isPhpExtensionLoaded('openssl')) {
// Then use it
- $this->cryptoStreamInstance = ObjectFactory::createObjectByName('Org\Mxchange\CoreFramework\Stream\Crypto\McryptStream', array($this->getRngInstance()));
- } elseif ($this->isPhpExtensionLoaded('openssl')) {
- // Then use it
- $this->cryptoStreamInstance = ObjectFactory::createObjectByName('Org\Mxchange\CoreFramework\Stream\Crypto\OpenSslStream', array($this->getRngInstance()));
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('CRYPTO-HELPER: Attaching openssl crypto stream ...');
+ $this->cryptoStreamInstance = ObjectFactory::createObjectByConfiguredName('crypto_openssl_stream_class', [$this->getRngInstance()]);
} else {
// If nothing works ...
- $this->cryptoStreamInstance = ObjectFactory::createObjectByName('Org\Mxchange\CoreFramework\Stream\Crypto\NullCryptoStream');
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('CRYPTO-HELPER: Attaching NULL crypto stream ...');
+ $this->cryptoStreamInstance = ObjectFactory::createObjectByConfiguredName('crypto_null_stream_class');
}
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CRYPTO-HELPER: EXIT!');
}
/**
$randomString = $this->getRngInstance()->randomString() . $this->createUuid();
// Get config entry for salt length
- $length = $this->getConfigInstance()->getConfigEntry('salt_length');
+ $length = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('salt_length');
// Keep only defined number of characters
$this->salt = substr(sha1($randomString), -$length, $length);
$uuid = '';
// Is the UUID extension loaded and enabled? (see pecl)
- if ($this->getConfigInstance()->getConfigEntry('extension_uuid_loaded') === true) {
+ if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('extension_uuid_loaded') === true) {
// Then add it as well
$uuid = uuid_create();
- } // END - if
+ }
// Return it
return $uuid;
* @param $withFixed Whether to include a fixed salt (not recommended in p2p applications)
* @return $hashed The hashed and salted string
*/
- public function hashString ($str, $oldHash = '', $withFixed = true) {
- // Cast the string
- $str = (string) $str;
-
+ public function hashString (string $str, string $oldHash = '', bool $withFixed = true) {
// Default is the default salt ;-)
$salt = $this->salt;
// Is the old password set?
if (!empty($oldHash)) {
// Use the salt from hash, first get length
- $length = $this->getConfigInstance()->getConfigEntry('salt_length');
+ $length = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('salt_length');
// Then extract the X first characters from the hash as our salt
$salt = substr($oldHash, 0, $length);
- } // END - if
+ }
// Hash the password with salt
//* DEBUG: */ echo "salt=".$salt."/plain=".$str."<br />\n";
if ($withFixed === true) {
// Use additional fixed salt
- $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_extra_mask'),
+ $hashed = $salt . md5(sprintf(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('hash_extra_mask'),
$salt,
$this->getRngInstance()->getFixedSalt(),
$str
));
} else {
// Use salt+string to hash
- $hashed = $salt . md5(sprintf($this->getConfigInstance()->getConfigEntry('hash_normal_mask'),
+ $hashed = $salt . md5(sprintf(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('hash_normal_mask'),
$salt,
$str
));
* @param $key Optional key, if none provided, a random key will be generated
* @return $encrypted Encrypted string
*/
- public function encryptString ($str, $key = NULL) {
+ public function encryptString (string $str, string $key = NULL) {
// Encrypt the string through the stream
$encrypted = $this->cryptoStreamInstance->encryptStream($str, $key);
* @param $encrypted Encrypted string
* @return $str The unencrypted string
*/
- public function decryptString ($encrypted) {
+ public function decryptString (string $encrypted) {
// Encrypt the string through the stream
$str = $this->cryptoStreamInstance->decryptStream($encrypted);
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Database\Backend;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Database\Backend\DatabaseBackend;
+use Org\Mxchange\CoreFramework\Generic\FrameworkException;
+use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+
+/**
+ * An abstract database access class for handling database I/O requests
+ *
+ * @see DatabaseBackend - An interface for database backends
+ * @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/>.
+ */
+abstract class BaseDatabaseBackend extends BaseFrameworkSystem implements DatabaseBackend {
+ // Constants for exceptions
+ const EXCEPTION_SQL_QUERY = 0x140;
+
+ // Constants for MySQL backward-compatiblity (PLEASE FIX THEM!)
+ const DB_CODE_TABLE_MISSING = 0x100;
+ const DB_CODE_TABLE_UNWRITEABLE = 0x101;
+ const DB_CODE_DATA_FILE_CORRUPT = 0x102;
+
+ // Status results
+ const RESULT_OKAY = 'ok';
+
+ /**
+ * Last thrown exception or NULL if all is fine
+ */
+ private $lastException = NULL;
+
+ /**
+ * Protected constructor
+ *
+ * @param $className Name of the class
+ * @return void
+ */
+ protected function __construct (string $className) {
+ // Call parent constructor
+ parent::__construct($className);
+ }
+
+ /**
+ * Getter for last exception
+ *
+ * @return $lastException Last thrown exception
+ */
+ public final function getLastException () {
+ return $this->lastException;
+ }
+
+ /**
+ * Setter for last exception
+ *
+ * @param $lastException Last thrown exception
+ * @return void
+ */
+ public final function setLastException (FrameworkException $exceptionInstance) {
+ $this->lastException = $exceptionInstance;
+ }
+
+ /**
+ * Reset the last exception instance. This should be done after a "query"
+ * was completed without any errors.
+ *
+ * @return void
+ */
+ protected final function resetLastException () {
+ $this->lastException = NULL;
+ }
+
+ /**
+ * 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.
+ */
+ public abstract function removeNonPublicDataFromArray (array $data);
+
+}
namespace Org\Mxchange\CoreFramework\Database\Backend\Lfdb;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Criteria\Criteria;
use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
use Org\Mxchange\CoreFramework\Database\Backend\BaseDatabaseBackend;
use Org\Mxchange\CoreFramework\Database\Backend\DatabaseBackend;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Database\Sql\SqlException;
+use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
use Org\Mxchange\CoreFramework\Generic\FrameworkException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Result\Database\BaseDatabaseResult;
+use Org\Mxchange\CoreFramework\Traits\Compressor\Channel\CompressorChannelTrait;
+use Org\Mxchange\CoreFramework\Traits\Handler\Io\IoHandlerTrait;
// Import SPL stuff
+use \BadMethodCallException;
+use \InvalidArgumentException;
use \SplFileInfo;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class CachedLocalFileDatabase extends BaseDatabaseBackend implements DatabaseBackend {
+ // Load traits
+ use CompressorChannelTrait;
+ use IoHandlerTrait;
+
/**
* The file's extension
*/
/**
* The last read file's content including header information
*/
- private $lastContents = array();
+ private $lastContents = [];
/**
* Whether the "connection is already up
/**
* Table information array
*/
- private $tableInfo = array();
+ private $tableInfo = [];
/**
* Element for index
*/
private $indexKey = '__idx';
+ /**
+ * Cached file names based on table name to avoid "expensive" invocations
+ * of FrameworkConfiguration->getConfigEntry().
+ */
+ private $pathNames = [];
+
/**
* The protected constructor. Do never instance from outside! You need to
* set a local file path. The class will then validate it.
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public static final function createCachedLocalFileDatabase () {
// Get an instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-LOCAL-FILE-DATABASE: CALLED!');
$databaseInstance = new CachedLocalFileDatabase();
- // Get a new compressor channel instance
- $compressorInstance = ObjectFactory::createObjectByConfiguredName('compressor_channel_class');
-
// Set the compressor channel
- $databaseInstance->setCompressorChannel($compressorInstance);
-
- // Get a file IO handler
- $fileIoInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
+ $databaseInstance->setCompressorChannelInstance(ObjectFactory::createObjectByConfiguredName('compressor_channel_class'));
- // ... and set it
- $databaseInstance->setFileIoInstance($fileIoInstance);
+ // Get a file IO handler and set it
+ $databaseInstance->setFileIoInstance(ObjectFactory::createObjectByConfiguredName('file_io_class'));
// "Connect" to the database
$databaseInstance->connectToDatabase();
// Return database instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: databaseInstance=%s - EXIT!', $databaseInstance->__toString()));
return $databaseInstance;
}
* @return $dataArray
*/
private function getDataArrayFromFile (SplFileInfo $infoInstance) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Reading elements from database file ' . $infoInstance . ' ...');
-
// Init compressed data
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: infoInstance=%s - CALLED!', $infoInstance->__toString()));
$compressedData = $this->getFileIoInstance()->loadFileContents($infoInstance);
- $compressedData = $compressedData['data'];
+
+ // Is it valid?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: compressedData[]=%s', gettype($compressedData)));
+ //* DEBUG-DIE: */ die(sprintf('[%s:%d]: compressedData=%s', __METHOD__, __LINE__, print_r($compressedData, TRUE)));
+ if (!isset($compressedData['data'])) {
+ // Important element not found
+ ApplicationEntryPoint::exitApplication(sprintf('compressedData()=%d has no element "data"', count($compressedData)), FrameworkInterface::EXCEPTION_OUT_OF_BOUNDS);
+ }
// Decompress it
- $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
+ $serializedData = $this->getCompressorChannelInstance()->getCompressor()->decompressStream($compressedData['data']);
// Unserialize it
$dataArray = json_decode($serializedData, true);
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Read ' . count($dataArray) . ' elements from database file ' . $infoInstance . '.');
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: dataArray=' . print_r($dataArray, true));
-
// Finally return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: dataArray()=%d - EXIT!', count($dataArray)));
return $dataArray;
}
* @return void
*/
private function writeDataArrayToFqfn (SplFileInfo $infoInstance, array $dataArray) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Flushing ' . count($dataArray) . ' elements to database file ' . $infoInstance . ' ...');
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: dataArray=' . print_r($dataArray, true));
-
// Serialize and compress it
- $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(json_encode($dataArray));
-
- // Write data
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Writing ' . strlen($compressedData) . ' bytes ...');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-LOCAL-FILE-DATABASE: Flushing ' . count($dataArray) . ' elements to database file ' . $infoInstance . ' ...');
+ $compressedData = $this->getCompressorChannelInstance()->getCompressor()->compressStream(json_encode($dataArray));
// Write this data BASE64 encoded to the file
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: Writing ' . strlen($compressedData) . ' bytes ...');
$this->getFileIoInstance()->saveStreamToFile($infoInstance, $compressedData, $this);
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Flushing ' . count($dataArray) . ' elements to database file completed.');
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-LOCAL-FILE-DATABASE: Flushing ' . count($dataArray) . ' elements to database file completed.');
}
/**
*/
private function getContentsFromTableInfoFile (StoreableCriteria $dataSetInstance) {
// Default content is no data
- $infoArray = array();
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
+ $infoArray = [];
// Create FQFN for getting the table information file
$infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
// Get the file contents
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: infoInstance=%s', $infoInstance->__toString()));
try {
$infoArray = $this->getDataArrayFromFile($infoInstance);
} catch (FileNotFoundException $e) {
}
// ... and return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: infoArray()=%d - EXIT!', count($infoArray)));
return $infoArray;
}
* @param $rowName Name of the row
* @return $infoInstance An instance of a SplFileInfo class
*/
- private function generateFileFromDataSet (Criteria $dataSetInstance, $rowName) {
+ private function generateFileFromDataSet (Criteria $dataSetInstance, string $rowName) {
// Instanciate new file object
- $infoInstance = new SplFileInfo($this->getConfigInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR . $rowName . '.' . $this->getFileExtension());
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: dataSetInstance=%s,rowName=%s - CALLED!', $dataSetInstance->__toString(), $rowName));
+ $infoInstance = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR . $rowName . '.' . $this->getFileExtension());
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: infoInstance=%s - EXIT!', $infoInstance->__toString()));
return $infoInstance;
}
* @return void
*/
private function createTableInfoFile (StoreableCriteria $dataSetInstance) {
- // Create FQFN for creating the table information file
- $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
+ // Get table name
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
+ $tableName = $dataSetInstance->getTableName();
// Get the data out from dataset in a local array
- $this->tableInfo[$dataSetInstance->getTableName()] = array(
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: tableName=%', $tableName));
+ $this->tableInfo[$tableName] = [
'primary' => $dataSetInstance->getPrimaryKey(),
'created' => time(),
- 'last_updated' => time()
- );
+ 'last_updated' => time(),
+ ];
+
+ // Get info instance
+ $infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
// Write the data to the file
- $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$dataSetInstance->getTableName()]);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: Invoking this->writeDataArrayToFqfn(%s,this->tableInfo[%s]()=%d) ...', $infoInstance->__toString(), $tableName, count($this->tableInfo[$tableName])));
+ $this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$tableName]);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-LOCAL-FILE-DATABASE: EXIT!');
}
/**
*/
private function updateTableInfoFile (StoreableCriteria $dataSetInstance) {
// Get table name from criteria
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
$tableName = $dataSetInstance->getTableName();
// Create FQFN for creating the table information file
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: tableName=%', $tableName));
$infoInstance = $this->generateFileFromDataSet($dataSetInstance, 'info');
// Get the data out from dataset in a local array
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: infoInstance=%s', $infoInstance->__toString()));
$this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
$this->tableInfo[$tableName]['last_updated'] = time();
// Write the data to the file
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: Invoking this->writeDataArrayToFqfn(%s,this->tableInfo[%s]()=%d) ...', $infoInstance->__toString(), $tableName, count($this->tableInfo[$tableName])));
$this->writeDataArrayToFqfn($infoInstance, $this->tableInfo[$tableName]);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-LOCAL-FILE-DATABASE: EXIT!');
}
/**
*/
private function updatePrimaryKey (StoreableCriteria $dataSetInstance) {
// Get table name from criteria
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
$tableName = $dataSetInstance->getTableName();
// Get the information array from lower method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: tableName=%s', $tableName));
$infoArray = $this->getContentsFromTableInfoFile($dataSetInstance);
// Is the primary key there?
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: tableInfo=' . print_r($this->tableInfo, true));
+ //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CACHED-LOCAL-FILE-DATABASE: tableInfo=' . print_r($this->tableInfo, true));
if (!isset($this->tableInfo[$tableName]['primary'])) {
// Then create the info file
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: Creating info table for tableName=%s ...', $tableName));
$this->createTableInfoFile($dataSetInstance);
- } elseif (($this->getConfigInstance()->getConfigEntry('db_update_primary_forced') == 'Y') && ($dataSetInstance->getPrimaryKey() != $this->tableInfo[$tableName]['primary'])) {
+ } elseif (FrameworkBootstrap::getConfigurationInstance()->isEnabled('db_update_primary_forced') && $dataSetInstance->getPrimaryKey() != $this->tableInfo[$tableName]['primary']) {
// Set the array element
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: Setting primaryKey=%s for tableName=%s ...', $dataSetInstance->getPrimaryKey(), $tableName));
$this->tableInfo[$tableName]['primary'] = $dataSetInstance->getPrimaryKey();
// Update the entry
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CACHED-LOCAL-FILE-DATABASE: Updating info table for tableName=%s ...', $tableName));
$this->updateTableInfoFile($dataSetInstance);
}
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-LOCAL-FILE-DATABASE: EXIT!');
}
/**
* @todo Do some checks on the database directory and files here
*/
public function connectToDatabase () {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-LOCAL-FILE-DATABASE: CALLED!');
}
/**
* @param $tableName Name of the database table
* @param $searchInstance Local search criteria class
* @return $resultData Result data of the query
+ * @throws InvalidArgumentException If a parameter is not valid
* @throws UnsupportedCriteriaException If the criteria is unsupported
* @throws SqlException If an 'SQL error' occurs
*/
- public function querySelect ($tableName, LocalSearchCriteria $searchInstance) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: tableName=' . $tableName . ' - CALLED!');
+ public function querySelect (string $tableName, LocalSearchCriteria $searchInstance) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: tableName=%s,searchInstance=%s - CALLED!', $tableName, $searchInstance->__toString()));
+ if (empty($tableName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "tableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!isset($this->pathNames[$tableName])) {
+ // "Cache" is not present, so create and assign it
+ $this->pathNames[$tableName] = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
+ }
// The result is null by any errors
$resultData = NULL;
- // Create full path name
- $pathName = $this->getConfigInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
-
/*
* A 'select' query is not that easy on local files, so first try to
* find the 'table' which is in fact a directory on the server
*/
try {
// Get a directory pointer instance
- $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: Getting directory_class for this->pathNames[%s]=%s ...', $tableName, $this->pathNames[$tableName]));
+ $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', [$this->pathNames[$tableName]]);
// Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
- $resultData = array(
- BaseDatabaseBackend::RESULT_INDEX_STATUS => self::RESULT_OKAY,
- BaseDatabaseBackend::RESULT_INDEX_ROWS => array()
- );
+ $resultData = [
+ BaseDatabaseResult::RESULT_NAME_STATUS => self::RESULT_OKAY,
+ BaseDatabaseResult::RESULT_NAME_ROWS => [],
+ BaseDatabaseResult::RESULT_NAME_EXCEPTION => NULL,
+ ];
// Initialize limit/skip
$limitFound = 0;
$idx = 1;
// Read the directory with some exceptions
- while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: fileInstance.extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
-
+ while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(['.gitkeep', 'info.' . $this->getFileExtension()])) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
// Does the extension match?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: fileInfoInstance->extension=%s,this->fileExtension=%s', $fileInfoInstance->getExtension(), $this->getFileExtension()));
if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
// Skip this file!
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: Skipping fileInfoInstance->filename=%s ...', $fileInfoInstance->getFilename()));
+ $directoryInstance->getDirectoryIteratorInstance()->next();
continue;
- } // END - if
+ }
// Read the file
$dataArray = $this->getDataArrayFromFile($fileInfoInstance);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
// Is this an array?
+ //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('CACHED-LOCAL-FILE-DATABASE: fileInfoInstance->pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
if (is_array($dataArray)) {
// Default is nothing found
$isFound = true;
// Search in the criteria with FMFW (First Matches, First Wins)
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: data[]=%d', count($dataArray)));
foreach ($dataArray as $key => $value) {
- // Make sure value is not bool
- assert(!is_bool($value));
-
// Found one entry?
- $isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: key=' . $key . ',value=' . $value . ',isFound=' . intval($isFound));
- } // END - foreach
+ $isFound = ($isFound && $searchInstance->isCriteriaMatching($key, $value));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: key=%s,value[%s]=%s,isFound=%s', $key, gettype($value), $value, intval($isFound)));
+ }
// Is all found?
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: isFound=' . intval($isFound) . ',limitFound=' . $limitFound . ',limit=' . $searchInstance->getLimit());
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: isFound=%d,limitFound=%d,limit=%d', intval($isFound), $limitFound, $searchInstance->getLimit()));
if ($isFound === true) {
// Shall we skip this entry?
- if ($searchInstance->getSkip() > 0) {
- // We shall skip some entries
- if ($skipFound < $searchInstance->getSkip()) {
- // Skip this entry
- $skipFound++;
- break;
- } // END - if
- } // END - if
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: searchInstance->skip=%d,skipFound=%d', $searchInstance->getSkip(), $skipFound));
+ if ($searchInstance->getSkip() > 0 && $skipFound < $searchInstance->getSkip()) {
+ // Skip this entry
+ $skipFound++;
+ break;
+ }
// Set id number
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: Setting dataArray[%s]=%d', $this->getIndexKey(), $idx));
$dataArray[$this->getIndexKey()] = $idx;
// Entry found!
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: indexKey=' . $this->getIndexKey() . ',idx=' . $idx . ',dataArray=' . print_r($dataArray, true));
- array_push($resultData[BaseDatabaseBackend::RESULT_INDEX_ROWS], $dataArray);
+ array_push($resultData[BaseDatabaseResult::RESULT_NAME_ROWS], $dataArray);
// Count found entries up
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: resultData[%s]()=%d', BaseDatabaseResult::RESULT_NAME_ROWS, count($resultData[BaseDatabaseResult::RESULT_NAME_ROWS])));
$limitFound++;
- } // END - if
+ }
} else {
// Throw an exception here
throw new SqlException(array($this, sprintf('File '%s' contains invalid data.', $fileInfoInstance->getPathname()), self::DB_CODE_DATA_FILE_CORRUPT), self::EXCEPTION_SQL_QUERY);
// Count entry up
$idx++;
- } // END - while
+
+ // Advance to next entry
+ $directoryInstance->getDirectoryIteratorInstance()->next();
+ }
// Close directory and throw the instance away
$directoryInstance->closeDirectory();
}
// Return the gathered result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: resultData()=%d - EXIT!', count($resultData)));
return $resultData;
}
*/
public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
// Try to save the request away
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
try {
// Create full path name
$infoInstance = $this->generateFileFromDataSet($dataSetInstance, md5($dataSetInstance->getUniqueValue()));
$this->setLastException($e);
// Throw an SQL exception
- throw new SqlException(array($this, sprintf('Cannot write data to table '%s', is the table created?', $dataSetInstance->getTableName()), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
+ throw new SqlException([
+ $this,
+ sprintf('Cannot write data to table '%s', is the table created? e=%s,e->message=%s',
+ $dataSetInstance->getTableName(),
+ $e->__toString(),
+ $e->getMessage()
+ ),
+ self::DB_CODE_TABLE_UNWRITEABLE
+ ],
+ self::EXCEPTION_SQL_QUERY
+ );
}
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-LOCAL-FILE-DATABASE: EXIT!');
}
/**
* "Updates" a data set instance with a database layer
*
- * @param $dataSetInstance A storeable data set
+ * @param $dataSetInstance An instance of a StorableCriteria class
* @return void
+ * @throws InvalidArgumentException If $tableName is empty
* @throws SqlException If an SQL error occurs
*/
public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
- // Create full path name
- $pathName = $this->getConfigInstance()->getConfigEntry('local_database_path') . $dataSetInstance->getTableName() . DIRECTORY_SEPARATOR;
+ // Get table name
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
+ $tableName = $dataSetInstance->getTableName();
+
+ // Is "cache" there?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: tableName=%s', $tableName));
+ if (empty($tableName)) {
+ // Should never be an empty string
+ throw new InvalidArgumentException('Class field dataSetInstance->tableName is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!isset($this->pathNames[$tableName])) {
+ // "Cache" is not present, so create and assign it
+ $this->pathNames[$tableName] = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
+ }
// Try all the requests
try {
// Get a file pointer instance
- $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
+ $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', [$this->pathNames[$tableName]]);
// Initialize limit/skip
$limitFound = 0;
$searchArray = $dataSetInstance->getCriteriaArray();
// Get search criteria
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: searchArray()=%d', count($searchArray)));
$searchInstance = $dataSetInstance->getSearchInstance();
// Read the directory with some exceptions
- while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: fileInstance.extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
-
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: searchInstance=%s', $searchInstance->__toString()));
+ while (($fileInfoInstance = $directoryInstance->readDirectoryExcept(['.gitkeep', 'info.' . $this->getFileExtension()])) && (($limitFound < $searchInstance->getLimit()) || ($searchInstance->getLimit() == 0))) {
// Does the extension match?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: fileInfoInstance->extension=%s,this->fileExtension=%s', $fileInfoInstance->getExtension(), $this->getFileExtension()));
if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
// Skip this file!
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: fileInfoInstance->extension=%s,this->fileExtension=%s - SKIPPED!', $fileInfoInstance->getExtension(), $this->getFileExtension()));
+ $directoryInstance->getDirectoryIteratorInstance()->next();
continue;
- } // END - if
+ }
// Open this file for reading
$dataArray = $this->getDataArrayFromFile($fileInfoInstance);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
// Is this an array?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('CACHED-LOCAL-FILE-DATABASE: fileInfoInstance->pathname=' . $fileInfoInstance->getPathname() . ',dataArray='.print_r($dataArray, true));
if (is_array($dataArray)) {
// Default is nothing found
$isFound = true;
// Search in the criteria with FMFW (First Matches, First Wins)
foreach ($dataArray as $key => $value) {
- // Make sure value is not bool
- assert(!is_bool($value));
-
// Found one entry?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: isFound=%d,key=%s,value[]=%s', intval($isFound), $key, gettype($value)));
$isFound = (($isFound === true) && ($searchInstance->isCriteriaMatching($key, $value)));
- } // END - foreach
+ }
// Is all found?
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: isFound=' . intval($isFound));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: isFound=%s', intval($isFound)));
if ($isFound === true) {
// Shall we skip this entry?
if ($searchInstance->getSkip() > 0) {
// We shall skip some entries
if ($skipFound < $searchInstance->getSkip()) {
// Skip this entry
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Found entry, but skipping ...');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('CACHED-LOCAL-FILE-DATABASE: Found entry, but skipping ...');
$skipFound++;
break;
- } // END - if
- } // END - if
+ }
+ }
// Entry found, so update it
foreach ($searchArray as $searchKey => $searchValue) {
// Make sure the value is not bool again
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: searchKey=%s,searchValue[]=%s', $searchKey, gettype($searchValue)));
assert(!is_bool($searchValue));
- assert($searchKey != $this->indexKey);
+ assert($searchKey != $this->getIndexKey());
// Debug message + add/update it
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: criteriaKey=' . $searchKey . ',criteriaValue=' . $searchValue);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: criteriaKey=%s,criteriaValue[%s]=%s', $searchKey, gettype($searchValue), $searchValue));
$dataArray[$searchKey] = $searchValue;
- } // END - foreach
+ }
// Write the data to a local file
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: Writing dataArray()=' . count($dataArray) . ' to ' . $fileInfoInstance->getPathname() . ' ...');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: Writing data()=%d to %s ...', count($dataArray), $fileInfoInstance->getPathname()));
$this->writeDataArrayToFqfn($fileInfoInstance, $dataArray);
// Count found entries up
$limitFound++;
- } // END - if
- } // END - if
- } // END - while
+ }
+ }
+
+ // Advance to next entry
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-LOCAL-FILE-DATABASE: Invoking directoryInstance->directoryIteratorInstance->next() ...');
+ $directoryInstance->getDirectoryIteratorInstance()->next();
+ }
// Close the file pointer
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-LOCAL-FILE-DATABASE: Invoking directoryInstance->closeDirectory() ...');
$directoryInstance->closeDirectory();
// Update the primary key
$this->resetLastException();
} catch (FrameworkException $e) {
// Catch all exceptions and store them in last error
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: e=%s,e->code=%d,e->message=%s', $e->__toString(), $e->getCode(), $e->getMessage()));
$this->setLastException($e);
// Throw an SQL exception
throw new SqlException(array($this, sprintf('Cannot write data to table '%s', is the table created? Exception: %s, message:%s', $dataSetInstance->getTableName(), $e->__toString(), $e->getMessage()), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
}
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-LOCAL-FILE-DATABASE: EXIT!');
}
/**
*
* @param $tableName Name of the table we need the primary key from
* @return $primaryKey Primary key column of the given table
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @todo Rename method to getPrimaryKeyFromTableInfo()
*/
- public function getPrimaryKeyOfTable ($tableName) {
+ public function getPrimaryKeyOfTable (string $tableName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: tableName=%s - CALLED!', $tableName));
+ if (empty($tableName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "tableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Default key is null
$primaryKey = NULL;
if (isset($this->tableInfo[$tableName])) {
// Then return the primary key
$primaryKey = $this->tableInfo[$tableName]['primary'];
- } // END - if
+ }
// Return the column
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: primaryKey[%s]=%s - EXIT!', gettype($primaryKey), $primaryKey));
return $primaryKey;
}
*
* @param $data An array with possible non-public data that needs to be removed.
* @return $data A cleaned up array with only public data.
+ * @throws BadMethodCallException If some non-public is already not found but method was called
* @todo Add more generic non-public data for removal
*/
public function removeNonPublicDataFromArray (array $data) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: data()=%d - CALLED!', count($data)));
+ if (!isset($data[$this->getIndexKey()])) {
+ // Throw BMCE
+ throw new BadMethodCallException(sprintf('data()=%d does not contain this->indexKey=%s', count($data), $this->getIndexKey()));
+ }
+
// Remove '__idx'
- unset($data[$this->indexKey]);
+ unset($data[$this->getIndexKey()]);
// Return it
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: data[' . gettype($data) . ']='.print_r($data, true));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: data()=%d - EXIT!', count($data)));
return $data;
}
*
* @param $tableName Table name
* @return $count Total rows of given table
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- public function countTotalRows($tableName) {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: tableName=' . $tableName . ' - CALLED!');
-
- // Create full path name
- $pathName = $this->getConfigInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
+ public function countTotalRows (string $tableName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: tableName=%s - CALLED!', $tableName));
+ if (empty($tableName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "tableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!isset($this->pathNames[$tableName])) {
+ // "Cache" is not present, so create and assign it
+ $this->pathNames[$tableName] = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('local_database_path') . $tableName . DIRECTORY_SEPARATOR;
+ }
// Try all the requests
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: this->pathNames[%s]=%s', $tableName, $this->pathNames[$tableName]));
try {
// Get a file pointer instance
- $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($pathName));
+ $directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', [$this->pathNames[$tableName]]);
// Initialize counter
$count = 0;
// Read the directory with some exceptions
- while ($fileInfoInstance = $directoryInstance->readDirectoryExcept(array('.htaccess', 'info.' . $this->getFileExtension()))) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: fileInstance.extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
-
+ while ($fileInfoInstance = $directoryInstance->readDirectoryExcept(['.gitkeep', 'info.' . $this->getFileExtension()])) {
// Does the extension match?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('CACHED-LOCAL-FILE-DATABASE: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',this->getFileExtension()=' . $this->getFileExtension());
if ($fileInfoInstance->getExtension() !== $this->getFileExtension()) {
// Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: fileInfoInstance.extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('CACHED-LOCAL-FILE-DATABASE: fileInfoInstance->extension=' . $fileInfoInstance->getExtension() . ',getFileExtension()=' . $this->getFileExtension() . ' - SKIPPED!');
// Skip this file!
continue;
- } // END - if
+ }
// Count this row up
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: fileInfoInstance.pathname=' . $fileInfoInstance->getPathname() . ',getFileExtension()=' . $this->getFileExtension() . ' - COUNTED!');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('CACHED-LOCAL-FILE-DATABASE: fileInfoInstance->pathname=' . $fileInfoInstance->getPathname() . ',getFileExtension()=' . $this->getFileExtension() . ' - COUNTED!');
$count++;
- } // END - while
+ }
} catch (FrameworkException $e) {
// Catch all exceptions and store them in last error
$this->setLastException($e);
}
// Return count
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DATABASE: tableName=' . $tableName . ',count=' . $count . ' - EXIT!');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-LOCAL-FILE-DATABASE: count=%d - EXIT!', $count));
return $count;
}
* @see DatabaseBackendInterface - An interface for database backends
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Database\Backend;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Database\Backend\DatabaseBackend;
-use Org\Mxchange\CoreFramework\Generic\FrameworkException;
-use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
-
-/**
- * An abstract database access class for handling database I/O requests
- *
- * @see DatabaseBackend - An interface for database backends
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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/>.
- */
-abstract class BaseDatabaseBackend extends BaseFrameworkSystem implements DatabaseBackend {
- // Constants for exceptions
- const EXCEPTION_SQL_QUERY = 0x140;
-
- // Result array indexes
- const RESULT_INDEX_ROWS = 'rows';
- const RESULT_INDEX_STATUS = 'status';
- const RESULT_INDEX_EXCEPTION = 'exception';
-
- // Constants for MySQL backward-compatiblity (PLEASE FIX THEM!)
- const DB_CODE_TABLE_MISSING = 0x100;
- const DB_CODE_TABLE_UNWRITEABLE = 0x101;
- const DB_CODE_DATA_FILE_CORRUPT = 0x102;
-
- // Status results
- const RESULT_OKAY = 'ok';
-
- /**
- * Last thrown exception or NULL if all is fine
- */
- private $lastException = NULL;
-
- /**
- * Protected constructor
- *
- * @param $className Name of the class
- * @return void
- */
- protected function __construct ($className) {
- // Call parent constructor
- parent::__construct($className);
- }
-
- /**
- * Getter for last exception
- *
- * @return $lastException Last thrown exception
- */
- public final function getLastException () {
- return $this->lastException;
- }
-
- /**
- * Setter for last exception
- *
- * @param $lastException Last thrown exception
- * @return void
- */
- public final function setLastException (FrameworkException $exceptionInstance) {
- $this->lastException = $exceptionInstance;
- }
-
- /**
- * Reset the last exception instance. This should be done after a "query"
- * was completed without any errors.
- *
- * @return void
- */
- protected final function resetLastException () {
- $this->lastException = NULL;
- }
-
- /**
- * 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.
- */
- public abstract function removeNonPublicDataFromArray (array $data);
-
-}
namespace Org\Mxchange\CoreFramework\Result\Database;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Criteria\Local\LocalUpdateCriteria;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
/**
* @see DatabaseBackend - An interface for database backends
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseDatabaseResult extends BaseFrameworkSystem {
+ // Result array names
+ const RESULT_NAME_ROWS = 'rows';
+ const RESULT_NAME_STATUS = 'status';
+ const RESULT_NAME_EXCEPTION = 'exception';
+
+ /**
+ * Update criteria instance
+ */
+ private $updateInstance = NULL;
+
/**
* Protected constructor
*
* @return void
*/
- protected function __construct($class = __CLASS__) {
+ protected function __construct (string $className) {
// Call parent constructor
- parent::__construct($class);
+ parent::__construct($className);
+ }
+
+ /**
+ * Setter for update instance
+ *
+ * @param $updateInstance An instance of a LocalUpdateCriteria clase
+ * @return void
+ */
+ public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
+ $this->updateInstance = $updateInstance;
+ }
+
+ /**
+ * Getter for update instance
+ *
+ * @return $updateInstance Updateable criteria instance
+ */
+ public final function getUpdateInstance () {
+ return $this->updateInstance;
}
}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Database\Frontend;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\Criteria\Criteria;
-use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
-use Org\Mxchange\CoreFramework\Database\Backend\BaseDatabaseBackend;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
-
-/**
- * A generic database wrapper
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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/>.
- */
-abstract class BaseDatabaseWrapper extends BaseFrameworkSystem {
- /**
- * Cache instance
- */
- private $cacheInstance = NULL;
-
- /**
- * Current table name to use
- */
- private $tableName = 'unknown';
-
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct ($class) {
- // Call parent constructor
- parent::__construct($class);
-
- // Initialize the cache instance
- $this->initCacheInstance();
- }
-
- /**
- * Initializes the cache instance with a new object
- *
- * @return void
- */
- private final function initCacheInstance () {
- // Is the cache enabled?
- if ($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === true) {
- // Set the new instance
- $this->cacheInstance = CacheFactory::getFactory()->createConfiguredCache();
- } // END - if
- }
-
- /**
- * Setter for table name
- *
- * @param $tableName Name of table name to set
- * @return void
- */
- protected final function setTableName ($tableName) {
- $this->tableName = (string) $tableName;
- }
-
- /**
- * Getter for table name
- *
- * @return $tableName Name of table name to set
- */
- protected final function getTableName () {
- return $this->tableName;
- }
-
- /**
- * 'Inserts' a data set instance into a local file database folder
- *
- * @param $dataSetInstance A storeable data set
- * @param $onlyKeys Only use these keys for a cache key
- * @return void
- */
- protected function queryInsertDataSet (StoreableCriteria $dataSetInstance, array $onlyKeys = array()) {
- // Default cache key is NULL
- $cacheKey = NULL;
-
- // Is cache enabled?
- if ($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === true) {
- // First get a key suitable for our cache and extend it with this class name
- $cacheKey = $this->getCacheKeyByCriteria($dataSetInstance, $onlyKeys);
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-WRAPPER: Using cache key ' . $cacheKey . ' for purging ...');
- } // END - if
-
- // Does this key exists in cache?
- if (($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === true) && ($this->cacheInstance->offsetExists($cacheKey))) {
- // Purge the cache
- $this->cacheInstance->purgeOffset($cacheKey);
- } // END - if
-
- // Handle it over to the middleware
- FrameworkBootstrap::getDatabaseInstance()->queryInsertDataSet($dataSetInstance);
- }
-
- /**
- * 'Updates' a data set instance with a database layer
- *
- * @param $dataSetInstance A storeable data set
- * @param $onlyKeys Only use these keys for a cache key
- * @return void
- */
- protected function queryUpdateDataSet (StoreableCriteria $dataSetInstance, array $onlyKeys = array()) {
- // Init cache key
- $cacheKey = NULL;
-
- // Is cache enabled?
- if ($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === true) {
- // First get a key suitable for our cache and extend it with this class name
- $cacheKey = $this->getCacheKeyByCriteria($dataSetInstance, $onlyKeys);
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-WRAPPER: Using cache key ' . $cacheKey . ' for purging ...');
- } // END - if
-
- // Does this key exists in cache?
- if (($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === true) && ($this->cacheInstance->offsetExists($cacheKey))) {
- // Purge the cache
- $this->cacheInstance->purgeOffset($cacheKey);
- } // END - if
-
- // Handle it over to the middleware
- FrameworkBootstrap::getDatabaseInstance()->queryUpdateDataSet($dataSetInstance);
- }
-
- /**
- * Getter for index key
- *
- * @return $indexKey Index key
- */
- public final function getIndexKey () {
- return FrameworkBootstrap::getDatabaseInstance()->getIndexKey();
- }
-
- /**
- * Getter for last exception
- *
- * @return $lastException Last exception or NULL if none occured
- */
- public final function getLastException () {
- return FrameworkBootstrap::getDatabaseInstance()->getLastException();
- }
-
- /**
- * Do a "select" query on the current table with the given search criteria and
- * store it in cache for later usage
- *
- * @param $criteriaInstance An instance of a Criteria class
- * @param $onlyKeys Only use these keys for a cache key
- * @return $resultInstance An instance of a database result class
- */
- public function doSelectByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
- // Default cache key if cache is not enabled
- $cacheKey = NULL;
-
- // Is the cache enabled?
- if ($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === true) {
- // First get a key suitable for our cache and extend it with this class name
- $cacheKey = $this->getCacheKeyByCriteria($criteriaInstance, $onlyKeys);
- } // END - if
-
- // Does this key exists in cache?
- if (($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === true) && ($this->cacheInstance->offsetExists($cacheKey, BaseDatabaseBackend::RESULT_INDEX_ROWS, 1))) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-WRAPPER: Cache used for cacheKey=' . $cacheKey . ':' . print_r($this->cacheInstance->offsetGet($cacheKey), true));
-
- // Then use this result
- $result = $this->cacheInstance->offsetGet($cacheKey);
- } else {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-WRAPPER: Quering database, cacheKey=' . $cacheKey);
-
- // Now it's time to ask the database layer for this select statement
- $result = FrameworkBootstrap::getDatabaseInstance()->doSelectByTableCriteria($this->getTableName(), $criteriaInstance);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-WRAPPER: result[]=' . gettype($result));
-
- // Cache the result if not null
- if (!is_null($result)) {
- // Is cache enabled?
- if ($this->getConfigInstance()->getConfigEntry('database_cache_enabled') === true) {
- // A valid result has returned from the database layer
- $this->cacheInstance->offsetSet($cacheKey, $result);
- } // END - if
- } else {
- // This invalid result must be wrapped
- $result = array(
- BaseDatabaseBackend::RESULT_INDEX_STATUS => 'invalid',
- BaseDatabaseBackend::RESULT_INDEX_EXCEPTION => FrameworkBootstrap::getDatabaseInstance()->getLastException()
- );
- }
- }
-
- // Create an instance of a CachedDatabaseResult class with the given result
- // @TODO Minor: Update above comment to e.g. BaseDatabaseResult
- $resultInstance = ObjectFactory::createObjectByConfiguredName('database_result_class', array($result));
-
- // And return the instance
- return $resultInstance;
- }
-
- /**
- * Count the numbers of rows we shall receive
- *
- * @param $criteriaInstance An instance of a Criteria class
- * @param $onlyKeys Only use these keys for a cache key
- * @return $numRows Numbers of rows of database entries
- */
- public function doSelectCountByCriteria (Criteria $criteriaInstance, $onlyKeys = array()) {
- // Total numbers is -1 so we can distinglish between failed and valid queries
- $numRows = 0;
-
- // Get the result from above method
- $resultInstance = $this->doSelectByCriteria($criteriaInstance, $onlyKeys);
-
- // Was that query fine?
- if ($resultInstance->ifStatusIsOkay()) {
- // Then get the number of rows
- $numRows = $resultInstance->getAffectedRows();
-
- // Debug message
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-WRAPPER: numRows=' . $numRows);
- } // END - if
-
- // Return the result
- return $numRows;
- }
-
- /**
- * Getter for primary key used in wrapped table
- *
- * @return $primaryKey Primary key used in wrapped table
- */
- public final function getPrimaryKeyValue () {
- // Get the table name and a database instance and ask for it
- $primaryKey = FrameworkBootstrap::getDatabaseInstance()->getPrimaryKeyOfTable($this->getTableName());
-
- // Return value
- return $primaryKey;
- }
-
- /**
- * Count rows of this table
- *
- * @return $count Count of total rows in this table
- */
- public final function countTotalRows () {
- // Get the table name and a database instance and ask for it
- $count = FrameworkBootstrap::getDatabaseInstance()->countTotalRows($this->getTableName());
-
- // Return value
- return $count;
- }
-
- /**
- * 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.
- */
- public function removeNonPublicDataFromArray (array $data) {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('WRAPPER[' . $this->__toString() . ']: Calling this->getDatabaseInstance()->removeNonPublicDataFromArray(data) ...');
- $data = FrameworkBootstrap::getDatabaseInstance()->removeNonPublicDataFromArray($data);
-
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('WRAPPER[' . $this->__toString() . ']: data[]=' . gettype($data));
- return $data;
- }
-
-}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Database\Frontend;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Criteria\Criteria;
+use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
+use Org\Mxchange\CoreFramework\Database\Backend\BaseDatabaseBackend;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+use Org\Mxchange\CoreFramework\Result\Database\BaseDatabaseResult;
+use Org\Mxchange\CoreFramework\Traits\Cache\CacheableTrait;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+
+/**
+ * A generic database frontend
+ *
+ * @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/>.
+ */
+abstract class BaseDatabaseFrontend extends BaseFrameworkSystem {
+ // Load traits
+ use CacheableTrait;
+
+ /**
+ * Current table name to use
+ */
+ private $tableName = 'unknown';
+
+ /**
+ * "Cached" value 'database_cache_enabled' from configuration
+ */
+ private $databaseCacheEnabled = false;
+
+ /**
+ * Protected constructor
+ *
+ * @param $className Name of the class
+ * @return void
+ */
+ protected function __construct (string $className) {
+ // Call parent constructor
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-DATABASE-FRONTEND: className=%s - CONSTRUCTED!', $className));
+ parent::__construct($className);
+
+ // Initialize the cache instance
+ $this->initCacheInstance();
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-DATABASE-FRONTEND: EXIT!');
+ }
+
+ /**
+ * Initializes the cache instance with a new object
+ *
+ * @return void
+ */
+ private final function initCacheInstance () {
+ // Set "cache" attributes
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-DATABASE-FRONTEND: CALLED!');
+ $this->databaseCacheEnabled = FrameworkBootstrap::getConfigurationInstance()->isEnabled('database_cache');
+
+ // Is the cache enabled?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-DATABASE-FRONTEND: this->databaseCacheEnabled=%d', intval($this->databaseCacheEnabled)));
+ if ($this->databaseCacheEnabled === true) {
+ // Set the new instance
+ $this->setCacheInstance(ObjectFactory::createObjectByConfiguredName('cache_class'));
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-DATABASE-FRONTEND: EXIT!');
+ }
+
+ /**
+ * Setter for table name
+ *
+ * @param $tableName Name of table name to set
+ * @return void
+ */
+ protected final function setTableName (string $tableName) {
+ $this->tableName = $tableName;
+ }
+
+ /**
+ * Getter for table name
+ *
+ * @return $tableName Name of table name to set
+ */
+ protected final function getTableName () {
+ return $this->tableName;
+ }
+
+ /**
+ * Gets a cache key from Criteria instance
+ *
+ * @param $criteriaInstance An instance of a Criteria class
+ * @param $onlyKeys Only use these keys for a cache key
+ * @return $cacheKey A cache key suitable for lookup/storage purposes
+ */
+ protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = []) {
+ // Generate it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-DATABASE-FRONTEND: criteriaInstance=%s,onlyKeys()=%d - CALLED!', $criteriaInstance->__toString(), count($onlyKeys)));
+ $cacheKey = sprintf('%s@%s',
+ $this->__toString(),
+ $criteriaInstance->getCacheKey($onlyKeys)
+ );
+
+ // And return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FRAMEWORK-SYSTEM: cacheKey=' . $cacheKey . ' - EXIT!');
+ return $cacheKey;
+ }
+
+ /**
+ * 'Inserts' a data set instance into a local file database folder
+ *
+ * @param $dataSetInstance A storeable data set
+ * @param $onlyKeys Only use these keys for a cache key
+ * @return void
+ */
+ protected function queryInsertDataSet (StoreableCriteria $dataSetInstance, array $onlyKeys = []) {
+ // Default cache key is NULL
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-DATABASE-FRONTEND: dataSetInstance=%s,onlyKeys()=%d - CALLED!', $dataSetInstance->__toString(), count($onlyKeys)));
+ $cacheKey = NULL;
+
+ // Is cache enabled?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-DATABASE-FRONTEND: this->databaseCacheEnabled=%d', intval($this->databaseCacheEnabled)));
+ if ($this->databaseCacheEnabled === true) {
+ // First get a key suitable for our cache and extend it with this class name
+ $cacheKey = $this->getCacheKeyByCriteria($dataSetInstance, $onlyKeys);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-DATABASE-FRONTEND: Using cache key %s for purging ...', $cacheKey));
+ }
+
+ // Does this key exists in cache?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-DATABASE-FRONTEND: this->databaseCacheEnabled=%d,cacheKey[%s]=%s', intval($this->databaseCacheEnabled), gettype($cacheKey), $cacheKey));
+ if (($this->databaseCacheEnabled === true) && ($this->getCacheInstance()->offsetExists($cacheKey))) {
+ // Purge the cache
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-DATABASE-FRONTEND: Invoking this->cacheInstance->purgeOffset(%s) ...', $cacheKey));
+ $this->getCacheInstance()->purgeOffset($cacheKey);
+ }
+
+ // Handle it over to the middleware
+ FrameworkBootstrap::getDatabaseInstance()->queryInsertDataSet($dataSetInstance);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-DATABASE-FRONTEND: EXIT!');
+ }
+
+ /**
+ * 'Updates' a data set instance with a database layer
+ *
+ * @param $dataSetInstance A storeable data set
+ * @param $onlyKeys Only use these keys for a cache key
+ * @return void
+ */
+ protected function queryUpdateDataSet (StoreableCriteria $dataSetInstance, array $onlyKeys = []) {
+ // Init cache key
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-DATABASE-FRONTEND: dataSetInstance=%s,onlyKeys()=%d - CALLED!', $dataSetInstance->__toString(), count($onlyKeys)));
+ $cacheKey = NULL;
+
+ // Is cache enabled?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-DATABASE-FRONTEND: this->databaseCacheEnabled=%d', intval($this->databaseCacheEnabled)));
+ if ($this->databaseCacheEnabled === true) {
+ // First get a key suitable for our cache and extend it with this class name
+ $cacheKey = $this->getCacheKeyByCriteria($dataSetInstance, $onlyKeys);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('BASE-DATABASE-FRONTEND: Using cache key ' . $cacheKey . ' for purging ...');
+ }
+
+ // Does this key exists in cache?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-DATABASE-FRONTEND: this->databaseCacheEnabled=%d,cacheKey=%s', intval($this->databaseCacheEnabled), $cacheKey));
+ if (($this->databaseCacheEnabled === true) && ($this->getCacheInstance()->offsetExists($cacheKey))) {
+ // Purge the cache
+ $this->getCacheInstance()->purgeOffset($cacheKey);
+ }
+
+ // Handle it over to the middleware
+ FrameworkBootstrap::getDatabaseInstance()->queryUpdateDataSet($dataSetInstance);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-DATABASE-FRONTEND: EXIT!');
+ }
+
+ /**
+ * Getter for index key
+ *
+ * @return $indexKey Index key
+ */
+ public final function getIndexKey () {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-DATABASE-FRONTEND: CALLED!');
+ return FrameworkBootstrap::getDatabaseInstance()->getIndexKey();
+ }
+
+ /**
+ * Getter for last exception
+ *
+ * @return $lastException Last exception or NULL if none occured
+ */
+ public final function getLastException () {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-DATABASE-FRONTEND: CALLED!');
+ return FrameworkBootstrap::getDatabaseInstance()->getLastException();
+ }
+
+ /**
+ * Do a "select" query on the current table with the given search criteria and
+ * store it in cache for later usage
+ *
+ * @param $criteriaInstance An instance of a Criteria class
+ * @param $onlyKeys Only use these keys for a cache key
+ * @return $resultInstance An instance of a database result class
+ */
+ public function doSelectByCriteria (Criteria $criteriaInstance, array $onlyKeys = []) {
+ // Default cache key if cache is not enabled
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-DATABASE-FRONTEND: criteriaInstance=%s,onlyKeys()=%d - CALLED!', $criteriaInstance->__toString(), count($onlyKeys)));
+ $cacheKey = NULL;
+ $result = [];
+
+ // Is the cache enabled?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-DATABASE-FRONTEND: this->databaseCacheEnabled=%d', intval($this->databaseCacheEnabled)));
+ if ($this->databaseCacheEnabled === true) {
+ // First get a key suitable for our cache and extend it with this class name
+ $cacheKey = $this->getCacheKeyByCriteria($criteriaInstance, $onlyKeys);
+ }
+
+ // Does this key exists in cache?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-DATABASE-FRONTEND: this->databaseCacheEnabled=%d,cacheKey[%s]=%s', intval($this->databaseCacheEnabled), gettype($cacheKey), $cacheKey));
+ if (($this->databaseCacheEnabled === true) && ($this->getCacheInstance()->offsetExists($cacheKey, BaseDatabaseResult::RESULT_NAME_ROWS, 1))) {
+ // Then use this result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-DATABASE-FRONTEND: Cache used for cacheKey=%s', $cacheKey));
+ $result = $this->getCacheInstance()->offsetGet($cacheKey);
+ } else {
+ // Now it's time to ask the database layer for this select statement
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-DATABASE-FRONTEND: Quering database, cacheKey=%s ...', $cacheKey));
+ $result = FrameworkBootstrap::getDatabaseInstance()->doSelectByTableCriteria($this->getTableName(), $criteriaInstance);
+
+ // Cache the result if not null
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-DATABASE-FRONTEND: result[]=%s', gettype($result)));
+ if (!is_null($result)) {
+ // Is cache enabled?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-DATABASE-FRONTEND: this->databaseCacheEnabled=%d', intval($this->databaseCacheEnabled)));
+ if ($this->databaseCacheEnabled === true) {
+ // A valid result has returned from the database layer
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-DATABASE-FRONTEND: Setting cacheKey=%s with result()=%d entries', $cacheKey, count($result)));
+ $this->getCacheInstance()->offsetSet($cacheKey, $result);
+ }
+ } else {
+ // This invalid result must be wrapped
+ $result = [
+ BaseDatabaseResult::RESULT_NAME_STATUS => 'invalid',
+ BaseDatabaseResult::RESULT_NAME_EXCEPTION => FrameworkBootstrap::getDatabaseInstance()->getLastException(),
+ ];
+ }
+ }
+
+ // Create an instance of a CachedDatabaseResult class with the given result
+ // @TODO Minor: Update above comment to e.g. BaseDatabaseResult
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-DATABASE-FRONTEND: result[%s]=%s,result[%s]?=%d,result[%s]?=%d', BaseDatabaseResult::RESULT_NAME_STATUS, $result[BaseDatabaseResult::RESULT_NAME_STATUS], BaseDatabaseResult::RESULT_NAME_ROWS, isset($result[BaseDatabaseResult::RESULT_NAME_ROWS]), BaseDatabaseResult::RESULT_NAME_EXCEPTION, isset($result[BaseDatabaseResult::RESULT_NAME_EXCEPTION])));
+ $resultInstance = ObjectFactory::createObjectByConfiguredName('database_result_class', array($result));
+
+ // And return the instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-DATABASE-FRONTEND: resultInstance=%s - EXIT!', $resultInstance->__toString()));
+ return $resultInstance;
+ }
+
+ /**
+ * Count the numbers of rows we shall receive
+ *
+ * @param $criteriaInstance An instance of a Criteria class
+ * @param $onlyKeys Only use these keys for a cache key
+ * @return $numRows Numbers of rows of database entries
+ */
+ public function doSelectCountByCriteria (Criteria $criteriaInstance, array $onlyKeys = []) {
+ // Total numbers is -1 so we can distinglish between failed and valid queries
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-DATABASE-FRONTEND: criteriaInstance=%s,onlyKeys()=%d - CALLED!', $criteriaInstance->__toString(), count($onlyKeys)));
+ $numRows = 0;
+
+ // Get the result from above method
+ $resultInstance = $this->doSelectByCriteria($criteriaInstance, $onlyKeys);
+
+ // Was that query fine?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-DATABASE-FRONTEND: resultInstance->ifStatusIsOkay()=%d', $resultInstance->ifStatusIsOkay()));
+ if ($resultInstance->ifStatusIsOkay()) {
+ // Then get the number of rows
+ $numRows = $resultInstance->getAffectedRows();
+ }
+
+ // Return the result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-DATABASE-FRONTEND: numRows=%d - EXIT!', $numRows));
+ return $numRows;
+ }
+
+ /**
+ * Generates a primary key for this database frontend
+ *
+ * @return $primaryKey Primary key used in wrapped table
+ */
+ public final function generatePrimaryKey () {
+ // Get the table name and a database instance and ask for it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-DATABASE-FRONTEND: CALLED!');
+ $primaryKey = FrameworkBootstrap::getDatabaseInstance()->getPrimaryKeyOfTable($this->getTableName());
+
+ // Return value
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-DATABASE-FRONTEND: primaryKey=%s - EXIT!', $primaryKey));
+ return $primaryKey;
+ }
+
+ /**
+ * Count rows of this table
+ *
+ * @return $count Count of total rows in this table
+ */
+ public final function countTotalRows () {
+ // Get the table name and a database instance and ask for it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-DATABASE-FRONTEND: CALLED!');
+ $count = FrameworkBootstrap::getDatabaseInstance()->countTotalRows($this->getTableName());
+
+ // Return value
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-DATABASE-FRONTEND: count=%d - EXIT!', $count));
+ return $count;
+ }
+
+ /**
+ * 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.
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ */
+ public function removeNonPublicDataFromArray (array $data) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-DATABASE-FRONTEND: data()=%d - CALLED!', count($data)));
+ if (count($data) == 0) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "data" is an empty array', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Remove non-public data (aka. sensitive)
+ $data = FrameworkBootstrap::getDatabaseInstance()->removeNonPublicDataFromArray($data);
+
+ // Return cleaned array
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-DATABASE-FRONTEND: data()=%d - EXIT!', count($data)));
+ return $data;
+ }
+
+}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Database\Frontend\News;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Database\Frontend\BaseDatabaseWrapper;
-use Org\Mxchange\CoreFramework\Registry\Registerable;
-
-/**
- * A database wrapper for news classes
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.shipsimu.org
- * @todo Add missing own interface for public methods
- *
- * 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 NewsDatabaseWrapper extends BaseDatabaseWrapper implements Registerable {
- // Constants for database table names
- const DB_TABLE_NEWS = 'news';
-
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of this database wrapper by a provided user class
- *
- * @return $wrapperInstance An instance of the created wrapper class
- */
- public static final function createNewsDatabaseWrapper () {
- // Get a new instance
- $wrapperInstance = new NewsDatabaseWrapper();
-
- // Set (primary!) table name
- $wrapperInstance->setTableName(self::DB_TABLE_NEWS);
-
- // Return the instance
- return $wrapperInstance;
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Database\Frontend;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Database\Frontend\BaseDatabaseWrapper;
-use Org\Mxchange\CoreFramework\Registry\Registerable;
-
-/**
- * A database wrapper for payments
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.shipsimu.org
- * @todo Add missing own interface for public methods
- *
- * 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 PaymentsDatabaseWrapper extends BaseDatabaseWrapper implements Registerable {
- // Constants for exceptions
- const EXCEPTION_CLIENT_USERNAME_NOT_FOUND = 0x180;
-
- // Constants for database table names
- const DB_TABLE_PAYMENTS = 'payments';
-
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of this database wrapper by a provided user class
- *
- * @return $wrapperInstance An instance of the created wrapper class
- */
- public static final function createPaymentsDatabaseWrapper () {
- // Get a new instance
- $wrapperInstance = new PaymentsDatabaseWrapper();
-
- // Set (primary!) table name
- $wrapperInstance->setTableName(self::DB_TABLE_PAYMENTS);
-
- // Return the instance
- return $wrapperInstance;
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Database\Frontend\User;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\Database\Frontend\BaseDatabaseWrapper;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Generic\NullPointerException;
-use Org\Mxchange\CoreFramework\Registration\User\UserRegister;
-use Org\Mxchange\CoreFramework\Registry\Registerable;
-use Org\Mxchange\CoreFramework\Result\Update\UpdateableResult;
-use Org\Mxchange\CoreFramework\Wrapper\Account\ManageableAccountWrapper;
-
-/**
- * A database wrapper for the User class
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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 UserDatabaseWrapper extends BaseDatabaseWrapper implements ManageableAccountWrapper, Registerable {
- // Constants for exceptions
- const EXCEPTION_CLIENT_USERNAME_NOT_FOUND = 0x180;
-
- // Constants for database columns
- const DB_COLUMN_USERID = 'userid';
- const DB_COLUMN_USERNAME = 'username';
- const DB_COLUMN_EMAIL = 'email';
- const DB_COLUMN_CONFIRM_HASH = 'confirm_hash';
- const DB_COLUMN_USER_STATUS = 'user_status';
-
- // Constants for database table names
- const DB_TABLE_USER = 'user';
-
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of this database wrapper by a provided user class
- *
- * @return $wrapperInstance An instance of the created wrapper class
- */
- public static final function createUserDatabaseWrapper () {
- // Get a new instance
- $wrapperInstance = new UserDatabaseWrapper();
-
- // Set (primary!) table name
- $wrapperInstance->setTableName(self::DB_TABLE_USER);
-
- // Return the instance
- return $wrapperInstance;
- }
-
- /**
- * Handles inserting the registration data from a registration instance into the database
- *
- * @param $registrationInstance An instance of a registration class
- * @return void
- */
- public function insertRegistrationObject (UserRegister $registrationInstance) {
- // Generate a data set for the request
- $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_USER));
-
- // Set the primary key
- $dataSetInstance->setUniqueKey(self::DB_COLUMN_USERNAME);
-
- // Add registration elements to the dataset
- $registrationInstance->addElementsToDataSet($dataSetInstance);
-
- // "Insert" this request instance completely into the database
- $this->queryInsertDataSet($dataSetInstance);
- }
-
- /**
- * Updates an user database entry with given result
- *
- * @param $resultInstance An instance of a Updateable database result
- * @return void
- * @throws NullPointerException If $updateInstance or $searchInstance is null
- */
- public function doUpdateByResult (UpdateableResult $resultInstance) {
- // Get the search instance from result
- $searchInstance = $resultInstance->getSearchInstance();
-
- // Is this null?
- if (is_null($searchInstance)) {
- // Get the update instance
- $updateInstance = $resultInstance->getUpdateInstance();
-
- // Is this null?
- if (is_null($updateInstance)) {
- // Throw an exception here
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } // END - if
-
- // Get search instance from update instance
- $searchInstance = $updateInstance->getSearchInstance();
-
- // Is it still null?
- if (is_null($searchInstance)) {
- // Throw an exception here
- throw new NullPointerException($updateInstance, self::EXCEPTION_IS_NULL_POINTER);
- } // END - if
- } // END - if
-
- // Generate a data set object
- $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_USER));
-
- // Add seach criteria
- $dataSetInstance->setSearchInstance($searchInstance);
-
- // Set the primary key
- $dataSetInstance->setUniqueKey(self::DB_COLUMN_USERNAME);
-
- // Add all update criteria to the database set
- $resultInstance->addElementsToDataSet($dataSetInstance);
-
- // "Update" this request with the database
- FrameworkBootstrap::getDatabaseInstance()->queryUpdateDataSet($dataSetInstance);
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Database\Frontend\Points;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\Database\Frontend\BaseDatabaseWrapper;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\Registerable;
-use Org\Mxchange\CoreFramework\Result\Update\UpdateableResult;
-
-/**
- * A database wrapper for user points classes
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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 UserPointsDatabaseWrapper extends BaseDatabaseWrapper implements BookablePointsWrapper, Registerable {
- /**
- * Constants for database table names
- */
- const DB_TABLE_USER_POINTS = 'user_points';
-
- /**
- * Name of the user->points column
- */
- const DB_COLUMN_POINTS_UID = 'points_uid';
-
- /**
- * Name of the points column
- */
- const DB_COLUMN_POINTS = 'points';
-
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of this database wrapper by a provided user class
- *
- * @return $wrapperInstance An instance of the created wrapper class
- */
- public static final function createUserPointsDatabaseWrapper () {
- // Get a new instance
- $wrapperInstance = new UserPointsDatabaseWrapper();
-
- // Set (primary!) table name
- $wrapperInstance->setTableName(self::DB_TABLE_USER_POINTS);
-
- // Return the instance
- return $wrapperInstance;
- }
-
- /**
- * Inserts the given points for the given user in the database
- *
- * @param $pointsInstance An instance of a user class
- * @return void
- */
- public function insertUserPoints (BookablePoints $pointsInstance) {
- // Generate a data set for the request
- $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_USER_POINTS));
-
- // Set the primary key
- $dataSetInstance->setUniqueKey(self::DB_COLUMN_POINTS_UID);
-
- // Add registration elements to the dataset
- $pointsInstance->addElementsToDataSet($dataSetInstance);
-
- // "Insert" this request instance completely into the database
- $this->queryInsertDataSet($dataSetInstance);
- }
-
- /**
- * Updates an user database entry with given result
- *
- * @param $resultInstance An instance of a Updateable database result
- * @return void
- */
- public function doUpdateByResult (UpdateableResult $resultInstance) {
- // Generate a data set object
- $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_USER_POINTS));
-
- // Add all update criteria to the database set
- $resultInstance->addElementsToDataSet($dataSetInstance);
-
- // Add seach criteria
- $dataSetInstance->setSearchInstance($resultInstance->getUpdateInstance()->getSearchInstance());
-
- // Set the primary key
- $dataSetInstance->setUniqueKey(self::DB_COLUMN_POINTS_UID);
-
- // "Update" this request with the database
- FrameworkBootstrap::getDatabaseInstance()->queryUpdateDataSet($dataSetInstance);
- }
-
-}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Database\Frontend\News;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Database\Frontend\BaseDatabaseFrontend;
+use Org\Mxchange\CoreFramework\Registry\Registerable;
+
+/**
+ * A database frontend for news classes
+ *
+ * @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
+ * @todo Add missing own interface for public methods
+ *
+ * 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 NewsDatabaseFrontend extends BaseDatabaseFrontend implements Registerable {
+ // Constants for database table names
+ const DB_TABLE_NEWS = 'news';
+
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Creates an instance of this database frontend by a provided user class
+ *
+ * @return $frontendInstance An instance of the created frontend class
+ */
+ public static final function createNewsDatabaseFrontend () {
+ // Get a new instance
+ $frontendInstance = new NewsDatabaseFrontend();
+
+ // Set (primary!) table name
+ $frontendInstance->setTableName(self::DB_TABLE_NEWS);
+
+ // Return the instance
+ return $frontendInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Database\Frontend;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Database\Frontend\BaseDatabaseFrontend;
+use Org\Mxchange\CoreFramework\Registry\Registerable;
+
+/**
+ * A database frontend for payments
+ *
+ * @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
+ * @todo Add missing own interface for public methods
+ *
+ * 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 PaymentsDatabaseFrontend extends BaseDatabaseFrontend implements Registerable {
+ // Constants for exceptions
+ const EXCEPTION_CLIENT_USERNAME_NOT_FOUND = 0x180;
+
+ // Constants for database table names
+ const DB_TABLE_PAYMENTS = 'payments';
+
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Creates an instance of this database frontend by a provided user class
+ *
+ * @return $frontendInstance An instance of the created frontend class
+ */
+ public static final function createPaymentsDatabaseFrontend () {
+ // Get a new instance
+ $frontendInstance = new PaymentsDatabaseFrontend();
+
+ // Set (primary!) table name
+ $frontendInstance->setTableName(self::DB_TABLE_PAYMENTS);
+
+ // Return the instance
+ return $frontendInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Database\Frontend\User;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Database\Frontend\BaseDatabaseFrontend;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Frontend\Account\ManageableAccountFrontend;
+use Org\Mxchange\CoreFramework\Generic\NullPointerException;
+use Org\Mxchange\CoreFramework\Registration\User\UserRegister;
+use Org\Mxchange\CoreFramework\Registry\Registerable;
+use Org\Mxchange\CoreFramework\Result\Update\UpdateableResult;
+
+/**
+ * A database frontend for the User class
+ *
+ * @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 UserDatabaseFrontend extends BaseDatabaseFrontend implements ManageableAccountFrontend, Registerable {
+ // Constants for exceptions
+ const EXCEPTION_CLIENT_USERNAME_NOT_FOUND = 0x180;
+
+ // Constants for database columns
+ const DB_COLUMN_USERID = 'userid';
+ const DB_COLUMN_USERNAME = 'username';
+ const DB_COLUMN_EMAIL = 'email';
+ const DB_COLUMN_CONFIRM_HASH = 'confirm_hash';
+ const DB_COLUMN_USER_STATUS = 'user_status';
+
+ // Constants for database table names
+ const DB_TABLE_USER = 'user';
+
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Creates an instance of this database frontend by a provided user class
+ *
+ * @return $frontendInstance An instance of the created frontend class
+ */
+ public static final function createUserDatabaseFrontend () {
+ // Get a new instance
+ $frontendInstance = new UserDatabaseFrontend();
+
+ // Set (primary!) table name
+ $frontendInstance->setTableName(self::DB_TABLE_USER);
+
+ // Return the instance
+ return $frontendInstance;
+ }
+
+ /**
+ * Handles inserting the registration data from a registration instance into the database
+ *
+ * @param $registrationInstance An instance of a registration class
+ * @return void
+ */
+ public function insertRegistrationObject (UserRegister $registrationInstance) {
+ // Generate a data set for the request
+ $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_USER));
+
+ // Set the primary key
+ $dataSetInstance->setUniqueKey(self::DB_COLUMN_USERNAME);
+
+ // Add registration elements to the dataset
+ $registrationInstance->addElementsToDataSet($dataSetInstance);
+
+ // "Insert" this request instance completely into the database
+ $this->queryInsertDataSet($dataSetInstance);
+ }
+
+ /**
+ * Updates an user database entry with given result
+ *
+ * @param $resultInstance An instance of a UpdateableResult class
+ * @return void
+ * @throws NullPointerException If $updateInstance or $searchInstance is null
+ */
+ public function doUpdateByResult (UpdateableResult $resultInstance) {
+ // Get the search instance from result
+ $searchInstance = $resultInstance->getSearchInstance();
+
+ // Is this null?
+ if (is_null($searchInstance)) {
+ // Get the update instance
+ $updateInstance = $resultInstance->getUpdateInstance();
+
+ // Is this null?
+ if (is_null($updateInstance)) {
+ // Throw an exception here
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
+ }
+
+ // Get search instance from update instance
+ $searchInstance = $updateInstance->getSearchInstance();
+
+ // Is it still null?
+ if (is_null($searchInstance)) {
+ // Throw an exception here
+ throw new NullPointerException($updateInstance, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
+ }
+ }
+
+ // Generate a data set object
+ $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_USER));
+
+ // Add seach criteria
+ $dataSetInstance->setSearchInstance($searchInstance);
+
+ // Set the primary key
+ $dataSetInstance->setUniqueKey(self::DB_COLUMN_USERNAME);
+
+ // Add all update criteria to the database set
+ $resultInstance->addElementsToDataSet($dataSetInstance);
+
+ // "Update" this request with the database
+ FrameworkBootstrap::getDatabaseInstance()->queryUpdateDataSet($dataSetInstance);
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Database\Frontend\Points;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Database\Frontend\BaseDatabaseFrontend;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Registry\Registerable;
+use Org\Mxchange\CoreFramework\Result\Update\UpdateableResult;
+
+/**
+ * A database frontend for user points classes
+ *
+ * @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 UserPointsDatabaseFrontend extends BaseDatabaseFrontend implements BookablePointsFrontend, Registerable {
+ /**
+ * Constants for database table names
+ */
+ const DB_TABLE_USER_POINTS = 'user_points';
+
+ /**
+ * Name of the user->points column
+ */
+ const DB_COLUMN_POINTS_UID = 'points_uid';
+
+ /**
+ * Name of the points column
+ */
+ const DB_COLUMN_POINTS = 'points';
+
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Creates an instance of this database frontend by a provided user class
+ *
+ * @return $frontendInstance An instance of the created frontend class
+ */
+ public static final function createUserPointsDatabaseFrontend () {
+ // Get a new instance
+ $frontendInstance = new UserPointsDatabaseFrontend();
+
+ // Set (primary!) table name
+ $frontendInstance->setTableName(self::DB_TABLE_USER_POINTS);
+
+ // Return the instance
+ return $frontendInstance;
+ }
+
+ /**
+ * Inserts the given points for the given user in the database
+ *
+ * @param $pointsInstance An instance of a user class
+ * @return void
+ */
+ public function insertUserPoints (BookablePoints $pointsInstance) {
+ // Generate a data set for the request
+ $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_USER_POINTS));
+
+ // Set the primary key
+ $dataSetInstance->setUniqueKey(self::DB_COLUMN_POINTS_UID);
+
+ // Add registration elements to the dataset
+ $pointsInstance->addElementsToDataSet($dataSetInstance);
+
+ // "Insert" this request instance completely into the database
+ $this->queryInsertDataSet($dataSetInstance);
+ }
+
+ /**
+ * Updates an user database entry with given result
+ *
+ * @param $resultInstance An instance of a UpdateableResult class
+ * @return void
+ */
+ public function doUpdateByResult (UpdateableResult $resultInstance) {
+ // Generate a data set object
+ $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_USER_POINTS));
+
+ // Add all update criteria to the database set
+ $resultInstance->addElementsToDataSet($dataSetInstance);
+
+ // Add seach criteria
+ $dataSetInstance->setSearchInstance($resultInstance->getUpdateInstance()->getSearchInstance());
+
+ // Set the primary key
+ $dataSetInstance->setUniqueKey(self::DB_COLUMN_POINTS_UID);
+
+ // "Update" this request with the database
+ FrameworkBootstrap::getDatabaseInstance()->queryUpdateDataSet($dataSetInstance);
+ }
+
+}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct($class = __CLASS__) {
+ protected function __construct (string $className) {
// Call parent constructor
- parent::__construct($class);
+ parent::__construct($className);
}
}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct($class = __CLASS__) {
+ protected function __construct (string $className) {
// Call parent constructor
- parent::__construct($class);
+ parent::__construct($className);
}
}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
use Org\Mxchange\CoreFramework\Criteria\Local\LocalUpdateCriteria;
use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
-use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseWrapper;
+use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseFrontend;
use Org\Mxchange\CoreFramework\Database\Backend\BaseDatabaseBackend;
+use Org\Mxchange\CoreFramework\Result\Database\BaseDatabaseResult;
use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
use Org\Mxchange\CoreFramework\Result\Update\UpdateableResult;
// Import SPL stuff
use \InvalidArgumentException;
+use \OutOfBoundsException;
use \SeekableIterator;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: CONSTRUCTED!');
parent::__construct(__CLASS__);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: EXIT!');
}
/**
*/
public static final function createCachedDatabaseResult (array $resultArray) {
// Misses an element?
+ //* DEBUG-DIE: */ die(sprintf('[%s:%d]: resultArray=%s', __METHOD__, __LINE__, print_r($resultArray, true)));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: resultArray()=%d - CALLED!', count($resultArray)));
if (count($resultArray) == 0) {
// Cannot be empty
- throw new InvalidArgumentException('Array "resultArray" cannot be empty.');
- } elseif (!array_key_exists(BaseDatabaseBackend::RESULT_INDEX_ROWS, $resultArray)) {
+ throw new InvalidArgumentException('Array "resultArray" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!array_key_exists(BaseDatabaseResult::RESULT_NAME_ROWS, $resultArray)) {
+ // Yes, then abort here
+ throw new InvalidArgumentException(sprintf('resultArray(%d)=%s has no element "%s".', count($resultArray), print_r($resultArray, TRUE), BaseDatabaseResult::RESULT_NAME_ROWS));
+ } elseif (!array_key_exists(BaseDatabaseResult::RESULT_NAME_STATUS, $resultArray)) {
// Yes, then abort here
- throw new InvalidArgumentException(sprintf('resultArray(%d)=%s has no element "%s".', count($resultArray), print_r($resultArray, TRUE), BaseDatabaseBackend::RESULT_INDEX_ROWS));
+ throw new InvalidArgumentException(sprintf('resultArray(%d)=%s has no element "%s".', count($resultArray), print_r($resultArray, TRUE), BaseDatabaseResult::RESULT_NAME_STATUS));
}
// Get a new instance
$resultInstance = new CachedDatabaseResult();
// Set the result array
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-DATABASE-RESULT: Setting resultArray()=%d ...', count($resultArray)));
$resultInstance->setResultArray($resultArray);
+ // Reset current position
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: Invoking resultInstance->resetCurrentPosition() ...');
+ $resultInstance->resetCurrentPosition();
+
// Set affected rows
- $resultInstance->setAffectedRows(count($resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS]));
+ $resultInstance->setAffectedRows(count($resultArray[BaseDatabaseResult::RESULT_NAME_ROWS]));
// Return the instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: resultInstance=%s - EXIT!', $resultInstance->__toString()));
return $resultInstance;
}
*/
private function updateCurrentEntryByCriteria (LocalUpdateCriteria $updateInstance) {
// Get the current entry key
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: updateInstance=%s - CALLED!', $updateInstance->__toString()));
$entryKey = $this->key();
// Now get the update criteria array and update all entries
foreach ($updateInstance->getUpdateCriteria() as $criteriaKey => $criteriaValue) {
// Update data
- $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$entryKey][$criteriaKey] = $criteriaValue;
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-DATABASE-RESULT: criteriaKey=%s,criteriaValue[%s]=%s', $criteriaKey, gettype($criteriaValue), $criteriaValue));
+ $this->resultArray[BaseDatabaseResult::RESULT_NAME_ROWS][$entryKey][$criteriaKey] = $criteriaValue;
// Mark it as out-dated
$this->outDated[$criteriaKey] = 1;
- } // END - foreach
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: EXIT!');
}
/**
*/
public function next () {
// Default is not valid
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: CALLED!');
$nextValid = false;
+ // Increase position
+ $this->currentPos++;
+
// Is the result valid?
if ($this->valid()) {
- // Next entry found, so count one up and cache it
- $this->currentPos++;
- $this->currentRow = $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos];
+ // Next entry found, so cache it
+ $this->currentRow = $this->resultArray[BaseDatabaseResult::RESULT_NAME_ROWS][$this->currentPos];
$nextValid = true;
- } // END - if
+ }
// Return the result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: nextValid=%d - EXIT!', intval($nextValid)));
return $nextValid;
}
/**
* Seeks for to a specified position
*
- * @param $index Index to seek for
+ * @param $seekPosition Position to seek to
* @return void
+ * @throws OutOfBoundsException If the position is not seekable
*/
- public function seek ($index) {
+ public function seek (int $seekPosition) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: seekPosition=%d - CALLED!', $seekPosition));
+ if ($seekPosition < 0) {
+ // Throw exception
+ throw new OutOfBoundsException(sprintf('seekPositon=%d is not seekable', $seekPosition));
+ }
+
// Rewind to beginning
$this->rewind();
// Search for the entry
- while (($this->currentPos < $index) && ($this->valid())) {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-DATABASE-RESULT: this->currentPos=%d,seekPosition=%d', $this->currentPos, $seekPosition));
+ while (($this->currentPos < $seekPosition) && ($this->valid())) {
// Continue on
$this->next();
- } // END - while
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: EXIT!');
}
/**
*/
public function current () {
// Default is not found
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: CALLED!');
$current = NULL;
// Does the current enty exist?
- if (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos])) {
+ if (isset($this->resultArray[BaseDatabaseResult::RESULT_NAME_ROWS][$this->currentPos])) {
// Then get it
- $current = $this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][$this->currentPos];
- } // END - if
+ $current = $this->resultArray[BaseDatabaseResult::RESULT_NAME_ROWS][$this->currentPos];
+ }
// Return the result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: current[]=%s - EXIT!', gettype($current)));
return $current;
}
* @return $isValid Whether the next/rewind entry is valid
*/
public function valid () {
- // By default nothing is valid
- $isValid = false;
-
- // Debug message
- //*NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] this->currentPos=' . $this->currentPos);
-
// Check if all is fine ...
- if (($this->ifStatusIsOkay()) && (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][($this->currentPos + 1)])) && (isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS][0]))) {
- // All fine!
- $isValid = true;
- } // END - if
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: this->currentPos=%d - CALLED!', $this->currentPos));
+ $isValid = ($this->ifStatusIsOkay() && isset($this->resultArray[BaseDatabaseResult::RESULT_NAME_ROWS][$this->currentPos]) && isset($this->resultArray[BaseDatabaseResult::RESULT_NAME_ROWS][0]));
// Return the result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: isValid=%d - EXIT!', intval($isValid)));
return $isValid;
}
* @return $isValid Whether the next/rewind entry is valid
*/
public function count () {
+ // Count rows
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: CALLED!');
+ $count = count($this->resultArray[BaseDatabaseResult::RESULT_NAME_ROWS]);
+
// Return it
- return count($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_ROWS]);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: count=%d - EXIT!', $count));
+ return $count;
}
/**
* @return $ifStatusOkay Whether the status of the query was okay
*/
public function ifStatusIsOkay () {
- $ifStatusOkay = ((isset($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_STATUS])) && ($this->resultArray[BaseDatabaseBackend::RESULT_INDEX_STATUS] === BaseDatabaseBackend::RESULT_OKAY));
- //*NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] ifStatusOkay=' . intval($ifStatusOkay));
+ // Check all conditions
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: this->currentPos=%d - CALLED!', $this->currentPos));
+ $ifStatusOkay = (isset($this->resultArray[BaseDatabaseResult::RESULT_NAME_STATUS]) && $this->resultArray[BaseDatabaseResult::RESULT_NAME_STATUS] === BaseDatabaseBackend::RESULT_OKAY);
+
+ // Return status
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: ifStatusOkay=%s - EXIT!', intval($ifStatusOkay)));
return $ifStatusOkay;
}
* @return $currentPos Key from iterator
*/
public function key () {
+ // Return current array position
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: this->currentPos=%d - CALLED!', $this->currentPos));
return $this->currentPos;
}
* @return void
*/
public function rewind () {
- $this->currentPos = -1;
+ // Reset both current array position and current row
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: this->currentPos=%d - CALLED!', $this->currentPos));
+ $this->resetCurrentPosition();
$this->currentRow = [];
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: EXIT!');
+ }
+
+ /**
+ * Resets current array position to 0 if at least one record is there or -1
+ * if no record is there.
+ *
+ * @return void
+ */
+ private function resetCurrentPosition () {
+ // Reset position
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: CALLED!');
+ $this->currentPos = ($this->count() > 0 ? 0 : -1);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: this->currentPos=%d - EXIT!', $this->currentPos));
}
/**
* @todo 0% done
*/
public function searchEntry (LocalSearchCriteria $criteriaInstance) {
- $this->debugBackTrace('[' . '[' . __METHOD__ . ':' . __LINE__ . ']: Unfinished!');
+ // Unfinished code
+ $this->debugBackTrace(sprintf('[%s:%d]: criteriaInstance=%s', __METHOD__, __LINE__, print_r($criteriaInstance, TRUE)));
}
/**
* Adds an update request to the database result for writing it to the
* database layer
*
- * @param $criteriaInstance An instance of a updateable criteria
+ * @param $updateInstance An instance of a updateable criteria
* @return void
* @throws ResultUpdateException If no result was updated
*/
- public function add2UpdateQueue (LocalUpdateCriteria $criteriaInstance) {
+ public function add2UpdateQueue (LocalUpdateCriteria $updateInstance) {
// Rewind the pointer
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: updateInstance=%s - CALLED!', $updateInstance->__toString()));
$this->rewind();
// Get search criteria
- $searchInstance = $criteriaInstance->getSearchInstance();
+ $searchInstance = $updateInstance->getSearchInstance();
+
+ // Get affected rows
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-DATABASE-RESULT: searchInstance=%s', $searchInstance->__toString()));
+ $foundEntries = $this->getAffectedRows();
// And start looking for the result
- $foundEntries = 0;
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-DATABASE-RESULT: foundEntries=%d,searchInstance->limit=%d', $foundEntries, $searchInstance->getLimit()));
while (($this->valid()) && ($foundEntries < $searchInstance->getLimit())) {
// Get next entry
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: Invoking this->next() ...');
$this->next();
+
+ // Get current entry
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: Invoking this->current() ...');
$currentEntry = $this->current();
// Is this entry found?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: currentEntry[]=%s - EXIT!', gettype($currentEntry)));
if ($searchInstance->ifEntryMatches($currentEntry)) {
// Update this entry
- $this->updateCurrentEntryByCriteria($criteriaInstance);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: Invoking this->updateCurrentEntryByCriteria(%s) ...', $updateInstance->__toString()));
+ $this->updateCurrentEntryByCriteria($updateInstance);
// Count one up
$foundEntries++;
- } // END - if
- } // END - while
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-DATABASE-RESULT: foundEntries=%d', $foundEntries));
+ }
+ }
// If no entry is found/updated throw an exception
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-DATABASE-RESULT: foundEntries=%d', $foundEntries));
if ($foundEntries == 0) {
// Throw an exception here
throw new ResultUpdateException($this, self::EXCEPTION_RESULT_UPDATE_FAILED);
- } // END - if
+ }
// Set affected rows
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: Invoking this->setAffectedRows(%d) ...', $foundEntries));
$this->setAffectedRows($foundEntries);
// Set update instance
- $this->setUpdateInstance($criteriaInstance);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: Invoking this->setUpdateInstance(%s) ...', $updateInstance->__toString()));
+ $this->setUpdateInstance($updateInstance);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: EXIT!');
}
/**
* @param $rows Number of affected rows
* @return void
*/
- public final function setAffectedRows ($rows) {
+ public final function setAffectedRows (int $rows) {
$this->affectedRows = $rows;
}
* @return $needsUpdate Whether we have out-dated entries
*/
public function ifDataNeedsFlush () {
+ // Check if records are out-dated
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: CALLED!');
$needsUpdate = (count($this->outDated) > 0);
+
+ // Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: needsUpdate=%d - EXIT!', intval($needsUpdate)));
return $needsUpdate;
}
*/
public function addElementsToDataSet (StoreableCriteria $criteriaInstance) {
// Walk only through out-dated columns
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: criteriaInstance=%s - CALLED!', $criteriaInstance->__toString()));
foreach ($this->outDated as $key => $dummy) {
// Does this key exist?
- //* DEBUG: */ echo "outDated: {$key}<br />\n";
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-DATABASE-RESULT: key=%s,dummy[]=%s', $key, gettype($dummy)));
if ($this->find($key)) {
// Then update it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: Invoking criteriaInstance->addCriteria(%s,foundValue[]=%s) ...', $key, gettype($this->getFoundValue())));
$criteriaInstance->addCriteria($key, $this->getFoundValue());
- } // END - if
- } // END - foreach
+ }
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: EXIT!');
}
/**
*
* @param $key The key we shall find
* @return $found Whether the key was found or not
+ * @throws InvalidArgumentException If a parameter is invalid
*/
- public function find ($key) {
+ public function find (string $key) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: key=%s - CALLED!', $key));
+ if (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// By default nothing is found
$found = false;
// Rewind the pointer
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: Invoking this->rewind() ...');
$this->rewind();
// Walk through all entries
while ($this->valid()) {
// Advance to next entry
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: Invoking this->next() ...');
$this->next();
// Get the whole array
$currentEntry = $this->current();
// Is the element there?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: currentEntry[]=%s - EXIT!', gettype($currentEntry)));
if (isset($currentEntry[$key])) {
// Okay, found!
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-DATABASE-RESULT: key=%s is found in currentEntry', $key));
$found = true;
// So "cache" it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-DATABASE-RESULT: Setting this->foundValue to currentEntry[%s][]=%s is found in currentEntry', $key, gettype($currentEntry[$key])));
$this->foundValue = $currentEntry[$key];
// And stop searching
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('CACHED-DATABASE-RESULT: BREAK!');
break;
- } // END - if
- } // END - while
+ }
+ }
// Return the result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: found=%d - EXIT!', intval($found)));
return $found;
}
* Solver for result index value with call-back method
*
* @param $databaseColumn Database column where the index might be found
- * @param $wrapperInstance The wrapper instance to ask for array element
- * @para $callBack Call-back object for setting the index;
+ * @param $frontendInstance The frontend instance to ask for array element
+ * @para $callback Call-back object for setting the index;
* 0=object instance,1=method name
* @return void
+ * @throws InvalidArgumentException If a parameter is invalid
* @todo Find a caching way without modifying the result array
*/
- public function solveResultIndex ($databaseColumn, DatabaseWrapper $wrapperInstance, array $callBack) {
+ public function solveResultIndex (string $databaseColumn, DatabaseFrontend $frontendInstance, array $callback) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: databaseColumn=%s,frontendInstance=%s,callback()=%d - CALLED!', $databaseColumn, $frontendInstance->__toString(), count($callback)));
+ if (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (count($callback) != 2) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('callback()=%d must be exactly 2', count($callback)), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!is_callable($callback)) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('%s:%s() is not callable', $callback[0], $callback[1]), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// By default nothing is found
$indexValue = 0;
// Is the element in result itself found?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: Invoking this->find(%s),frontendInstance->indexKey=%s ...', $databaseColumn, $frontendInstance->getIndexKey()));
if ($this->find($databaseColumn)) {
// Use this value
$indexValue = $this->getFoundValue();
- } elseif ($this->find($wrapperInstance->getIndexKey())) {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-DATABASE-RESULT: indexValue[]=%s from this->find(%s) - databaseColumn', gettype($indexValue), $databaseColumn));
+ } elseif ($this->find($frontendInstance->getIndexKey())) {
// Use this value
$indexValue = $this->getFoundValue();
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CACHED-DATABASE-RESULT: indexValue[]=%s from this->find(%s) - frontendInstance->indexKey', gettype($indexValue), $frontendInstance->getIndexKey()));
}
// Set the index
- call_user_func_array($callBack, array($indexValue));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CACHED-DATABASE-RESULT: Invoking %s:%s(indexValue[]=%s) ...', $callback[0], $callback[1], gettype($indexValue)));
+ call_user_func_array($callback, [$indexValue]);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CACHED-DATABASE-RESULT: EXIT!');
}
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Template\Xml;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Generic\BaseDecorator;
-use Org\Mxchange\CoreFramework\Response\Responseable;
-use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
-
-/**
- * A decorator for XML template engines which rewrites the XML for compacting
- * it.
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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 XmlRewriterTemplateDecorator extends BaseDecorator implements CompileableTemplate {
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of the class TemplateEngine and prepares it for usage
- *
- * @param $innerTemplateInstance A CompileableTemplate instance
- * @return $templateInstance An instance of TemplateEngine
- */
- public static final function createXmlRewriterTemplateDecorator (CompileableTemplate $innerTemplateInstance) {
- // Get a new instance
- $templateInstance = new XmlRewriterTemplateDecorator();
-
- // Set the inner template engine
- $templateInstance->setTemplateInstance($innerTemplateInstance);
-
- // Return the prepared instance
- return $templateInstance;
- }
-
- /**
- * Settter for variable group
- *
- * @param $groupName Name of variable group
- * @param $add Whether add this group
- * @return void
- */
- public function setVariableGroup ($groupName, $add = true) {
- // Call the inner class' method
- $this->getTemplateInstance()->setVariableGroup($groupName, $add);
- }
-
- /**
- * Adds a variable to current group
- *
- * @param $var Variable to set
- * @param $value Value to store in variable
- * @return void
- */
- public function addGroupVariable ($var, $value) {
- // Call the inner class' method
- $this->getTemplateInstance()->addGroupVariable($var, $value);
- }
-
- /**
- * Getter for base path
- *
- * @return $templateBasePath The relative base path for all templates
- */
- public final function getTemplateBasePath () {
- // Call the inner class' method
- return $this->getTemplateInstance()->getTemplateBasePath();
- }
-
- /**
- * Getter for generic base path
- *
- * @return $templateBasePath The relative base path for all templates
- */
- public final function getGenericBasePath () {
- // Call the inner class' method
- return $this->getTemplateInstance()->getGenericBasePath();
- }
-
- /**
- * Getter for template extension
- *
- * @return $templateExtension The file extension for all uncompiled templates
- */
- public final function getRawTemplateExtension () {
- // Call the inner class' method
- return $this->getTemplateInstance()->getRawTemplateExtension();
- }
-
- /**
- * Getter for given variable group
- *
- * @param $variableGroup Variable group to check
- * @return $varStack Found variable group
- */
- public function getVarStack ($variableGroup) {
- // Call the inner class' method
- return $this->getTemplateInstance()->getVarStack($variableGroup);
- }
-
- /**
- * Getter for code-template extension
- *
- * @return $codeExtension The file extension for all code templates
- */
- public final function getCodeTemplateExtension () {
- // Call the inner class' method
- return $this->getTemplateInstance()->getCodeTemplateExtension();
- }
-
- /**
- * Getter for template type
- *
- * @return $templateType The current template's type
- */
- public final function getTemplateType () {
- // Call the inner class' method
- return $this->getTemplateInstance()->getTemplateType();
- }
-
- /**
- * Assign (add) a given variable with a value
- *
- * @param $var The variable we are looking for
- * @param $value The value we want to store in the variable
- * @return void
- */
- public function assignVariable ($var, $value) {
- // Call the inner class' method
- $this->getTemplateInstance()->assignVariable($var, $value);
- }
-
- /**
- * Removes a given variable
- *
- * @param $variableName The variable we are looking for
- * @param $variableGroup Name of variable group (default: 'general')
- * @return void
- */
- public function removeVariable ($variableName, $variableGroup = 'general') {
- // Call the inner class' method
- $this->getTemplateInstance()->removeVariable($variableName, $variableGroup);
- }
-
- /**
- * Load a specified HTML template into the engine
- *
- * @param $template The web template we shall load which is located in
- * 'html' by default
- * @return void
- */
- public function loadHtmlTemplate ($template) {
- // Call the inner class' method
- $this->getTemplateInstance()->loadHtmlTemplate($template);
- }
-
- /**
- * Assign a given congfiguration variable with a value
- *
- * @param $variableName The configuration variable we want to assign
- * @return void
- */
- public function assignConfigVariable ($variableName) {
- // Call the inner class' method
- $this->getTemplateInstance()->assignConfigVariable($variableName);
- }
-
- /**
- * Load a specified code template into the engine
- *
- * @param $template The code template we shall load which is
- * located in 'code' by default
- * @return void
- */
- public function loadCodeTemplate ($template) {
- // Call the inner class' method
- $this->getTemplateInstance()->loadCodeTemplate($template);
- }
-
- /**
- * Load a specified email template into the engine for later compilation
- * with other code/web/email templates.
- *
- * @param $template The email template we shall load which is
- * located in "html" by default
- * @return void
- */
- public function loadEmailTemplate ($template) {
- // Call the inner class' method
- $this->getTemplateInstance()->loadEmailTemplate($template);
- }
-
- /**
- * Compiles configuration place-holders in all variables. This 'walks'
- * through the variable stack 'general'. It interprets all values from that
- * variables as configuration entries after compiling them.
- *
- * @return void
- */
- public function compileConfigInVariables () {
- // Call the inner class' method
- $this->getTemplateInstance()->compileConfigInVariables();
- }
-
- /**
- * Compile all variables by inserting their respective values
- *
- * @return void
- */
- public function compileVariables () {
- // Call the inner class' method
- $this->getTemplateInstance()->compileVariables();
- }
-
- /**
- * Compile all required templates into the current loaded one
- *
- * @return void
- */
- public function compileTemplate () {
- // Call the inner class' method
- $this->getTemplateInstance()->compileTemplate();
- }
-
- /**
- * Assigns the last loaded raw template content with a given variable
- *
- * @param $templateName Name of the template we want to assign
- * @param $variableName Name of the variable we want to assign
- * @return void
- */
- public function assignTemplateWithVariable ($templateName, $variableName) {
- // Call the inner class' method
- $this->getTemplateInstance()->assignTemplateWithVariable($templateName, $variableName);
- }
-
- /**
- * Transfers the content of this template engine to a given response instance
- *
- * @param $responseInstance An instance of a Responseable class
- * @return void
- */
- public function transferToResponse (Responseable $responseInstance) {
- // Call the inner class' method
- $this->getTemplateInstance()->transportToResponse($responseInstance);
- }
-
- /**
- * Assigns all the application data with template variables
- *
- * @return void
- */
- public function assignApplicationData () {
- // Call the inner class' method
- $this->getTemplateInstance()->assignApplicationData();
- }
-
- /**
- * "Compiles" a variable by replacing {?var?} with it's content
- *
- * @param $rawCode Raw code to compile
- * @param $setMatchAsCode Sets $match if readVariable() returns empty result
- * @return $rawCode Compile code with inserted variable value
- */
- public function compileRawCode ($rawCode, $setMatchAsCode = false) {
- return $this->getTemplateInstance()->compileRawCode($rawCode, $setMatchAsCode);
- }
-
- /**
- * Getter for variable group array
- *
- * @return $variableGroups All variable groups
- */
- public final function getVariableGroups () {
- // Call the inner class' method
- return $this->getTemplateInstance()->getVariableGroups();
- }
-
- /**
- * Getter for raw template data
- *
- * @return $rawTemplateData The raw data from the template
- */
- public function getRawTemplateData () {
- // Call the inner class' method
- return $this->getTemplateInstance()->getRawTemplateData();
- }
-
- /**
- * Renames a variable in code and in stack
- *
- * @param $oldName Old name of variable
- * @param $newName New name of variable
- * @return void
- */
- public function renameVariable ($oldName, $newName) {
- // Call the inner class' method
- $this->getTemplateInstance()->renameVariable($oldName, $newName);
- }
-
- /**
- * Renders the given XML content
- *
- * @param $content Valid XML content or if not set the current loaded raw content
- * @return void
- * @throws XmlParserException If an XML error was found
- */
- public function renderXmlContent ($content = NULL) {
- // Call the inner class' method
- $this->getTemplateInstance()->renderXmlContent($content);
- }
-
- /**
- * Enables or disables language support
- *
- * @param $languageSupport New language support setting
- * @return void
- */
- public function enableLanguageSupport ($languageSupport = true) {
- // Call the inner class' method
- $this->getTemplateInstance()->enableLanguageSupport($languageSupport);
- }
-
- /**
- * Checks whether language support is enabled
- *
- * @return $languageSupport Whether language support is enabled or disabled
- */
- public function isLanguageSupportEnabled () {
- // Call the inner class' method
- return $this->getTemplateInstance()->isLanguageSupportEnabled();
- }
-
- /**
- * Enables or disables XML compacting
- *
- * @param $xmlCompacting New XML compacting setting
- * @return void
- */
- public function enableXmlCompacting ($xmlCompacting = true) {
- // Call the inner class' method
- $this->getTemplateInstance()->enableXmlCompacting($xmlCompacting);
- }
-
- /**
- * Checks whether XML compacting is enabled
- *
- * @return $xmlCompacting Whether XML compacting is enabled or disabled
- */
- public function isXmlCompactingEnabled () {
- // Call the inner class' method
- return $this->getTemplateInstance()->isXmlCompactingEnabled();
- }
-
- /**
- * Handles the start element of an XML resource
- *
- * @param $resource XML parser resource (currently ignored)
- * @param $element The element we shall handle
- * @param $attributes All attributes
- * @return void
- * @throws InvalidXmlNodeException If an unknown/invalid XML node name was found
- */
- public function startElement ($resource, $element, array $attributes) {
- // Call the inner class' method
- $this->getTemplateInstance()->startElement($resource, $element, $attributes);
- }
-
- /**
- * Ends the main or sub node by sending out the gathered data
- *
- * @param $resource An XML resource pointer (currently ignored)
- * @param $nodeName Name of the node we want to finish
- * @return void
- * @throws XmlNodeMismatchException If current main node mismatches the closing one
- */
- public function finishElement ($resource, $nodeName) {
- // Call the inner class' method
- $this->getTemplateInstance()->finishElement($resource, $nodeName);
- }
-
- /**
- * Currently not used
- *
- * @param $resource XML parser resource (currently ignored)
- * @param $characters Characters to handle
- * @return void
- * @todo Find something useful with this!
- */
- public function characterHandler ($resource, $characters) {
- // Call the inner class' method but trim the characters before
- $this->getTemplateInstance()->characterHandler($resource, trim($characters));
- }
-
- /**
- * Removes all comments, tabs and new-line charcters to compact the content
- *
- * @param $uncompactedContent The uncompacted content
- * @return $compactedContent The compacted content
- */
- public function compactContent ($uncompactedContent) {
- // Compact it ...
- $compactedContent = $this->getTemplateInstance()->compactContent($uncompactedContent);
-
- // ... and return it
- return $compactedContent;
- }
-
- /**
- * Assigns a lot variables into the stack of currently loaded template.
- * This method should only be used in very rare circumstances, e.g. when
- * you have to copy a whole set of variables into the template engine.
- * Before you use this method, please make sure you have considered all
- * other possiblities.
- *
- * @param $variables An array with variables to be assigned
- * @return void
- */
- public function assignMultipleVariables (array $variables) {
- // Call the inner class' method but trim the characters before
- $this->getTemplateInstance()->assignMultipleVariables($variables);
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Parser\Xml;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Generic\BaseDecorator;
-use Org\Mxchange\CoreFramework\Parser\Parseable;
-
-/**
- * A XML compacting decorator class for XML parsers
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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 XmlCompactorDecorator extends BaseDecorator implements Parseable {
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of the class Parser and prepares it for usage
- *
- * @param $innerParserInstance A Parseable instance
- * @return $parserInstance An instance of this parser
- */
- public static final function createXmlCompactorDecorator (Parseable $innerParserInstance) {
- // Get a new instance
- $parserInstance = new XmlCompactorDecorator();
-
- // Get a new decorator instance for the template engine
- $templateInstance = ObjectFactory::createObjectByConfiguredName('deco_xml_rewriter_template_class', array($innerParserInstance->getTemplateInstance()));
-
- // Re-set the parser's template instance to the decorator instance
- $innerParserInstance->setTemplateInstance($templateInstance);
-
- // Set the inner parser instance
- $parserInstance->setParserInstance($innerParserInstance);
-
- // Return the prepared instance
- return $parserInstance;
- }
-
- /**
- * Parses the given XML content
- *
- * @param $content Valid XML content
- * @return void
- * @throws XmlCompactorDecoratorException If an XML error was found
- */
- public function parseXmlContent ($content) {
- // Remove all comments for better compacting
- $content = $this->getParserInstance()->getTemplateInstance()->compactContent($content);
-
- // Parse the content
- $this->getParserInstance()->parseXmlContent($content);
- }
-
-}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Parser\Xml;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Generic\BaseDecorator;
+use Org\Mxchange\CoreFramework\Parser\Parseable;
+
+/**
+ * A XML compacting decorator class for XML parsers
+ *
+ * @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 XmlCompactorDecorator extends BaseDecorator implements Parseable {
+ /**
+ * Instance of the parser class
+ */
+ private $parserInstance = NULL;
+
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Creates an instance of the class Parser and prepares it for usage
+ *
+ * @param $innerParserInstance A Parseable instance
+ * @return $parserInstance An instance of this parser
+ */
+ public static final function createXmlCompactorDecorator (Parseable $innerParserInstance) {
+ // Get a new instance
+ $parserInstance = new XmlCompactorDecorator();
+
+ // Get a new decorator instance for the template engine
+ $templateInstance = ObjectFactory::createObjectByConfiguredName('deco_xml_rewriter_template_class', array($innerParserInstance->getTemplateInstance()));
+
+ // Re-set the parser's template instance to the decorator instance
+ $innerParserInstance->setTemplateInstance($templateInstance);
+
+ // Set the inner parser instance
+ $parserInstance->setParserInstance($innerParserInstance);
+
+ // Return the prepared instance
+ return $parserInstance;
+ }
+
+ /**
+ * Setter for Parseable instance
+ *
+ * @param $parserInstance An instance of an Parseable
+ * @return void
+ */
+ protected final function setParserInstance (Parseable $parserInstance) {
+ $this->parserInstance = $parserInstance;
+ }
+
+ /**
+ * Getter for Parseable instance
+ *
+ * @return $parserInstance An instance of an Parseable
+ */
+ private final function getParserInstance () {
+ return $this->parserInstance;
+ }
+
+ /**
+ * Parses the given XML content
+ *
+ * @param $content Valid XML content
+ * @return void
+ * @throws XmlCompactorDecoratorException If an XML error was found
+ */
+ public function parseXmlContent (string $content) {
+ // Remove all comments for better compacting
+ $content = $this->getParserInstance()->getTemplateInstance()->compactContent($content);
+
+ // Parse the content
+ $this->getParserInstance()->parseXmlContent($content);
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Template\Xml;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Generic\BaseDecorator;
+use Org\Mxchange\CoreFramework\Response\Responseable;
+use Org\Mxchange\CoreFramework\Template\Xml\CompileableXmlTemplate;
+use Org\Mxchange\CoreFramework\Traits\Template\CompileableTemplateTrait;
+
+/**
+ * A decorator for XML template engines which rewrites the XML for compacting
+ * it.
+ *
+ * @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 XmlRewriterTemplateDecorator extends BaseDecorator implements CompileableXmlTemplate {
+ // Load traits
+ use CompileableTemplateTrait;
+
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Creates an instance of the class TemplateEngine and prepares it for usage
+ *
+ * @param $innerTemplateInstance A CompileableXmlTemplate instance
+ * @return $templateInstance An instance of TemplateEngine
+ */
+ public static final function createXmlRewriterTemplateDecorator (CompileableXmlTemplate $innerTemplateInstance) {
+ // Get a new instance
+ $templateInstance = new XmlRewriterTemplateDecorator();
+
+ // Set the inner template engine
+ $templateInstance->setTemplateInstance($innerTemplateInstance);
+
+ // Return the prepared instance
+ return $templateInstance;
+ }
+
+ /**
+ * Settter for variable group
+ *
+ * @param $groupName Name of variable group
+ * @param $add Whether add this group
+ * @return void
+ */
+ public function setVariableGroup (string $groupName, bool $add = true) {
+ // Call the inner class' method
+ $this->getTemplateInstance()->setVariableGroup($groupName, $add);
+ }
+
+ /**
+ * Adds a variable to current group
+ *
+ * @param $variableName Variable to set
+ * @param $value Value to store in variable
+ * @return void
+ */
+ public function addGroupVariable (string $variableName, $value) {
+ // Call the inner class' method
+ $this->getTemplateInstance()->addGroupVariable($variableName, $value);
+ }
+
+ /**
+ * Getter for base path
+ *
+ * @return $templateBasePath The relative base path for all templates
+ */
+ public final function getTemplateBasePath () {
+ // Call the inner class' method
+ return $this->getTemplateInstance()->getTemplateBasePath();
+ }
+
+ /**
+ * Getter for generic base path
+ *
+ * @return $templateBasePath The relative base path for all templates
+ */
+ public final function getGenericBasePath () {
+ // Call the inner class' method
+ return $this->getTemplateInstance()->getGenericBasePath();
+ }
+
+ /**
+ * Getter for template extension
+ *
+ * @return $templateExtension The file extension for all uncompiled templates
+ */
+ public final function getRawTemplateExtension () {
+ // Call the inner class' method
+ return $this->getTemplateInstance()->getRawTemplateExtension();
+ }
+
+ /**
+ * Getter for given variable group
+ *
+ * @param $variableGroup Variable group to check
+ * @return $varStack Found variable group
+ */
+ public function getVarStack (string $variableGroup) {
+ // Call the inner class' method
+ return $this->getTemplateInstance()->getVarStack($variableGroup);
+ }
+
+ /**
+ * Getter for code-template extension
+ *
+ * @return $codeExtension The file extension for all code templates
+ */
+ public final function getCodeTemplateExtension () {
+ // Call the inner class' method
+ return $this->getTemplateInstance()->getCodeTemplateExtension();
+ }
+
+ /**
+ * Getter for template type
+ *
+ * @return $templateType The current template's type
+ */
+ public final function getTemplateType () {
+ // Call the inner class' method
+ return $this->getTemplateInstance()->getTemplateType();
+ }
+
+ /**
+ * Assign (add) a given variable with a value
+ *
+ * @param $variableName The variable we are looking for
+ * @param $value The value we want to store in the variable
+ * @return void
+ */
+ public function assignVariable (string $variableName, $value) {
+ // Call the inner class' method
+ $this->getTemplateInstance()->assignVariable($variableName, $value);
+ }
+
+ /**
+ * Removes a given variable
+ *
+ * @param $variableName The variable we are looking for
+ * @param $variableGroup Name of variable group (default: 'general')
+ * @return void
+ */
+ public function removeVariable (string $variableName, string $variableGroup = 'general') {
+ // Call the inner class' method
+ $this->getTemplateInstance()->removeVariable($variableName, $variableGroup);
+ }
+
+ /**
+ * Load a specified HTML template into the engine
+ *
+ * @param $template The web template we shall load which is located in
+ * 'html' by default
+ * @return void
+ */
+ public function loadHtmlTemplate (string $template) {
+ // Call the inner class' method
+ $this->getTemplateInstance()->loadHtmlTemplate($template);
+ }
+
+ /**
+ * Assign a given congfiguration variable with a value
+ *
+ * @param $variableName The configuration variable we want to assign
+ * @return void
+ */
+ public function assignConfigVariable (string $variableName) {
+ // Call the inner class' method
+ $this->getTemplateInstance()->assignConfigVariable($variableName);
+ }
+
+ /**
+ * Load a specified code template into the engine
+ *
+ * @param $template The code template we shall load which is
+ * located in 'code' by default
+ * @return void
+ */
+ public function loadCodeTemplate (string $template) {
+ // Call the inner class' method
+ $this->getTemplateInstance()->loadCodeTemplate($template);
+ }
+
+ /**
+ * Load a specified email template into the engine for later compilation
+ * with other code/web/email templates.
+ *
+ * @param $template The email template we shall load which is
+ * located in "html" by default
+ * @return void
+ */
+ public function loadEmailTemplate ($template) {
+ // Call the inner class' method
+ $this->getTemplateInstance()->loadEmailTemplate($template);
+ }
+
+ /**
+ * Compiles configuration place-holders in all variables. This 'walks'
+ * through the variable stack 'general'. It interprets all values from that
+ * variables as configuration entries after compiling them.
+ *
+ * @return void
+ */
+ public function compileConfigInVariables () {
+ // Call the inner class' method
+ $this->getTemplateInstance()->compileConfigInVariables();
+ }
+
+ /**
+ * Compile all variables by inserting their respective values
+ *
+ * @return void
+ */
+ public function compileVariables () {
+ // Call the inner class' method
+ $this->getTemplateInstance()->compileVariables();
+ }
+
+ /**
+ * Compile all required templates into the current loaded one
+ *
+ * @return void
+ */
+ public function compileTemplate () {
+ // Call the inner class' method
+ $this->getTemplateInstance()->compileTemplate();
+ }
+
+ /**
+ * Assigns the last loaded raw template content with a given variable
+ *
+ * @param $templateName Name of the template we want to assign
+ * @param $variableName Name of the variable we want to assign
+ * @return void
+ */
+ public function assignTemplateWithVariable (string $templateName, string $variableName) {
+ // Call the inner class' method
+ $this->getTemplateInstance()->assignTemplateWithVariable($templateName, $variableName);
+ }
+
+ /**
+ * Transfers the content of this template engine to a given response instance
+ *
+ * @param $responseInstance An instance of a Responseable class
+ * @return void
+ */
+ public function transferToResponse (Responseable $responseInstance) {
+ // Call the inner class' method
+ $this->getTemplateInstance()->transportToResponse($responseInstance);
+ }
+
+ /**
+ * Assigns all the application data with template variables
+ *
+ * @return void
+ */
+ public function assignApplicationData () {
+ // Call the inner class' method
+ $this->getTemplateInstance()->assignApplicationData();
+ }
+
+ /**
+ * "Compiles" a variable by replacing {?var?} with it's content
+ *
+ * @param $rawCode Raw code to compile
+ * @param $setMatchAsCode Sets $match if readVariable() returns empty result
+ * @return $rawCode Compile code with inserted variable value
+ */
+ public function compileRawCode (string $rawCode, bool $setMatchAsCode = false) {
+ return $this->getTemplateInstance()->compileRawCode($rawCode, $setMatchAsCode);
+ }
+
+ /**
+ * Getter for variable group array
+ *
+ * @return $variableGroups All variable groups
+ */
+ public final function getVariableGroups () {
+ // Call the inner class' method
+ return $this->getTemplateInstance()->getVariableGroups();
+ }
+
+ /**
+ * Getter for raw template data
+ *
+ * @return $rawTemplateData The raw data from the template
+ */
+ public function getRawTemplateData () {
+ // Call the inner class' method
+ return $this->getTemplateInstance()->getRawTemplateData();
+ }
+
+ /**
+ * Renames a variable in code and in stack
+ *
+ * @param $oldName Old name of variable
+ * @param $newName New name of variable
+ * @return void
+ */
+ public function renameVariable (string $oldName, string $newName) {
+ // Call the inner class' method
+ $this->getTemplateInstance()->renameVariable($oldName, $newName);
+ }
+
+ /**
+ * Renders the given XML content
+ *
+ * @param $content Valid XML content or if not set the current loaded raw content
+ * @return void
+ * @throws XmlParserException If an XML error was found
+ */
+ public function renderXmlContent (string $content = NULL) {
+ // Call the inner class' method
+ $this->getTemplateInstance()->renderXmlContent($content);
+ }
+
+ /**
+ * Enables or disables language support
+ *
+ * @param $languageSupport New language support setting
+ * @return void
+ */
+ public function enableLanguageSupport (bool $languageSupport = true) {
+ // Call the inner class' method
+ $this->getTemplateInstance()->enableLanguageSupport($languageSupport);
+ }
+
+ /**
+ * Checks whether language support is enabled
+ *
+ * @return $languageSupport Whether language support is enabled or disabled
+ */
+ public function isLanguageSupportEnabled () {
+ // Call the inner class' method
+ return $this->getTemplateInstance()->isLanguageSupportEnabled();
+ }
+
+ /**
+ * Enables or disables XML compacting
+ *
+ * @param $xmlCompacting New XML compacting setting
+ * @return void
+ */
+ public function enableXmlCompacting (bool $xmlCompacting = true) {
+ // Call the inner class' method
+ $this->getTemplateInstance()->enableXmlCompacting($xmlCompacting);
+ }
+
+ /**
+ * Checks whether XML compacting is enabled
+ *
+ * @return $xmlCompacting Whether XML compacting is enabled or disabled
+ */
+ public function isXmlCompactingEnabled () {
+ // Call the inner class' method
+ return $this->getTemplateInstance()->isXmlCompactingEnabled();
+ }
+
+ /**
+ * Handles the start element of an XML resource
+ *
+ * @param $resource XML parser resource (currently ignored)
+ * @param $element The element we shall handle
+ * @param $attributes All attributes
+ * @return void
+ * @throws InvalidXmlNodeException If an unknown/invalid XML node name was found
+ */
+ public function startElement ($resource, string $element, array $attributes) {
+ // Call the inner class' method
+ $this->getTemplateInstance()->startElement($resource, $element, $attributes);
+ }
+
+ /**
+ * Ends the main or sub node by sending out the gathered data
+ *
+ * @param $resource An XML resource pointer (currently ignored)
+ * @param $nodeName Name of the node we want to finish
+ * @return void
+ * @throws XmlNodeMismatchException If current main node mismatches the closing one
+ */
+ public function finishElement ($resource, string $nodeName) {
+ // Call the inner class' method
+ $this->getTemplateInstance()->finishElement($resource, $nodeName);
+ }
+
+ /**
+ * Currently not used
+ *
+ * @param $resource XML parser resource (currently ignored)
+ * @param $characters Characters to handle
+ * @return void
+ * @todo Find something useful with this!
+ */
+ public function characterHandler ($resource, string $characters) {
+ // Call the inner class' method but trim the characters before
+ $this->getTemplateInstance()->characterHandler($resource, trim($characters));
+ }
+
+ /**
+ * Removes all comments, tabs and new-line charcters to compact the content
+ *
+ * @param $uncompactedContent The uncompacted content
+ * @return $compactedContent The compacted content
+ */
+ public function compactContent (string $uncompactedContent) {
+ // Compact it ...
+ $compactedContent = $this->getTemplateInstance()->compactContent($uncompactedContent);
+
+ // ... and return it
+ return $compactedContent;
+ }
+
+ /**
+ * Assigns a lot variables into the stack of currently loaded template.
+ * This method should only be used in very rare circumstances, e.g. when
+ * you have to copy a whole set of variables into the template engine.
+ * Before you use this method, please make sure you have considered all
+ * other possiblities.
+ *
+ * @param $variables An array with variables to be assigned
+ * @return void
+ */
+ public function assignMultipleVariables (array $variables) {
+ // Call the inner class' method but trim the characters before
+ $this->getTemplateInstance()->assignMultipleVariables($variables);
+ }
+
+}
<?php
// Own namespace
-namespace CoreFramework\Disovery\;
+namespace Org\Mxchange\CoreFramework\Disovery\;
// Import framework stuff
use Org\Mxchange\CoreFramework\Helper\Template\HelpableTemplate;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
/**
* A ??? discovery class.
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @todo 0% done
*/
public function discover (Requestable $requestInstance) {
- $this->partialStub("Please implement this method.");
+ DebugMiddleware::getSelfInstance()->partialStub("Please implement this method.");
}
/**
* @todo 0% done
*/
public function addResultsToHelper (HelpableTemplate $helperInstance) {
- $this->partialStub("Please implement this method.");
+ DebugMiddleware::getSelfInstance()->partialStub("Please implement this method.");
}
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
* @param $actionName Action name to set
* @return void
*/
- protected final function setActionName ($actionName) {
- $this->actionName = (string) $actionName;
+ protected final function setActionName (string $actionName) {
+ $this->actionName = $actionName;
}
/**
// Import framework stuff
use Org\Mxchange\CoreFramework\Discovery\BaseDiscovery;
use Org\Mxchange\CoreFramework\Discovery\Discoverable;
-use Org\Mxchange\CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Database\Frontend\DatabaseFrontendFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filter\Filterable;
use Org\Mxchange\CoreFramework\Helper\Template\HelpableTemplate;
use Org\Mxchange\CoreFramework\Registry\Registerable;
use Org\Mxchange\CoreFramework\Request\Requestable;
+use Org\Mxchange\CoreFramework\Traits\Result\Search\SearchableResultTrait;
/**
* A local payment discovery class. This class looks in local database for
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class LocalPaymentDiscovery extends BaseDiscovery implements Discoverable, Registerable {
+ // Load traits
+ use SearchableResultTrait;
+
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$criteriaInstance->addCriteria('payment_action', $this->getActionName() . '_action');
$criteriaInstance->setLimit(1);
- // Get a wrapper instance
- $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName('payment_db_wrapper_class');
+ // Get a frontend instance
+ $frontendInstance = DatabaseFrontendFactory::createFrontendByConfiguredName('payment_db_frontend_class');
// Get result back
- $resultInstance = $wrapperInstance->doSelectByCriteria($criteriaInstance);
+ $resultInstance = $frontendInstance->doSelectByCriteria($criteriaInstance);
// Advanced to next entry and assert on it as it should always be there
assert($resultInstance->valid());
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Factory\Cache;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\BaseFactory;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-
-/**
- * A cache factory
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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 CacheFactory extends BaseFactory {
- /**
- * Singleton instance
- */
- private static $selfInstance = NULL;
-
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Singleton getter for this class
- *
- * @return $selfInstance An instance of this class
- */
- public static final function getFactory () {
- // Is the instance null?
- if (is_null(self::$selfInstance)) {
- // Set a new one
- self::$selfInstance = new CacheFactory();
- } // END - if
-
- // Return the instance
- return self::$selfInstance;
- }
-
- /**
- * Creates a configured cache instance
- *
- * @return $cacheInstance An instance of the configured cache
- */
- public function createConfiguredCache () {
- // Read the config entry
- $cacheType = $this->getConfigInstance()->getConfigEntry('cache_class');
-
- // And get a new instance
- $cacheInstance = ObjectFactory::createObjectByName($cacheType);
-
- // Return the instance
- return $cacheInstance;
- }
-
-}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
namespace Org\Mxchange\CoreFramework\Factory;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+// Import SPL stuff
+use \InvalidArgumentException;
+
/**
* A general (base) factory
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* Counter of all objects
*/
- private static $objectCounters = array();
+ private static $objectCounters = [];
/**
* Protected constructor
* @param $className Name of the real class (not BaseFactory)
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
/**
* Count given object
*
- * @param $className Name of the class we shall count
+ * @param $fullClassName Name of the class we shall count
+ * @return void
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- protected static final function countObject ($className) {
+ protected static final function countObject (string $fullClassName) {
+ // Is the parameter valid?
+ if (empty($fullClassName)) {
+ // No empty class name
+ throw new InvalidArgumentException('fullClassName is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Count it up in total sum
self::$total++;
// Do we have an entry?
- if (!isset(self::$objectCounters[$className])) {
+ if (!self::isClassCounted($fullClassName)) {
// No, then generate one
- self::$objectCounters[$className] = 0;
- } // END - if
+ self::$objectCounters[$fullClassName] = 0;
+ }
// Count it up again
- //* NOISY-DEBUG: */ print __METHOD__.': className=' .$className . PHP_EOL;
- self::$objectCounters[$className]++;
+ //* NOISY-DEBUG: */ print __METHOD__.': className=' .$fullClassName . PHP_EOL;
+ self::$objectCounters[$fullClassName]++;
}
/**
return self::$objectCounters;
}
+ /**
+ * Checks whether given full class name is already counted
+ *
+ * @param $fullClassName Full name of class
+ * @return $isCounted Whether given class name is counted
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ public static final function isClassCounted (string $fullClassName) {
+ // Is the parameter valid?
+ if (empty($fullClassName)) {
+ // No empty class name
+ throw new InvalidArgumentException('fullClassName is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Return isset() result
+ return isset(self::$objectCounters[$fullClassName]);
+ }
+
}
namespace Org\Mxchange\CoreFramework\Factory\Client;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\BaseFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
/**
* An object factory for clients
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
+ * @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
*
* 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 ClientFactory extends ObjectFactory {
+class ClientFactory extends BaseFactory {
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$registryKey = strtolower($protocolInstance->getProtocolName()) . '_client';
// Is the key already in registry?
- if (GenericRegistry::getRegistry()->instanceExists($registryKey)) {
+ if (ObjectRegistry::getRegistry('factory')->instanceExists($registryKey)) {
// Then use that instance
- $clientInstance = GenericRegistry::getRegistry()->getInstance($registryKey);
+ $clientInstance = ObjectRegistry::getRegistry('factory')->getInstance($registryKey);
// Set socket resource
$clientInstance->setSocketResource($socketResource);
} else {
// Generate object instance
- $clientInstance = self::createObjectByConfiguredName($registryKey, array($socketResource));
+ $clientInstance = ObjectFactory::createObjectByConfiguredName($registryKey, array($socketResource));
// Set it in registry for later re-use
- GenericRegistry::getRegistry()->addInstance($registryKey, $clientInstance);
+ ObjectRegistry::getRegistry('factory')->addInstance($registryKey, $clientInstance);
}
// Return the prepared instance
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Factory\Database\Frontend;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Factory\BaseFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+
+/**
+ * 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 DatabaseFrontendFactory extends BaseFactory {
+ /**
+ * "Cache" for frontend factory
+ */
+ private static $registryInstance = NULL;
+
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Some "static initializer
+ *
+ * @return void
+ */
+ public final static function staticInitializer () {
+ // Is it initialized?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('frontend-FACTORY: self::registryInstance[]=%s - CALLED!', gettype(self::$registryInstance)));
+ if (is_null(self::$registryInstance)) {
+ // No, then initialize it
+ self::$registryInstance = ObjectRegistry::getRegistry('factory');
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('frontend-FACTORY: self::registryInstance=%s - EXIT!', self::$registryInstance));
+ }
+
+ /**
+ * 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 $frontendInstance A database frontend instance
+ */
+ public static final function createFrontendByConfiguredName (string $frontendName) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-FRONTEND-FACTORY: frontendName=%s - CALLED!', $frontendName));
+ if (empty($frontendName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "frontendName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Invoke "static initializer"
+ self::staticInitializer();
+
+ // Do we have an instance in the registry?
+ if (self::$registryInstance->instanceExists($frontendName)) {
+ // Then use this instance
+ $frontendInstance = self::$registryInstance->getInstance($frontendName);
+ } else {
+ // Get the registry instance
+ $frontendInstance = ObjectFactory::createObjectByConfiguredName($frontendName);
+
+ // Set the instance in registry for further use
+ self::$registryInstance->addInstance($frontendName, $frontendInstance);
+ }
+
+ // Return the instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-FRONTEND-FACTORY: frontendInstance=%s - EXIT!', $frontendInstance->__toString()));
+ return $frontendInstance;
+ }
+
+}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Factory\Database\Wrapper;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
-
-/**
- * A factory class for socket registries
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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 DatabaseWrapperFactory extends ObjectFactory {
- /**
- * Protected constructor
- *
- * @return void
- */
- protected 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 $wrapperInstance A database wrapper instance
- */
- public static final function createWrapperByConfiguredName ($wrapperName) {
- // Get registry instance
- $registryInstance = GenericRegistry::getRegistry();
-
- // Do we have an instance in the registry?
- if ($registryInstance->instanceExists($wrapperName)) {
- // Then use this instance
- $wrapperInstance = $registryInstance->getInstance($wrapperName);
- } else {
- // Get the registry instance
- $wrapperInstance = self::createObjectByConfiguredName($wrapperName);
-
- // Set the instance in registry for further use
- $registryInstance->addInstance($wrapperName, $wrapperInstance);
- }
-
- // Return the instance
- return $wrapperInstance;
- }
-
-}
namespace Org\Mxchange\CoreFramework\Factory\News;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Factory\BaseFactory;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Request\Requestable;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
if (!empty($action)) {
// Then use both for config entry
$configEntry = sprintf('news_reader_%s_%s_class', $command, $action);
- } // END - if
- } // END - if
+ }
+ }
// Get the news reader class name from config
- $className = $requestInstance->getConfigInstance()->getConfigEntry($configEntry);
+ $className = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($configEntry);
// Once we have that name, try to load initialize it
$newsInstance = ObjectFactory::createObjectByName($className, array($requestInstance));
<?php
// Own namespace
-namespace Org\Mxchange\CoreFramework\Factory\Filesystem\Stack;
+namespace Org\Mxchange\CoreFramework\Factory\Stack\File;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
-use Org\Mxchange\CoreFramework\Stacker\Index\IndexableStack;
+use Org\Mxchange\CoreFramework\Factory\BaseFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
// Import SPL stuff
+use \InvalidArgumentException;
use \SplFileInfo;
/**
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* 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 FileStackIndexFactory extends ObjectFactory {
+class FileStackIndexFactory extends BaseFactory {
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
/**
* Returns a singleton (registry-based) StackableFile instance
*
- * @param $infoInstance An instance of a SplFileInfo class
+ * @param $fileInfoInstance An instance of a SplFileInfo class
* @return $indexInstance An instance of a IndexableStack class
+ * @throws InvalidArgumentException If a parameter is invalid
*/
- public static final function createFileStackIndexInstance (SplFileInfo $infoInstance, $type) {
+ public static final function createFileStackIndexInstance (SplFileInfo $fileInfoInstance, string $type) {
// If there is no handler?
- if (GenericRegistry::getRegistry()->instanceExists($type . '_index')) {
+ if (empty($type)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "type" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (ObjectRegistry::getRegistry('factory')->instanceExists($type . '_index')) {
// Get handler from registry
- $indexInstance = GenericRegistry::getRegistry()->getInstance($type . '_index');
+ $indexInstance = ObjectRegistry::getRegistry('factory')->getInstance($type . '_index');
} else {
// Get the handler instance
- $indexInstance = self::createObjectByConfiguredName($type . '_file_stack_index_class', array($infoInstance));
-
- // Add check for interface
- assert($indexInstance instanceof IndexableStack);
+ $indexInstance = ObjectFactory::createObjectByConfiguredName($type . '_file_stack_index_class', [$fileInfoInstance]);
// Add it to the registry
- GenericRegistry::getRegistry()->addInstance($type . '_index', $indexInstance);
+ ObjectRegistry::getRegistry('factory')->addInstance($type . '_index', $indexInstance);
}
// Return the instance
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
namespace Org\Mxchange\CoreFramework\Factory\Login;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Factory\BaseFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* 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 LoginFactory extends ObjectFactory {
+class LoginFactory extends BaseFactory {
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public static final function createLoginObjectByRequest (Requestable $requestInstance) {
// Get registry instance
- $registryInstance = GenericRegistry::getRegistry();
+ $registryInstance = ObjectRegistry::getRegistry('factory');
// Do we have an instance in the registry?
if ($registryInstance->instanceExists('login_helper')) {
// Probe on member instance
try {
// Try to instance member login class
- $loginInstance = self::createObjectByConfiguredName('user_login_class');
+ $loginInstance = ObjectFactory::createObjectByConfiguredName('user_login_class');
// Test login
$loginInstance->testLogin($requestInstance);
} catch (UnexpectedGuestAccountException $e) {
// Then try guest login
- $loginInstance = self::createObjectByConfiguredName('guest_login_class');
+ $loginInstance = ObjectFactory::createObjectByConfiguredName('guest_login_class');
// Test login again
$loginInstance->testLogin($requestInstance);
<?php
// Own namespace
-namespace Org\Mxchange\CoreFramework\Factory;
+namespace Org\Mxchange\CoreFramework\Factory\Object;
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Factory\BaseFactory;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Loader\NoClassException;
// Import SPL stuff
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Name of this class
* @return void
*/
- protected function __construct ($className = __CLASS__) {
+ protected function __construct (string $className = __CLASS__) {
// Call parent constructor
parent::__construct($className);
}
* the class was not found. No parameters for the object are currently
* supported.
*
- * @param $className Name of the class we shall construct
+ * @param $fullClassName Name of the class we shall construct
* @param $args Arguments in an indexed array
* @return $objectInstance An instance of the requested object
* @throws NoClassException If the requested class was not found
* @throws InvalidArgumentException If className is empty or the name not following naming-convention
*/
- public static final function createObjectByName ($className, array $args = array()) {
+ public static final function createObjectByName (string $fullClassName, array $args = []) {
// Is the class name valid and is the class there?
- if (empty($className)) {
+ if (empty($fullClassName)) {
// Throw an exception here
- throw new InvalidArgumentException('Parameter "className" is empty');
- } elseif (!class_exists($className)) {
+ throw new InvalidArgumentException('Parameter "fullClassName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!self::isClassCounted($fullClassName) && !class_exists($fullClassName)) {
// First get an instance of this factory
$factoryInstance = new ObjectFactory();
// Then throw an exception
- throw new NoClassException(array($factoryInstance, $className), self::EXCEPTION_CLASS_NOT_FOUND);
+ throw new NoClassException([$factoryInstance, $fullClassName], FrameworkInterface::EXCEPTION_CLASS_NOT_FOUND);
}
// Split class name on backslash to check naming-convention
- $classNameParts = explode("\\", $className);
+ $classNameParts = explode("\\", $fullClassName);
// Okay, does it follow naming-convention?
if (count($classNameParts) < 4) {
// Namespaces are missing
- throw new InvalidArgumentException(sprintf('Class name "%s" is not conform to naming-convention: Tld\Domain\Project\Package[\SubPackage...]\SomeFooBar', $className));
- } // END - if
+ throw new InvalidArgumentException(sprintf('Class name "%s" is not conform to naming-convention: Tld\Domain\Project\Package[\SubPackage...]\SomeFooBar', $fullClassName));
+ }
// Create method name
- $methodName = sprintf('create%s', self::stripNamespaceFromClassName($className));
+ $methodName = sprintf('create%s', self::stripNamespaceFromClassName($fullClassName));
// Run the user function
- $objectInstance = call_user_func_array(array($className, $methodName), $args);
+ $objectInstance = call_user_func_array([$fullClassName, $methodName], $args);
// Count this one up
- self::countObject($className);
+ self::countObject($fullClassName);
// Return the prepared instance
return $objectInstance;
/**
* Creates an object by it's configured name
*
- * @param $configEnttry Configuration entry to read
+ * @param $configKey Configuration key to read
* @param $args Arguments in an indexed array
* @return $objectInstance An instance of the requested object
*/
- public static final function createObjectByConfiguredName ($configEntry, array $args = array()) {
+ public static final function createObjectByConfiguredName (string $configKey, array $args = []) {
// Read the configuration entry
- $className = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($configEntry);
+ $fullClassName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($configKey);
// Send this to the other factory...
- $objectInstance = self::createObjectByName($className, $args);
+ $objectInstance = self::createObjectByName($fullClassName, $args);
// Return the instance
return $objectInstance;
*
* @param $fullClassName Class name with namespace
* @return $shortClassName Stripped class name (no namespace)
- * @throws InvalidArgumentException If the class name does not follow naming convention
*/
- private static function stripNamespaceFromClassName ($fullClassName) {
+ private static function stripNamespaceFromClassName (string $fullClassName) {
// The class name should contain at least 2 back-slashes, so split at them
$classNameParts = explode("\\", $fullClassName);
- // At least 4 parts should be there
- if (count($classNameParts) < 4) {
- // Namespace scheme is: Tld\Project\Package[\SubPackage...]
- throw new InvalidArgumentException($fullClassName, self::EXCEPTION_INVALID_CLASS_NAME);
- } // END - if
-
// Get last element
$shortClassName = array_pop($classNameParts);
namespace Org\Mxchange\CoreFramework\Factory\Registry\Socket;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Factory\BaseFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
/**
* A factory class for socket registries
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* 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 ObjectFactory {
+class SocketRegistryFactory extends BaseFactory {
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public static final function createSocketRegistryInstance () {
// Get registry instance
- $registryInstance = GenericRegistry::getRegistry();
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('SOCKET-REGISTRY-FACTORY: CALLED!');
+ $objectRegistryInstance = ObjectRegistry::getRegistry('factory');
// Do we have an instance in the registry?
- if ($registryInstance->instanceExists('socket_registry')) {
+ if ($objectRegistryInstance->instanceExists('socket_registry')) {
// Then use this instance
- $registryInstance = $registryInstance->getInstance('socket_registry');
+ /* 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
- $registryInstance->addInstance('socket_registry', $registryInstance);
+ /* 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;
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Factory\BaseFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
// Import SPL stuff
+use \InvalidArgumentException;
use \SplFileInfo;
/**
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* 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 FileStackFactory extends ObjectFactory {
+class FileStackFactory extends BaseFactory {
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @param $stackName Name of the stack
* @return $stackInstance An instance of a StackableFile class
*/
- public static final function createFileStackInstance ($prefix, $stackName) {
+ public static final function createFileStackInstance (string $prefix, string $stackName) {
+ // Validate parameter
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-STACK-FACTORY: prefix=%s,stackName=%s - CALLED!', $prefix, $stackName));
+ if (empty($prefix)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "prefix" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($stackName)) {
+ // Throw it again
+ throw new InvalidArgumentException('Paramter "stackName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Construct file stack name
$fileInfoInstance = new SplFileInfo(sprintf('%s%s/%s.%s',
FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('root_base_path'),
));
// If there is no handler?
- if (GenericRegistry::getRegistry()->instanceExists($stackName . '_stack')) {
+ if (ObjectRegistry::getRegistry('factory')->instanceExists($stackName . '_stack')) {
// Get handler from registry
- $stackInstance = GenericRegistry::getRegistry()->getInstance($stackName . '_stack');
+ $stackInstance = ObjectRegistry::getRegistry('factory')->getInstance($stackName . '_stack');
} else {
// Get the handler instance
- $stackInstance = self::createObjectByConfiguredName($prefix . '_' . $stackName . '_stack_class', array($fileInfoInstance, $prefix . '_' . $stackName));
+ $stackInstance = ObjectFactory::createObjectByConfiguredName($prefix . '_' . $stackName . '_stack_class', array($fileInfoInstance, $prefix . '_' . $stackName));
// Add it to the registry
- GenericRegistry::getRegistry()->addInstance($stackName . '_stack', $stackInstance);
+ ObjectRegistry::getRegistry('factory')->addInstance($stackName . '_stack', $stackInstance);
}
// Return the instance
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-STACK-FACTORY: stackInstance=%s - EXIT!', $stackInstance->__toString()));
return $stackInstance;
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Factory\BaseFactory;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* 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 UserFactory extends ObjectFactory {
+class UserFactory extends BaseFactory {
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public static final function createUserByRequest (Requestable $requestInstance) {
// Get registry instance
- $registryInstance = GenericRegistry::getRegistry();
+ $registryInstance = ObjectRegistry::getRegistry('factory');
// Do we have an instance in the registry?
if ($registryInstance->instanceExists('user')) {
namespace Org\Mxchange\CoreFramework\Factory\Template;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Factory\BaseFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
+
+// Import SPL stuff
+use \InvalidArgumentException;
/**
* A factory class for XML template engines. All instances generated by this
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* 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 XmlTemplateEngineFactory extends ObjectFactory {
+class XmlTemplateEngineFactory extends BaseFactory {
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* the registry it will be returned, else a new instance is created and
* stored in the same registry entry.
*
- * @param $configEntry Config entry name for the template engine
+ * @param $configKey Config entry name for the template engine
* @return $templateInstance A template engine instance
*/
- public static final function createXmlTemplateEngineInstance ($configEntry) {
+ public static final function createXmlTemplateEngineInstance (string $configKey) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('XML-TEMPLATE-ENGINE-FACTORY: configKey=%s - CALLED!', $configKey));
+ if (empty($configKey)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Paramter "configKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Do we have an instance in the registry?
- if (GenericRegistry::getRegistry()->instanceExists($configEntry)) {
+ if (ObjectRegistry::getRegistry('factory')->instanceExists($configKey)) {
// Then use this instance
- $templateInstance = GenericRegistry::getRegistry()->getInstance($configEntry);
+ $templateInstance = ObjectRegistry::getRegistry('factory')->getInstance($configKey);
} else {
- // Now prepare the tags instance
- $templateInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
+ // Get the XML template instance
+ $templateInstance = ObjectFactory::createObjectByConfiguredName($configKey);
// Disable language support
$templateInstance->enableLanguageSupport(false);
$templateInstance->enableXmlCompacting();
// Set the instance in registry for further use
- GenericRegistry::getRegistry()->addInstance($configEntry, $templateInstance);
+ ObjectRegistry::getRegistry('factory')->addInstance($configKey, $templateInstance);
}
// Return the instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('XML-TEMPLATE-ENGINE-FACTORY: templateInstance=%s - EXIT!', $templateInstance->__toString()));
return $templateInstance;
}
<?php
// Own namespace
-namespace CoreFramework\Feature\!!!;
+namespace Org\Mxchange\CoreFramework\Feature\!!!;
// Import framework stuff
use Org\Mxchange\CoreFramework\Feature\BaseFeature;
use Org\Mxchange\CoreFramework\Feature\Feature;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
/**
* A ??? feature class
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$isAvailable = false;
// Unfinished:
- $this->partialStub('Please implement this method.');
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this method.');
// Return status
return $isAvailable;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Loader\NoClassException;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
+
+// Import SPL stuff
+use \BadMethodCallException;
+use \InvalidArgumentException;
/**
* The general feature management class. No instance is needed as this class
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* 'instance' => NULL
* )
*/
- private static $enabledFeatures = array();
+ private static $enabledFeatures = [];
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*
* @param $featureName Name of the feature to be checked
* @return $isEnabled Whether the given feature is enabled
+ * @throws InvalidArgumentException If a parameter is invalid
*/
- public static function isFeatureEnabled ($featureName) {
+ public static function isFeatureEnabled (string $featureName) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FRAMEWORK-FEATURE: featureName=%s - CALLED!', $featureName));
+ if (empty($featureName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "featureName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Is the cache set?
if (!isset(self::$enabledFeatures[$featureName]['is_enabled'])) {
// Generate config key
// Check configuration
self::$enabledFeatures[$featureName]['is_enabled'] = (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($configKey) === 'Y');
- } // END - if
+ }
// Return "cached" status
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FRAMEWORK-FEATURE: is_enabled[%s]=%d - EXIT!', $featureName, intval(self::$enabledFeatures[$featureName]['is_enabled'])));
return self::$enabledFeatures[$featureName]['is_enabled'];
}
*
* @param $featureName Name of the feature to be checked on availability
* @return $isAvailable Whether the given feature is available
+ * @throws InvalidArgumentException If a parameter is invalid
*/
- public static function isFeatureAvailable ($featureName) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d]: featureName=%s - CALLED!', __METHOD__, __LINE__, $featureName));
+ public static function isFeatureAvailable (string $featureName) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FRAMEWORK-FEATURE: featureName=%s - CALLED!', $featureName));
+ if (empty($featureName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "featureName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Is the cache set?
if (!isset(self::$enabledFeatures[$featureName]['is_available'])) {
// Is the feature enabled?
if (!self::isFeatureEnabled($featureName)) {
// Then it can't be available
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d]: Feature "%s"is not enabled.', __METHOD__, __LINE__, $featureName));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FRAMEWORK-FEATURE: Feature "%s"is not enabled. - EXIT!', $featureName));
return false;
- } // END - if
+ }
// Create config key (for feature class lookup)
$configKey = sprintf('feature_%s_class', $featureName);
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d]: configKey=%s', __METHOD__, __LINE__, $configKey));
-
// Now try to get the instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FRAMEWORK-FEATURE: configKey=%s', $configKey));
try {
// Try to get an instance
self::$enabledFeatures[$featureName]['instance'] = ObjectFactory::createObjectByConfiguredName($configKey);
self::$enabledFeatures[$featureName]['is_available'] = self::$enabledFeatures[$featureName]['instance']->isFeatureAvailable();
} catch (NoClassException $e) {
// Feature class not found
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d]: Feature "%s"is not available due to missing feature class. Disabling feature ...', __METHOD__, __LINE__, $featureName));
+ self::createDebugInstance(__CLASS__, __LINE__)->warningMessage(sprintf('FRAMEWORK-FEATURE: Feature "%s"is not available due to missing feature class. Disabling feature ...', $featureName));
}
- } // END - if
-
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d]: featureName=%s,isAvailable=%d - EXIT!', __METHOD__, __LINE__, $featureName, intval(self::$enabledFeatures[$featureName]['is_available'])));
+ }
// Return "cached" status
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FRAMEWORK-FEATURE: featureName=%s,isAvailable=%d - EXIT!', $featureName, intval(self::$enabledFeatures[$featureName]['is_available'])));
return self::$enabledFeatures[$featureName]['is_available'];
}
* @param $featureMethod Method name of the feature's class
* @param $args Any arguments that should be handled over
* @return $return Anything the feature's method has returned
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ * @throws BadMethodCallException If this method has been invoked but the feature isn't available
* @throws FeatureMethodNotCallableException If the requested method cannot be called
*/
- public static function callFeature ($featureName, $featureMethod, array $args = NULL) {
- /*
- * Please make sure that isFeatureAvailable() has been called and it has
- * returned true before calling this method.
- */
- assert(self::isFeatureAvailable($featureName));
+ public static function callFeature (string $featureName, string $featureMethod, array $args = NULL) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FRAMEWORK-FEATURE: featureName=%s,featureMethod=%s,args[]=%s - CALLED!', $featureName, $featureMethod, gettype($args)));
+ if (empty($featureName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "featureName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($featureMethod)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "featureMethod" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!self::isFeatureAvailable($featureName)) {
+ // Throw BMCE
+ throw new BadMethodCallException(sprintf('Feature "%s" is not available but method "%s" should be invoked.', $featureName, $featureMethod), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Array for call-back
- $callable = array(self::$enabledFeatures[$featureName]['instance'], 'featureMethod' . self::convertToClassName($featureMethod));
+ $callable = array(
+ self::$enabledFeatures[$featureName]['instance'],
+ sprintf('featureMethod%s', StringUtils::convertToClassName($featureMethod))
+ );
// So is the feature's method callable?
if (!is_callable($callable)) {
// Not callable method requested
throw new FeatureMethodNotCallableException(array(self::$enabledFeatures[$featureName]['instance'], $featureMethod), self::EXCEPTION_FEATURE_METHOD_NOT_CALLABLE);
- } // END - if
+ }
// Then call it
$return = call_user_func_array($callable, $args);
// Return any returned value
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FRAMEWORK-FEATURE: return[]=%s - EXIT!', gettype($return)));
return $return;
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Feature\BaseFeature;
use Org\Mxchange\CoreFramework\Feature\Feature;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
/**
* A FUSE feature class
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$isAvailable = false;
// Unfinished:
- $this->partialStub('Please implement this method.');
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this method.');
// Return status
return $isAvailable;
namespace Org\Mxchange\CoreFramework\Filesystem\File;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Filesystem\Block;
-use Org\Mxchange\CoreFramework\Filesystem\Block\CalculatableBlock;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filesystem\File\BaseAbstractFile;
+use Org\Mxchange\CoreFramework\Filesystem\FilePointer;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+use Org\Mxchange\CoreFramework\Traits\Index\IndexableTrait;
+use Org\Mxchange\CoreFramework\Traits\Stack\StackableTrait;
// Import SPL stuff
+use \BadMethodCallException;
+use \InvalidArgumentException;
+use \LogicException;
+use \OutOfBoundsException;
use \SplFileInfo;
+use \UnexpectedValueException;
/**
* A general binary file class
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-abstract class BaseBinaryFile extends BaseAbstractFile {
- /**
- * Separator for header data
- */
- const SEPARATOR_HEADER_DATA = 0x01;
-
- /**
- * Separator header->entries
- */
- const SEPARATOR_HEADER_ENTRIES = 0x02;
-
- /**
- * Separator group->hash
- */
- const SEPARATOR_GROUP_HASH = 0x03;
-
- /**
- * Separator hash->value
- */
- const SEPARATOR_HASH_VALUE = 0x04;
-
- /**
- * Separator entry->entry
- */
- const SEPARATOR_ENTRIES = 0x05;
-
- /**
- * Separator type->position
- */
- const SEPARATOR_TYPE_POSITION = 0x06;
-
- /**
- * Length of count
- */
- const LENGTH_COUNT = 20;
-
- /**
- * Length of position
- */
- const LENGTH_POSITION = 20;
-
- /**
- * Length of group
- */
- const LENGTH_GROUP = 10;
+abstract class BaseBinaryFile extends BaseAbstractFile implements BinaryFile {
+ // Load traits
+ use StackableTrait;
+ use IndexableTrait;
/**
- * Maximum length of entry type
+ * Configuration cache
*/
- const LENGTH_TYPE = 20;
-
- //***** Array elements for 'gaps' array *****
-
- /**
- * Start of gap
- */
- const GAPS_INDEX_START = 'start';
-
- /**
- * End of gap
- */
- const GAPS_INDEX_END = 'end';
+ private static $configCache = [];
/**
* Current seek position
/**
* File header
*/
- private $header = array();
+ private $header = [];
/**
* Seek positions for gaps ("fragmentation")
*/
- private $gaps = array();
+ private $gaps = [];
/**
* Seek positions for damaged entries (e.g. mismatching hash sum, ...)
*/
- private $damagedEntries = array();
+ private $damagedEntries = [];
/**
* Back-buffer
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: className=%s - CALLED!', $className));
parent::__construct($className);
- // Init counters and gaps array
- $this->initCountersGapsArray();
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FRAMEWORK-DIRECTORY-POINTER: EXIT!');
}
/**
- * Checks whether the abstracted file only contains gaps by counting all
- * gaps' bytes together and compare it to total length.
+ * Setter for backBuffer field
*
- * @return $isGapsOnly Whether the abstracted file only contains gaps
+ * @param $backBuffer Characters to "store" in back-buffer
+ * @return void
*/
- private function isFileOnlyGaps () {
- // First/last gap found?
- /* Only for debugging
- if (isset($this->gaps[0])) {
- // Output first and last gap
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] this->gaps[0]=%s,this->gaps[%s]=%s', __METHOD__, __LINE__, print_r($this->gaps[0], true), (count($this->gaps) - 1), print_r($this->gaps[count($this->gaps) - 1], true)));
- } // END - if
- */
-
- // Now count every gap
- $gapsSize = 0;
- foreach ($this->gaps as $gap) {
- // Calculate size of found gap: end-start including both
- $gapsSize += ($gap[self::GAPS_INDEX_END] - $gap[self::GAPS_INDEX_START]);
- } // END - if
-
- // Debug output
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] gapsSize=%s,this->headerSize=%s', __METHOD__, __LINE__, $gapsSize, $this->getHeaderSize()));
-
- // Total gap size + header size must be same as file size
- $isGapsOnly = (($this->getHeaderSize() + $gapsSize) == $this->getFileSize());
+ private function setBackBuffer (string $backBuffer) {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Setting backBuffer(%d)=%s - CALLED!', strlen($backBuffer), $backBuffer));
+ $this->backBuffer = $backBuffer;
+ }
- // Return status
- return $isGapsOnly;
+ /**
+ * Getter for backBuffer field
+ *
+ * @return $backBuffer Characters "stored" in back-buffer
+ */
+ private function getBackBuffer () {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Getting this->backBuffer(%d)=%s - CALLED!', strlen($this->backBuffer), $this->backBuffer));
+ return $this->backBuffer;
}
/**
- * Initializes counter for valid entries, arrays for damaged entries and
- * an array for gap seek positions. If you call this method on your own,
- * please re-analyze the file structure. So you are better to call
- * analyzeFile() instead of this method.
+ * Setter for current field
*
+ * @param $current Characters to set a currently loaded block
* @return void
*/
- public function initCountersGapsArray () {
- // Init counter and seek position
- $this->setCounter(0);
- $this->setSeekPosition(0);
+ private function setCurrentBlock (string $currentBlock) {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Setting currentBlock(%d)=%s - CALLED!', strlen($currentBlock), $currentBlock));
+ $this->currentBlock = $currentBlock;
+ }
- // Init arrays
- $this->gaps = array();
- $this->damagedEntries = array();
+ /**
+ * Gets currently read data
+ *
+ * @return $current Currently read data
+ */
+ public function getCurrentBlock () {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Getting this->currentBlock(%d)=%s - CALLED!', strlen($this->currentBlock), $this->currentBlock));
+ return $this->currentBlock;
}
/**
* @return $totalEntries Size of file header
*/
public final function getHeaderSize () {
- // Get it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Getting this->headerSize=%d - CALLED!', $this->headerSize));
return $this->headerSize;
}
* @param $headerSize Size of file header
* @return void
*/
- public final function setHeaderSize ($headerSize) {
- // Set it
+ public final function setHeaderSize (int $headerSize) {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Setting headerSize=%d - CALLED!', $headerSize));
$this->headerSize = $headerSize;
}
* @return $seekPosition Current seek position (stored here in object)
*/
public final function getSeekPosition () {
- // Get it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Getting this->seekPosition=%d - CALLED!', $this->seekPosition));
return $this->seekPosition;
}
* @param $seekPosition Current seek position (stored here in object)
* @return void
*/
- protected final function setSeekPosition ($seekPosition) {
- // And set it
+ protected final function setSeekPosition (int $seekPosition) {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Setting seekPosition=%d - CALLED!', $seekPosition));
$this->seekPosition = $seekPosition;
}
/**
- * Updates seekPosition attribute from file to avoid to much access on file.
+ * Checks whether the abstracted file only contains gaps by counting all
+ * gaps' bytes together and compare it to total length.
*
+ * @return $isGapsOnly Whether the abstracted file only contains gaps
+ * @throws OutOfBoundsException If calculated file size is larger than actual
+ */
+ public function isFileGapsOnly () {
+ // Count every gap
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: CALLED!');
+ $gapsSize = 0;
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: this->gaps()=%d', count($this->gaps)));
+ foreach ($this->gaps as $gap) {
+ // Calculate size of found gap: end-start including both
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: gap[%s]=%d,ga[%s]=%d', BinaryFile::GAPS_INDEX_START, $gap[BinaryFile::GAPS_INDEX_START], BinaryFile::GAPS_INDEX_END, $gap[BinaryFile::GAPS_INDEX_END]));
+ $gapsSize += ($gap[BinaryFile::GAPS_INDEX_END] - $gap[BinaryFile::GAPS_INDEX_START]);
+
+ // Debug message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: gapsSize=%d', $gapsSize));
+ }
+
+ // Total gap size + header size + 1 must be same as file size
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: gapsSize=%d,this->headerSize=%d,this->fileSize=%d', $gapsSize, $this->getHeaderSize(), $this->getFileSize()));
+ $determinedFileSize = ($gapsSize + $this->getHeaderSize() + 1);
+
+ // Should not be more!
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: determinedFileSize=%d,this->fileSize=%d', $determinedFileSize, $this->getFileSize()));
+ if ($determinedFileSize > $this->getFileSize()) {
+ // Should not happen
+ throw new OutOfBoundsException(sprintf('determinedFileSize=%d is larger than this->fileSize=%d', $determinedFileSize, $this->getFileSize()));
+ }
+
+ // Is it same?
+ $isGapsOnly = ($determinedFileSize == $this->getFileSize());
+
+ // Return flag
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: isGapsOnly=%d - EXIT!', intval($isGapsOnly)));
+ return $isGapsOnly;
+ }
+
+ /**
+ * Marks whole file as gaps-only (freshly created file
+ *
+ * @param $type Type of file
+ * @param $minimumBlockLength Minimum block length
* @return void
*/
- public function updateSeekPosition () {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
+ private function markFileGapsOnly (string $type, int $minimumBlockLength) {
+ // Is config cache there?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: type=%s,minimumBlockLength=%d - CALLED!', $type, $minimumBlockLength));
+ if (!isset(self::$configCache[$type . '_pre_allocate_count'])) {
+ // Then set it
+ self::$configCache[$type . '_pre_allocate_count'] = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($type . '_pre_allocate_count');
+ }
- // Get key (= seek position)
- $seekPosition = $this->key();
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Setting seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
+ // Very simple to do ...
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: self:configCache[%s_pre_allocate_count]=%d', $type, self::$configCache[$type . '_pre_allocate_count']));
+ for ($idx = 0; $idx < self::$configCache[$type . '_pre_allocate_count']; $idx++) {
+ // Calculate start/end positions
+ $startPosition = $idx * $minimumBlockLength;
+ $endPosition = $idx * $minimumBlockLength + $minimumBlockLength;
- // And set it here
- $this->setSeekPosition($seekPosition);
+ // Mark start and end position as gap
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Invoking this->addGap(%d, %d) ...', $startPosition, $endPosition));
+ $this->addGap($startPosition, $endPosition);
+ }
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: EXIT!');
}
/**
- * Seeks to beginning of file, updates seek position in this object and
- * flushes the header.
+ * Adds a gap for given start and end position
*
+ * @param $startPosition Start seek position
+ * @param $endPosition End seek position
* @return void
*/
- protected function rewindUpdateSeekPosition () {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
+ private function addGap(int $startPosition, int $endPosition) {
+ // Push to gaps array
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: startPosition=%d,endPosition=%d - CALLED!', $startPosition, $endPosition));
+ array_push($this->gaps, [
+ BinaryFile::GAPS_INDEX_START => $startPosition,
+ BinaryFile::GAPS_INDEX_END => $endPosition,
+ ]);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: EXIT!');
+ }
- // flushFileHeader must be callable
- assert(is_callable(array($this, 'flushFileHeader')));
+ /**
+ * Initializes the back-buffer by setting it to an empty string.
+ *
+ * @return void
+ */
+ private function initBackBuffer () {
+ // Simply call the setter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: CALLED!');
+ $this->setBackBuffer('');
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: EXIT!');
+ }
+ /**
+ * Seeks to beginning of file, updates seek position in this object and
+ * flushes the header.
+ *
+ * @param $flushHeader Wether the file's header should be flushed (default: false)
+ * @return void
+ */
+ protected function rewindUpdateSeekPosition (bool $flushHeader = false) {
// Seek to beginning of file
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: flushHeader=%d - CALLED!', intval($flushHeader)));
$this->rewind();
// And update seek position ...
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->updateSeekPosition() ...');
$this->updateSeekPosition();
- // ... to write it back into the file
- $this->flushFileHeader();
+ // Flush headers?
+ if ($flushHeader) {
+ // ... to write it back into the file
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->flushFileHeader() ...');
+ $this->flushFileHeader();
+ }
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: EXIT!');
}
/**
* @return void
*/
protected function seekToOldPosition () {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
-
// Seek to currently ("old") saved position
- $this->seek($this->getSeekPosition());
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: CALLED!');
+ $this->seek($this->determineSeekPosition());
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: EXIT!');
}
/**
- * Checks whether the block separator has been found
+ * Initializes this file class
*
- * @param $str String to look in
- * @return $isFound Whether the block separator has been found
+ * @param $fileInfoInstance An instance of a SplFileInfo class
+ * @return void
*/
- public static function isBlockSeparatorFound ($str) {
- // Determine it
- $isFound = (strpos($str, chr(self::SEPARATOR_ENTRIES)) !== false);
+ protected function initFile (SplFileInfo $fileInfoInstance) {
+ // Get a file i/o pointer instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: fileInfoInstance[%s]=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance));
+ $pointerInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_output_class', array($fileInfoInstance));
- // Return result
- return $isFound;
+ // ... and set it here
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: Setting pointerInstance=%s ...', $pointerInstance->__toString()));
+ $this->setPointerInstance($pointerInstance);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: EXIT!');
}
/**
- * Initializes the back-buffer by setting it to an empty string.
+ * Marks the currently loaded block as empty (with length of the block)
*
+ * @param $length Length of the block
* @return void
+ * @throws InvalidArgumentException If a parameter is invalid
*/
- private function initBackBuffer () {
- // Simply call the setter
- $this->setBackBuffer('');
+ protected function markCurrentBlockAsEmpty (int $length) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: length=%d - CALLED!', $length));
+ if ($length < 1) {
+ // Length cannot below one
+ throw new InvalidArgumentException(sprintf('length=%d is not valid', $length), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Get current seek position
+ $currentPosition = $this->determineSeekPosition();
+
+ // Now add it as gap entry
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Invoking this->addGap(%d, %d) ..', ($currentPosition - $length), $currentPosition));
+ $this->addGap(($currentPosition - $length), $currentPosition);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: EXIT!');
}
/**
- * Setter for backBuffer field
+ * Initializes counter for valid entries, arrays for damaged entries and
+ * an array for gap seek positions. If you call this method on your own,
+ * please re-analyze the file structure. So you are better to call
+ * analyzeFileStructure() instead of this method.
*
- * @param $backBuffer Characters to "store" in back-buffer
* @return void
*/
- private function setBackBuffer ($backBuffer) {
- // Cast to string (so no arrays or objects)
- $backBuffer = (string) $backBuffer;
+ public function initCountersGapsArray () {
+ // Init counter and seek position to header size
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->determineSeekPosition() - CALLED!');
+ $seekPosition = $this->getSeekPosition();
- // ... and set it
- $this->backBuffer = $backBuffer;
- }
+ // Set counter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: seekPosition=%d', $seekPosition));
+ $this->setCounter(0);
- /**
- * Getter for backBuffer field
- *
- * @return $backBuffer Characters "stored" in back-buffer
- */
- private function getBackBuffer () {
- return $this->backBuffer;
+ // Get header size
+ $headerSize = $this->getHeaderSize();
+
+ // Set it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: Setting this->seekPosition=%d ...', $headerSize));
+ $this->setSeekPosition($headerSize);
+
+ // Init arrays
+ $this->gaps = [];
+ $this->damagedEntries = [];
+
+ // Seek back to old position
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Invoking this->seek(%d) ...', $seekPosition));
+ $this->seek($seekPosition);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: EXIT!');
}
/**
- * Setter for currentBlock field
+ * Updates seekPosition attribute from file to avoid to much access on file.
*
- * @param $currentBlock Characters to set a currently loaded block
* @return void
*/
- private function setCurrentBlock ($currentBlock) {
- // Cast to string (so no arrays or objects)
- $currentBlock = (string) $currentBlock;
+ public function updateSeekPosition () {
+ // Get key (= seek position)
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: CALLED!');
+ $seekPosition = $this->determineSeekPosition();
- // ... and set it
- $this->currentBlock = $currentBlock;
- }
+ // And set it here
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: seekPosition=%d', $seekPosition));
+ $this->setSeekPosition($seekPosition);
- /**
- * Gets currently read data
- *
- * @return $current Currently read data
- */
- public function getCurrentBlock () {
- // Return it
- return $this->currentBlock;
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: EXIT!');
}
/**
- * Initializes this file class
+ * Checks whether the block separator has been found
*
- * @param $infoInstance An instance of a SplFileInfo class
- * @return void
+ * @param $str String to look in
+ * @return $isFound Whether the block separator has been found
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- protected function initFile (SplFileInfo $infoInstance) {
- // Get a file i/o pointer instance
- $pointerInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_output_class', array($infoInstance));
+ public static function isBlockSeparatorFound (string $str) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: str=%s - CALLED!', $str));
+ if (empty($str)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "str" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
- // ... and set it here
- $this->setPointerInstance($pointerInstance);
+ // Determine it
+ $isFound = (strpos($str, chr(BinaryFile::SEPARATOR_ENTRIES)) !== false);
+
+ // Return result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: isFound=%d - EXIT!', intval($isFound)));
+ return $isFound;
}
/**
* @param $data Data to be written
* @param $flushHeader Whether to flush the header (default: flush)
* @return void
+ * @throws OutOfBoundsException If the position is not seekable
+ * @throws InvalidArgumentException If a parameter is invalid
*/
- public function writeData ($seekPosition, $data, $flushHeader = true) {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data()=%d - CALLED!', __METHOD__, __LINE__, $seekPosition, strlen($data)));
+ public function writeData (int $seekPosition, string $data, bool $flushHeader = true) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: seekPosition=%s,data()=%d,flushHeader=%d - CALLED!', $seekPosition, strlen($data), intval($flushHeader)));
+ if ($seekPosition < 0) {
+ // Invalid seek position
+ throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid', $seekPosition));
+ } elseif (empty($data)) {
+ // Empty data is invalid, too
+ throw new InvalidArgumentException('Parameter "data" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Write data at given position
- $this->getPointerInstance()->writeAtPosition($seekPosition, $data);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Invoking this->writeAtPosition(%d,%s) ...', $seekPosition, $data));
+ $this->writeAtPosition($seekPosition, $data);
// Increment counter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->incrementCounter() ...');
$this->incrementCounter();
// Update seek position
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->updateSeekPosition() ...');
$this->updateSeekPosition();
// Flush the header?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: flushHeader=%d', intval($flushHeader)));
if ($flushHeader === true) {
// Flush header
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->flushFileHeader() ...');
$this->flushFileHeader();
// Seek to old position
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->seekToOldPosition() ...');
$this->seekToOldPosition();
- } // END - if
+ }
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: EXIT!');
}
/**
- * Marks the currently loaded block as empty (with length of the block)
+ * Writes at given position by seeking to it.
*
- * @param $length Length of the block
- * @return void
+ * @param $seekPosition Seek position in file
+ * @param $dataStream Data to be written
+ * @return mixed Number of writes bytes or false on error
+ * @throws OutOfBoundsException If the position is not seekable
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- protected function markCurrentBlockAsEmpty ($length) {
- // Get current seek position
- $currentPosition = $this->key();
+ public function writeAtPosition (int $seekPosition, string $dataStream) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: seekPosition=%d,dataStream(%d)=%s - CALLED!', $seekPosition, strlen($dataStream), $dataStream));
+ if ($seekPosition < 0) {
+ // Invalid seek position
+ throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid.', $seekPosition));
+ } elseif (empty($dataStream)) {
+ // Empty dataStream
+ throw new InvalidArgumentException('Parameter "dataStream" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
- // Now add it as gap entry
- array_push($this->gaps, array(
- self::GAPS_INDEX_START => ($currentPosition - $length),
- self::GAPS_INDEX_END => $currentPosition,
- ));
+ // Call pointer's method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Invoking this->pointerInstance->writeAtPosition(%d, %s) ...', $seekPosition, $dataStream));
+ $status = $this->getPointerInstance()->writeAtPosition($seekPosition, $dataStream);
+
+ // Return status
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: status[%s]=%d - EXIT!', gettype($status), $status));
+ return $status;
}
/**
* @return $isInitialized Whether the file header is initialized
*/
public function isFileHeaderInitialized () {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
-
// Default is not initialized
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: CALLED!');
$isInitialized = false;
// Is the file initialized?
if ($this->isFileInitialized()) {
// Some bytes has been written, so rewind to start of it.
- $rewindStatus = $this->rewind();
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] rewindStatus=%s', __METHOD__, __LINE__, $rewindStatus));
-
- // Is the rewind() call successfull?
- if ($rewindStatus != 1) {
- // Something bad happened
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Could not rewind().', __METHOD__, __LINE__));
- } // END - if
+ $this->rewind();
// Read file header
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->readFileHeader() ...');
$this->readFileHeader();
+ // Get header count
+ $headerCount = count($this->getHeader());
+
// The above method does already check the header
- $isInitialized = true;
- } // END - if
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: headerCount=%d', $headerCount));
+ $isInitialized = ($headerCount > 0);
+ }
// Return result
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: isInitialized=%d - EXIT!', intval($isInitialized)));
return $isInitialized;
}
* Checks whether the assigned file has been initialized
*
* @return $isInitialized Whether the file's size is zero
+ * @throws UnexpectedValueException If an unexpected value was returned
*/
public function isFileInitialized () {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
-
// Get it from iterator which holds the pointer instance. If false is returned
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: CALLED!');
$fileSize = $this->size();
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] fileSize=%s', __METHOD__, __LINE__, $fileSize));
/*
* The returned file size should not be false or NULL as this means
* that the pointer class does not work correctly.
*/
- assert(is_int($fileSize));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: fileSize[%s]=%d', gettype($fileSize), $fileSize));
+ if (!is_int($fileSize)) {
+ // Bad file?
+ throw new UnexpectedValueException(sprintf('fileSize[]=%s is unexpected', gettype($fileSize)), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// Is more than 0 returned?
$isInitialized = ($fileSize > 0);
// Return result
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] isInitialized=%d - EXIT!', __METHOD__, __LINE__, intval($isInitialized)));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: isInitialized=%d - EXIT!', intval($isInitialized)));
return $isInitialized;
}
* Creates the assigned file
*
* @return void
+ * @throws BadMethodCallException If this file's header is already initialized
*/
public function createFileHeader () {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
-
// The file's header should not be initialized here
- assert(!$this->isFileHeaderInitialized());
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: CALLED!');
+ if ($this->isFileHeaderInitialized()) {
+ // Bad method call
+ //* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this=%s', __METHOD__, __LINE__, print_r($this, TRUE)));
+ throw new BadMethodCallException('File header is already initialized but method called', FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Simple flush file header which will create it.
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->flushFileHeader() ...');
$this->flushFileHeader();
// Rewind seek position (to beginning of file) and update/flush file header
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->rewindUpdateSeekPosition() ...');
$this->rewindUpdateSeekPosition();
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
- }
-
- /**
- * Pre-allocates file (if enabled) with some space for later faster write access.
- *
- * @param $type Type of the file
- * @return void
- */
- public function preAllocateFile ($type) {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
-
- // Is it enabled?
- if ($this->getConfigInstance()->getConfigEntry($type . '_pre_allocate_enabled') != 'Y') {
- // Not enabled
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Not pre-allocating file.', __METHOD__, __LINE__));
-
- // Don't continue here.
- return;
- } // END - if
-
- // Message to user
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Pre-allocating file ...', __METHOD__, __LINE__));
-
- // Calculate minimum length for one entry
- $minLengthEntry = $this->getBlockInstance()->calculateMinimumBlockLength();
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] minLengthEntry=%s', __METHOD__, __LINE__, $minLengthEntry));
-
- // Calulcate seek position
- $seekPosition = $minLengthEntry * $this->getConfigInstance()->getConfigEntry($type . '_pre_allocate_count');
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s', __METHOD__, __LINE__, $seekPosition));
-
- // Now simply write a NUL there. This will pre-allocate the file.
- $this->writeData($seekPosition, chr(0));
-
- // Rewind seek position (to beginning of file) and update/flush file header
- $this->rewindUpdateSeekPosition();
-
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: EXIT!');
}
/**
*/
public function determineSeekPosition () {
// Call pointer instance
- return $this->getPointerInstance()->determineSeekPosition();
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: CALLED!');
+ $seekPosition = $this->getPointerInstance()->determineSeekPosition();
+
+ // Return position
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: seekPosition=%d - EXIT!', $seekPosition));
+ return $seekPosition;
}
/**
* @param $offset Offset to seek to (or used as "base" for other seeks)
* @param $whence Added to offset (default: only use offset to seek to)
* @return $status Status of file seek: 0 = success, -1 = failed
+ * @throws OutOfBoundsException If the position is not seekable
*/
- public function seek ($offset, $whence = SEEK_SET) {
+ public function seek (int $offset, int $whence = SEEK_SET) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: offset=%d,whence=%d - CALLED!', $offset, $whence));
+ if ($offset < 0) {
+ // No offset is smaller than zero
+ throw new OutOfBoundsException(sprintf('offset=%d is not valid', $offset));
+ }
+
// Call pointer instance
- return $this->getPointerInstance()->seek($offset, $whence);
+ $status = $this->getPointerInstance()->seek($offset, $whence);
+
+ // Return status
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: status[%s]=%d - EXIT!', gettype($status), $status));
+ return $status;
}
/**
*
* @param $bytes Amount of bytes to read
* @return $data Data read from file
+ * @throws OutOfBoundsException If the position is not seekable
*/
- public function read ($bytes = NULL) {
- // $bytes shall be integer
- assert(is_int($bytes));
+ public function read (int $bytes = 0) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: bytes=%d - CALLED!', $bytes));
+ if ($bytes < 0) {
+ // Throw exception
+ throw new OutOfBoundsException(sprintf('bytes=%d is not valid', $bytes));
+ }
// Call pointer instance
- return $this->getPointerInstance()->read($bytes);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Invoking this->pointerInstance->read(%d) ...', $bytes));
+ $data = $this->getPointerInstance()->read($bytes);
+
+ // Update seek position
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->updateSeekPosition() ...');
+ $this->updateSeekPosition();
+
+ // Return data
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: data[%s]=%s - EXIT!', gettype($data), $data));
+ return $data;
}
/**
* Rewinds to the beginning of the file
*
- * @return $status Status of this operation
+ * @return void
*/
public function rewind () {
// Call pointer instance
- return $this->getPointerInstance()->rewind();
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: CALLED!');
+ $this->getPointerInstance()->rewind();
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: EXIT!');
}
/**
* only gaps are found, the file is considered as "virgin" (no entries).
*
* @return void
+ * @throws BadMethodCallException If this method is called but file is not initialized
*/
- public function analyzeFile () {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
-
+ public function analyzeFileStructure () {
// Make sure the file is initialized
- assert($this->isFileInitialized());
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: CALLED!');
+ if (!$this->isFileInitialized()) {
+ // Bad method call
+ throw new BadMethodCallException('Method called but file is not initialized.', FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Init counters and gaps array
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->initCounterGapsArrays() ...');
$this->initCountersGapsArray();
// Output message (as this may take some time)
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Analyzing file structure ... (this may take some time)', __METHOD__, __LINE__));
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('Analyzing file structure ... (this may take some time)'));
- // First rewind to the begining
- $this->rewind();
+ // First Seek to right after file header
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Invoking this->seek(%d) ...', $this->getHeaderSize() + 1));
+ $this->seek($this->getHeaderSize() + 1);
// Then try to load all entries
- while ($this->valid()) {
- // Go to next entry
- $this->next();
-
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: this->seekPosition=%d, looping through file ...', $this->getSeekPosition()));
+ while ($this->isValid()) {
// Get current entry
$current = $this->getCurrentBlock();
+ // Go to next entry
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: current=%s, Invoking this->readNextBlock() ...', $current));
+ $this->readNextBlock();
+
/*
* If the block is empty, maybe the whole file is? This could mean
* that the file has been pre-allocated.
*/
- if (empty($current)) {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: current(%d)[]=%s', strlen($current), gettype($current)));
+ if (empty(trim($current, chr(0)))) {
// Then skip this part
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: current[]=%s is empty - CONTINUE!', gettype($current)));
continue;
- } // END - if
+ }
- // Debug message
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] current()=%d', __METHOD__, __LINE__, strlen($current)));
- } // END - while
+ // Handle current record
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: current(%d)[%s]=%s', strlen($current), gettype($current), $current));
+ }
// If the last read block is empty, check gaps
- if (empty($current)) {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: current()=%d', strlen($current)));
+ if (empty(trim($current, chr(0)))) {
// Output message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Found a total of %s gaps.', __METHOD__, __LINE__, count($this->gaps)));
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: Found a total of %d gaps.', count($this->gaps)));
// Check gaps, if the whole file is empty.
- if ($this->isFileOnlyGaps()) {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->isFileGapsOnly() ...');
+ if ($this->isFileGapsOnly()) {
// Only gaps, so don't continue here.
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('BASE-BINARY-FILE: File is gaps-only - EXIT!');
return;
- } // END - if
+ }
+ }
- /*
- * The above call has calculated a total size of all gaps. If the
- * percentage of gaps passes a "soft" limit and last
- * defragmentation is to far in the past, or if a "hard" limit has
- * reached, run defragmentation.
- */
- if ($this->isDefragmentationNeeded()) {
- // Run "defragmentation"
- $this->doRunDefragmentation();
- } // END - if
- } // END - if
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
+ /*
+ * The above call has calculated a total size of all gaps. If the
+ * percentage of gaps passes a "soft" limit and last
+ * defragmentation is to far in the past, or if a "hard" limit has
+ * reached, run defragmentation.
+ */
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->isDefragmentationNeeded() ...');
+ if ($this->isDefragmentationNeeded()) {
+ // Run "defragmentation"
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->doRunDefragmentation() ...');
+ $this->doRunDefragmentation();
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: EXIT!');
}
/**
- * Advances to next "block" of bytes
+ * Reads next "block" of given bytes into $currentBlock field. THis method
+ * loads the whole file into memory when the file is just freshly
+ * initialized (only zeros in it).
*
* @return void
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- public function next () {
- // Is there nothing to read?
- if (!$this->valid()) {
- // Nothing to read
- return;
- } // END - if
-
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d] key()=%d', __FUNCTION__, __LINE__, $this->key()));
-
- // Make sure the block instance is set
- assert($this->getBlockInstance() instanceof CalculatableBlock);
-
- // First calculate minimum block length
- $length = $this->getBlockInstance()->calculateMinimumBlockLength();
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d] length=%s', __FUNCTION__, __LINE__, $length));
-
- // Short be more than zero!
- assert($length > 0);
+ protected function readNextBlockByLength (int $length) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: this->seekPosition=%d,length=%d - CALLED!', $this->getSeekPosition(), $length));
+ if ($length < 1) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('length=%d is not valid', $length), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Read possibly back-buffered bytes from previous call of next().
$data = $this->getBackBuffer();
* "block" may not fit, so this loop will continue until the EOB or EOF
* has been reached whatever comes first.
*/
- while ((!$this->isEndOfFileReached()) && (!self::isBlockSeparatorFound($data))) {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: this->seekPosition=%d,data()=%d', $this->getSeekPosition(), strlen($data)));
+ while ((!$this->isEndOfFileReached()) && (empty($data) || !self::isBlockSeparatorFound($data))) {
// Then read the next possible block
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: this->seekPosition=%d, Invoking this->read(%d) ...', $this->getSeekPosition(), $length));
$block = $this->read($length);
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d] block()=%d,length=%s', __FUNCTION__, __LINE__, strlen($block), $length));
-
- // Is it all empty?
- if (strlen(trim($block)) == 0) {
- // Mark this block as empty
- $this->markCurrentBlockAsEmpty(strlen($block));
-
- // Skip to next block
- continue;
- } // END - if
+ // Is the block empty?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: block()=%d,length=%d', strlen($block), $length));
+ if (strlen($block) == 0) {
+ // Read empty block, maybe EOF
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: this->seekPosition=%d, block is empty, maybe EOF reached - BREAK!', $this->getSeekPosition()));
+ break;
+ } elseif (empty(trim($block, chr(0)))) {
+ // Mark it as empty
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: this->seekPosition=%d, Invoking this->markCurrentBlockAsEmpty(%d) ...', $this->getSeekPosition(), $length));
+ $this->markCurrentBlockAsEmpty($length);
+ }
// At this block then
$data .= $block;
- // A debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d] data()=%d', __FUNCTION__, __LINE__, strlen($data)));
- } // END - while
-
- // EOF reached?
- if ($this->isEndOfFileReached()) {
- // Set whole data as current read block
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Calling setCurrentBlock(' . strlen($data) . ') ...');
- $this->setCurrentBlock($data);
-
- // Then abort here silently
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('EOF reached.');
- return;
- } // END - if
+ // Debug message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: this->seekPosition=%d,data()=%d', $this->getSeekPosition(), strlen($data)));
+ }
/*
* Init back-buffer which is the data that has been found beyond the
* separator.
*/
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->initBackBuffer(), clearing this->currentBlock ...');
$this->initBackBuffer();
+ $this->setCurrentBlock('');
- // Separate data
- $dataArray = explode(chr(self::SEPARATOR_ENTRIES), $data);
+ // Is $data empty?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: data(%d)=%s', strlen($data), $data));
+ if (empty(trim($data, chr(0)))) {
+ // Yes, maybe whole file was ...
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: this->seekPosition=%d, maybe empty file found - EXIT!', $this->getSeekPosition()));
+ return;
+ }
- // This array must contain two elements
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('dataArray=' . print_r($dataArray, true));
- assert(count($dataArray) == 2);
+ // Separate data
+ $dataArray = explode(chr(BinaryFile::SEPARATOR_ENTRIES), $data);
- // Left part is the actual block, right one the back-buffer data
+ // Left part is the actual block, right one the back-buffer data, if found
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: dataArray()=%d', count($dataArray)));
+ //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: dataArray=%s', print_r($dataArray, true)));
$this->setCurrentBlock($dataArray[0]);
- $this->setBackBuffer($dataArray[1]);
+
+ // Is back buffere data found?
+ if (isset($dataArray[1]) && !empty(trim($dataArray[1], chr(0)))) {
+ // Set back buffer
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: Setting this->backBuffer=%s ...', $dataArray[1]));
+ $this->setBackBuffer($dataArray[1]);
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: EXIT!');
+ }
+
+ /**
+ * Pre-allocates file (if enabled) with some space for later faster write access.
+ *
+ * @param $type Type of the file
+ * @return void
+ * @throws InvalidArgumentException If a parameter is empty
+ */
+ protected function preAllocateFileByTypeLength (string $type, int $minimumBlockLength) {
+ // Is it enabled?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: type=%s,minimumBlockLength=%d - CALLED!', $type, $minimumBlockLength));
+ if (empty($type)) {
+ // Empty type
+ throw new InvalidArgumentException('Parameter "type" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($minimumBlockLength < 1) {
+ // Invalid block length
+ throw new InvalidArgumentException(sprintf('Parameter minimumBlockLength=%d is not valid', $minimumBlockLength), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!FrameworkBootstrap::getConfigurationInstance()->isEnabled($type . '_pre_allocate')) {
+ // Don't continue here.
+ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Not pre-allocating file. - EXIT!');
+ return;
+ }
+
+ // Get file size
+ $fileSize = $this->getFileSize();
+
+ // Calulcate seek position
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: minimumBlockLength=%d,fileSize=%d', $minimumBlockLength, $fileSize));
+ $seekPosition = $this->getHeaderSize() + $minimumBlockLength * FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($type . '_pre_allocate_count') + $fileSize ;
+
+ // Now simply write a NUL there. This will pre-allocate the file.
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Invoking this->writeAtPosition(%d,NUL) ...', $seekPosition));
+ $this->writeAtPosition($seekPosition, chr(0));
+
+ // Is the seek position zero?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: fileSize=%d', $fileSize));
+ if ($fileSize == 0) {
+ // Mark file as gaps-only
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: Invoking this->markGapsOnly(%s,%d) ...', $type, $minimumBlockLength));
+ $this->markFileGapsOnly($type, $minimumBlockLength);
+ } else {
+ // Analyze file structure
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->analyzeFileStructure() ...');
+ $this->analyzeFileStructure();
+ }
+
+ // Rewind seek position
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: Invoking this->rewind() ...');
+ $this->rewind();
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-BINARY-FILE: EXIT!');
}
/**
* This method will return true if an emptied (nulled) entry has been found.
*
* @return $isValid Whether the next entry is valid
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- public function valid () {
- // Make sure the block instance is set
- assert($this->getBlockInstance() instanceof Block);
-
- // First calculate minimum block length
- $length = $this->getBlockInstance()->calculateMinimumBlockLength();
-
- // Short be more than zero!
- assert($length > 0);
+ protected function isValidByLength (int $length) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: length=%d - CALLED!', $length));
+ if ($length < 1) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('Parameter length=%d is not valid', $length), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Get current seek position
- $seekPosition = $this->key();
+ $seekPosition = $this->determineSeekPosition();
// Then try to read it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: seekPosition=%d', $seekPosition));
$data = $this->read($length);
// If some bytes could be read, all is fine
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: data[%s]()=%d', gettype($data), strlen($data)));
$isValid = ((is_string($data)) && (strlen($data) > 0));
// Get header size
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: isValid=%d', intval($isValid)));
$headerSize = $this->getHeaderSize();
// Is the seek position at or beyond the header?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-BINARY-FILE: seekPosition=%d,headerSize=%d', $seekPosition, $headerSize));
if ($seekPosition >= $headerSize) {
// Seek back to old position
- $this->seek($seekPosition);
+ $isValid = ($isValid && $this->seek($seekPosition) === 0);
} else {
// Seek directly behind the header
- $this->seek($headerSize);
+ $isValid = ($isValid && $this->seek($headerSize) === 0);
}
// Return result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: isValid=%d - EXIT!', intval($isValid)));
return $isValid;
}
/**
- * Gets current seek position ("key").
- *
- * @return $key Current key in iteration
- */
- public function key () {
- // Call pointer instance
- return $this->getPointerInstance()->determineSeekPosition();
- }
-
- /**
- * Reads the file header
+ * Reads next "block" of bytes into $currentBlock field. THis method loads
+ * the whole file into memory when the file is just freshly initialized
+ * (only zeros in it).
*
* @return void
*/
- public function readFileHeader () {
- // Make sure the block instance is set
- assert($this->getBlockInstance() instanceof Block);
-
- // Call block instance
- $this->getBlockInstance()->readFileHeader();
- }
+ protected abstract function readNextBlock ();
/**
- * Flushes the file header
+ * Reads the file header
*
* @return void
+ * @throws LogicException If both instances are not set
*/
- public function flushFileHeader () {
- // Make sure the block instance is set
- assert($this->getBlockInstance() instanceof Block);
-
- // Call block instance
- $this->getBlockInstance()->flushFileHeader();
- }
+ public abstract function readFileHeader ();
/**
* Searches for next suitable gap the given length of data can fit in
*
* @param $length Length of raw data
* @return $seekPosition Found next gap's seek position
+ * @throws InvalidArgumentException If the parameter is not valid
*/
- public function searchNextGap ($length) {
+ public function searchNextGap (int $length) {
// If the file is only gaps, no need to seek
- if ($this->isFileOnlyGaps()) {
- // The first empty block is the first one right after the header
- return ($this->getHeaderSize() + 1);
- } // END - if
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: length=%d - CALLED!', $length));
+ if ($length <= 0) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('length=%d is not valid', $length), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($this->isFileGapsOnly()) {
+ /*
+ * The first empty block is the 2nd one right after the header, so
+ * one byte gap to the header.
+ */
+ $seekPosition = ($this->getHeaderSize() + 2);
+
+ // Return position
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-BINARY-FILE: seekPosition=%d - EXIT!', $seekPosition));
+ return $seekPosition;
+ }
// @TODO Unfinished
- $this->partialStub('length=' . $length);
+ DebugMiddleware::getSelfInstance()->partialStub('length=' . $length);
}
}
namespace Org\Mxchange\CoreFramework\Filesystem\Index;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Filesystem\Block;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
+use Org\Mxchange\CoreFramework\Filesystem\Index\IndexableFile;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
+use Org\Mxchange\CoreFramework\Index\Indexable;
+use Org\Mxchange\CoreFramework\Utils\Crypto\CryptoUtils;
// Import SPL stuff
+use \BadMethodCallException;
+use \InvalidArgumentException;
use \SplFileInfo;
/**
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* 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 IndexFile extends BaseBinaryFile implements Block {
+class IndexFile extends BaseBinaryFile implements IndexableFile {
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* Creates an instance of this File class and prepares it for usage
*
* @param $fileInfoInstance An instance of a SplFileInfo class
- * @param $blockInstance An instance of a Block class
- * @return $fileInstance An instance of this File class
+ * @param $indexInstance An instance of a Indexable class
+ * @return $indexFileInstance An instance of an IndexableFile class
*/
- public final static function createIndexFile (SplFileInfo $fileInfoInstance, Block $blockInstance) {
+ public final static function createIndexFile (SplFileInfo $fileInfoInstance, Indexable $indexInstance) {
// Get a new instance
- $fileInstance = new IndexFile();
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('INDEX-FILE: fileInfoInstance[%s]=%s,indexInstance=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance, $indexInstance->__toString()));
+ $indexFileInstance = new IndexFile();
- // Set block instance here for callbacks
- $fileInstance->setBlockInstance($blockInstance);
+ // Set file instance here for callbacks
+ $indexFileInstance->setIndexInstance($indexInstance);
+
+ // Expand file name with .idx
+ $indexInfoInstance = new SplFileInfo(sprintf('%s.idx', $fileInfoInstance->__toString()));
// Init this abstract file
- $fileInstance->initFile($fileInfoInstance);
+ $indexFileInstance->initFile($indexInfoInstance);
+
+ // Init counters and gaps array
+ $indexFileInstance->initCountersGapsArray();
// Return the prepared instance
- return $fileInstance;
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('INDEX-FILE: indexFileInstance=%s - EXIT!', $indexFileInstance->__toString()));
+ return $indexFileInstance;
+ }
+
+ /**
+ * Flushes the file header
+ *
+ * @return void
+ * @throws BadMethodCallException If this->indexInstance is not properly set
+ */
+ public function flushFileHeader () {
+ // Validate call
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('INDEX-FILE: CALLED!');
+ if (!($this->getIndexInstance() instanceof Indexable)) {
+ // Index instance not set
+ throw new BadMethodCallException('this->indexInstance[] is not properly set.');
+ }
+
+ // Call block instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('INDEX-FILE: Invoking this->indexInstance->flushFileHeader() ...');
+ $this->getIndexInstance()->flushFileHeader();
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('INDEX-FILE: EXIT!');
+ }
+
+ /**
+ * Pre-allocates file (if enabled) with some space for later faster write access.
+ *
+ * @param $type Type of the file
+ * @return void
+ * @throws InvalidArgumentException If a parameter is empty
+ * @throws BadMethodCallException If this->indexInstance is not properly set
+ */
+ public function preAllocateFile (string $type) {
+ // Is it enabled?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('INDEX-FILE: type=%s - CALLED!', $type));
+ if (empty($type)) {
+ // Empty type
+ throw new InvalidArgumentException('Parameter "type" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!($this->getIndexInstance() instanceof Indexable)) {
+ // Index instance not set
+ throw new BadMethodCallException('this->indexInstance[] is not properly set.');
+ }
+
+ // Message to user
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('INDEX-FILE: Pre-allocating file ...');
+
+ // Calculate minimum block length
+ $minimumBlockLength = $this->getIndexInstance()->calculateMinimumBlockLength();
+
+ // Call protected method
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('INDEX-FILE: Invoking this->preAllocateFileByTypeLength(%s,%d) ...', $type, $minimumBlockLength));
+ $this->preAllocateFileByTypeLength($type, $minimumBlockLength);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('INDEX-FILE: EXIT!');
+ }
+
+ /**
+ * Checks wether the current entry is valid (not at the end of the file).
+ * This method will return true if an emptied (nulled) entry has been found.
+ *
+ * @return $isValid Whether the next entry is valid
+ * @throws BadMethodCallException If this->indexInstance is not properly set
+ */
+ public function isValid () {
+ // Validate call
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('INDEX-FILE: CALLED!');
+ if (!($this->getIndexInstance() instanceof Indexable)) {
+ // Index instance not set
+ throw new BadMethodCallException('this->indexInstance[] is not properly set.');
+ }
+
+ // Get length from index
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('INDEX-FILE: Invoking this->indexInstance->calculateMinimumBlockLength() ...');
+ $length = $this->getIndexInstance()->calculateMinimumBlockLength();
+
+ // Call protected method
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('INDEX-FILE: Invoking this->isValidByLength(%d) ...', $length));
+ $isValid = $this->isValidByLength($length);
+
+ // Return result
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('INDEX-FILE: isValid=%d - EXIT!', intval($isValid)));
+ return $isValid;
+ }
+
+ /**
+ * Reads next "block" of bytes into $currentBlock field. THis method loads
+ * the whole file into memory when the file is just freshly initialized
+ * (only zeros in it).
+ *
+ * @return void
+ */
+ protected function readNextBlock () {
+ // First calculate minimum block length
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('INDEX-FILE: this->seekPosition=%d - CALLED!', $this->getSeekPosition()));
+ $length = $this->getIndexInstance()->calculateMinimumBlockLength();
+
+ // Call protected method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('INDEX-FILE: Invoking parent::readNextBlockByLength(%d) ...', $length));
+ parent::readNextBlockByLength($length);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('INDEX-FILE: EXIT!');
+ }
+
+ /**
+ * Reads the file header
+ *
+ * @return void
+ */
+ public function readFileHeader () {
+ // Call index class' method
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('INDEX-FILE: Invoking this->indexInstance->readIndexHeader() - CALLED!');
+ $this->getIndexInstance()->readIndexHeader();
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('INDEX-FILE: EXIT!');
}
/**
* Writes given value to the file and returns a hash and gap position for it
*
- * @param $groupId Group identifier
+ * @param $stackName Group identifier
* @param $value Value to be added to the stack
* @return $data Hash and gap position
- * @throws UnsupportedOperationException If this method is called
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If this->indexInstance is not properly set
*/
- public function writeValueToFile ($groupId, $value) {
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',value[' . gettype($value) . ']=' . print_r($value, true));
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ public function writeValueToFile (string $stackName, $value) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('INDEX-FILE: stackName=%s,value[]=%s - CALLED!', $stackName, gettype($value)));
+ if (empty($stackName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "stackName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (is_object($value) || is_resource($value)) {
+ // Not wanted here
+ throw new InvalidArgumentException(sprintf('value[]=%s is not stackable in files', gettype($value)));
+ } elseif (!($this->getIndexInstance() instanceof Indexable)) {
+ // Index instance not set
+ throw new BadMethodCallException('this->indexInstance[] is not properly set.');
+ }
+
+ // Encode/convert the value into a "binary format"
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('INDEX-FILE: Invoking StringUtils::encodeData(value[]=%s) ...', gettype($value)));
+ $encoded = StringUtils::encodeData($value);
+
+ // Get a strong hash for the "encoded" data
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('INDEX-FILE: encoded(%d)=%s', strlen($encoded), $encoded));
+ $hash = CryptoUtils::hash($encoded);
+
+ // Then write it to the next free gap
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('INDEX-FILE: hash=%s', $hash));
+ $data = $this->getIndexInstance()->writeDataToFreeGap($stackName, $hash, $encoded);
+
+ // Return info
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('INDEX-FILE: data[]=%s - EXIT!', gettype($data)));
+ return $data;
}
/**
* Writes given raw data to the file and returns a gap position and length
*
- * @param $groupId Group identifier
+ * @param $stackName Group identifier
* @param $hash Hash from encoded value
* @param $encoded Encoded value to be written to the file
* @return $data Gap position and length of the raw data
* @throws UnsupportedOperationException If this method is called
*/
- public function writeDataToFreeGap ($groupId, $hash, $encoded) {
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',encoded()=' . strlen($encoded));
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ public function writeDataToFreeGap (string $stackName, string $hash, string $encoded) {
+ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('INDEX-FILE: stackName=' . $stackName . ',hash=' . $hash . ',encoded()=' . strlen($encoded));
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
}
<?php
// Own namespace
-namespace Org\Mxchange\CoreFramework\Filesystem\Stack;
+namespace Org\Mxchange\CoreFramework\Stack\File;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Filesystem\Block;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Filesystem\Stack\FileStacker;
use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
+use Org\Mxchange\CoreFramework\Stack\File\StackableFile;
+use Org\Mxchange\CoreFramework\Utils\Crypto\CryptoUtils;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
// Import SPL stuff
+use \BadMethodCallException;
+use \InvalidArgumentException;
use \SplFileInfo;
/**
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* 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 StackFile extends BaseBinaryFile implements Block {
+class StackFile extends BaseBinaryFile implements FileStacker {
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* Creates an instance of this File class and prepares it for usage
*
* @param $infoInstance An instance of a SplFileInfo class
- * @param $blockInstance An instance of a Block class
- * @return $fileInstance An instance of this File class
+ * @param $stackInstance An instance of a StackableFile class
+ * @return $stackFileInstance An instance of this File class
*/
- public final static function createStackFile (SplFileInfo $infoInstance, Block $blockInstance) {
+ public final static function createStackFile (SplFileInfo $infoInstance, StackableFile $stackInstance) {
// Get a new instance
- $fileInstance = new StackFile();
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: infoInstance[%s]=%s,stackInstance=%s - CALLED!', get_class($infoInstance), $infoInstance, $stackInstance->__toString()));
+ $stackFileInstance = new StackFile();
- // Set block instance here for callbacks
- $fileInstance->setBlockInstance($blockInstance);
+ // Set stack instance here for callbacks
+ $stackFileInstance->setStackInstance($stackInstance);
// Init this abstract file
- $fileInstance->initFile($infoInstance);
+ $stackFileInstance->initFile($infoInstance);
+
+ // Init counters and gaps array
+ $stackFileInstance->initCountersGapsArray();
// Return the prepared instance
- return $fileInstance;
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: stackFileInstance=%s - EXIT!', $stackFileInstance->__toString()));
+ return $stackFileInstance;
+ }
+
+ /**
+ * Flushes the file header
+ *
+ * @return void
+ * @throws BadMethodCallException If this->stackInstance is not properly set
+ */
+ public function flushFileHeader () {
+ // Validate call
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: CALLED!');
+ if (!($this->getStackInstance() instanceof StackableFIle)) {
+ // Index instance not set
+ throw new BadMethodCallException('this->stackInstance[] is not properly set.');
+ }
+
+ // Call block instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: Invoking this->indexInstance->flushFileHeader() ...');
+ $this->getStackInstance()->flushFileHeader();
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: EXIT!');
+ }
+
+ /**
+ * Pre-allocates file (if enabled) with some space for later faster write access.
+ *
+ * @param $type Type of the file
+ * @return void
+ * @throws InvalidArgumentException If a parameter is empty
+ * @throws BadMethodCallException If this->stackInstance is not properly set
+ */
+ public function preAllocateFile (string $type) {
+ // Is it enabled?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: type=%s - CALLED!', $type));
+ if (empty($type)) {
+ // Empty type
+ throw new InvalidArgumentException('Parameter "type" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!($this->getStackInstance() instanceof StackableFile) && !($this->getStackInstance() instanceof StackableFile)) {
+ // Index instance not set
+ throw new BadMethodCallException('this->stackInstance[] and this->pointerInstance are not properly set.');
+ }
+
+ // Message to user
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('STACK-FILE: Pre-allocating file ...');
+
+ // Calculate minimum block length and get file size
+ $minimumBlockLength = $this->getStackInstance()->calculateMinimumBlockLength();
+
+ // Call protected method
+ $this->preAllocateFileByTypeLength($type, $minimumBlockLength);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: EXIT!');
+ }
+
+ /**
+ * Checks wether the current entry is valid (not at the end of the file).
+ * This method will return true if an emptied (nulled) entry has been found.
+ *
+ * @return $isValid Whether the next entry is valid
+ * @throws BadMethodCallException If this->stackInstance is not properly set
+ */
+ public function isValid () {
+ // Validate call
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: CALLED!');
+ if (!($this->getStackInstance() instanceof StackableFile)) {
+ // Index instance not set
+ throw new BadMethodCallException('this->stackInstance[] is not properly set.');
+ }
+
+ // Get length from index
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: Invoking this->stackInstance->calculateMinimumBlockLength() ...');
+ $length = $this->getStackInstance()->calculateMinimumBlockLength();
+
+ // Call protected method
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STACK-FILE: Invoking this->isValidByLength(%d) ...', $length));
+ $isValid = $this->isValidByLength($length);
+
+ // Return result
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: isValid=%d - EXIT!', intval($isValid)));
+ return $isValid;
+ }
+
+ /**
+ * Reads the file header
+ *
+ * @return void
+ * @throws LogicException If both instances are not set
+ */
+ public function readFileHeader () {
+ // Call stacke instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: Invoking this->stackInstance->readStackHeader() - CALLED!');
+ $this->getStackInstance()->readStackHeader();
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: EXIT!');
+ }
+
+ /**
+ * Reads next "block" of bytes into $currentBlock field. THis method loads
+ * the whole file into memory when the file is just freshly initialized
+ * (only zeros in it).
+ *
+ * @return void
+ */
+ protected function readNextBlock () {
+ // First calculate minimum block length
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: this->seekPosition=%d - CALLED!', $this->getSeekPosition()));
+ $length = $this->getStackInstance()->calculateMinimumBlockLength();
+
+ // Call protected method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: Invoking parent::readNextBlockByLength(%d) ...', $length));
+ parent::readNextBlockByLength($length);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: EXIT!');
}
/**
* Writes given value to the file and returns a hash and gap position for it
*
- * @param $groupId Group identifier
+ * @param $stackName Group identifier
* @param $value Value to be added to the stack
* @return $data Hash and gap position
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- public function writeValueToFile ($groupId, $value) {
- // Make sure no objects/resources are added as the serialization may fail
- assert(!is_object($value));
- assert(!is_resource($value));
+ public function writeValueToFile (string $stackName, $value) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: stackName=%s,value[]=%s - CALLED!', $stackName, gettype($value)));
+ if (empty($stackName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "stackName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (is_object($value) || is_resource($value)) {
+ // Not wanted here
+ throw new InvalidArgumentException(sprintf('value[]=%s is not stackable in files', gettype($value)));
+ }
// Encode/convert the value into a "binary format"
- $encoded = $this->encodeData($value);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: Invoking StringUtils::encodeData(value[]=%s) ...', gettype($value)));
+ $encoded = StringUtils::encodeData($value);
// Get a strong hash for the "encoded" data
- $hash = self::hash($encoded);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: Invoking CryptoUtils::hash(%s) ...', $encoded));
+ $hash = CryptoUtils::hash($encoded);
// Then write it to the next free gap
- $data = $this->getBlockInstance()->writeDataToFreeGap($groupId, $hash, $encoded);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: Invoking this->stackInstance->writeDataToFreeGap(%s,%s,%s) ...', $stackName, $hash, $encoded));
+ $data = $this->getStackInstance()->writeDataToFreeGap($stackName, $hash, $encoded);
// Return info
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: data[]=%s - EXIT!', gettype($data)));
return $data;
}
/**
* Writes given raw data to the file and returns a gap position and length
*
- * @param $groupId Group identifier
+ * @param $stackName Group identifier
* @param $hash Hash from encoded value
* @param $encoded Encoded value to be written to the file
* @return $data Gap position and length of the raw data
* @throws UnsupportedOperationException If this method is called
*/
- public function writeDataToFreeGap ($groupId, $hash, $encoded) {
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',hash=' . $hash . ',encoded()=' . strlen($encoded));
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ public function writeDataToFreeGap (string $stackName, string $hash, string $encoded) {
+ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: stackName=' . $stackName . ',hash=' . $hash . ',encoded()=' . strlen($encoded));
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Filesystem\CloseableFile;
use Org\Mxchange\CoreFramework\Filesystem\FilePointer;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+// Import SPL stuff
+use \InvalidArgumentException;
+
/**
* An abstract file class
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*/
private $totalEntries = 0;
+ /**
+ * An instance of a file I/O pointer class (not handler)
+ */
+ private $pointerInstance = NULL;
+
/**
* Protected constructor
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-ABSTRACT-FILE: className=%s - CONSTRUCTED!', $className));
parent::__construct($className);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-ABSTRACT-FILE: EXIT!');
+ }
+
+ /**
+ * Setter for FilePointer instance
+ *
+ * @param $pointerInstance An instance of an FilePointer class
+ * @return void
+ */
+ protected final function setPointerInstance (FilePointer $pointerInstance = NULL) {
+ $this->pointerInstance = $pointerInstance;
+ }
+
+ /**
+ * Getter for FilePointer instance
+ *
+ * @return $pointerInstance An instance of an FilePointer class
+ */
+ public final function getPointerInstance () {
+ return $this->pointerInstance;
+ }
+
+ /**
+ * Unsets pointer instance which triggers a call of __destruct() if the
+ * instance is still there. This is surely not fatal on already "closed"
+ * file pointer instances.
+ *
+ * I don't want to mess around with above setter by giving it a default
+ * value NULL as setter should always explicitly only set (existing) object
+ * instances and NULL is NULL.
+ *
+ * @return void
+ */
+ protected final function unsetPointerInstance () {
+ // Simply invoke setter with no parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-ABSTRACT-FILE: CALLED!');
+ $this->setPointerInstance();
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-ABSTRACT-FILE: EXIT!');
}
/**
*/
public final function __destruct() {
// Try to close a file
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-ABSTRACT-FILE: DESTRUCTED!');
$this->closeFile();
// Call the parent destructor
parent::__destruct();
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-ABSTRACT-FILE: EXIT!');
}
/**
*/
public function getFileSize () {
// Call pointer instanze
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-ABSTRACT-FILE: CALLED!');
return $this->getPointerInstance()->getFileSize();
}
*/
public final function getCounter () {
// Get it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-ABSTRACT-FILE: Getting this->totalEntries=%d ... - CALLED!', $this->totalEntries));
return $this->totalEntries;
}
* @param $totalEntries Total entries in this file
* @return void
*/
- protected final function setCounter ($counter) {
+ protected final function setCounter (int $counter) {
// Set it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-ABSTRACT-FILE: Setting this->totalEntries=%d ... - CALLED!', $counter));
$this->totalEntries = $counter;
}
* @return void
*/
protected final function incrementCounter () {
- // Get it
+ // Count up
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-ABSTRACT-FILE: CALLED!');
$this->totalEntries++;
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-ABSTRACT-FILE: EXIT!');
}
/**
* @return $fileObject An instance of a SplFileObject
*/
public final function getFileObject () {
+ // Call pointer instanze
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-ABSTRACT-FILE: CALLED!');
return $this->getPointerInstance()->getFileObject();
}
+ /**
+ * Getter for file's name
+ */
+ public final function getFilename () {
+ // Invole file object's method
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-ABSTRACT-FILE: CALLED!');
+ return $this->getFileObject()->getFilename();
+ }
+
/**
* Close a file source and set it's instance to null and the file name
* to empty
* @return void
*/
public function closeFile () {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d]: CALLED!', __METHOD__, __LINE__));
-
// Close down pointer instance as well by unsetting it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-ABSTRACT-FILE: CALLED!');
$this->unsetPointerInstance();
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d]: EXIT!', __METHOD__, __LINE__));
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-ABSTRACT-FILE: EXIT!');
}
/**
*/
public function size () {
// Call pointer instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-ABSTRACT-FILE: CALLED!');
return $this->getPointerInstance()->size();
}
*/
public function readFromFile () {
// Call pointer instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-ABSTRACT-FILE: CALLED!');
return $this->getPointerInstance()->readFromFile();
}
* @throws InvalidResourceException If there is being set
* an invalid file resource
*/
- public function writeToFile ($dataStream) {
+ public function writeToFile (string $dataStream) {
+ // Check parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-ABSTRACT-FILE: dataStream()=%d - CALLED!', strlen($dataStream)));
+ if (empty($dataStream)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "dataStream" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Call pointer instance
return $this->getPointerInstance()->writeToFile($dataStream);
}
*/
public final function isEndOfFileReached () {
// Call pointer instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-ABSTRACT-FILE: CALLED!');
return $this->getPointerInstance()->isEndOfFileReached();
}
<?php
// Own namespace
-namespace Org\Mxchange\CoreFramework\FileSystem;
+namespace Org\Mxchange\CoreFramework\Filesystem;
// Import framework stuff
use Org\Mxchange\CoreFramework\Filesystem\CloseableFile;
use Org\Mxchange\CoreFramework\Filesystem\FilePointer;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
// Import SPL stuff
+use \OutOfBoundsException;
use \SplFileObject;
/**
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FILE-IO: className=%s - CONSTRUCTED!', $className));
parent::__construct($className);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FILE-IO: EXIT!');
}
/**
*/
public final function __destruct() {
// Is there a resource pointer? Then we have to close the file here!
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FILE-IO: this->fileObject[]=%s - DESTRUCTOR!', gettype($this->getFileObject())));
if (is_object($this->getFileObject())) {
// Try to close a file
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FILE-IO: Invoking this->closeFile() ...');
$this->closeFile();
- } // END - if
+ }
// Call the parent destructor
parent::__destruct();
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FILE-IO: EXIT!');
}
/**
* @throws LogicException If there is no object being set
*/
public function closeFile () {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d]: fileName=%s - CALLED!', __METHOD__, __LINE__, $this->getFileObject()->getPathname()));
-
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FILE-IO: fileName=%s - CALLED!', $this->getFileObject()->getPathname()));
if (is_null($this->getFileObject())) {
// Pointer not initialized
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
} elseif (!is_object($this->getFileObject())) {
// Pointer is not a valid resource!
- throw new LogicException(sprintf('this->fileObject[]=%s is no object', gettype($this->getFileObject())));
+ throw new LogicException(sprintf('this->fileObject[]=%s is no object', gettype($this->getFileObject())), FrameworkInterface::EXCEPTION_LOGIC_EXCEPTION);
}
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d]: Closing file %s ...', __METHOD__, __LINE__, $this->getFileObject()->getPathname()));
-
// Close the file pointer by NULL-ing it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FILE-IO: Closing file %s ...', $this->getFileObject()->getPathname()));
$this->resetFileObject();
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d]: EXIT!', __METHOD__, __LINE__));
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FILE-IO: EXIT!');
}
/**
*/
protected final function resetFileObject () {
// Set it to NULL
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FILE-IO: Setting this->fileObject=NULL - CALLED!');
$this->fileObject = NULL;
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FILE-IO: EXIT!');
}
/**
* @param $whence Added to offset (default: only use offset to seek to)
* @return $status Status of file seek: 0 = success, -1 = failed
*/
- public function seek ($offset, $whence = SEEK_SET) {
+ public function seek (int $offset, int $whence = SEEK_SET) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FILE-IO: offset=%d,whence=%d - CALLED!', $offset, $whence));
+ if ($offset < 0) {
+ // Throw exception
+ throw new OutOfBoundsException(sprintf('offset=%d is not valid', $offset));
+ }
+
// Seek to position
$status = $this->getFileObject()->fseek($offset, $whence);
// Return status
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] status=%d', __METHOD__, __LINE__, $status));
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FILE-IO: status=%d - EXIT!', $status));
return $status;
}
* @todo Handle seekStatus
*/
public function size () {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
-
// Get current seek position
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-FILE-IO: CALLED!');
$seekPosition = $this->determineSeekPosition();
// Seek to end
$seekStatus = $this->seek(0, SEEK_END);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] seekStatus=%d', __METHOD__, __LINE__, $seekStatus));
- // Get position again (which is the end of the file)
+ // Get position again (which is the end of the file)
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FILE-IO: seekStatus[%s]=%d', gettype($seekStatus), $seekStatus));
$size = $this->determineSeekPosition();
// Reset seek position to old
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-FILE-IO: size[%s]=%d', gettype($size), $size));
$this->seek($seekPosition);
// Return size
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] size=%s - EXIT!', __METHOD__, __LINE__, $size));
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-FILE-IO: size=%d - EXIT!', $size));
return $size;
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Filesystem\FrameworkDirectory;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
// Import SPL stuff
use \DirectoryIterator;
+use \InvalidArgumentException;
/**
* A class for directory reading and getting its contents, no recursion!
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* Protected constructor
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function __destruct() {
// Is there a resource pointer? Then we have to close the directory here!
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FRAMEWORK-DIRECTORY-POINTER: DESTRUCTED!');
if ($this->getDirectoryIteratorInstance() instanceof DirectoryIterator) {
// Try to close a directory
$this->closeDirectory();
- } // END - if
+ }
// Call the parent destructor
parent::__destruct();
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FRAMEWORK-DIRECTORY-POINTER: EXIT!');
}
/**
* @throws PathIsNoDirectoryException If the provided path name is not valid
* @throws PathReadProtectedException If the provided path name is read-protected
*/
- public static final function createFrameworkDirectoryPointer ($pathName) {
+ public static final function createFrameworkDirectoryPointer (string $pathName) {
// Some pre-sanity checks...
- if (is_null($pathName)) {
- // No pathname given
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } elseif (!is_string($pathName)) {
- // Is not a string
- throw new InvalidPathStringException(NULL, self::EXCEPTION_INVALID_STRING);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FRAMEWORK-DIRECTORY-POINTER: pathName=%s - CALLED!', $pathName));
+ if (empty($pathName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "pathName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif (!is_dir($pathName)) {
// Not a directory
throw new PathIsNoDirectoryException($pathName, self::EXCEPTION_INVALID_PATH_NAME);
$pointerInstance->setPathName($pathName);
// Return the instance
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DIRECTORY[' . __METHOD__ . ':' . __LINE__ . ']: Opened pathName=' . $pathName . ' - EXIT!');
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DIRECTORY-POINTER: pointerInstance=%s - EXIT!', $pointerInstance->__toString()));
return $pointerInstance;
}
* @return $currentEntry Current entry from encapsulated iterator
*/
public function readRawDirectory () {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DIRECTORY[' . __METHOD__ . ':' . __LINE__ . '] - CALLED!');
-
// Can the next entry be read?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('DIRECTORY-POINTER: CALLED!');
assert($this->getDirectoryIteratorInstance()->valid());
// Read data from the directory pointer and return it
$currentEntry = $this->getDirectoryIteratorInstance()->current();
// Return found entry
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DIRECTORY[' . __METHOD__ . ':' . __LINE__ . ']: currentEntry[]=' . gettype($currentEntry) . ' - EXIT!');
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DIRECTORY-POINTER: currentEntry[%s]=%s - EXIT!', gettype($currentEntry), $currentEntry));
return $currentEntry;
}
*
* @param $except Some parts of a directory we want to ignore. Valid: directory and file names, other values will be silently ignored
* @return SplFileInfo An instance of a SplFileInfo class
+ * @throws InvalidArgumentException If a parameter has an invalid value
*/
- public function readDirectoryExcept (array $except = array()) {
+ public function readDirectoryExcept (array $except = []) {
// No exceptions given?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DIRECTORY-POINTER: except()=%d - CALLED!', count($except)));
if (count($except) == 0) {
// No exception given, so read all files and directories, but not recursive
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DIRECTORY[' . __METHOD__ . ':' . __LINE__ . ']: No exceptions given, please use readRawDirectory() instead!');
- return $this->readRawDirectory();
+ throw new InvalidArgumentException('Parameter "except" is an empty array', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif (!$this->getDirectoryIteratorInstance()->valid()) {
// No more left to read
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DIRECTORY[' . __METHOD__ . ':' . __LINE__ . ']: EOD reached.');
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('DIRECTORY-POINTER: EOD reached - EXIT!');
return NULL;
}
// Read a raw line...
$currentEntry = $this->readRawDirectory();
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DIRECTORY[' . __METHOD__ . ':' . __LINE__ . ']: currentEntry[]=' . gettype($currentEntry));
// Shall we exclude directories?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DIRECTORY-POINTER: currentEntry[]=%s', gettype($currentEntry)));
if (is_object($currentEntry)) {
// Get file name
$fileInfoInstance = $currentEntry;
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DIRECTORY[' . __METHOD__ . ':' . __LINE__ . ']: fileInfoInstance[' . gettype($fileInfoInstance) . ']=' . $fileInfoInstance . ',isDot=' . intval($this->getDirectoryIteratorInstance()->isDot()));
// Is it a dot-directory or excluded?
- if (($this->getDirectoryIteratorInstance()->isDot()) && (!in_array($fileInfoInstance, $except))) {
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('DIRECTORY-POINTER: fileInfoInstance->filename=%s,isDot=%d', $fileInfoInstance->getFilename(), intval($this->getDirectoryIteratorInstance()->isDot())));
+ while ($this->getDirectoryIteratorInstance()->valid() && ($this->getDirectoryIteratorInstance()->isDot() || in_array($fileInfoInstance->getFilename(), $except))) {
+ // Update current instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('DIRECTORY-POINTER: fileInfoInstance->filename=%s,isDot=%d', $fileInfoInstance->getFilename(), intval($this->getDirectoryIteratorInstance()->isDot())));
+ $fileInfoInstance = $this->readRawDirectory();
+
// To next entry
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('DIRECTORY-POINTER: Invoking directoryIteratorInstance->next() ...');
$this->getDirectoryIteratorInstance()->next();
-
- // Exclude this part
- $fileInfoInstance = $this->readDirectoryExcept($except);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DIRECTORY[' . __METHOD__ . ':' . __LINE__ . ']: fileInfoInstance[' . gettype($fileInfoInstance) . ']=' . $fileInfoInstance . ' - Recursive call!');
- } // END - if
- } // END - if
-
- // To next entry
- $this->getDirectoryIteratorInstance()->next();
+ }
+ }
// Return read line
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DIRECTORY[' . __METHOD__ . ':' . __LINE__ . ']: fileInfoInstance[' . gettype($fileInfoInstance) . ']=' . $fileInfoInstance);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DIRECTORY-POINTER: fileInfoInstance[%s]=%s - EXIT!', gettype($fileInfoInstance), $fileInfoInstance));
return $fileInfoInstance;
}
*/
public function closeDirectory () {
// Close the directory by unsetting it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('DIRECTORY-POINTER: CALLED!');
$this->unsetDirectoryIteratorInstance();
$this->setPathName('');
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('DIRECTORY-POINTER: CALLED!');
}
/**
* @param $pathName The new path name
* @return void
*/
- protected final function setPathName ($pathName) {
- $pathName = (string) $pathName;
+ protected final function setPathName (string $pathName) {
$this->pathName = $pathName;
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\FileSystem\BaseFileIo;
+use Org\Mxchange\CoreFramework\Filesystem\BaseFileIo;
+use Org\Mxchange\CoreFramework\Filesystem\FileIoException;
use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
-use Org\Mxchange\CoreFramework\FileSystem\FileReadProtectedException;
+use Org\Mxchange\CoreFramework\Filesystem\FileReadProtectedException;
use Org\Mxchange\CoreFramework\Filesystem\Pointer\InputPointer;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
// Import SPL stuff
+use \InvalidArgumentException;
use \SplFileInfo;
+use \SplFileObject;
+use \UnexpectedValueException;
/**
* A class for reading files
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* Create a file pointer based on the given file. The file will also
* be verified here.
*
- * @param $infoInstance An instance of a SplFileInfo class
+ * @param $fileInstance An instance of a SplFileInfo class
* @throws FileIoException If the file is not reachable
* @throws FileReadProtectedException If the file is not found or cannot be read
* @throws FileNotFoundException If the file does not exist
* @return void
*/
- public static final function createFrameworkRawFileInputPointer (SplFileInfo $infoInstance) {
+ public static final function createFrameworkRawFileInputPointer (SplFileInfo $fileInstance) {
// Some pre-sanity checks...
- if (!FrameworkBootstrap::isReachableFilePath($infoInstance)) {
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('RAW-FILE-INPUT-POINTER: fileInstance[%s]=%s - CALLED!', get_class($fileInstance), $fileInstance->__toString()));
+ if (!FrameworkBootstrap::isReachableFilePath($fileInstance)) {
// File cannot be accessed (due to open_basedir restriction)
- throw new FileIoException($infoInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
- } elseif ((!FrameworkBootstrap::isReadableFile($infoInstance)) && (!$infoInstance->isFile())) {
+ throw new FileIoException($fileInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
+ } elseif ((!FrameworkBootstrap::isReadableFile($fileInstance)) && (!$fileInstance->isFile())) {
// File does not exist
- throw new FileNotFoundException($infoInstance, self::EXCEPTION_FILE_NOT_FOUND);
- } elseif ((!FrameworkBootstrap::isReadableFile($infoInstance)) && ($infoInstance->isFile())) {
+ throw new FileNotFoundException($fileInstance, self::EXCEPTION_FILE_NOT_FOUND);
+ } elseif ((!FrameworkBootstrap::isReadableFile($fileInstance)) && ($fileInstance->isFile())) {
// File exists but cannot be read from
- throw new FileReadProtectedException($infoInstance, self::EXCEPTION_FILE_CANNOT_BE_READ);
+ throw new FileReadProtectedException($fileInstance, self::EXCEPTION_FILE_CANNOT_BE_READ);
}
// Try to open a handler
- $fileObject = $infoInstance->openFile('rb');
- if ((is_null($fileObject)) || ($fileObject === false)) {
+ $fileObject = $fileInstance->openFile('rb');
+
+ // Is it valid?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('RAW-FILE-INPUT-POINTER: fileObject[]=%s', gettype($fileObject)));
+ if (!($fileObject instanceof SplFileObject)) {
// Something bad happend
- throw new FileIoException($infoInstance, self::EXCEPTION_FILE_POINTER_INVALID);
- } // END - if
+ throw new FileIoException($fileInstance, self::EXCEPTION_FILE_POINTER_INVALID);
+ }
// Create new instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('RAW-FILE-INPUT-POINTER: fileObject.pathname=%s', $fileObject->getPathname()));
$pointerInstance = new FrameworkRawFileInputPointer();
// Set file pointer and file name
$pointerInstance->setFileObject($fileObject);
// Return the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('RAW-FILE-INPUT-POINTER: pointerInstance=%s - EXIT!', $pointerInstance->__toString()));
return $pointerInstance;
}
* @throws LogicException If there is no object being set
*/
public function readFromFile () {
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('RAW-FILE-INPUT-POINTER: CALLED!');
if (is_null($this->getFileObject())) {
// Pointer not initialized
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
} elseif (!is_object($this->getFileObject())) {
// Pointer is not a valid resource!
- throw new LogicException(sprintf('this->fileObject[]=%s is no object', gettype($this->getFileObject())));
+ throw new LogicException(sprintf('this->fileObject[]=%s is no object', gettype($this->getFileObject())), FrameworkInterface::EXCEPTION_LOGIC_EXCEPTION);
}
// Read data from the file pointer and return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('RAW-FILE-INPUT-POINTER: Invoking this->read(1024) - EXIT!');
return $this->read(1024);
}
*/
public function readLine () {
// Not supported in binary files ...
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
*
* @param $bytes Amount of bytes to read
* @return $data Data read from file
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws UnexpectedValueException If fread() returns a non-string value
*/
- public function read ($bytes = NULL) {
- // $bytes shall be integer
- assert(is_int($bytes));
+ public function read (int $bytes = 0) {
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('RAW-FILE-INPUT-POINTER: bytes=%d - CALLED!', $bytes));
+ if ($bytes < 0) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('bytes=%d is an invalid value, only zero or postive numbers are accepted', $bytes));
+ }
// Try to read given characters
$data = $this->getFileObject()->fread($bytes);
+ // Is it valid?
+ if (!is_string($data)) {
+ // Is not a string
+ throw new UnexpectedValueException(sprintf('Returned data[]=%s is not expected.', gettype($data)), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
+
// Then return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('RAW-FILE-INPUT-POINTER: data()=%d - EXIT!', strlen($data)));
return $data;
}
* @return void
* @throws UnsupportedOperationException If this method is called
*/
- public function analyzeFile () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ public function analyzeFileStructure () {
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException If this method is called
*/
public function next () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException If this method is called
*/
public function valid () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException If this method is called
*/
public function key () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\FileSystem\BaseFileIo;
+use Org\Mxchange\CoreFramework\Filesystem\BaseFileIo;
+use Org\Mxchange\CoreFramework\Filesystem\FileIoException;
use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
-use Org\Mxchange\CoreFramework\FileSystem\FileReadProtectedException;
+use Org\Mxchange\CoreFramework\Filesystem\FileReadProtectedException;
use Org\Mxchange\CoreFramework\Filesystem\Pointer\InputPointer;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
// Import SPL stuff
use \SplFileInfo;
+use \SplFileObject;
/**
* A class for reading text files
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @throws FileReadProtectedException If the file cannot be read from
* @return void
*/
- public static final function createFrameworkTextFileInputPointer (SplFileInfo $infoInstance) {
+ public static final function createFrameworkTextFileInputPointer (SplFileInfo $fileInstance) {
// Check parameter
- if (!FrameworkBootstrap::isReachableFilePath($infoInstance)) {
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('RAW-FILE-INPUT-POINTER: fileInstance[%s]=%s - CALLED!', get_class($fileInstance), $fileInstance->__toString()));
+ if (!FrameworkBootstrap::isReachableFilePath($fileInstance)) {
// File cannot be reached
- throw new FileIoException($infoInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
- } elseif ((!FrameworkBootstrap::isReadableFile($infoInstance)) && (!$infoInstance->isFile())) {
+ throw new FileIoException($fileInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
+ } elseif ((!FrameworkBootstrap::isReadableFile($fileInstance)) && (!$fileInstance->isFile())) {
// File does not exist!
- throw new FileNotFoundException($infoInstance, self::EXCEPTION_FILE_CANNOT_BE_READ);
- } elseif ((!FrameworkBootstrap::isReadableFile($infoInstance)) && ($infoInstance->isFile())) {
+ throw new FileNotFoundException($fileInstance, self::EXCEPTION_FILE_CANNOT_BE_READ);
+ } elseif ((!FrameworkBootstrap::isReadableFile($fileInstance)) && ($fileInstance->isFile())) {
// File cannot be read from (but exists)
- throw new FileReadProtectedException($infoInstance, self::EXCEPTION_FILE_CANNOT_BE_READ);
+ throw new FileReadProtectedException($fileInstance, self::EXCEPTION_FILE_CANNOT_BE_READ);
}
// Try to open a handler
- $fileObject = $infoInstance->openFile('r');
-
- // Debug message
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TEXT-FILE-INPUT: fileObject[]=' . gettype($fileObject));
+ $fileObject = $fileInstance->openFile('r');
// Is it valid?
- if ((is_null($fileObject)) || ($fileObject === false)) {
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TEXT-FILE-INPUT-POINTER: fileObject[]=%s', gettype($fileObject)));
+ if (!($fileObject instanceof SplFileObject)) {
// Something bad happend
- throw new FileIoException($infoInstance, self::EXCEPTION_FILE_POINTER_INVALID);
- } // END - if
+ throw new FileIoException($fileInstance, self::EXCEPTION_FILE_POINTER_INVALID);
+ }
// Create new instance
$pointerInstance = new FrameworkTextFileInputPointer();
$pointerInstance->setFileObject($fileObject);
// Return the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TEXT-FILE-INPUT-POINTER: pointerInstance=%s - EXIT!', $pointerInstance->__toString()));
return $pointerInstance;
}
*/
public function readFromFile () {
// Read 1024 Byte data from the file pointer and return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('RAW-FILE-INPUT-POINTER: CALLED!');
return $this->read(1024);
}
*/
public function readLine () {
// Read whole line from the file pointer and return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('RAW-FILE-INPUT-POINTER: CALLED!');
return $this->read();
}
*
* @param $bytes Amount of bytes to read or whole line (only text files)
* @return $data Data read from file
+ * @throws OutOfBoundsException If the position is not seekable
* @throws NullPointerException If the file pointer instance is not set by setFileObject()
- * @throws InvalidResourceException If there is no object being set
+ * @throws LogicException If $fileObject is not an object
*/
- public function read ($bytes = NULL) {
+ public function read (int $bytes = 0) {
// Some sanity checks
- if (is_null($this->getFileObject())) {
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('RAW-FILE-INPUT-POINTER: bytes=%d - CALLED!', $bytes));
+ if ($bytes < 0) {
+ // Cannot be below zero
+ throw new OutOfBoundsException(sprintf('bytes=%d is not valid', $bytes));
+ } elseif (is_null($this->getFileObject())) {
// Pointer not initialized
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
} elseif (!is_object($this->getFileObject())) {
// Pointer is not a valid resource!
- throw new LogicException(sprintf('this->fileObject[]=%s is no object', gettype($this->getFileObject())));
+ throw new LogicException(sprintf('this->fileObject[]=%s is no object', gettype($this->getFileObject())), FrameworkInterface::EXCEPTION_LOGIC_EXCEPTION);
}
// Is $bytes set?
- if (is_int($bytes)) {
+ if ($bytes > 0) {
// Try to read given characters
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('RAW-FILE-INPUT-POINTER: Invoking this->fileObject->fread(%d) ...', $bytes));
$data = $this->getFileObject()->fread($bytes);
} else {
// Try to read whole line
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('RAW-FILE-INPUT-POINTER: Invoking this->fileObject->fgets() ...');
$data = $this->getFileObject()->fgets();
}
// Then return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('RAW-FILE-INPUT-POINTER: data()=%d - EXIT!', strlen($data)));
return $data;
}
* @return void
* @throws UnsupportedOperationException If this method is called
*/
- public function analyzeFile () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ public function analyzeFileStructure () {
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException If this method is called
*/
public function next () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException If this method is called
*/
public function valid () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException If this method is called
*/
public function key () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\FileSystem\BaseFileIo;
-use Org\Mxchange\CoreFramework\FileSystem\FileReadProtectedException;
-use Org\Mxchange\CoreFramework\FileSystem\FileWriteProtectedException;
+use Org\Mxchange\CoreFramework\Filesystem\BaseFileIo;
+use Org\Mxchange\CoreFramework\Filesystem\FileIoException;
+use Org\Mxchange\CoreFramework\Filesystem\FileReadProtectedException;
+use Org\Mxchange\CoreFramework\Filesystem\FileWriteProtectedException;
use Org\Mxchange\CoreFramework\Filesystem\PathWriteProtectedException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
// Import SPL stuff
+use \InvalidArgumentException;
use \SplFileInfo;
+use \SplFileObject;
+use \OutOfBoundsException;
+use \UnexpectedValueException;
/**
* A class for reading files
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public static final function createFrameworkFileInputOutputPointer (SplFileInfo $fileInstance) {
// Some pre-sanity checks...
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: fileInstance[%s]=%s - CALLED!', get_class($fileInstance), $fileInstance));
if (!FrameworkBootstrap::isReachableFilePath($fileInstance)) {
// File exists but cannot be read
throw new FileIoException($fileInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
$fileObject = $fileInstance->openFile('c+b');
// Is it valid?
- if ((is_null($fileObject)) || ($fileObject === false)) {
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: fileObject[]=%s', gettype($fileObject)));
+ if (!($fileObject instanceof SplFileObject)) {
// Something bad happend
throw new FileIoException($fileInstance->getPathname(), self::EXCEPTION_FILE_POINTER_INVALID);
- } // END - if
+ }
// Create new instance
$pointerInstance = new FrameworkFileInputOutputPointer();
$pointerInstance->setFileObject($fileObject);
// Return the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: pointerInstance=%s - EXIT!', $pointerInstance->__toString()));
return $pointerInstance;
}
- /**
- * Validates file pointer and throws exceptions. This method does not return
- * anything (not reliable) as this method checks the file pointer and on
- * case of an error it throws an exception. If this method does not throw
- * any exceptions, the file pointer seems to be fine.
- *
- * @return void
- * @throws NullPointerException If the file pointer instance
- * is not set by setFileObject()
- * @todo Add more checks
- */
- private function validateFilePointer () {
- if (is_null($this->getFileObject())) {
- // Pointer not initialized
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } // END - if
-
- // All fine here
- }
-
/**
* Read 1024 bytes data from a file pointer
*
* @return mixed The result of fread()
*/
public function readFromFile () {
- // Validate the pointer
- $this->validateFilePointer();
-
// Read data from the file pointer and return it
- return $this->read(1024);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-INPUT-OUTPUT-POINTER: CALLED!');
+ $data = $this->read(1024);
+
+ // Return data
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%d - EXIT!', gettype($data), $data));
+ return $data;
}
/**
* @param $dataStream The data stream we shall write to the file
* @return mixed Number of writes bytes or false on error
*/
- public function writeToFile ($dataStream) {
- // Validate the pointer
- $this->validateFilePointer();
+ public function writeToFile (string $dataStream) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: dataStream(%d)=%s - CALLED!', strlen($dataStream), $dataStream));
+ if (empty($dataStream)) {
+ // Empty dataStream
+ throw new InvalidArgumentException('Parameter "dataStream" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Get length
+ $length = strlen($dataStream);
// Write data to the file pointer and return written bytes
- return $this->getFileObject()->fwrite($dataStream, strlen($dataStream));
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: Invoking this->fileObject->fwrite(%s,%d) ...', $dataStream, $length));
+ $status = $this->getFileObject()->fwrite($dataStream, $length);
+
+ // Return status
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
+ return $status;
}
/**
* Writes at given position by seeking to it.
*
* @param $seekPosition Seek position in file
- * @param $data Data to be written
+ * @param $dataStream Data to be written
* @return mixed Number of writes bytes or false on error
+ * @throws OutOfBoundsException If the position is not seekable
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- public function writeAtPosition ($seekPosition, $data) {
- // First seek to it
- $this->seek($seekPosition);
+ public function writeAtPosition (int $seekPosition, string $dataStream) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: seekPosition=%d,dataStream(%d)=%s - CALLED!', $seekPosition, strlen($dataStream), $dataStream));
+ if ($seekPosition < 0) {
+ // Invalid seek position
+ throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid.', $seekPosition));
+ } elseif (empty($dataStream)) {
+ // Empty dataStream
+ throw new InvalidArgumentException('Parameter "dataStream" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (($this->getFileSize() > 0 || $seekPosition > 0) && $this->seek($seekPosition) === -1) {
+ // Could not seek
+ throw new InvalidArgumentException(sprintf('Could not seek to seekPosition=%d', $seekPosition));
+ }
// Then write the data at that position
- return $this->writeToFile($data);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: Invoking this->writeToFile(%s) ...', $dataStream));
+ $status = $this->writeToFile($dataStream);
+
+ // Return status
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
+ return $status;
}
/**
* Rewinds to the beginning of the file
*
- * @return $status Status of this operation
+ * @return void
*/
public function rewind () {
- // Validate the pointer
- $this->validateFilePointer();
+ /// Rewind the pointer
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-INPUT-OUTPUT-POINTER: CALLED!');
+ $this->getFileObject()->rewind();
- // Rewind the pointer
- return $this->getFileObject()->rewind();
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-INPUT-OUTPUT-POINTER: EXIT!');
}
/**
* @param $seekPosition Seek position in file
* @param $whence "Seek mode" (see http://de.php.net/fseek)
* @return $status Status of this operation
+ * @throws OutOfBoundsException If the position is not seekable
*/
- public function seek ($seekPosition, $whence = SEEK_SET) {
- // Validate the pointer
- $this->validateFilePointer();
+ public function seek (int $seekPosition, int $whence = SEEK_SET) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: seekPosition=%d,whence=%d - CALLED!', $seekPosition, $whence));
+ if ($seekPosition < 0) {
+ // Invalid seek position
+ throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid.', $seekPosition));
+ } elseif ($whence < 0) {
+ // Invalid seek position
+ throw new OutOfBoundsException(sprintf('whence=%d is not valid.', $whence));
+ }
// Move the file pointer
- return $this->getFileObject()->fseek($seekPosition, $whence);
+ $status = $this->getFileObject()->fseek($seekPosition, $whence);
+
+ // Return status
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
+ return $status;
}
/**
*/
public function readLine () {
// Read whole line
- return $this->read();
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-INPUT-OUTPUT-POINTER: CALLED!');
+ $data = $this->read();
+
+ // Return data
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%s - EXIT!', gettype($data), $data));
+ return $data;
}
/**
*
* @param $bytes Amount of bytes to read
* @return $data Data read from file
+ * @throws OutOfBoundsException If the position is not seekable
*/
- public function read ($bytes = NULL) {
- // Validate the pointer
- $this->validateFilePointer();
+ public function read (int $bytes = 0) {
+ // Validatre parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: bytes=%d - CALLED!', $bytes));
+ if ($bytes < 0) {
+ // Bytes cannot be lesser than zero
+ throw new OutOfBoundsException(sprintf('bytes=%d is not valid', $bytes));
+ }
- // Is $bytes set?
- if (is_int($bytes)) {
+ // Is $bytes bigger than zero?
+ if ($bytes > 0) {
// Try to read given characters
$data = $this->getFileObject()->fread($bytes);
} else {
}
// Then return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%s - EXIT!', gettype($data), $data));
return $data;
}
* @return void
* @throws UnsupportedOperationException If this method is called
*/
- public function analyzeFile () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ public function analyzeFileStructure () {
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException If this method is called
*/
public function next () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException If this method is called
*/
public function valid () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException If this method is called
*/
public function key () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* "Getter" for file size
*
* @return $fileSize Size of currently loaded file
+ * @throws UnexpectedValueException If $fileData does not contain "size"
*/
public function getFileSize () {
- // Check if the pointer is still valid
- $this->validateFilePointer();
-
// Get file's data
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-INPUT-OUTPUT-POINTER: CALLED!');
$fileData = $this->getFileObject()->fstat();
// Make sure the required array key is there
- assert(isset($fileData['size']));
+ if (!isset($fileData['size'])) {
+ // Not valid array
+ throw new UnexpectedValueException(sprintf('fileData=%s has no element "size"', print_r($fileData, TRUE)), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// Return size
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: fileData[size]=%d - EXIT!', $fileData['size']));
return $fileData['size'];
}
// Import framework stuff
use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
use Org\Mxchange\CoreFramework\Stream\Filesystem\FileInputStreamer;
use Org\Mxchange\CoreFramework\Stream\Filesystem\FileOutputStreamer;
// Import SPL stuff
+use \InvalidArgumentException;
+use \OutOfBoundsException;
use \SplFileInfo;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* Protected constructor
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public static final function createFileIoStream () {
// Create new instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-IO-STREAM: CALLED!');
$ioInstance = new FileIoStream();
// Return the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-IO-STREAM: ioInstance=%s - EXIT!', $ioInstance->__toString()));
return $ioInstance;
}
* @param $dataArray The data we shall store to the file
* @return void
* @see FileOutputStreamer
- * @todo This method needs heavy rewrite
+ * @throws InvalidArgumentException If an invalid parameter was given
+ * @throws OutOfBoundsException If an expected array element wasn't found
*/
public final function saveFile (SplFileInfo $fileInfoInstance, array $dataArray) {
- // Try it five times
- $dirName = '';
- $fileInstance = NULL;
-
- for ($idx = 0; $idx < 5; $idx++) {
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-IO-STREAM: fileInfoInstance=%s,dataArray()=%d - CALLED!', $fileInfoInstance, count($dataArray)));
+ if (count($dataArray) < 2) {
+ // Not valid array, at least 2 elements must be there!
+ throw new InvalidArgumentException(sprintf('Parameter "dataArray" should have at least 2 elements, has %d', count($dataArray)));
+ } else if (!isset($dataArray[0])) {
+ // Array element 0 not found
+ throw new OutOfBoundsException(sprintf('Array element dataArray[0] not found, dataArray=%s', json_encode($dataArray)));
+ } else if (!isset($dataArray[1])) {
+ // Array element 1 not found
+ throw new OutOfBoundsException(sprintf('Array element dataArray[1] not found, dataArray=%s', json_encode($dataArray)));
+ }
+
+ try {
// Get a file output pointer
- try {
- $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_output_class', array($fileInfoInstance, 'wb'));
- } catch (FileNotFoundException $e) {
- // Bail out
- ApplicationEntryPoint::exitApplication('The application has made a fatal error. Exception: ' . $e->__toString() . ' with message: ' . $e->getMessage());
- }
- } // END - for
+ $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_output_class', [$fileInfoInstance, 'wb']);
+ } catch (FileNotFoundException $e) {
+ // Bail out
+ ApplicationEntryPoint::exitApplication('The application has made a fatal error. Exception: ' . $e->__toString() . ' with message: ' . $e->getMessage());
+ }
// Write a header information for validation purposes
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: Writing header to fileInstance=%s ...', $fileInstance->__toString()));
$fileInstance->writeToFile(sprintf('%s%s%s%s%s%s%s%s%s' . PHP_EOL,
self::FILE_IO_FILE_HEADER_ID,
self::FILE_IO_SEPARATOR,
));
// Encode the (maybe) binary stream with Base64
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: Encoding %d bytes to BASE64 string ...', strlen($dataArray[1])));
$b64Stream = base64_encode($dataArray[1]);
- // write the data line by line
+ // write the data line-by-line
$line = str_repeat(' ', 50); $idx = 0;
while (strlen($line) == 50) {
// Get 50 chars or less
$line = substr($b64Stream, $idx, 50);
// Save it to the stream
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: Writing %d bytes to file ...', strlen($line)));
$fileInstance->writeToFile(sprintf('%s%s%s%s%s' . PHP_EOL,
self::FILE_IO_DATA_BLOCK_ID,
self::FILE_IO_SEPARATOR,
// Advance to the next 50-chars block
$idx += 50;
- } // END - while
+ }
// Close the file
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('FILE-IO-STREAM: Closing file ...');
unset($fileInstance);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-IO-STREAM: EXIT!');
}
/**
*/
public final function loadFileContents (SplFileInfo $infoInstance) {
// Initialize some variables and arrays
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-IO-STREAM: infoInstance=%s - CALLED!', $infoInstance));
$inputBuffer = '';
$lastBuffer = '';
- $header = array();
- $data = array();
+ $header = [];
+ $data = [];
$readData = ''; // This will contain our read data
// Get a file input handler
$fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($infoInstance));
// Read all it's contents (we very and transparently decompress it below)
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: fileInstance=%s', $fileInstance->__toString()));
while ($readRawLine = $fileInstance->readFromFile()) {
// Add the read line to the buffer
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: Adding %d read bytes to input buffer.', strlen($readRawLine)));
$inputBuffer .= $readRawLine;
// Break infinite loop maybe caused by the input handler
if ($lastBuffer == $inputBuffer) {
+ // Break out of loop, EOF reached?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('FILE-IO-STREAM: EOF reached!');
break;
- } // END - if
+ }
// Remember last read line for avoiding possible infinite loops
$lastBuffer = $inputBuffer;
- } // END - while
+ }
// Close directory handle
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('FILE-IO-STREAM: Closing file ...');
unset($fileInstance);
// Convert it into an array
- $inputBuffer = explode(chr(10), $inputBuffer);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: Read inputBuffer=%d bytes from infoInstance=%s', strlen($inputBuffer), $infoInstance));
+ $inputArray = explode(chr(10), $inputBuffer);
// Now process the read lines and verify it's content
- foreach ($inputBuffer as $rawLine) {
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: inputArray()=%d', count($inputArray)));
+ foreach ($inputArray as $rawLine) {
// Trim it a little but not the leading spaces/tab-stops
$rawLine = rtrim($rawLine);
// Analyze this line
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: rawLine()=%d', strlen($rawLine)));
if (substr($rawLine, 0, 5) == self::FILE_IO_FILE_HEADER_ID) {
// Header found, so let's extract it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: Found header, rawLine=%s', $rawLine));
$header = explode(self::FILE_IO_SEPARATOR, $rawLine);
- $header = trim($header[1]);
+ $headerLine = trim($header[1]);
// Now we must convert it again into an array
- $header = explode(self::FILE_IO_CHUNKER, $header);
+ $header = explode(self::FILE_IO_CHUNKER, $headerLine);
// Is the header (maybe) valid?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: header()=%d', count($header)));
if (count($header) != 4) {
// Throw an exception
- throw new InvalidArrayCountException(array($this, 'header', count($header), 4), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
- } // END - if
+ throw new InvalidArrayCountException([$this, 'header', count($header), 4], self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
+ }
} elseif (substr($rawLine, 0, 5) == self::FILE_IO_DATA_BLOCK_ID) {
// Is a data line!
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: Data line found rawLine=%s', $rawLine));
$data = explode(self::FILE_IO_SEPARATOR, $rawLine);
- $data = $data[1];
+ $dataLine = $data[1];
// First element is the data, second the MD5 checksum
- $data = explode(self::FILE_IO_CHUNKER, $data);
+ $data = explode(self::FILE_IO_CHUNKER, $dataLine);
// Validate the read line
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: data()=%d', count($data)));
if (count($data) == 2) {
- if (md5($data[0]) != $data[1]) {
+ // Generate checksum (MD5 is okay here)
+ $checksum = md5($data[0]);
+
+ // Check if it matches provided one
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: checksum=%s,data[1]=%s', $checksum, $data[1]));
+ if ($checksum != $data[1]) {
// MD5 hash did not match!
- throw new InvalidMD5ChecksumException(array($this, md5($data[0]), $data[1]), self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
- } // END - if
+ throw new InvalidMD5ChecksumException([$this, $checksum, $data[1]], self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
+ }
} else {
// Invalid count!
- throw new InvalidArrayCountException(array($this, 'data', count($data), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
+ throw new InvalidArrayCountException([$this, 'data', count($data), 2], self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
}
// Add this to the readData string
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: Adding %d raw data to input stream', strlen($data[0])));
$readData .= $data[0];
} else {
// Other raw lines than header/data tagged lines and re-add the new-line char
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: Adding rawLine=%s(%d) + PHP_EOL to input stream', $rawLine, strlen($rawLine)));
$readData .= $rawLine . PHP_EOL;
}
- } // END - foreach
+ }
// Was raw lines read and no header/data?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: readData()=%d,header()=%d,data()=%d', strlen($readData), count($header), count($data)));
if ((!empty($readData)) && (count($header) == 0) && (count($data) == 0)) {
// Return raw lines back
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-IO-STREAM: readData()=%d - EXIT!', strlen($readData)));
return $readData;
- } // END - if
+ }
// Was a header found?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: header()=%d', count($header)));
if (count($header) != 4) {
// Throw an exception
- throw new InvalidArrayCountException(array($this, 'header', count($header), 4), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
- } // END - if
+ throw new InvalidArrayCountException([$this, 'header', count($header), 4], self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
+ }
// Decode all from Base64
- $readData = @base64_decode($readData);
+ $decodedData = @base64_decode($readData);
// Does the size match?
- if (strlen($readData) != $header[2]) {
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: decodedData()=%d,header[2]=%d', strlen($decodedData), $header[2]));
+ if (strlen($decodedData) != $header[2]) {
// Size did not match
- throw new InvalidDataLengthException(array($this, strlen($readData), $header[2]), self::EXCEPTION_UNEXPECTED_STRING_SIZE);
- } // END - if
+ throw new InvalidDataLengthException([$this, strlen($decodedData), $header[2]], self::EXCEPTION_UNEXPECTED_STRING_SIZE);
+ }
+
+ // Generate checksum from whole read data
+ $checksum = md5($decodedData);
// Validate the decoded data with the final MD5 hash
- if (md5($readData) != $header[3]) {
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-STREAM: checksum=%s,header[3]=%s', $checksum, $header[3]));
+ if ($checksum != $header[3]) {
// MD5 hash did not match!
- throw new InvalidMD5ChecksumException(array($this, md5($readData), $header[3]), self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
- } // END - if
+ throw new InvalidMD5ChecksumException([$this, $checksum, $header[3]], self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
+ }
// Return all in an array
- return array(
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-IO-STREAM: header()=%d,decodedData()=%d - EXIT!', count($header), strlen($decodedData)));
+ return [
'header' => $header,
- 'data' => $readData
- );
+ 'data' => $decodedData,
+ ];
}
/**
* @return $data The data (string mostly) to "stream"
* @throws UnsupportedOperationException If this method is called
*/
- public function streamData ($data) {
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ public function streamData (string $data) {
+ // Not supported
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-IO-STREAM: data=()=%d - CALLED!', strlen($data)));
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @todo 0% done
*/
public function determineSeekPosition () {
- $this->partialStub();
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-IO-STREAM: CALLED!');
+ DebugMiddleware::getSelfInstance()->partialStub();
}
/**
* @param $whence Added to offset (default: only use offset to seek to)
* @return $status Status of file seek: 0 = success, -1 = failed
*/
- public function seek ($offset, $whence = SEEK_SET) {
- $this->partialStub('offset=' . $offset . ',whence=' . $whence);
+ public function seek (int $offset, int $whence = SEEK_SET) {
+ // Check parameters
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-IO-STREAM: offset=%d,whence=%d - CALLED!', $offset, $whence));
+ if ($offset < 0) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('offset=%d is below zero', $offset), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($whence < 0) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('whence=%d is below zero', $whence), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ DebugMiddleware::getSelfInstance()->partialStub('offset=' . $offset . ',whence=' . $whence);
}
/**
* @return $size Size (in bytes) of file
*/
public function size () {
- $this->partialStub();
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-IO-STREAM: CALLED!');
+ DebugMiddleware::getSelfInstance()->partialStub();
}
}
namespace Org\Mxchange\CoreFramework\Filesystem\Pointer\Output;
// Import framework stuff
-use Org\Mxchange\CoreFramework\FileSystem\BaseFileIo;
+use Org\Mxchange\CoreFramework\Filesystem\BaseFileIo;
+use Org\Mxchange\CoreFramework\Filesystem\FileIoException;
use Org\Mxchange\CoreFramework\Filesystem\Pointer\OutputPointer;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
// Import SPL stuff
use \InvalidArgumentException;
use \SplFileInfo;
+use \SplFileObject;
/**
* A class for writing files
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* Create a file pointer based on the given file. The file will also
* be verified here.
*
- * @param $infoInstance An instance of a SplFileInfo class
+ * @param $fileInstance An instance of a SplFileInfo class
* @param $mode The output mode ('w', 'a' are valid)
+ * @return void
* @throws InvalidArgumentException If parameter mode is empty
* @throws FileIoException If fopen() returns not a file resource
- * @return void
*/
- public static final function createFrameworkRawFileOutputPointer (SplFileInfo $infoInstance, $mode) {
- // Some pre-sanity checks...
- if (is_null($mode)) {
- // No infoInstance given
- throw new InvalidArgumentException('Parameter "mode" is empty');
- } // END - if
+ public static final function createFrameworkRawFileOutputPointer (SplFileInfo $fileInstance, string $mode) {
+ // Is the parameter valid?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('RAW-FILE-OUTPUT-POINTER: fileInstance=%s,mode=%s - CALLED!', $fileInstance->__toString(), $mode));
+ if (empty($mode)) {
+ // No fileInstance given
+ throw new InvalidArgumentException('Parameter "mode" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Try to open a handler
- $fileObject = $infoInstance->openFile($mode);
- if ((is_null($fileObject)) || ($fileObject === false)) {
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('RAW-FILE-OUTPUT-POINTER: Invoking fileInstance->openFile(%s) ...', $mode));
+ $fileObject = $fileInstance->openFile($mode);
+
+ // Is it valid?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('RAW-FILE-OUTPUT-POINTER: fileObject[]=%s', gettype($fileObject)));
+ if (!($fileObject instanceof SplFileObject)) {
// Something bad happend
- throw new FileIoException($infoInstance, self::EXCEPTION_FILE_POINTER_INVALID);
- } // END - if
+ throw new FileIoException($fileInstance, self::EXCEPTION_FILE_POINTER_INVALID);
+ }
// Create new instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('RAW-FILE-OUTPUT-POINTER: Creating pointer instance ...');
$pointerInstance = new FrameworkRawFileOutputPointer();
// Set file pointer and file name
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('RAW-FILE-OUTPUT-POINTER: pointerInstance=%s,fileObject=%s', $pointerInstance->__toString(), get_class($fileObject)));
$pointerInstance->setFileObject($fileObject);
// Return the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('RAW-FILE-OUTPUT-POINTER: pointerInstance=%s - EXIT!', $pointerInstance->__toString()));
return $pointerInstance;
}
*
* @param $dataStream The data stream we shall write to the file
* @return mixed Number of writes bytes or false on error
+ * @throws InvalidArgumentException If a parameter is invalid
* @throws NullPointerException If the file pointer instance is not set by setFileObject()
* @throws LogicException If there is no object being set
*/
- public function writeToFile ($dataStream) {
- if (is_null($this->getFileObject())) {
+ public function writeToFile (string $dataStream) {
+ // Validate parameter and class own attributes
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('RAW-FILE-OUTPUT-POINTER: dataStream(%d)=%s (trimmed) - CALLED!', strlen($dataStream), trim($dataStream)));
+ if (empty($dataStream)) {
+ // Empty data stream
+ throw new InvalidArgumentException('Parameter "dataStream" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (is_null($this->getFileObject())) {
// Pointer not initialized
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
} elseif (!is_object($this->getFileObject())) {
// Pointer is not a valid resource!
- throw new LogicException(sprintf('this->fileObject[]=%s is no object', gettype($this->getFileObject())));
+ throw new LogicException(sprintf('this->fileObject[]=%s is no object', gettype($this->getFileObject())), FrameworkInterface::EXCEPTION_LOGIC_EXCEPTION);
}
// Write data to the file pointer and return written bytes
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('RAW-FILE-OUTPUT-POINTER: Invoking this->fileObject->fwrite(dataStream()=%d - EXIT!', strlen($dataStream)));
return $this->getFileObject()->fwrite($dataStream);
}
* @return void
* @throws UnsupportedOperationException If this method is called
*/
- public function analyzeFile () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ public function analyzeFileStructure () {
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @return mixed Number of writes bytes or false on error
* @throws UnsupportedOperationException If this method is called
*/
- public function writeAtPosition ($seedPosition, $data) {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ public function writeAtPosition (int $seedPosition, string $data) {
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException If this method is called
*/
public function next () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException If this method is called
*/
public function valid () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException If this method is called
*/
public function key () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
}
namespace Org\Mxchange\CoreFramework\Filesystem\Pointer\Text;
// Import framework stuff
-use Org\Mxchange\CoreFramework\FileSystem\BaseFileIo;
+use Org\Mxchange\CoreFramework\Filesystem\BaseFileIo;
+use Org\Mxchange\CoreFramework\Filesystem\FileIoException;
use Org\Mxchange\CoreFramework\Filesystem\Pointer\OutputPointer;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
// Import SPL stuff
use \InvalidArgumentException;
use \SplFileInfo;
+use \SplFileObject;
/**
* A class for writing files
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @throws FileIoException If fopen() returns not a file resource
* @return void
*/
- public static final function createFrameworkTextFileOutputPointer (SplFileInfo $fileInstance, $mode) {
+ public static final function createFrameworkTextFileOutputPointer (SplFileInfo $fileInstance, string $mode) {
// Some pre-sanity checks...
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('TEXT-FILE-OUTPUT-POINTER: fileInstance[%s]=%s,mode=%s - CALLED!', get_class($fileInstance), $fileInstance->__toString(), $mode));
if (empty($mode)) {
// No filename given
- throw new InvalidArgumentException('Parameter "mode" is empty');
- } // END - if
+ throw new InvalidArgumentException('Parameter "mode" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Try to open a handler
$fileObject = $fileInstance->openFile($mode);
// Is it valid?
- if ((is_null($fileObject)) || ($fileObject === false)) {
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('TEXT-FILE-OUTPUT-POINTER: fileObject[]=%s', gettype($fileObject)));
+ if (!($fileObject instanceof SplFileObject)) {
// Something bad happend
throw new FileIoException($fileInstance, self::EXCEPTION_FILE_POINTER_INVALID);
- } // END - if
+ }
// Create new instance
$pointerInstance = new FrameworkTextFileOutputPointer();
$pointerInstance->setFileObject($fileObject);
// Return the instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('TEXT-FILE-OUTPUT-POINTER: pointerInstance=%s - EXIT!', $pointerInstance->__toString()));
return $pointerInstance;
}
* @throws NullPointerException If the file pointer instance is not set by setFileObject()
* @throws LogicException If there is no object being set
*/
- public function writeToFile ($dataStream) {
- if (is_null($this->getFileObject())) {
+ public function writeToFile (string $dataStream) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('TEXT-FILE-OUTPUT-POINTER: dataStream=%s - CALLED!', $dataStream));
+ if (empty($dataStream)) {
+ // Invalid parameter
+ throw new InvalidArgumentException('Parameter "dataStream" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (is_null($this->getFileObject())) {
// Pointer not initialized
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
} elseif (!is_object($this->getFileObject())) {
// Pointer is not a valid object!
- throw new LogicException(sprintf('this->fileObject[]=%s is no object', gettype($this->getFileObject())));
+ throw new LogicException(sprintf('this->fileObject[]=%s is no object', gettype($this->getFileObject())), FrameworkInterface::EXCEPTION_LOGIC_EXCEPTION);
}
// Write data to the file pointer and return written bytes
* @return void
* @throws UnsupportedOperationException If this method is called
*/
- public function analyzeFile () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ public function analyzeFileStructure () {
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @return mixed Number of writes bytes or false on error
* @throws UnsupportedOperationException If this method is called
*/
- public function writeAtPosition ($seedPosition, $data) {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ public function writeAtPosition (int $seedPosition, string $data) {
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException If this method is called
*/
public function next () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException If this method is called
*/
public function valid () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException If this method is called
*/
public function key () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Filesystem\File\BaseAbstractFile;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
// Import SPL stuff
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
*/
public function determineSeekPosition () {
// Not possible in text files
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @param $whence Added to offset (default: only use offset to seek to)
* @return $status Status of file seek: 0 = success, -1 = failed
*/
- public function seek ($offset, $whence = SEEK_SET) {
+ public function seek (int $offset, int $whence = SEEK_SET) {
// Not possible in text files
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] offset=' . $offset . ',whence=' . $whence);
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEXT-FILE: offset=' . $offset . ',whence=' . $whence);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* This class (or its implementations) are special file readers/writers.
* There is no need to read/write the whole file.
*/
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] infoInstance=' . $infoInstance);
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEXT-FILE: infoInstance=' . $infoInstance);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
}
namespace Org\Mxchange\CoreFramework\Filesystem\Text;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filesystem\File\BaseTextFile;
// Import SPL stuff
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Filesystem\Text\BaseInputTextFile;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Stream\Filesystem\CsvInputStreamer;
// Import SPL stuff
+use \InvalidArgumentException;
use \SplFileInfo;
+use \UnexpectedValueException;
/**
* A CSV file input class for writing CSV files
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* column separators will be parsed or they may be interpreted incorrectly.
*
* @param $columnSeparator Character to use separting columns
+ * @param $expectedMatches Expected matches, 0 is default and means flexible
* @return $lineArray An indexed array with the read line
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws UnexpectedValueException If the array count is not matching expected count
*/
- public function readCsvFileLine ($columnSeparator) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] columnSeparator=%s - CALLED!', __METHOD__, __LINE__, $columnSeparator));
-
- // Read raw line
- $data = $this->getPointerInstance()->readLine();
-
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] data()=%d', __METHOD__, __LINE__, strlen($data)));
+ public function readCsvFileLine (string $columnSeparator, int $expectedMatches = 0) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] columnSeparator=%s,expectedMatches=%d - CALLED!', __METHOD__, __LINE__, $columnSeparator, $expectedMatches));
+ if (strlen($columnSeparator) === 0) {
+ // No empty column separator
+ throw new InvalidArgumentException('Parameter "columnSeparator" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($expectedMatches < 0) {
+ // Below zero is not valid
+ throw new InvalidArgumentException(sprintf('expectedMatches=%d is below zero', $expectedMatches));
+ }
+
+ // Read raw line and trim anything unwanted away
+ $data = trim($this->getPointerInstance()->readLine());
+
+ // Is the line empty?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] data(%d)=%s', __METHOD__, __LINE__, strlen($data), $data));
+ if (empty($data)) {
+ // Yes, then skip below code
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Read data is an empty line - EXIT!', __METHOD__, __LINE__));
+ return;
+ }
// Parse data
$lineArray = $this->parseDataToIndexedArray($data, $columnSeparator);
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] lineArray()=%d - EXIT!', __METHOD__, __LINE__, count($lineArray)));
+ // Is the expected count found?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] expectedMatches=%d,lineArray()=%d', __METHOD__, __LINE__, $expectedMatches, count($lineArray)));
+ if (($expectedMatches > 0) && (count($lineArray) !== $expectedMatches)) {
+ // Invalid line found as strict count matching is requested
+ throw new UnexpectedValueException(sprintf('lineArray()=%d has not expected count %d', count($lineArray), $expectedMatches), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// Return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] lineArray()=%d - EXIT!', __METHOD__, __LINE__, count($lineArray)));
return $lineArray;
}
* @param $columnSeparator Character to use separting columns
* @return $lineArray An indexed array with the read line
*/
- private function parseDataToIndexedArray ($data, $columnSeparator) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] data()=%d,columnSeparator=%s - CALLED!', __METHOD__, __LINE__, strlen($data), $columnSeparator));
-
+ private function parseDataToIndexedArray (string $data, string $columnSeparator) {
// Init return array
- $lineArray = array();
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] data()=%d,columnSeparator=%s - CALLED!', __METHOD__, __LINE__, strlen($data), $columnSeparator));
+ $lineArray = [];
// Whether the parser reads a quoted string (which may contain the column separator again)
$isInQuotes = false;
// "Cache" char
$char = substr($data, $idx, 1);
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] idx=%s,char=%s ...', __METHOD__, __LINE__, $idx, $char));
-
// Is the column separator found and not within quotes?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] idx=%d,char=%s ...', __METHOD__, __LINE__, $idx, $char));
if (($isInQuotes === false) && ($char == $columnSeparator)) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Adding column=%s ...', __METHOD__, __LINE__, $column));
-
// Add this line to the array
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Adding column=%s ...', __METHOD__, __LINE__, $column));
array_push($lineArray, $column);
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] lineArray()=%d - After add!', __METHOD__, __LINE__, count($lineArray)));
-
// Clear variable ...
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] line[]=%d - After add!', __METHOD__, __LINE__, count($lineArray)));
$column = '';
// ... and skip it
continue;
} elseif ($char == chr(34)) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] column=%s ...', __METHOD__, __LINE__, $column));
-
// $column must be empty at this point if we are at starting quote
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] column=%s ...', __METHOD__, __LINE__, $column));
assert(($isInQuotes === true) || (empty($column)));
// Double-quote found, so flip variable
$isInQuotes = (!$isInQuotes);
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] isInQuotes=%d ...', __METHOD__, __LINE__, intval($isInQuotes)));
-
// Skip double-quote (escaping of them is not yet supported)
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] isInQuotes=%d ...', __METHOD__, __LINE__, intval($isInQuotes)));
continue;
}
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Adding char=%s ...', __METHOD__, __LINE__, $idx, $char));
-
// Add char to column
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Adding char=%s ...', __METHOD__, __LINE__, $idx, $char));
$column .= $char;
- } // END - for
+ }
// Is there something outstanding?
if (!empty($column)) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Adding column=%s ...', __METHOD__, __LINE__, $column));
-
// Then don't forget this. :-)
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Adding column=%s ...', __METHOD__, __LINE__, $column));
array_push($lineArray, $column);
// Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] lineArray()=%d - After add!', __METHOD__, __LINE__, count($lineArray)));
- } // END - if
-
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] lineArray()=%d - EXIT!', __METHOD__, __LINE__, count($lineArray)));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] line[]=%d - After add!', __METHOD__, __LINE__, count($lineArray)));
+ }
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] line[]=%d - EXIT!', __METHOD__, __LINE__, count($lineArray)));
return $lineArray;
}
namespace Org\Mxchange\CoreFramework\Filesystem\Text;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filesystem\File\BaseAbstractFile;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Output\BaseOutput;
/**
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
*
* @param $fileName File's name
* @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
*/
- protected function initFile ($fileName) {
+ protected function initFile (string $fileName) {
+ // Check parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-OUTPUT-TEXT-FILE: fileName=%s - CALLED!', $fileName));
+ if (empty($fileName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "fileName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get a file i/o pointer instance
- $pointerInstance = ObjectFactory::createObjectByConfiguredName('text_file_output_class', array($fileName));
+ $pointerInstance = ObjectFactory::createObjectByConfiguredName('text_file_output_class', [$fileName]);
// ... and set it here
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-OUTPUT-TEXT-FILE: Setting pointerInstance=%s ...', $pointerInstance->__toString()));
$this->setPointerInstance($pointerInstance);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-OUTPUT-TEXT-FILE: EXIT!');
}
}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
namespace Org\Mxchange\CoreFramework\Filter\User\Auth;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
use Org\Mxchange\CoreFramework\Filter\Filterable;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Loader\NoClassException;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
use Org\Mxchange\CoreFramework\User\BaseUser;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @return void
*/
protected function setDefaultAuthMethod () {
- $this->authMethod = $this->getConfigInstance()->getConfigEntry('auth_method_class');
+ $this->authMethod = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('auth_method_class');
}
/**
$authInstance->destroyAuthData();
// Mark the request as invalid
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add fatal message
$responseInstance->addFatalMessage('auth_data_incomplete');
// Stop here
throw new UserAuthorizationException($this, self::EXCEPTION_AUTH_DATA_INVALID);
- } // END - if
+ }
// Regular user account
- $className = $this->getConfigInstance()->getConfigEntry('user_class');
+ $className = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('user_class');
$methodName = 'createMemberByUserName';
// Now, try to get a user or guest instance
- if ($authLogin == $this->getConfigInstance()->getConfigEntry('guest_login_user')) {
+ if ($authLogin == FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('guest_login_user')) {
// Set class
- $className = $this->getConfigInstance()->getConfigEntry('guest_class');
+ $className = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('guest_class');
$methodName = 'createGuestByUserName';
- } // END - if
+ }
// Does the guest class exist?
if (!class_exists($className)) {
// Then abort here
- throw new NoClassException (array($this, $className), self::EXCEPTION_CLASS_NOT_FOUND);
- } // END - if
+ throw new NoClassException ([$this, $className], FrameworkInterface::EXCEPTION_CLASS_NOT_FOUND);
+ }
// Now try the dynamic login
- $userInstance = call_user_func_array(array($className, $methodName), array($authLogin));
+ $userInstance = call_user_func_array([$className, $methodName], [$authLogin]);
// Is the password correct?
if ($userInstance->getPasswordHash() !== $authHash) {
// Mismatching password
throw new UserPasswordMismatchException(array($this, $userInstance), BaseUser::EXCEPTION_USER_PASS_MISMATCH);
- } // END - if
+ }
// Remember auth and user instances in registry
- GenericRegistry::getRegistry()->addInstance('auth', $authInstance);
- GenericRegistry::getRegistry()->addInstance('user', $userInstance);
+ ObjectRegistry::getRegistry('generic')->addInstance('auth', $authInstance);
+ ObjectRegistry::getRegistry('generic')->addInstance('user', $userInstance);
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
+use Org\Mxchange\CoreFramework\Filter\Chain\FilterChainException;
use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Is only first email set?
if ((!empty($email1)) && (empty($email2))) {
// Request is invalid!
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Email 2 is empty
$responseInstance->addFatalMessage('email2_empty');
// Stop processing here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
// Is only second email set?
if ((empty($email1)) && (!empty($email2))) {
// Request is invalid!
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Email 1 is empty
$responseInstance->addFatalMessage('email1_empty');
// Stop processing here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
// Do both match?
if ($email1 != $email2) {
// Request is invalid!
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Emails are mismatching
$responseInstance->addFatalMessage('emails_mismatch');
// Stop processing here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
// Are email and confirmation empty?
if ((empty($email1)) && (empty($email2))) {
// No email change required!
return true;
- } // END - if
+ }
// Now, get a user instance for comparison
- $userInstance = GenericRegistry::getRegistry()->getInstance('user');
+ $userInstance = ObjectRegistry::getRegistry('generic')->getInstance('user');
// Get the email field
$userEmail = $userInstance->getField('email');
if ($userEmail == $email1) {
// Nothing has been changed is fine...
return true;
- } // END - if
+ }
// Update the "new_email" field
- $this->partialStub('Unfinished part.');
+ DebugMiddleware::getSelfInstance()->partialStub('Unfinished part.');
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
+use Org\Mxchange\CoreFramework\Filter\Chain\FilterChainException;
use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Is only first email set?
if ((!empty($pass1)) && (empty($pass2))) {
// Request is invalid!
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Email 2 is empty
$responseInstance->addFatalMessage('pass2_empty');
// Stop processing here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
// Is only second pass set?
if ((empty($pass1)) && (!empty($pass2))) {
// Request is invalid!
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Email 1 is empty
$responseInstance->addFatalMessage('pass1_empty');
// Stop processing here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
// Are password and confirmation empty?
if ((empty($pass1)) && (empty($pass2))) {
// Don't change password here
return true;
- } // END - if
+ }
// Do both match?
if ($pass1 != $pass2) {
// Request is invalid!
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Emails are mismatching
$responseInstance->addFatalMessage('pass_mismatch');
// Stop processing here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
// Now, get a user instance for comparison
- $userInstance = GenericRegistry::getRegistry()->getInstance('user');
+ $userInstance = ObjectRegistry::getRegistry('generic')->getInstance('user');
// Update the "password" field
- $this->partialStub('Unfinished part.');
+ DebugMiddleware::getSelfInstance()->partialStub('Unfinished part.');
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
+use Org\Mxchange\CoreFramework\Filter\Chain\FilterChainException;
use Org\Mxchange\CoreFramework\Filter\Filterable;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Was the "rules" value found in form? And is it set?
if (is_null($rules)) {
// Not found in form so stop processing here
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('rules_unchecked');
// Skip further processing
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
use Org\Mxchange\CoreFramework\Filter\Filterable;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Implement this!
- $this->partialStub('Please implement this method.');
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this method.');
}
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Name of the filter class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Name of the real class' name
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
namespace Org\Mxchange\CoreFramework\Chain\Filter;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Filter\Chain\FilterChainException;
use Org\Mxchange\CoreFramework\Filter\Filterable;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
use Org\Mxchange\CoreFramework\Registry\Registerable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
protected function getFilters () {
// Default is nothing found
- $filters = array();
+ $filters = [];
// Are some filters set?
if ($this->isValidGenericArrayKey('filters', 'generic', 'dummy')) {
// Then get them
$filters = $this->getGenericArrayKey('filters', 'generic', 'dummy');
- } // END - if
+ }
// Return it
return $filters;
*/
protected function getPostFilters () {
// Default is nothing found
- $filters = array();
+ $filters = [];
// Are some filters set?
if ($this->isValidGenericArrayKey('filters', 'post', 'dummy')) {
// Then get them
$filters = $this->getGenericArrayKey('filters', 'post', 'dummy');
- } // END - if
+ }
// Return it
return $filters;
// Run all filters
//* DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('COUNT=' . $this->countGenericArray('filters'));
foreach ($this->getFilters() as $filterInstance) {
- // Must be an instance of Filterable
- assert($filterInstance instanceof Filterable);
-
// Try to execute this filter
try {
//* DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILTER: ' . $filterInstance->__toString() . ': Processing started.');
self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Failed to execute lase filter ' . $filterInstance->__toString() . ': ' . $e->getMessage());
break;
}
- } // END - foreach
+ }
}
}
namespace Org\Mxchange\CoreFramework\Filter\Captcha;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
use Org\Mxchange\CoreFramework\Filter\Filterable;
use Org\Mxchange\CoreFramework\Helper\Crypto\CryptoHelper;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Is it there?
if (is_null($encryptRequest)) {
// Not found, so request is invalid
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Throw exception
throw new EncryptMissingException($this, CryptoHelper::EXCEPTION_ENCRYPT_MISSING);
- } // END - if
+ }
// Decode it fully
$encryptDecoded = base64_decode(str_replace(' ', '+', urldecode($encryptRequest)));
// Get a crypto helper and decrypt the string
- $decryptedString = ObjectFactory::createObjectByConfiguredName('crypto_class')->decryptString($encryptDecoded);
+ $decryptedString = CryptoHelper::getSelfInstance()->decryptString($encryptDecoded);
// Is it the expected length?
- if (strlen($decryptedString) != $this->getConfigInstance()->getConfigEntry('captcha_string_length')) {
+ if (strlen($decryptedString) != FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('captcha_string_length')) {
// Not found, so request is invalid
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Throw exception
throw new EncryptInvalidLengthException($this, CryptoHelper::EXCEPTION_ENCRYPT_INVALID);
- } // END - if
+ }
// Write it to the request
$requestInstance->setRequestElement('decrypted', $decryptedString);
namespace Org\Mxchange\CoreFramework\Filter\User\Username;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
use Org\Mxchange\CoreFramework\Filter\Filterable;
use Org\Mxchange\CoreFramework\Request\Requestable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$userName = $requestInstance->getRequestElement('username');
// Does the user name match the guest login?
- if ($userName == $this->getConfigInstance()->getConfigEntry('guest_login_user')) {
+ if ($userName == FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('guest_login_user')) {
// Then set the password to the configured password
- $requestInstance->setRequestElement('pass1', $this->getConfigInstance()->getConfigEntry('guest_login_passwd'));
- $requestInstance->setRequestElement('pass2', $this->getConfigInstance()->getConfigEntry('guest_login_passwd'));
- } // END - if
+ $requestInstance->setRequestElement('pass1', FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('guest_login_passwd'));
+ $requestInstance->setRequestElement('pass2', FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('guest_login_passwd'));
+ }
}
}
use Org\Mxchange\CoreFramework\Factory\News\HtmlNewsFactory;
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
/**
* Creates an instance of this filter class
*
- * @return $filterInstance An instance of this filter class
+ * @return $filterInstance An instance of this filter class
*/
public static final function createNewsDownloadFilter () {
// Get a new instance
$newsInstance = HtmlNewsFactory::createFactoryByRequest($requestInstance);
// Store the news instance in registry
- GenericRegistry::getRegistry()->addInstance('news', $newsInstance);
+ ObjectRegistry::getRegistry('generic')->addInstance('news', $newsInstance);
}
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Action\PerformableAction;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Configuration\NoConfigEntryException;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
+use Org\Mxchange\CoreFramework\Filter\Chain\FilterChainException;
use Org\Mxchange\CoreFramework\Filter\Filterable;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
use Org\Mxchange\CoreFramework\Loader\NoClassException;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Is the resolver set?
if (is_null($resolverInstance)) {
// Throw an exception here
- throw new NullPointerException($filterInstance, self::EXCEPTION_IS_NULL_POINTER);
- } // END - if
+ throw new NullPointerException($filterInstance, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
+ }
// Get the action name from resolver
$actionName = $resolverInstance->getActionName();
* @param $actionName Action name to set
* @return void
*/
- protected final function setActionName ($actionName) {
- $this->actionName = (string) $actionName;
+ protected final function setActionName (string $actionName) {
+ $this->actionName = $actionName;
}
/**
// Try to get real discovery class
try {
// Get an instance from the object factory
- $discoveryInstance = ObjectFactory::createObjectByConfiguredName($this->getActionName() . '_payment_discovery', array($this));
+ $discoveryInstance = ObjectFactory::createObjectByConfiguredName($this->getActionName() . '_payment_discovery', [$this]);
// Call the discovery method
$discoveryInstance->discover($requestInstance);
// Remember this instance if all wents fine
- GenericRegistry::getRegistry()->addInstance('payments', $discoveryInstance);
+ ObjectRegistry::getRegistry('generic')->addInstance('payments', $discoveryInstance);
} catch (NoConfigEntryException $e) {
// Something bad happend
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('payment_config_entry_error');
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} catch (NoClassException $e) {
// Something bad happend
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('payment_class_error');
namespace Org\Mxchange\CoreFramework\Filter\User\Status;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseWrapper;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseFrontend;
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Get user instance from registry
- $userInstance = GenericRegistry::getRegistry()->getInstance('user');
+ $userInstance = ObjectRegistry::getRegistry('generic')->getInstance('user');
// Get "confirmed" status from config
- $confirmed = $this->getConfigInstance()->getConfigEntry('user_status_confirmed');
+ $confirmed = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('user_status_confirmed');
// Update the user status to "confirmed" here
- $userInstance->updateDatabaseField(UserDatabaseWrapper::DB_COLUMN_USER_STATUS, $confirmed);
+ $userInstance->updateDatabaseField(UserDatabaseFrontend::DB_COLUMN_USER_STATUS, $confirmed);
// Wipe out the confirm hash for extra security
- $userInstance->updateDatabaseField(UserDatabaseWrapper::DB_COLUMN_CONFIRM_HASH, '');
+ $userInstance->updateDatabaseField(UserDatabaseFrontend::DB_COLUMN_CONFIRM_HASH, '');
// Write all updates to the database
+ die(__METHOD__ . ': REWRITE!' . PHP_EOL);
$userInstance->flushPendingUpdates();
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Get user instance from registry
- $userInstance = GenericRegistry::getRegistry()->getInstance('user');
+ $userInstance = ObjectRegistry::getRegistry('generic')->getInstance('user');
// Now update last activity
$userInstance->updateLastActivity($requestInstance);
// Update auth data as well
- $authInstance = GenericRegistry::getRegistry()->getInstance('auth');
+ $authInstance = ObjectRegistry::getRegistry('generic')->getInstance('auth');
$authInstance->updateAuthData();
// Write all updates to the database
+ die(__METHOD__ . ': REWRITE!' . PHP_EOL);
$userInstance->flushPendingUpdates();
}
namespace Org\Mxchange\CoreFramework\Filter\Validator\Email;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
+use Org\Mxchange\CoreFramework\Filter\Chain\FilterChainException;
use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$email = $requestInstance->getRequestElement('email');
// Is the Email set?
- if ((is_null($email)) || ($this->getConfigInstance()->getConfigEntry('register_email_unique') == 'Y')) {
+ if ((is_null($email)) || (FrameworkBootstrap::getConfigurationInstance()->isEnabled('register_email_unique'))) {
// Try it again
$email1 = $requestInstance->getRequestElement('email1');
$email2 = $requestInstance->getRequestElement('email2');
// Is the email still not set?
if ((is_null($email1)) || (is_null($email2))) {
// Not found in form so stop the filtering process
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('email_unset');
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} elseif ((empty($email1)) || (empty($email2))) {
// Email is empty
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Is the email empty?
if (empty($email1)) {
// Add a message to the response
$responseInstance->addFatalMessage('email1_empty');
- } // END - if
+ }
// Is the confirmation empty?
if (empty($email2)) {
// Add a message to the response
$responseInstance->addFatalMessage('email2_empty');
- } // END - if
+ }
// Abort here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} elseif ($this->ifEmailIsTaken($email1)) {
// Email is already taken
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('email_taken');
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} elseif ($email1 != $email2) {
// Emails didn't match
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('emails_mismatch');
// Abort here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - elseif
+ }
} elseif (empty($email)) {
// Empty field!
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('email_empty');
// Abort here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - elseif
+ }
}
/**
* @param $email Email to check for existence
* @return $alreadyTaken Whether the email has been taken
*/
- private function ifEmailIsTaken ($email) {
+ private function ifEmailIsTaken (string $email) {
// Default is already taken
$alreadyTaken = true;
$userInstance = NULL;
// Get a registry instance
- $registry = GenericRegistry::getRegistry();
+ $registryInstance = ObjectRegistry::getRegistry('generic');
// Is the user already there?
- if ($registry->instanceExists('user')) {
+ if ($registryInstance->instanceExists('user')) {
// Use the instance for checking for the email
- $userInstance = $registry->getInstance('user');
+ $userInstance = $registryInstance->getInstance('user');
$userInstance->setEmailAddress($email);
} else {
// If this instance is created then the username *does* exist
- $userInstance = call_user_func_array(array($this->getConfigInstance()->getConfigEntry('user_class'), 'createMemberByEmail'), array($email));
+ $userInstance = call_user_func_array(array(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('user_class'), 'createMemberByEmail'), array($email));
// Remember this user instance in our registry for later usage
- $registry->addInstance('user', $userInstance);
+ $registryInstance->addInstance('user', $userInstance);
}
// Does the email exist?
// Import framework stuff
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
+use Org\Mxchange\CoreFramework\Filter\Chain\FilterChainException;
use Org\Mxchange\CoreFramework\Filter\Filterable;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Is the password still not set?
if ((is_null($password1)) || (is_null($password2))) {
// Not found in form so stop the filtering process
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('password_unset');
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} elseif ((empty($password1)) || (empty($password2))) {
// Password is empty
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Is the password empty?
if (empty($password1)) {
// Add a message to the response
$responseInstance->addFatalMessage('pass1_empty');
- } // END - if
+ }
// Is the confirmation empty?
if (empty($password2)) {
// Add a message to the response
$responseInstance->addFatalMessage('pass2_empty');
- } // END - if
+ }
// Abort here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} elseif ($password1 != $password2) {
// Passwords didn't match
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('pass_mismatch');
// Abort here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - elseif
+ }
}
}
namespace Org\Mxchange\CoreFramework\Filter\Validator\Username;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
+use Org\Mxchange\CoreFramework\Filter\Chain\FilterChainException;
use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
+use Org\Mxchange\CoreFramework\User\UsernameMissingException;
/**
* A concrete filter for validating the username. This filter may intercept the
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Is the username set?
if (is_null($userName)) {
// Not found in form so stop the filtering process
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('username_unset');
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} elseif (empty($userName)) {
// Empty field!
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('username_empty');
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} elseif ($this->ifUserNameIsTaken($userName)) {
// Username is already taken
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('username_taken');
* @param $userName Username to check for existence
* @return $alreadyTaken Whether the username has been taken
*/
- private function ifUserNameIsTaken ($userName) {
+ private function ifUserNameIsTaken (string $userName) {
// Default is already taken
$alreadyTaken = true;
$userInstance = NULL;
// Get a registry instance
- $registry = GenericRegistry::getRegistry();
+ $registryInstance = ObjectRegistry::getRegistry('generic');
// Is the user already there?
- if ($registry->instanceExists('user')) {
+ if ($registryInstance->instanceExists('user')) {
// Use the instance for checking for the email
- $userInstance = $registry->getInstance('user');
+ $userInstance = $registryInstance->getInstance('user');
$userInstance->setUserName($userName);
} else {
// If this instance is created then the username *does* exist
try {
// Get a new instance
- $userInstance = call_user_func_array(array($this->getConfigInstance()->getConfigEntry('user_class'), 'createMemberByUsername'), array($userName));
+ $userInstance = call_user_func_array(array(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('user_class'), 'createMemberByUsername'), array($userName));
// Remember this user instance in our registry for later usage
- $registry->addInstance('user', $userInstance);
+ $registryInstance->addInstance('user', $userInstance);
} catch (UsernameMissingException $e) {
// User was not found
}
if ((is_null($userInstance)) || ($userInstance->ifUsernameExists() === false)) {
// This username is still available
$alreadyTaken = false;
- } // END - if
+ }
// Return the result
return $alreadyTaken;
// Import framework stuff
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
+use Org\Mxchange\CoreFramework\Filter\Chain\FilterChainException;
use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Helper\Crypto\CryptoHelper;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
use Org\Mxchange\CoreFramework\User\BaseUser;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Is the password still not set?
if (is_null($password)) {
// Not found in form so stop the filtering process
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('password_unset');
// Abort here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
- } // END - if
+ }
+ }
if (empty($password)) {
// Password is empty
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('password_empty');
// Abort here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
// Get a user instance
- $userInstance = GenericRegistry::getRegistry()->getInstance('user');
+ $userInstance = ObjectRegistry::getRegistry('generic')->getInstance('user');
// Get current hash
$currentHash = $userInstance->getField('pass_hash');
// Get an encryption helper and encrypt the password
- $passHash = ObjectFactory::createObjectByConfiguredName('crypto_class')->hashString($password, $currentHash);
+ $passHash = CryptoHelper::getSelfInstance()->hashString($password, $currentHash);
// Does it match?
if ($currentHash != $passHash) {
// Throw an exception here to stop the proccessing
throw new AccountPasswordMismatchException($this, BaseUser::EXCEPTION_USER_PASS_MISMATCH);
- } // END - if
+ }
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
+use Org\Mxchange\CoreFramework\Filter\Chain\FilterChainException;
use Org\Mxchange\CoreFramework\Filter\Filterable;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Day of birth set?
if (!$requestInstance->isRequestElementSet('birth_day')) {
// Day of birth isn't set
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('day_of_birth_unset');
- } // END - if
+ }
// Month of birth set?
if (!$requestInstance->isRequestElementSet('birth_month')) {
// Month of birth isn't set
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('month_of_birth_unset');
- } // END - if
+ }
// Year of birth set?
if (!$requestInstance->isRequestElementSet('birth_year')) {
// Year of birth isn't set
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('year_of_birth_unset');
- } // END - if
+ }
// Is the request still valid?
if (!$requestInstance->isRequestValid()) {
// Abort here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
// Now comes the final check
$birthCheck = mktime(
// Is there a number or such? (we don't care about the value itself here)
if (empty($birthCheck)) {
// Validation has failed
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('birthday_invalid');
// Abort here
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
}
}
namespace Org\Mxchange\CoreFramework\Filter\Verifier\Confirmation;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseWrapper;
+use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseFrontend;
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
+use Org\Mxchange\CoreFramework\Filter\Chain\FilterChainException;
use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Is this code set?
if (is_null($confirmCode)) {
// Is not in request
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('confirm_code_unset');
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} elseif (empty($confirmCode)) {
// Email is empty
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('confirm_code_empty');
}
// Get a user instance from registry
- $userInstance = GenericRegistry::getRegistry()->getInstance('user');
+ $userInstance = ObjectRegistry::getRegistry('generic')->getInstance('user');
// Get the confirm code from user for comparison
- $userCode = $userInstance->getField(UserDatabaseWrapper::DB_COLUMN_CONFIRM_HASH);
+ $userCode = $userInstance->getField(UserDatabaseFrontend::DB_COLUMN_CONFIRM_HASH);
// Do we have the same code or different?
if ($userCode != $confirmCode) {
// Email is empty
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Redirect to error page
$responseInstance->redirectToConfiguredUrl('confirm_code_invalid');
// Stop processing here
exit();
- } // END - if
+ }
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
+use Org\Mxchange\CoreFramework\Filter\Chain\FilterChainException;
use Org\Mxchange\CoreFramework\Filter\Filterable;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Implement this!
- $this->partialStub('Please implement this method.');
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this method.');
}
}
namespace Org\Mxchange\CoreFramework\Filter\Verifier\Captcha;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
+use Org\Mxchange\CoreFramework\Filter\Chain\FilterChainException;
use Org\Mxchange\CoreFramework\Filter\Filterable;
+use Org\Mxchange\CoreFramework\Helper\Crypto\CryptoHelper;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Is the form set?
- if (($requestInstance->getRequestElement('command') !== 'do_form') || (!$requestInstance->isRequestElementSet('form'))) {
+ if (($requestInstance->getRequestElement('command') !== 'do_form') || (!$requestInstance->isRequestElementSet('form'))) {
// Required field not set
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add fatal message
$responseInstance->addFatalMessage('command_form_invalid');
// Skip further processing
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - if
+ }
// Create config entry
- $configKey = sprintf('%s_captcha_secured',
- $requestInstance->getRequestElement('form')
- );
+ $configKey = sprintf('%s_captcha_secured', $requestInstance->getRequestElement('form'));
// Is the CAPTCHA enabled?
- if ($this->getConfigInstance()->getConfigEntry($configKey) != 'Y') {
+ if (FrameworkBootstrap::getConfigurationInstance()->isEnabled($configKey)) {
// Not enabled, so don't check
return;
- } // END - if
+ }
// Get the captcha code
$captchaCode = $requestInstance->getRequestElement('c_code');
// Is this set?
if (is_null($captchaCode)) {
// Not set so request is invalid
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add fatal message
$responseInstance->addFatalMessage('captcha_code_unset');
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} elseif (empty($captchaCode)) {
// Empty value so request is invalid
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add fatal message
$responseInstance->addFatalMessage('captcha_code_empty');
// Is this set?
if (is_null($captchaHash)) {
// Not set so request is invalid
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add fatal message
$responseInstance->addFatalMessage('captcha_hash_unset');
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} elseif (empty($captchaHash)) {
// Empty value so request is invalid
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add fatal message
$responseInstance->addFatalMessage('captcha_hash_empty');
}
// Now, both are set hash the given one. First get a crypto instance
- $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
+ $cryptoInstance = CryptoHelper::getSelfInstance();
// Then hash the code
$hashedCode = $cryptoInstance->hashString($captchaCode, $captchaHash);
// Is this CAPTCHA valid?
if ($hashedCode != $captchaHash) {
// Not the same so request is invalid
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add fatal message
$responseInstance->addFatalMessage('captcha_hash_mismatch');
// Skip further processing
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
- } // END - not the same!
+ }
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
+use Org\Mxchange\CoreFramework\Filter\Chain\FilterChainException;
use Org\Mxchange\CoreFramework\Filter\Filterable;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Is the password still not set?
if (is_null($password)) {
// Not found in form so stop the filtering process
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('password_unset');
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} elseif (empty($password)) {
// Password is empty
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('password_empty');
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Is the password still not set?
if (is_null($password)) {
// Not found in form so stop the filtering process
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('password_unset');
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} elseif (empty($password)) {
// Password is empty
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('password_empty');
namespace Org\Mxchange\CoreFramework\Filter\Verifier\User;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
+use Org\Mxchange\CoreFramework\Filter\Chain\FilterChainException;
use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Is the username set?
if (is_null($userName)) {
// Not found in form so stop the filtering process
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('username_guest_unset');
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} elseif (empty($userName)) {
// Empty field!
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('username_guest_empty');
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} elseif ($this->ifUserGuestIsTaken($userName) === false) {
// Username is already taken
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('username_guest_not_found');
* @param $userName Username to check for existence
* @return $alreadyTaken Whether the username has been taken
*/
- private function ifUserGuestIsTaken ($userName) {
+ private function ifUserGuestIsTaken (string $userName) {
// Default is already taken
$alreadyTaken = true;
$userInstance = NULL;
// Get a registry instance
- $registry = GenericRegistry::getRegistry();
+ $registryInstance = ObjectRegistry::getRegistry('generic');
// Is the user already there?
- if ($registry->instanceExists('user')) {
+ if ($registryInstance->instanceExists('user')) {
// Use the instance for checking for the email
- $userInstance = $registry->getInstance('user');
+ $userInstance = $registryInstance->getInstance('user');
$userInstance->setUserGuest($userName);
} else {
// If this instance is created then the username *does* exist
try {
// Get a new instance
- $userInstance = call_user_func_array(array($this->getConfigInstance()->getConfigEntry('guest_class'), 'createGuestByUsername'), array($userName));
+ $userInstance = call_user_func_array(array(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('guest_class'), 'createGuestByUsername'), array($userName));
// Remember this user instance in our registry for later usage
- $registry->addInstance('user', $userInstance);
+ $registryInstance->addInstance('user', $userInstance);
} catch (UsernameMissingException $e) {
// User was not found
}
namespace Org\Mxchange\CoreFramework\Filter\Verifier\User;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
+use Org\Mxchange\CoreFramework\Filter\Chain\FilterChainException;
use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
+use Org\Mxchange\CoreFramework\User\UsernameMissingException;
/**
* A concrete filter for verfying the username. This filter may intercept the
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Is the username set?
if (is_null($userName)) {
// Not found in form so stop the filtering process
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('username_unset');
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} elseif (empty($userName)) {
// Empty field!
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('username_empty');
throw new FilterChainException($this, self::EXCEPTION_FILTER_CHAIN_INTERCEPTED);
} elseif ($this->ifUserNameIsTaken($userName) === false) {
// Username is already taken
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Add a message to the response
$responseInstance->addFatalMessage('username_not_found');
* @param $userName Username to check for existence
* @return $alreadyTaken Whether the username has been taken
*/
- private function ifUserNameIsTaken ($userName) {
+ private function ifUserNameIsTaken (string $userName) {
// Default is already taken
$alreadyTaken = true;
$userInstance = NULL;
// Get a registry instance
- $registry = GenericRegistry::getRegistry();
+ $registryInstance = ObjectRegistry::getRegistry('generic');
// Is the user already there?
- if ($registry->instanceExists('user')) {
+ if ($registryInstance->instanceExists('user')) {
// Use the instance for checking for the email
- $userInstance = $registry->getInstance('user');
+ $userInstance = $registryInstance->getInstance('user');
$userInstance->setUserName($userName);
} else {
// If this instance is created then the username *does* exist
try {
// Get a new instance
- $userInstance = call_user_func_array(array($this->getConfigInstance()->getConfigEntry('user_class'), 'createMemberByUsername'), array($userName));
+ $userInstance = call_user_func_array(array(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('user_class'), 'createMemberByUsername'), array($userName));
// Remember this user instance in our registry for later usage
- $registry->addInstance('user', $userInstance);
+ $registryInstance->addInstance('user', $userInstance);
} catch (UsernameMissingException $e) {
// User was not found
}
if ((is_null($userInstance)) || ($userInstance->ifUsernameExists() === false)) {
// This username is still available
$alreadyTaken = false;
- } // END - if
+ }
// Return the result
return $alreadyTaken;
namespace Org\Mxchange\CoreFramework\Filter\Verifier\User;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function execute (Requestable $requestInstance, Responseable $responseInstance) {
// Get a user instance for comparison
- $userInstance = GenericRegistry::getRegistry()->getInstance('user');
+ $userInstance = ObjectRegistry::getRegistry('generic')->getInstance('user');
// Is the user account confirmed?
- if ((!$userInstance->isConfirmed()) && (!$userInstance->isGuest()) && ($requestInstance->getRequestElement('action') != $this->getConfigInstance()->getConfigEntry('action_status_problem'))) {
+ if ((!$userInstance->isConfirmed()) && (!$userInstance->isGuest()) && ($requestInstance->getRequestElement('action') != FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('action_status_problem'))) {
// Request is invalid!
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Redirect to configured URL
$responseInstance->redirectToConfiguredUrl('login_user_status');
// Stop processing here
exit();
- } // END - if
+ }
}
}
namespace Org\Mxchange\CoreFramework\Filter\Verifier\User;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseWrapper;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseFrontend;
+use Org\Mxchange\CoreFramework\Factory\User\UserFactory;
use Org\Mxchange\CoreFramework\Filter\BaseFilter;
use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Response\Responseable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Is the email address valid?
if ($userInstance->ifEmailAddressExists() === false) {
// Request is invalid!
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Redirect to configured URL
$responseInstance->redirectToConfiguredUrl('user_unconfirmed_email_missing');
// Stop processing here
exit();
- } // END - if
+ }
// Is the user account confirmed?
- if ($userInstance->getField(UserDatabaseWrapper::DB_COLUMN_USER_STATUS) != $this->getConfigInstance()->getConfigEntry('user_status_unconfirmed')) {
+ if ($userInstance->getField(UserDatabaseFrontend::DB_COLUMN_USER_STATUS) != FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('user_status_unconfirmed')) {
// Request is invalid!
- $requestInstance->requestIsValid(false);
+ $requestInstance->setIsRequestValid(FALSE);
// Redirect to configured URL
$responseInstance->redirectToConfiguredUrl('user_not_unconfirmed');
// Stop processing here
exit();
- } // END - if
+ }
// Add this instance to registry
- GenericRegistry::getRegistry()->addInstance('user', $userInstance);
+ ObjectRegistry::getRegistry('generic')->addInstance('user', $userInstance);
}
}
<?php
// Own namespace
-namespace Org\Mxchange\CoreFramework\Wrapper\Fuse;
+namespace Org\Mxchange\CoreFramework\Frontend\Fuse;
// Import framework stuff
use Org\Mxchange\CoreFramework\Registry\Registerable;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
public function FsOpen ($path, FuseFileInfo $fi) {
if (($fi->flags & FUSE_O_ACCMODE) != FUSE_O_RDONLY) {
return -FUSE_ENOACCES;
- } // END - if
+ }
return -FUSE_ENOERR;
}
if ($offset > strlen($data)) {
return 0;
- } // END - if
+ }
$buf = substr( $data, $offset, $size );
public function FsReadDir ($path, array &$buf) {
if (strcmp($path, '/') != 0) {
return -FUSE_ENOENT;
- } // END - if
+ }
$buf[] = '.';
$buf[] = '..';
<?php
// Own namespace
-namespace CoreFramework\Handler\;
+namespace Org\Mxchange\CoreFramework\Handler\;
// Import framework stuff
use Org\Mxchange\CoreFramework\Handler\BaseHandler;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
// Import framework stuff
use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Handler\DataSet\HandleableDataSet;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+// Import SPL stuff
+use \InvalidArgumentException;
+
/**
* A general Handler
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-HANDLER: className=%s - CONSTRUCTED!', $className));
parent::__construct($className);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-HANDLER: EXIT!');
}
/**
* @param $handlerName Name of this handler
* @return void
*/
- protected final function setHandlerName ($handlerName) {
+ protected final function setHandlerName (string $handlerName) {
$this->handlerName = $handlerName;
}
* @todo Rewrite this to use DHT
*/
public function addArrayToDataSet (StoreableCriteria $dataSetInstance, array $messageData) {
- // Add some generic data all messageData arrays provide
- /*
- $dataSetInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_ANSWER_STATUS, $messageData[BaseXmlAnswerTemplateEngine::ANSWER_STATUS]);
- $dataSetInstance->addCriteria(NodeListDatabaseWrapper::DB_COLUMN_MESSAGE_TYPE , $messageData[NetworkPackage::MESSAGE_ARRAY_TYPE]);
- */
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-HANDLER: dataSetInstance=%s,messageData()=%d - CALLED!', $dataSetInstance->__toString(), count($messageData)));
+ if (count($messageData) == 0) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "messageData" is an empty array', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-HANDLER: EXIT!');
}
}
namespace Org\Mxchange\CoreFramework\Handler\Task;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Handler\BaseHandler;
-use Org\Mxchange\CoreFramework\Lists\Listable;
use Org\Mxchange\CoreFramework\Registry\Registerable;
use Org\Mxchange\CoreFramework\Task\Taskable;
+use Org\Mxchange\CoreFramework\Traits\Iterator\IteratorTrait;
+use Org\Mxchange\CoreFramework\Traits\Lists\ListableTrait;
+use Org\Mxchange\CoreFramework\Traits\Visitor\VisitorTrait;
use Org\Mxchange\CoreFramework\Visitor\Visitable;
+// Import SPL stuff
+use \InvalidArgumentException;
+use \UnexpectedValueException;
+
/**
* A Task handler
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class TaskHandler extends BaseHandler implements Registerable, HandleableTask {
+ // Load traits
+ use IteratorTrait;
+ use ListableTrait;
+ use VisitorTrait;
+
// Exception constants
const EXCEPTION_TASK_IS_INVALID = 0xb00;
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TASK-HANDLER: CONSTRUCTWD!');
parent::__construct(__CLASS__);
// Set handler name
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('TASK-HANDLER: Setting handlerName=task ...');
$this->setHandlerName('task');
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TASK-HANDLER: EXIT!');
}
/**
*/
public static final function createTaskHandler () {
// Get new instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TASK-HANDLER: CALLED!');
$handlerInstance = new TaskHandler();
// Output debug message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Initializing task handler.');
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('TASK-HANDLER: Initializing task handler.');
// Init the task list
$handlerInstance->setListInstance(ObjectFactory::createObjectByConfiguredName('task_list_class'));
$handlerInstance->registerTask('idle_loop', $taskInstance);
// Output debug message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task handler initialized.');
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('TASK-HANDLER: Task handler initialized.');
// Return the prepared instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TASK-HANDLER:handlerInstance=%s - EXIT!', $handlerInstance->__toString()));
return $handlerInstance;
}
*/
private function executeCurrentTask () {
// Update no task by default
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TASK-HANDLER: CALLED!');
$updateTask = false;
// Is the current task valid?
if (!$this->getListInstance()->getIterator()->valid()) {
// Not valid!
throw new InvalidTaskException($this, self::EXCEPTION_TASK_IS_INVALID);
- } // END - if
+ }
// Get current task
$currentTask = $this->getListInstance()->getIterator()->current();
// Is the task not yet started?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TASK-HANDLER: currentTask()=%d', count($currentTask)));
if ($currentTask['task_started'] === false) {
// Determine difference between current time and registration
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TASK-HANDLER: currentTask[id]=%s has not started yet, checking ...', $currentTask['id']));
$diff = ($this->getMilliTime() - $currentTask['task_registered']) * 1000;
// Should we start now?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TASK-HANDLER: diff=%d,currentTask[task_startup_delay]=%d', $diff, $currentTask['task_startup_delay']));
if ($diff < $currentTask['task_startup_delay']) {
// Skip this silently
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task ' . $currentTask['id'] . ' not started: diff=' . $diff . ',task_startup_delay=' . $currentTask['task_startup_delay']);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TASK-HANDLER: Task %s not started: diff=%d,task_startup_delay=%d', $currentTask['id'], $diff, $currentTask['task_startup_delay']));
return;
- } // END - if
+ }
// Launch the task and mark it as updated
$currentTask['task_started'] = true;
$updateTask = true;
// Debug message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task ' . $currentTask['id'] . ' started with startup_delay=' . $currentTask['task_startup_delay'] . 'ms');
- } // END - if
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TASK-HANDLER: Task %s started with startup_delay=%dms', $currentTask['id'], $currentTask['task_startup_delay']));
+ }
// Get time difference from interval delay
$diff = ($this->getMilliTime() - $currentTask['task_last_activity']) * 1000;
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task ' . $currentTask['id'] . ' diff=' . $diff . ',task_interval_delay=' . $currentTask['task_interval_delay'] . ',task_max_runs=' . $currentTask['task_max_runs'] . ',task_total_runs=' . $currentTask['task_total_runs']);
-
// Is the interval delay reached?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('TASK-HANDLER: Task ' . $currentTask['id'] . ' diff=' . $diff . ',task_interval_delay=' . $currentTask['task_interval_delay'] . ',task_max_runs=' . $currentTask['task_max_runs'] . ',task_total_runs=' . $currentTask['task_total_runs']);
if ((($diff < $currentTask['task_interval_delay']) && ($currentTask['task_max_runs'] == 0)) || (($currentTask['task_max_runs'] > 0) && ($currentTask['task_total_runs'] == $currentTask['task_max_runs']))) {
// Should we update the task from startup?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TASK-HANDLER: currentTask[id]=%s has reached interval ... updateTask=%d', $currentTask['id'], intval($updateTask)));
if ($updateTask === true) {
// Update the task before leaving
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TASK-HANDLER: Updating task %s ...', $currentTask['id']));
$this->updateTask($currentTask);
- } // END - if
+ }
// Skip this silently
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TASK-HANDLER: Task %s has been updated - EXIT!', $currentTask['id']));
return;
- } // END - if
+ }
// Set last activity
$currentTask['task_last_activity'] = $this->getMilliTime();
$currentTask['task_total_runs']++;
// Update the task
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TASK-HANDLER: Updating task %s ...', $currentTask['id']));
$this->updateTask($currentTask);
// And visit/run it
// @TODO Messurement can be added around this call
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TASK-HANDLER: Invoking currentTask[task_instance]->accept(%s), task_instance=%s ...', $this->getVisitorInstance()->__toString(), $currentTask['task_instance']->__toString()));
$currentTask['task_instance']->accept($this->getVisitorInstance());
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TASK-HANDLER: EXIT!');
}
/**
*/
private function updateTask (array $taskEntry) {
// Get the key from current iteration
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TASK-HANDLER: taskEntry()=%d - CALLED!', count($taskEntry)));
$key = $this->getListInstance()->getIterator()->key();
// Get the hash from key
- $hash = $this->getListInstance()->getHash($key);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TASK-HANDLER: key=%s', $key));
+ $hash = $this->getListInstance()->getHashByIndex($key);
// Update the entry
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TASK-HANDLER: Invoking this->listInstance->updateCurrentEntryByHash(%s,taskEntry()=%d) ...', $hash, count($taskEntry)));
$this->getListInstance()->updateCurrentEntryByHash($hash, $taskEntry);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TASK-HANDLER: EXIT!');
}
/**
* @return void
*/
private function unregisterTask (array $taskData) {
- // Debug output
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Removing task ' . $taskData['id'] . ' from queue - CALLED!');
-
// Remove the entry
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TASK-HANDLER: Removing task %s from queue - CALLED!', $taskData['id']));
$this->getListInstance()->removeEntry('tasks', $taskData);
- // Debug output
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Removing task ' . $taskData['id'] . ' from queue - EXIT!');
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TASK-HANDLER: Removing task %s from queue - EXIT!', $taskData['id']));
}
/**
*/
public function searchTask (Taskable $taskInstance) {
// Default is an empty (not found) task name
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TASK-HANDLER: taskInstance=%s - CALLED!', $taskInstance->__toString()));
$taskName = '';
// Get whole list
$taskList = $this->getListInstance()->getArrayFromList('tasks');
// Search all instances
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TASK-HANDLER: taskList()=%d', count($taskList)));
foreach ($taskList as $currentTask) {
// Does it match given task instance?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TASK-HANDLER: currentTask[id=%s', $currentTask['id']));
if ($currentTask['task_instance']->equals($taskInstance)) {
// Found it
$taskName = $currentTask['id'];
// Abort here
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TASK-HANDLER: taskName=%s - BREAK!', $taskName));
break;
- } // END - if
- } // END - foreach
+ }
+ }
// Return found name
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TASK-HANDLER: taskName=%s - EXIT!', $taskName));
return $taskName;
}
* Registers a task with a task handler.
*
* @param $taskName A task name to register the task on
- * @param $taskInstance The instance that should be registered as a task
+ * @param $taskInstance An instance of a Taskable class
* @return void
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws UnexpectedValueException If an unexpected value has been configured
*/
- public function registerTask ($taskName, Visitable $taskInstance) {
- // Get interval delay
- $intervalDelay = $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_interval_delay');
- $startupDelay = $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_startup_delay');
+ public function registerTask (string $taskName, Taskable $taskInstance) {
+ // Is the parameter valid
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TASK-HANDLER: taskName=%s,taskInstance - CALLED!', $taskName, $taskInstance->__toString()));
+ if (empty($taskName)) {
+ // Task name cannot be empty
+ throw new InvalidArgumentException('Parameter "taskName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Get interval delay, startup delay and max runs
+ $intervalDelay = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('task_' . $taskName . '_interval_delay');
+ $startupDelay = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('task_' . $taskName . '_startup_delay');
+ $maxRuns = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('task_' . $taskName . '_max_runs');
// If the task is 'idle_loop', a deplay of zero seconds is fine
- assert($intervalDelay >= 0);
- assert(($taskName === 'idle_loop') || (($taskName != 'idle_loop') && ($intervalDelay > 0)));
- assert(($taskName === 'idle_loop') || (($taskName != 'idle_loop') && ($startupDelay > 0)));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TASK-HANDLER: intervalDelay=%d,startupDelay=%d,maxRuns=%d', $intervalDelay, $startupDelay, $maxRuns));
+ if ($intervalDelay < 0) {
+ // Invalid configuration value
+ throw new UnexpectedValueException(sprintf('taskName=%s has intervalDelay=%d below zero', $taskName, $intervalDelay), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ } elseif ($startupDelay < 0) {
+ // Invalid configuration value
+ throw new UnexpectedValueException(sprintf('taskName=%s has startupDelay=%d below zero', $taskName, $startupDelay), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ } elseif ($maxRuns < 0) {
+ // Invalid configuration value
+ throw new UnexpectedValueException(sprintf('taskName=%s has maxRuns=%d below zero', $taskName, $maxRuns), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ } elseif ($taskName != 'idle_loop' && $intervalDelay == 0) {
+ // Only idle_loop can have a zero interval delay
+ throw new UnexpectedValueException(sprintf('taskName=%s has zero interval delay which is only valid for "idle_loop" task', $taskName), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ } elseif ($taskName != 'idle_loop' && $startupDelay == 0) {
+ // Only idle_loop can have a zero interval delay
+ throw new UnexpectedValueException(sprintf('taskName=%s has zero startup delay which is only valid for "idle_loop" task', $taskName), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// Create the entry
- $taskEntry = array(
+ $taskEntry = [
// Identifier for the generateHash() method
'id' => $taskName,
// Whether the task is started
// Interval time (delay) in milliseconds before this task is executed again
'task_interval_delay' => $intervalDelay,
// How often should this task run?
- 'task_max_runs' => $this->getConfigInstance()->getConfigEntry('task_' . $taskName . '_max_runs'),
- );
+ 'task_max_runs' => $maxRuns,
+ ];
// Add the entry
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TASK-HANDLER: Invoking this->listInstance->addEntry(tasks,taskEntry()=%d) ...', count($taskEntry)));
$this->getListInstance()->addEntry('tasks', $taskEntry);
// Debug message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Task registered: taskName=' . $taskName .
- ' (taskInstance=' . $taskInstance->__toString() . ')' .
- ', startupDelay=' . $taskEntry['task_startup_delay'] . 'ms' .
- ', intervalDelay=' . $taskEntry['task_interval_delay'] . 'ms' .
- ', maxRuns=' . $taskEntry['task_max_runs'] . ' ...'
- );
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TASK-HANDLER: Task registered: taskName=%s (taskInstance=%s), startupDelay=%dms, intervalDelay=%dms, maxRuns=%d ...',
+ $taskName,
+ $taskInstance->__toString(),
+ $taskEntry['task_startup_delay'],
+ $taskEntry['task_interval_delay'],
+ $taskEntry['task_max_runs'],
+ ));
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TASK-HANDLER: EXIT!');
}
/**
*/
public function hasTasksLeft () {
// Do we have tasks there?
- $tasksLeft = (($this->getListInstance() instanceof Listable) && ($this->getListInstance()->count() > 0));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TASK-HANDLER: CALLED!');
+ $tasksLeft = ($this->getListInstance()->count() > 0);
// Return result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TASK-HANDLER: tasksLeft=%d - EXIT!', intval($tasksLeft)));
return $tasksLeft;
}
*/
public function handleTasks () {
// Should we rewind?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TASK-HANDLER: CALLED!');
if (!$this->getListInstance()->getIterator()->valid()) {
// Rewind to the beginning for next loop
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TASK-HANDLER: Invoking this->listInstance->iterator->rewind() ...');
$this->getListInstance()->getIterator()->rewind();
- } // END - if
+ }
// Try to execute the task
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TASK-HANDLER: Invoking this->executeCurrentTask() ...');
$this->executeCurrentTask();
// Go to next entry
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TASK-HANDLER: Invoking this->listInstance->iterator->next() ...');
$this->getListInstance()->getIterator()->next();
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TASK-HANDLER: EXIT!');
}
/**
*/
public function doShutdown () {
// Always rewind to the beginning for next loop
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TASK-HANDLER: Invoking this->listInstance->iterator->rewind() - CALLED!');
$this->getListInstance()->getIterator()->rewind();
- // Debug message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down all ' . $this->getListInstance()->count() . ' tasks...');
-
// Remember all tasks that has been shutdown for removal
- $tasks = array();
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TASK-HANDLER: Shutting down all %d tasks...', $this->getListInstance()->count()));
+ $tasks = [];
// Instance a visitor
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('TASK-HANDLER: Setting visitorInstance=shutdown_task_visitor_class from configuration ...');
$this->setVisitorInstance(ObjectFactory::createObjectByConfiguredName('shutdown_task_visitor_class'));
// Shutdown all tasks in once go
// Get current entry
$currentTask = $this->getListInstance()->getIterator()->current();
- // Output debug message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down task ' . $currentTask['id'] . ' (taskInstance=' . $currentTask['task_instance']->__toString() . ') ...');
-
// Shutdown the task
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('TASK-HANDLER: Shutting down task ' . $currentTask['id'] . ' (taskInstance=' . $currentTask['task_instance']->__toString() . ') ...');
$currentTask['task_instance']->accept($this->getVisitorInstance());
// Remember this task
array_push($tasks, $currentTask);
// Advance to next one
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TASK-HANDLER: Invoking this->listInstance->iterator->next() ...');
$this->getListInstance()->getIterator()->next();
- } // END - while
-
- // Debug message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK-HANDLER[' . __METHOD__ . ':' . __LINE__ . ']: Shutdown of all tasks completed.');
+ }
// Remove all tasks
- foreach ($tasks as $entry) {
- $this->unregisterTask($entry);
- } // END - foreach
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('TASK-HANDLER: Shutdown of all tasks completed. tasks()=%d', count($tasks)));
+ foreach ($tasks as $taskEntry) {
+ // Unregister this task
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('TASK-HANDLER: Invokint this->unregisterTask(taskEntry()=%d) ...', count($taskEntry)));
+ $this->unregisterTask($taskEntry);
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('TASK-HANDLER: EXIT!');
}
}
<?php
// Own namespace
-namespace CoreFramework\Captcha\;
+namespace Org\Mxchange\CoreFramework\Captcha\;
// Import framework stuff
use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
/**
* A solveable CAPTCHA
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @todo 0% done
*/
public function initiateCaptcha () {
- $this->partialStub("Please implement this method.");
+ DebugMiddleware::getSelfInstance()->partialStub("Please implement this method.");
}
/**
* @todo 0% done
*/
public function renderCode () {
- $this->partialStub("Please implement this method.");
+ DebugMiddleware::getSelfInstance()->partialStub("Please implement this method.");
}
}
namespace Org\Mxchange\CoreFramework\Helper\Captcha;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Helper\BaseHelper;
+use Org\Mxchange\CoreFramework\Helper\Helper;
+use Org\Mxchange\CoreFramework\Traits\Helper\HelperTrait;
/**
* A general captcha
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-abstract class BaseCaptcha extends BaseHelper {
+abstract class BaseCaptcha extends BaseHelper implements Helper {
+ // Load traits
+ use HelperTrait;
+
+ /**
+ * Instance of a RNG
+ */
+ private $rngInstance = NULL;
+
/**
* Protected constructor
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
+ /**
+ * Setter for RNG instance
+ *
+ * @param $rngInstance An instance of a random number generator (RNG)
+ * @return void
+ */
+ protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
+ $this->rngInstance = $rngInstance;
+ }
+
+ /**
+ * Getter for RNG instance
+ *
+ * @return $rngInstance An instance of a random number generator (RNG)
+ */
+ public final function getRngInstance () {
+ return $this->rngInstance;
+ }
+
/**
* Initializes the random number generator (RNG)
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* Array for background color values
*/
- private $backgroundColor = array(
+ private $backgroundColor = [
'red' => 0,
'green' => 0,
'blue' => 0
- );
+ ];
/**
* Array for foreground color values
*/
- private $foregroundColor = array(
+ private $foregroundColor = [
'red' => 0,
'green' => 0,
'blue' => 0
- );
+ ];
/**
* All image strings
*/
- private $imageStrings = array();
+ private $imageStrings = [];
/**
* Current string name
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @param $imageType Type of the image
* @return $helperInstance A preparedf instance of this helper
*/
- public static final function createImageHelper (CompileableTemplate $templateInstance, $imageType) {
+ public static final function createImageHelper (CompileableTemplate $templateInstance, string $imageType) {
// Get new instance
$helperInstance = new ImageHelper();
* @param $imageType Type of the image
* @return void
*/
- protected final function setImageType ($imageType) {
- $this->imageType = (string) $imageType;
+ protected final function setImageType (string $imageType) {
+ $this->imageType = $imageType;
}
/**
* @param $baseImage A base image template
* @return void
*/
- public final function setBaseImage ($baseImage) {
- $this->baseImage = (string) $baseImage;
+ public final function setBaseImage (string $baseImage) {
+ $this->baseImage = $baseImage;
}
/**
* @param $imageName Name of the image
* @return void
*/
- public final function setImageName ($imageName) {
- $this->imageName = (string) $imageName;
+ public final function setImageName (string $imageName) {
+ $this->imageName = $imageName;
}
/**
* @param $width Width of the image
* @return void
*/
- public final function setWidth ($width) {
- $this->width = (int) $width;
+ public final function setWidth (int $width) {
+ $this->width = $width;
}
/**
* @param $height Height of the image
* @return void
*/
- public final function setHeight ($height) {
- $this->height = (int) $height;
+ public final function setHeight (int $height) {
+ $this->height = $height;
}
/**
// Random numbers?
if ($red === 'rand') {
$red = $this->getRngInstance()->randomNumber(0, 255);
- } // END - if
+ }
if ($green === 'rand') {
$green = $this->getRngInstance()->randomNumber(0, 255);
- } // END - if
+ }
if ($blue === 'rand') {
$blue = $this->getRngInstance()->randomNumber(0, 255);
- } // END - if
+ }
$this->backgroundColor['red'] = (int) $red;
$this->backgroundColor['green'] = (int) $green;
// Random numbers?
if ($red === 'rand') {
$red = $this->getRngInstance()->randomNumber(0, 255);
- } // END - if
+ }
if ($green === 'rand') {
$green = $this->getRngInstance()->randomNumber(0, 255);
- } // END - if
+ }
if ($blue === 'rand') {
$blue = $this->getRngInstance()->randomNumber(0, 255);
- } // END - if
+ }
$this->foregroundColor['red'] = (int) $red;
$this->foregroundColor['green'] = (int) $green;
*
* @param $stringName String name (identifier)
*/
- public function addTextLine ($stringName) {
+ public function addTextLine (string $stringName) {
// Create the image string
$this->imageStrings[$stringName] = array(
'x' => '',
* @param $imageString A message to display in image
* @return void
*/
- public final function setImageString ($imageString) {
- $this->imageStrings[$this->currString]['string'] = (string) $imageString;
+ public final function setImageString (string $imageString) {
+ $this->imageStrings[$this->currString]['string'] = $imageString;
}
/**
* @param $y Y coordinate
* @return void
*/
- public final function setCoord ($x, $y) {
- $this->imageStrings[$this->currString]['x'] = (int) $x;
- $this->imageStrings[$this->currString]['y'] = (int) $y;
+ public final function setCoord (int $x, int $y) {
+ $this->imageStrings[$this->currString]['x'] = $x;
+ $this->imageStrings[$this->currString]['y'] = $y;
}
/**
// Random font size?
if ($fontSize === 'rand') {
$fontSize = $this->getRngInstance()->randomNumber(4, 9);
- } // END - if
+ }
$this->imageStrings[$this->currString]['size'] = (int) $fontSize;
}
$templateInstance->addGroupVariable('image_y' , $this->getY());
$templateInstance->addGroupVariable('image_size' , $this->getFontSize());
$templateInstance->addGroupVariable('image_string', $this->getImageString());
- } // END - foreach
+ }
// Get the raw content
$imageContent = $templateInstance->getRawTemplateData();
namespace Org\Mxchange\CoreFramework\Helper\Captcha;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Helper\Crypto\CryptoHelper;
use Org\Mxchange\CoreFramework\Helper\Template\HelpableTemplate;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public function initiateCaptcha () {
// Get total length
- $captchaLength = $this->getConfigInstance()->getConfigEntry('captcha_string_length');
+ $captchaLength = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('captcha_string_length');
// Get max string length
- $strLength = $this->getConfigInstance()->getConfigEntry('random_string_length');
+ $strLength = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('random_string_length');
// Calculate starting position based on random place
$start = $this->getRngInstance()->randomNumber(0, ($strLength - $captchaLength));
$captchaString = substr($base64String, $start, $captchaLength);
// Get all characters we want to replace
- $searchChars = $this->getConfigInstance()->getConfigEntry('captcha_search_chars');
+ $searchChars = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('captcha_search_chars');
// Get fixed salt and use it as "replacement characters"
$replaceChars = $this->getRngInstance()->getExtraSalt();
// Replace character
$captchaString = str_replace($search, $replace, $captchaString, $captchaLength);
- } // END - foreach
+ }
// Get crypto instance
- $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
+ $cryptoInstance = CryptoHelper::getSelfInstance();
// Hash the CAPTCHA code for later comparison
$this->hashedString = $cryptoInstance->hashString($captchaString);
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
namespace Org\Mxchange\CoreFramework\Helper;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
+
+// Import SPL stuff
+use \BasMethodCallException;
+use \InvalidArgumentException;
/**
* A generic helper class with generic methods
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* Array with groups
*/
- private $groups = array();
+ private $groups = [];
/**
* Array with sub group
*/
- private $subGroups = array();
+ private $subGroups = [];
/**
* Previously opened group
private $totalCounter = 0;
// Exception constants
- const EXCEPTION_GROUP_NOT_OPENED = 0x1e3;
- const EXCEPTION_GROUP_ALREADY_FOUND = 0x1e4;
- const EXCEPTION_SUB_GROUP_ALREADY_FOUND = 0x1e5;
- const EXCEPTION_NO_PREVIOUS_SUB_GROUP_OPENED = 0x1e6;
- const EXCEPTION_NO_PREVIOUS_GROUP_OPENED = 0x1e7;
+ const EXCEPTION_GROUP_NOT_OPENED = 0x1e0;
+ const EXCEPTION_SUB_GROUP_ALREADY_FOUND = 0x1e1;
+ const EXCEPTION_NO_PREVIOUS_SUB_GROUP_OPENED = 0x1e2;
+ const EXCEPTION_NO_PREVIOUS_GROUP_OPENED = 0x1e3;
/**
* Protected constructor
* @param $className Real name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-HELPER: className=%s - CONSTRUCTED!', $className));
parent::__construct($className);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-HELPER: EXIT!');
}
/**
*
* @param $newContent New content to add
* @return void
- */
- protected final function addContent ($newContent) {
- $this->content .= (string) trim($newContent) . PHP_EOL;
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ */
+ protected final function addContent (string $newContent) {
+ // Check variable
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-HELPER: newContent=%s - CALLED!', $newContent));
+ if (empty(trim($newContent))) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "newContent" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Append content with EOL
+ $this->content .= trim($newContent) . PHP_EOL;
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-HELPER: this->content()=%d - EXIT!', strlen($this->content)));
}
/**
*
* @param $content Content to to the base
* @return void
- */
- protected function addHeaderContent ($content) {
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ */
+ protected function addHeaderContent (string $content) {
+ // Check variable
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-HELPER: content=%s - CALLED!', $content));
+ if (empty(trim($content))) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "content" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Add the header content
- $this->groups['header']['content'] = (string) trim($content);
+ $this->groups['header']['content'] = trim($content);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-HELPER: EXIT!');
}
/**
*
* @param $content Content to to the base
* @return void
- */
- protected function addFooterContent ($content) {
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ */
+ protected function addFooterContent (string $content) {
+ // Check variable
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-HELPER: content=%s - CALLED!', $content));
+ if (empty(trim($content))) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "content" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Add the footer content
- $this->groups['footer']['content'] = (string) trim($content);
+ $this->groups['footer']['content'] = trim($content);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-HELPER: EXIT!');
}
/**
*
* @param $newContent New content to add
* @return void
- */
- protected final function addContentToPreviousGroup ($newContent) {
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ */
+ protected final function addContentToPreviousGroup (string $newContent) {
+ // Check on parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: newContent=%s - CALLED!', $newContent));
+ if (empty($newContent)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "newContent" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Check for sub/group
if ($this->ifSubGroupOpenedPreviously()) {
// Get sub group id
// Add it directly
$this->addContent($newContent);
}
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HELPER: EXIT!');
}
/**
*
* @param $fieldName Name of the field to assign
* @return void
- */
- public function assignField ($fieldName) {
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ */
+ public function assignField (string $fieldName) {
+ // Check on parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: fieldName=%s - CALLED!', $fieldName));
+ if (empty($fieldName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "fieldName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get the value from value instance
$fieldValue = $this->getValueField($fieldName);
// Assign it with a template variable
$this->getTemplateInstance()->assignVariable('block_' . $fieldName, $fieldValue);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HELPER: EXIT!');
}
/**
* @param $fieldName Name of the field to assign
* @param $filterMethod Method name to call of the value instance
* @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
* @todo Rewrite this method using a helper class for filtering data
*/
- public function assignFieldWithFilter ($fieldName, $filterMethod) {
+ public function assignFieldWithFilter (string $fieldName, string $filterMethod) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: fieldName=%s,filterMethod=%s - CALLED!', $fieldName, $filterMethod));
+ if (empty($fieldName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "fieldName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($filterMethod)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "filterMethod" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get the value
$fieldValue = $this->getValueField($fieldName);
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.'='.$fieldValue);
// Now filter it through the value through the filter method
- $filteredValue = call_user_func_array(array($this, 'doFilter' . self::convertToClassName($filterMethod)), array($fieldValue));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: %s[%s]=%s', $fieldName, gettype($fieldValue), $fieldValue));
+ $filteredValue = call_user_func_array(array($this, 'doFilter' . StringUtils::convertToClassName($filterMethod)), array($fieldValue));
// Assign it with a template variable
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: filteredValue[%s]=%s', gettype($filteredValue), $filteredValue));
$this->getTemplateInstance()->assignVariable('block_' . $fieldName, $filteredValue);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HELPER: EXIT!');
}
/**
* @param $registryKey Registry key which holds an object with values
* @param $extraKey Extra value instance key used if registryKey is null
* @return void
- * @throws NullPointerException If recovery of requested value instance failed
- */
- public function prefetchValueInstance ($registryKey, $extraKey = NULL) {
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('O:'.$registryKey.'/'.$extraKey);
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ */
+ public function prefetchValueInstance (string $registryKey, string $extraKey = NULL) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: registryKey=%s,extraKey[%s]=%s - CALLED!', $registryKey, gettype($extraKey), $extraKey));
+ if (empty($registryKey)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "registryKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
try {
// Get the required instance
- $this->valueInstance = GenericRegistry::getRegistry()->getInstance($registryKey);
+ $this->valueInstance = ObjectRegistry::getRegistry('generic')->getInstance($registryKey);
} catch (NullPointerException $e) {
// Not set in registry
- // @TODO Try to log it here
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($registryKey.'=NULL!');
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: registryKey=%s returned no instance (NPE thrown)', $registryKey));
}
// Shall we get an extra instance?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: extraKey[%s]=%s', gettype($extraKey), $extraKey));
if (!is_null($extraKey)) {
try {
// Get the extra instance.
- $this->extraInstance = GenericRegistry::getRegistry()->getInstance($extraKey);
+ $this->extraInstance = ObjectRegistry::getRegistry('generic')->getInstance($extraKey);
} catch (NullPointerException $e) {
// Try to create it
- $this->extraInstance = ObjectFactory::createObjectByConfiguredName($extraKey . '_class', array($this->valueInstance));
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: extraKey=%s returned no instance (NPE thrown), this->valueInstance[]=%s', $extraKey, gettype($this->valueInstance)));
+ $this->extraInstance = ObjectFactory::createObjectByConfiguredName($extraKey . '_class', [$this->valueInstance]);
}
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($extraKey.'='.$this->extraInstance.' - EXTRA!');
- } // END - if
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: extraKey=%s,this->extraInstance[%s]=%s', $extraKey, gettype($this->extraInstance), $this->extraInstance));
+ }
// Is the value instance valid?
+ //* NOSIY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: this->valueInstance[]=%s - BEFORE!', gettype($this->valueInstance)));
if (is_null($this->valueInstance)) {
// Get the requested instance
$this->valueInstance = ObjectFactory::createObjectByConfiguredName($registryKey . '_class', array($this->extraInstance));
- } // END - if
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: this->valueInstance[]=%s - AFTER/EXIT!', gettype($this->valueInstance)));
}
/**
* @param $content Initial content to add to the group
* @param $tag HTML tag used to open this group
* @return void
- * @throws HelperGroupAlreadyCreatedException If the group was already created before
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ * @throws BadMethodCallException If the group was already created before
*/
- protected function openGroupByIdContent ($groupId, $content, $tag) {
- //* DEBUG: */ echo "OPEN:groupId={$groupId},content=<pre>".htmlentities($content)."</pre>\n";
+ protected function openGroupByIdContent (string $groupId, string $content, string $tag) {
// Is the group already there?
- if (isset($this->groups[$groupId])) {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: groupdId=%s,content=%s,tag=%s - CALLED!', $groupdId, $content, $tag));
+ if (empty($groupId)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "groupId" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (isset($this->groups[$groupId])) {
// Then throw an exception here
- throw new HelperGroupAlreadyCreatedException(array($this, $groupId), self::EXCEPTION_GROUP_ALREADY_FOUND);
- } // END - if
+ throw new BadMethodCallException(sprintf('[%s:%d]: groupId=%s is already opened.', $this->__toString(), $groupId), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ } elseif (empty($content)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "content" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($tag)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "tag" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Count one up
$this->totalCounter++;
// Add the group to the stack
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: this->totalCounter=%d', $this->totalCounter));
$this->groups[$this->totalCounter] = $groupId;
$this->groups[$groupId]['opened'] = true;
$this->groups[$groupId]['content'] = sprintf(
$this->groups[$groupId]['tag'] = $tag;
// Mark this group as previously opened
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: Setting this->previousGroupId=%s ...', $groupId));
$this->setPreviousGroupId($groupId);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HELPER: EXIT!');
}
/**
* @return void
* @throws HelperNoPreviousOpenedGroupException If no previously opened group was found
*/
- public function closePreviousGroupByContent ($content = '') {
+ public function closePreviousGroupByContent (string $content = '') {
// Check if any sub group was opened before
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: content(%d)=%s - CALLED!', strlen($content), $content));
if ($this->ifSubGroupOpenedPreviously()) {
// Close it automatically
$this->closePreviousSubGroupByContent();
- } // END - if
+ }
// Check if any group was opened before
if ($this->ifGroupOpenedPreviously() === false) {
// Then throw an exception
throw new HelperNoPreviousOpenedGroupException(array($this, $content), self::EXCEPTION_NO_PREVIOUS_SUB_GROUP_OPENED);
- } // END - if
+ }
// Get previous group
$groupId = $this->getPreviousGroupId();
$groupId,
$this->groups[$groupId]['tag']
);
- } // END - if
+ }
// Add content to it and mark it as closed
$this->groups[$groupId]['content'] .= sprintf(
// Mark previous group as closed
$this->setPreviousGroupId('');
- //* DEBUG: */ echo "CLOSE:groupId={$groupId}<br />\n";
+ //* NOISY-DEBUG: */ echo "CLOSE:groupId={$groupId}<br />\n";
}
/**
* @return void
* @throws HelperSubGroupAlreadyCreatedException If the sub group was already created before
*/
- protected function openSubGroupByIdContent ($subGroupId, $content, $tag) {
- //* DEBUG: */ echo "OPEN:subGroupId={$subGroupId},content=".htmlentities($content)."<br />\n";
+ protected function openSubGroupByIdContent (string $subGroupId, string $content, string $tag) {
+ //* NOISY-DEBUG: */ echo "OPEN:subGroupId={$subGroupId},content=".htmlentities($content)."<br />\n";
// Is the group already there?
- if (isset($this->subGroups[$subGroupId])) {
+ if (empty($subGroupId)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "subGroupId" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (isset($this->subGroups[$subGroupId])) {
// Then throw an exception here
throw new HelperSubGroupAlreadyCreatedException(array($this, $subGroupId), self::EXCEPTION_SUB_GROUP_ALREADY_FOUND);
- } // END - if
+ }
// Count one up
$this->totalCounter++;
* @return void
* @throws HelperNoPreviousOpenedSubGroupException If no previously opened sub group was found
*/
- public function closePreviousSubGroupByContent ($content = '') {
+ public function closePreviousSubGroupByContent (string $content = '') {
// Check if any sub group was opened before
if ($this->ifSubGroupOpenedPreviously() === false) {
// Then throw an exception
throw new HelperNoPreviousOpenedSubGroupException(array($this, $content), self::EXCEPTION_NO_PREVIOUS_SUB_GROUP_OPENED);
- } // END - if
+ }
// Get previous sub group
$subGroupId = $this->getPreviousSubGroupId();
if ((empty($content)) && (!empty($this->subGroups[$subGroupId]['tag']))) {
// Get it from opener
$content = sprintf('<!-- sub-group %s auto-closed //--></%s>', $subGroupId, $this->subGroups[$subGroupId]['tag']);
- } // END - if
+ }
// Add content to it and mark it as closed
$this->subGroups[$subGroupId]['content'] .= sprintf('<!-- sub-group %s closed (length: %s, tag: %s) //-->%s' . PHP_EOL, $subGroupId, strlen($content), $this->subGroups[$subGroupId]['tag'], $content);
// Mark previous sub group as closed
$this->setPreviousSubGroupId('');
- //* DEBUG: */ echo "CLOSE:subGroupId={$subGroupId}<br />\n";
+ //* NOISY-DEBUG: */ echo "CLOSE:subGroupId={$subGroupId}<br />\n";
}
/**
if (isset($this->groups['header'])) {
// Then add it
$content .= $this->groups['header']['content'] . PHP_EOL;
- } // END - if
+ }
// Initiate content
$content .= $this->getContent();
if ((isset($this->groups[$idx])) && ($this->groups[$this->groups[$idx]]['opened'] === false)) {
// Then add it's content
$groupContent = trim($this->groups[$this->groups[$idx]]['content']);
- //* DEBUG: */ echo "group={$this->groups[$idx]},content=<pre>".htmlentities($groupContent)."</pre><br />\n";
+ //* NOISY-DEBUG: */ echo "group={$this->groups[$idx]},content=<pre>".htmlentities($groupContent)."</pre><br />\n";
$content .= $groupContent;
} elseif ((isset($this->subGroups[$idx])) && ($this->subGroups[$this->subGroups[$idx]]['opened'] === false)) {
// Then add it's content
$subGroupContent = $this->subGroups[$this->subGroups[$idx]]['content'];
- //* DEBUG: */ echo "subgroup={$this->subGroups[$idx]},content=<pre>".htmlentities($subGroupContent)."</pre><br />\n";
+ //* NOISY-DEBUG: */ echo "subgroup={$this->subGroups[$idx]},content=<pre>".htmlentities($subGroupContent)."</pre><br />\n";
$content .= trim($subGroupContent);
} else {
// Something went wrong
$this->debugInstance(__METHOD__ . '(): Something unexpected happened here.');
}
- } // END - for
+ }
// Is footer content there?
if (isset($this->groups['footer'])) {
// Then add it
$content .= $this->groups['footer']['content'] . PHP_EOL;
- } // END - if
+ }
// Return it
- //* DEBUG: */ echo "content=<pre>".htmlentities($content)."</pre> (".strlen($content).")<br />\n";
+ //* NOISY-DEBUG: */ echo "content=<pre>".htmlentities($content)."</pre> (".strlen($content).")<br />\n";
return $content;
}
*
* @param $groupId Id of group to check
* @return $isOpened Whether the specified group is open
- */
- protected function ifGroupIsOpened ($groupId) {
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ */
+ protected function ifGroupIsOpened (string $groupId) {
+ // Check on parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: groupId=%s - CALLED!', $groupId));
+ if (empty($groupId)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "groupId" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Is the group open?
$isOpened = ((isset($this->groups[$groupId])) && ($this->groups[$groupId]['opened'] === true));
// Return status
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: isOpened=%d - EXIT!', intval($isOpened)));
return $isOpened;
}
*
* @param $fieldName Name of the field we shall fetch
* @return $fieldValue Value from field
+ * @throws InvalidArgumentException If a parameter has an invalid value
* @throws NullPointerException Thrown if $valueInstance is null
*/
- public function getValueField ($fieldName) {
+ public function getValueField (string $fieldName) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: fieldName=%s - CALLED!', $fieldName));
+ if (empty($fieldName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "fieldName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Init value
$fieldValue = NULL;
// The $valueInstance attribute should not be null!
if (is_null($this->getValueInstance())) {
// Throws an exception here
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } // END - if
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
+ }
// Is the field set?
if ($this->getValueInstance()->isFieldSet($fieldName)) {
// Get the field value
$fieldValue = $this->getValueInstance()->getField($fieldName);
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.'[]='.gettype($fieldValue).'('.strlen($fieldValue).') - Value instance!');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.'[]='.gettype($fieldValue).'('.strlen($fieldValue).') - Value instance!');
} elseif ((!is_null($this->extraInstance)) && ($this->extraInstance->isFieldSet($fieldName))) {
// So try the extra instance
$fieldValue = $this->extraInstance->getField($fieldName);
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.'[]='.gettype($fieldValue).'('.strlen($fieldValue).') - Extra instance!');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.'[]='.gettype($fieldValue).'('.strlen($fieldValue).') - Extra instance!');
} else {
// Field is not set
- $this->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] fieldName=' . $fieldName . ' is not set! - @TODO');
- } // END - if
+ $this->debugOutput('BASE-HELPER: fieldName=' . $fieldName . ' is not set! - @TODO');
+ }
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-HELPER: fieldValue[%s]=%s - EXIT!', gettype($fieldValue), $fieldValue));
return $fieldValue;
}
* @param $previousGroupId Id of previously opened group
* @return void
*/
- protected final function setPreviousGroupId ($previousGroupId) {
- $this->previousGroupId = (string) $previousGroupId;
+ protected final function setPreviousGroupId (string $previousGroupId) {
+ $this->previousGroupId = $previousGroupId;
}
/**
* @param $previousSubGroupId Id of previously opened sub group
* @return void
*/
- protected final function setPreviousSubGroupId ($previousSubGroupId) {
- $this->previousSubGroupId = (string) $previousSubGroupId;
+ protected final function setPreviousSubGroupId (string $previousSubGroupId) {
+ $this->previousSubGroupId = $previousSubGroupId;
}
}
namespace Org\Mxchange\CoreFramework\Helper;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Helper\Template\HelpableTemplate;
use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @param $blockName Name of the block we shall generate
* @return $helperInstance A prepared instance of this helper
*/
- public static final function createHtmlBlockHelper (CompileableTemplate $templateInstance, $blockName) {
+ public static final function createHtmlBlockHelper (CompileableTemplate $templateInstance, string $blockName) {
// Get new instance
$helperInstance = new HtmlBlockHelper();
* @param $blockName Name of the block we shall generate
* @return void
*/
- protected final function setBlockName ($blockName) {
- $this->blockName = (string) $blockName;
+ protected final function setBlockName (string $blockName) {
+ $this->blockName = $blockName;
}
/**
* @return $withRegistration Whether with registration date
*/
public function ifIncludeRegistrationStamp () {
- $withRegistration = ($this->getConfigInstance()->getConfigEntry('block_shows_registration') == 'Y');
+ $withRegistration = FrameworkBootstrap::getConfigurationInstance()->isEnabled('block_shows_registration');
return $withRegistration;
}
* @param $messageId Message id to load an assign
* @return void
*/
- public function assignMessageField ($templateVariable, $messageId) {
+ public function assignMessageField (string $templateVariable, string $messageId) {
// Get message
- $message = $this->getLanguageInstance()->getMessage($messageId);
+ $message = FrameworkBootstrap::getLanguageInstance()->getMessage($messageId);
// And assign it
$this->getTemplateInstance()->assignVariable($templateVariable, $message);
* @param $actionValue Action value to assign
* @return void
*/
- public function assignLinkFieldWithAction ($linkField, $actionValue) {
+ public function assignLinkFieldWithAction (string $linkField, $actionValue) {
$this->getTemplateInstance()->assignVariable($linkField . '_action', $actionValue);
}
* @param $userStatus Raw user status from database layer
* @return $translated Translated user status
*/
- protected function doFilterUserStatusTranslator ($userStatus) {
+ protected function doFilterUserStatusTranslator (string $userStatus) {
// Generate message id
- $messageId = 'user_status_' . strtolower($userStatus);
+ $messageId = sprintf('user_status_%s', strtolower($userStatus));
// Get that message
- $translated = $this->getLanguageInstance()->getMessage($messageId);
+ $translated = FrameworkBootstrap::getLanguageInstance()->getMessage($messageId);
// Return it
return $translated;
<?php
// Own namespace
-namespace CoreFramework\Helper\;
+namespace Org\Mxchange\CoreFramework\Helper\;
// Import framework stuff
use Org\Mxchange\CoreFramework\Helper\Template\HelpableTemplate;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
/**
*
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
* @todo 0% done
*/
public function flushContent () {
- $this->partialStub("Please implement this method.");
+ DebugMiddleware::getSelfInstance()->partialStub("Please implement this method.");
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Helper\BaseHelper;
+use Org\Mxchange\CoreFramework\Traits\Template\CompileableTemplateTrait;
/**
* A general purpose web helper. You should not instance this like all the other
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseHtmlHelper extends BaseHelper {
+ // Load traits
+ use CompileableTemplateTrait;
+
/**
* Protected constructor
*
* @param $className The real class name
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
namespace Org\Mxchange\CoreFramework\Helper;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseWrapper;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseFrontend;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
use Org\Mxchange\CoreFramework\Helper\Template\HelpableTemplate;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
// Import SPL stuff
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @param $withForm Whether include the form tag
* @return $helperInstance A preparedf instance of this helper
*/
- public static final function createHtmlFormHelper (CompileableTemplate $templateInstance, $formName, $formId = false, $withForm = true) {
+ public static final function createHtmlFormHelper (CompileableTemplate $templateInstance, string $formName, string $formId = NULL, bool $withForm = true) {
// Get new instance
$helperInstance = new HtmlFormHelper();
$helperInstance->setTemplateInstance($templateInstance);
// Is the form id not set?
- if ($formId === false) {
+ if (is_null($formId)) {
// Use form id from form name
$formId = $formName;
- } // END - if
+ }
// Set form name
$helperInstance->setFormName($formName);
* @throws InvalidFormNameException If the form name is invalid ( = false)
* @todo Add some unique PIN here to bypass problems with some browser and/or extensions
*/
- public function addFormTag ($formName = false, $formId = false) {
+ public function addFormTag (string $formName = NULL, string $formId = NULL) {
// When the form is not yet opened at least form name must be valid
- if (($this->formOpened === false) && ($formName === false)) {
+ if (($this->formOpened === false) && (is_null($formName))) {
// Thrown an exception
throw new InvalidFormNameException ($this, self::EXCEPTION_FORM_NAME_INVALID);
- } // END - if
+ }
// Close the form is default
$formContent = '</form>';
// Add HTML code
$formContent = sprintf("<form name=\"%s\" class=\"forms\" action=\"%s/%s\" method=\"%s\" target=\"%s\" id=\"%s_form\">",
$formName,
- $this->getConfigInstance()->getConfigEntry('base_url'),
- $this->getConfigInstance()->getConfigEntry('form_action'),
- $this->getConfigInstance()->getConfigEntry('form_method'),
- $this->getConfigInstance()->getConfigEntry('form_target'),
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('base_url'),
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('form_action'),
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('form_method'),
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('form_target'),
$formId
);
if ($this->ifGroupOpenedPreviously()) {
// Then automatically close it here
$this->addFormGroup();
- } // END - if
+ }
// Simply close it
$this->formOpened = false;
* @return void
* @throws FormClosedException If the form is not yet opened
*/
- public function addInputTextField ($fieldName, $fieldValue = '') {
+ public function addInputTextField (string $fieldName, string $fieldValue = '') {
// Is the form opened?
if (($this->formOpened === false) && ($this->formEnabled === true)) {
// Throw an exception
throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
- } // END - if
+ }
// Generate the content
$inputContent = sprintf('<input type="text" class="form-control" id="%s_%s_field" name="%s" value="%s" />',
* @param $fieldName Input field name
* @return void
*/
- public function addInputTextFieldWithDefault ($fieldName) {
+ public function addInputTextFieldWithDefault (string $fieldName) {
// Get the value from instance
$fieldValue = $this->getValueField($fieldName);
//* DEBUG: */ print __METHOD__.':'.$fieldName.'='.$fieldValue."<br />\n";
* @return void
* @throws FormClosedException If the form is not yet opened
*/
- public function addInputPasswordField ($fieldName, $fieldValue = '') {
+ public function addInputPasswordField (string $fieldName, string $fieldValue = '') {
// Is the form opened?
if (($this->formOpened === false) && ($this->formEnabled === true)) {
// Throw an exception
throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
- } // END - if
+ }
// Generate the content
$inputContent = sprintf('<input type="password" class="form-control" id="%s_%s_field" name="%s" value="%s" />',
* @return void
* @throws FormClosedException If the form is not yet opened
*/
- public function addInputHiddenField ($fieldName, $fieldValue = '') {
+ public function addInputHiddenField (string $fieldName, string $fieldValue = '') {
// Is the form opened?
if (($this->formOpened === false) && ($this->formEnabled === true)) {
// Throw an exception
throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
- } // END - if
+ }
// Generate the content
$inputContent = sprintf('<input type="hidden" name="%s" value="%s" />',
* @param $fieldName Input field name
* @return void
*/
- public function addInputHiddenFieldWithDefault ($fieldName) {
+ public function addInputHiddenFieldWithDefault (string $fieldName) {
// Get the value from instance
$fieldValue = $this->getValueField($fieldName);
//* DEBUG: */ print __METHOD__.':'.$fieldName.'='.$fieldValue."<br />\n";
* @param $prefix Prefix for configuration without trailing _
* @return void
*/
- public function addInputHiddenConfiguredField ($fieldName, $prefix) {
+ public function addInputHiddenConfiguredField (string $fieldName, string $prefix) {
// Get the value from instance
- $fieldValue = $this->getConfigInstance()->getConfigEntry("{$prefix}_{$fieldName}");
+ $fieldValue = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry("{$prefix}_{$fieldName}");
//* DEBUG: */ print __METHOD__.':'.$fieldName.'='.$fieldValue."<br />\n";
// Add the text field
* @return void
* @throws FormClosedException If the form is not yet opened
*/
- public function addInputCheckboxField ($fieldName, $fieldChecked = true) {
+ public function addInputCheckboxField (string $fieldName, bool $fieldChecked = true) {
// Is the form opened?
if (($this->formOpened === false) && ($this->formEnabled === true)) {
// Throw an exception
throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
- } // END - if
+ }
// Set whether the check box is checked...
- $checked = ' checked="checked"';
- if ($fieldChecked === false) $checked = ' ';
+ $checked = ($fieldChecked ? ' checked="checked"' : ' ');
// Generate the content
$inputContent = sprintf('<input type="checkbox" name="%s" class="checkbox" id="%s_%s_field" value="1"%s />',
- $this->getFormId(),
$fieldName,
+ $this->getFormId(),
$fieldName,
$checked
);
* @return void
* @throws FormClosedException If the form is not yet opened
*/
- public function addInputResetButton ($buttonText) {
+ public function addInputResetButton (string $buttonText) {
// Is the form opened?
if (($this->formOpened === false) && ($this->formEnabled === true)) {
// Throw an exception
throw new FormClosedException (array($this, 'reset'), self::EXCEPTION_CLOSED_FORM);
- } // END - if
+ }
// Generate the content
$inputContent = sprintf('<input type="reset" class="reset_button" id="%s_reset" value="%s" />',
* @return void
* @throws FormClosedException If the form is not yet opened
*/
- public function addInputSubmitButton ($buttonText) {
+ public function addInputSubmitButton (string $buttonText) {
// Is the form opened?
if (($this->formOpened === false) && ($this->formEnabled === true)) {
// Throw an exception
throw new FormClosedException (array($this, 'submit'), self::EXCEPTION_CLOSED_FORM);
- } // END - if
+ }
// Generate the content
$inputContent = sprintf('<input type="submit" class="submit_button" id="%s_submit" name="%s_submit" value="%s" />',
* @throws FormClosedException If no form has been opened before
* @throws InvalidArgumentException If $groupId is not set
*/
- public function addFormGroup ($groupId = '', $groupText = '') {
+ public function addFormGroup (string $groupId = '', string $groupText = '') {
// Is a form opened?
if (($this->formOpened === false) && ($this->formEnabled === true)) {
// Throw exception here
if (($this->ifGroupOpenedPreviously() === false) && ($groupId === $this->getPreviousGroupId())) {
// Abort here silently
return false;
- } // END - if
+ }
// Initialize content with closing div by default
$content = " </div>\n</div><!-- Group - CLOSE //-->";
if ($this->ifSubGroupOpenedPreviously()) {
// Close it here
$this->addFormSubGroup();
- } // END - if
+ }
// Get previous group id
$prevGroupId = $this->getPreviousGroupId();
if ((!empty($groupId)) && ($groupId != $prevGroupId)) {
//* DEBUG: */ echo $groupId.'/'.$prevGroupId."<br />\n";
$this->addFormGroup($groupId, $groupText);
- } // END - if
+ }
}
}
* @throws FormFormClosedException If no group has been opened before
* @throws InvalidArgumentException If $subGroupId is not set
*/
- public function addFormSubGroup ($subGroupId = '', $subGroupText = '') {
+ public function addFormSubGroup (string $subGroupId = '', string $subGroupText = '') {
// Is a group opened?
if ($this->ifGroupOpenedPreviously() === false) {
// Throw exception here
if (($this->ifSubGroupOpenedPreviously() === false) && ($subGroupId == $this->getPreviousSubGroupId())) {
// Abort here silently
return false;
- } // END - if
+ }
// Initialize content with closing div by default
$content = " </div>\n</div><!-- Sub group- CLOSE //-->";
// All call it again if sub group name is not empty
if ((!empty($subGroupId)) && ($subGroupId != $prevSubGroupId)) {
$this->addFormSubGroup($subGroupId, $subGroupText);
- } // END - if
+ }
}
}
* @return void
* @throws FormClosedException If the form is not yet opened
*/
- public function addFieldLabel ($fieldName, $fieldText, $fieldTitle = '') {
+ public function addFieldLabel (string $fieldName, string $fieldText, string $fieldTitle = '') {
// Is the form opened?
if (($this->formOpened === false) && ($this->formEnabled === true)) {
// Throw an exception
throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
- } // END - if
+ }
// Default is no title attribute
$titleAttribute = '';
if (!empty($fieldTitle)) {
// Create title attribute
$titleAttribute = sprintf(' title="%s" data-toggle="tooltip"', $fieldTitle);
- } // END - if
+ }
// Generate the content
$inputContent = sprintf('<label class="col-form-label" for="%s_%s_field"%s>
* @return void
* @throws FormClosedException If the form is not yet opened
*/
- public function addFormNote ($noteId, $formNotes) {
+ public function addFormNote (string $noteId, string $formNotes) {
// Is the form opened?
if (($this->formOpened === false) && ($this->formEnabled === true)) {
// Throw an exception
throw new FormClosedException (array($this, 'form_notes'), self::EXCEPTION_CLOSED_FORM);
- } // END - if
+ }
// Generate the content
$inputContent = sprintf(" <div id=\"form_note_%s\">
* @return void
* @throws FormClosedException If the form is not yet opened
*/
- public function addInputSelectField ($selectId, $firstEntry) {
+ public function addInputSelectField (string $selectId, string $firstEntry) {
// Is the form group opened?
if (($this->formOpened === false) && ($this->formEnabled === true)) {
// Throw an exception
throw new FormClosedException (array($this, 'form_notes'), self::EXCEPTION_CLOSED_FORM);
- } // END - if
+ }
// Shall we close or open the sub group?
if (($this->ifSubGroupOpenedPreviously() === false) && ($this->getPreviousSubGroupId() !== $selectId)) {
$firstEntry = sprintf("<option value=\"invalid\" disabled=\"disabled\">%s</option>\n",
$firstEntry
);
- } // END - if
+ }
// Construct the opening select tag
$content = sprintf("<select class=\"select_box\" id=\"%s_%s\" name=\"%s\">\n%s",
* @throws HelperNoPreviousOpenedSubGroupException If no previously opened sub group was found
* @todo Add checking if sub option is already added
*/
- public function addSelectSubOption ($subName, $subValue) {
+ public function addSelectSubOption (string $subName, string $subValue) {
// Is there a sub group (shall be a selection box!)
if ($this->ifSubGroupOpenedPreviously() === false) {
// Then throw an exception here
throw new HelperNoPreviousOpenedSubGroupException(array($this, $content), self::EXCEPTION_NO_PREVIOUS_SUB_GROUP_OPENED);
- } // END - if
+ }
// Render the content
$content = sprintf("<option value=\"invalid\" class=\"suboption suboption_%s\" disabled=\"disabled\">%s</option>\n",
* @throws HelperNoPreviousOpenedSubGroupException If no previously opened sub group was found
* @todo Add checking if sub option is already added
*/
- public function addSelectOption ($optionName, $optionValue) {
+ public function addSelectOption (string $optionName, string $optionValue) {
// Is there a sub group (shall be a selection box!)
if ($this->ifSubGroupOpenedPreviously() === false) {
// Then throw an exception here
throw new HelperNoPreviousOpenedSubGroupException(array($this, $content), self::EXCEPTION_NO_PREVIOUS_SUB_GROUP_OPENED);
- } // END - if
+ }
// Render the content
$content = sprintf("<option value=\"%s\" class=\"option option_%s\">%s</option>\n",
try {
// Get last executed pre filter
- $extraInstance = GenericRegistry::getRegistry()->getInstance('extra');
+ $extraInstance = ObjectRegistry::getRegistry('generic')->getInstance('extra');
} catch (NullPointerException $e) {
// Instance in registry is not set (NULL)
// @TODO We need to log this later
* @param $formEnabled Whether form is enabled or disabled
* @return void
*/
- public final function enableForm ($formEnabled = true) {
- $this->formEnabled = (bool) $formEnabled;
+ public final function enableForm (bool $formEnabled = true) {
+ $this->formEnabled = $formEnabled;
}
/**
* @param $formName Name of this form
* @return void
*/
- public final function setFormName ($formName) {
- $this->formName = (string) $formName;
+ public final function setFormName (string $formName) {
+ $this->formName = $formName;
}
/**
* @param $formId Id of this form
* @return void
*/
- public final function setFormId ($formId) {
- $this->formId = (string) $formId;
+ public final function setFormId (string $formId) {
+ $this->formId = $formId;
}
/**
* @return $required Whether the email address is required
*/
public function ifRegisterRequiresEmailVerification () {
- $required = ($this->getConfigInstance()->getConfigEntry('register_requires_email') == 'Y');
+ $required = FrameworkBootstrap::getConfigurationInstance()->isEnabled('register_requires_email');
return $required;
}
* @return $required Whether profile data shall be asked
*/
public function ifRegisterIncludesProfile () {
- $required = ($this->getConfigInstance()->getConfigEntry('register_includes_profile') == 'Y');
+ $required = FrameworkBootstrap::getConfigurationInstance()->isEnabled('register_includes_profile');
return $required;
}
* @return $isSecured Whether this form is secured by a CAPTCHA
*/
public function ifFormSecuredWithCaptcha () {
- $isSecured = ($this->getConfigInstance()->getConfigEntry($this->getFormName() . '_captcha_secured') == 'Y');
+ $isSecured = FrameworkBootstrap::getConfigurationInstance()->isEnabled($this->getFormName() . '_captcha_secured');
return $isSecured;
}
* @return $required Whether personal data shall be asked
*/
public function ifRegisterIncludesPersonaData () {
- $required = ($this->getConfigInstance()->getConfigEntry('register_personal_data') == 'Y');
+ $required = FrameworkBootstrap::getConfigurationInstance()->isEnabled('register_personal_data');
return $required;
}
* @return $required Whether birthday shall be asked
*/
public function ifProfileIncludesBirthDay () {
- $required = ($this->getConfigInstance()->getConfigEntry('profile_includes_birthday') == 'Y');
+ $required = FrameworkBootstrap::getConfigurationInstance()->isEnabled('profile_includes_birthday');
return $required;
}
* @return $isUnique
*/
public function ifEmailMustBeUnique () {
- $isUnique = ($this->getConfigInstance()->getConfigEntry('register_email_unique') == 'Y');
+ $isUnique = FrameworkBootstrap::getConfigurationInstance()->isEnabled('register_email_unique');
return $isUnique;
}
*
* @return $required Whether the specified chat protocol is enabled
*/
- public function ifChatEnabled ($chatProtocol) {
- $required = ($this->getConfigInstance()->getConfigEntry('chat_enabled_' . $chatProtocol) == 'Y');
+ public function ifChatEnabled (string $chatProtocol) {
+ $required = FrameworkBootstrap::getConfigurationInstance()->isEnabled('chat_protocol_' . $chatProtocol);
return $required;
}
* @return $isEnabled Whether the login is enabled or disabled
*/
public function ifLoginIsEnabled () {
- $isEnabled = ($this->getConfigInstance()->getConfigEntry('login_enabled') == 'Y');
+ $isEnabled = FrameworkBootstrap::getConfigurationInstance()->isEnabled('user_login');
return $isEnabled;
}
* @return $isEnabled Whether the login shall be done by username
*/
public function ifLoginWithUsername () {
- $isEnabled = ($this->getConfigInstance()->getConfigEntry('login_type') == "username");
+ $isEnabled = (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('login_type') == 'username');
return $isEnabled;
}
* @return $isEnabled Whether the login shall be done by email
*/
public function ifLoginWithEmail () {
- $isEnabled = ($this->getConfigInstance()->getConfigEntry('login_type') == "email");
+ $isEnabled = (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('login_type') == 'email');
return $isEnabled;
}
* @return $isAllowed Whether guest login is allowed
*/
public function ifGuestLoginAllowed () {
- $isAllowed = ($this->getConfigInstance()->getConfigEntry('guest_login_allowed') == 'Y');
+ $isAllowed = FrameworkBootstrap::getConfigurationInstance()->isEnabled('guest_login');
return $isAllowed;
}
* @return $requireConfirm Whether email change must be confirmed
*/
public function ifEmailChangeRequireConfirmation () {
- $requireConfirm = ($this->getConfigInstance()->getConfigEntry('email_change_confirmation') == 'Y');
+ $requireConfirm = FrameworkBootstrap::getConfigurationInstance()->isEnabled('email_change_confirmation');
return $requireConfirm;
}
* @return $emailChange Whether changing email address is allowed
*/
public function ifEmailChangeAllowed () {
- $emailChange = ($this->getConfigInstance()->getConfigEntry('email_change_allowed') == 'Y');
+ $emailChange = FrameworkBootstrap::getConfigurationInstance()->isEnabled('email_change');
return $emailChange;
}
* @return $isUnconfirmed Whether the user account is unconfirmed
*/
public function ifUserAccountUnconfirmed () {
- $isUnconfirmed = ($this->getValueField(UserDatabaseWrapper::DB_COLUMN_USER_STATUS) === $this->getConfigInstance()->getConfigEntry('user_status_unconfirmed'));
+ $isUnconfirmed = ($this->getValueField(UserDatabaseFrontend::DB_COLUMN_USER_STATUS) === FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('user_status_unconfirmed'));
return $isUnconfirmed;
}
* @return $isUnconfirmed Whether the user account is locked
*/
public function ifUserAccountLocked () {
- $isUnconfirmed = ($this->getValueField(UserDatabaseWrapper::DB_COLUMN_USER_STATUS) === $this->getConfigInstance()->getConfigEntry('user_status_locked'));
+ $isUnconfirmed = ($this->getValueField(UserDatabaseFrontend::DB_COLUMN_USER_STATUS) === FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('user_status_locked'));
return $isUnconfirmed;
}
* @return $isUnconfirmed Whether the user account is a guest
*/
public function ifUserAccountGuest () {
- $isUnconfirmed = ($this->getValueField(UserDatabaseWrapper::DB_COLUMN_USER_STATUS) === $this->getConfigInstance()->getConfigEntry('user_status_guest'));
+ $isUnconfirmed = ($this->getValueField(UserDatabaseFrontend::DB_COLUMN_USER_STATUS) === FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('user_status_guest'));
return $isUnconfirmed;
}
* @return $refillActive Whether the refill page is active
*/
public function ifRefillPageActive () {
- $refillActive = ($this->getConfigInstance()->getConfigEntry('refill_page_active') == 'Y');
+ $refillActive = FrameworkBootstrap::getConfigurationInstance()->isEnabled('refill_page_active');
return $refillActive;
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Configuration\FrameworkConfiguration;
+use Org\Mxchange\CoreFramework\Configuration\NoConfigEntryException;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Helper\Template\HelpableTemplate;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
-use Org\Mxchange\CoreFramework\String\Utils\StringUtils;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @return $helperInstance A prepared instance of this helper
* @throws NoConfigEntryException A deprecated exception at this point
*/
- public static final function createHtmlLinkHelper (CompileableTemplate $templateInstance, $linkName, $linkBase = NULL) {
+ public static final function createHtmlLinkHelper (CompileableTemplate $templateInstance, string $linkName, $linkBase = NULL) {
// Get new instance
$helperInstance = new HtmlLinkHelper();
$helperInstance->setLinkName($linkName);
// Get the application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Get the request instance
$requestInstance = FrameworkBootstrap::getRequestInstance();
// Sanity-check on it
if (is_null($requestInstance)) {
// Throw an exception here
- throw new NullPointerException($helperInstance, self::EXCEPTION_IS_NULL_POINTER);
- } // END - if
+ throw new NullPointerException($helperInstance, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
+ }
// Get page (this will throw an exception if not set)
$command = StringUtils::convertDashesToUnderscores($requestInstance->getRequestElement('command'));
if (!is_null($linkBase)) {
// Then output a deprecation message
$helperInstance->deprecationWarning('[' . __METHOD__ . ':' . __LINE__ . ']: linkBase is deprecated. Please remove it from your templates and add a config entry ' . $configEntry . ' in your config.php file.');
- } // END - if
+ }
// Determine link base from config now and 'command' request
try {
- $newLinkBase = $helperInstance->getConfigInstance()->getConfigEntry($configEntry);
+ $newLinkBase = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($configEntry);
$linkBase = $newLinkBase;
} catch (NoConfigEntryException $e) {
// Is the deprecated linkBase not set?
if (is_null($linkBase)) {
// Then throw again the exception
throw new NoConfigEntryException(array(__CLASS__, ($configEntry)), FrameworkConfiguration::EXCEPTION_CONFIG_ENTRY_WAS_NOT_FOUND);
- } // END - if
+ }
}
// Set link base
* @param $extraContent Optional extra HTML content
* @return $linkContent Rendered text link content
*/
- private function renderLinkContentWithTextExtraContent ($linkText, $linkTitle, $extraContent='') {
+ private function renderLinkContentWithTextExtraContent (string $linkText, string $linkTitle, string $extraContent = '') {
// Construct link content
$linkContent = sprintf('<a href="{?base_url?}/%s%s" title="%s">%s</a>',
$this->getLinkBase(),
* @param $linkName Name of the link we shall generate
* @return void
*/
- protected final function setLinkName ($linkName) {
- $this->linkName = (string) $linkName;
+ protected final function setLinkName (string $linkName) {
+ $this->linkName = $linkName;
}
/**
* @param $linkBase Base of the link we shall generate
* @return void
*/
- protected final function setLinkBase ($linkBase) {
- $this->linkBase = (string) $linkBase;
+ protected final function setLinkBase (string $linkBase) {
+ $this->linkBase = $linkBase;
}
/**
if ($this->ifGroupOpenedPreviously()) {
// Then close it
$this->closePreviousGroupByContent('');
- } // END - if
+ }
// Get the content
$content = $this->renderContent();
* @param $groupCode Code to open and close groups
* @return void
*/
- public function addLinkGroup ($groupId, $groupText, $groupCode = 'div') {
+ public function addLinkGroup (string $groupId, string $groupText, string $groupCode = 'div') {
// Is a group with that name open?
if ($this->ifGroupOpenedPreviously()) {
// Then close it here
$this->closePreviousGroupByContent('');
- } // END - if
+ }
// Generate the group content
$content = sprintf('<%s id="group_%s_%s">%s',
* @return void
* @throws NoGroupOpenedException If no previous group was opened
*/
- public function addLinkNote ($groupId, $groupNote, $groupCode = 'div') {
+ public function addLinkNote (string $groupId, string $groupNote, string $groupCode = 'div') {
// Check if a previous group was opened
if ($this->ifGroupOpenedPreviously() === false) {
// No group was opened before!
throw new NoGroupOpenedException(array($this, $groupNote), self::EXCEPTION_GROUP_NOT_OPENED);
- } // END - if
+ }
// Is a previous sub group open?
if ($this->ifSubGroupOpenedPreviously()) {
// Then close it
$this->closePreviousSubGroupByContent('</' . $groupCode . '>');
- } // END - if
+ }
// Generate the group content
$content = sprintf('<%s id="subgroup_%s_%s">%s',
* @return void
* @throws NoGroupOpenedException If no previous group was opened
*/
- protected function addActionLink ($linkAction, $linkText, $linkTitle) {
+ protected function addActionLink (string $linkAction, string $linkText, string $linkTitle) {
// Check if a previous group was opened
if ($this->ifGroupOpenedPreviously() === false) {
// No group was opened before!
throw new NoGroupOpenedException(array($this, $linkAction . '(' . $linkText . ')'), self::EXCEPTION_GROUP_NOT_OPENED);
- } // END - if
+ }
// Default parameter SEPARATOR is &
$separator = self::EXTRA_PARAMETER_SEPARATOR;
if (count($linkArray) == 0) {
// No question mark
$separator = self::FIRST_PARAMETER_SEPARATOR;
- } // END - if
+ }
// Prepare action
$action = sprintf('%saction=%s',
* @param $languageId Language id string to use
* @return void
*/
- public function addActionLinkById ($linkAction, $languageId) {
+ public function addActionLinkById (string $linkAction, string $languageId) {
// Resolve the language string
- $languageResolvedText = $this->getLanguageInstance()->getMessage('link_' . $languageId . '_text');
+ $languageResolvedText = FrameworkBootstrap::getLanguageInstance()->getMessage('link_' . $languageId . '_text');
// Resolve the language string
- $languageResolvedTitle = $this->getLanguageInstance()->getMessage('link_' . $languageId . '_title');
+ $languageResolvedTitle = FrameworkBootstrap::getLanguageInstance()->getMessage('link_' . $languageId . '_title');
// Add the action link
$this->addActionLink($linkAction, $languageResolvedText, $languageResolvedTitle);
* @param $languageId Language id string to use
* @return void
*/
- public function addLinkWithTextById ($languageId) {
+ public function addLinkWithTextById (string $languageId) {
// Resolve the language string
- $languageResolvedText = $this->getLanguageInstance()->getMessage('link_' . $languageId . '_text');
+ $languageResolvedText = FrameworkBootstrap::getLanguageInstance()->getMessage('link_' . $languageId . '_text');
// Resolve the language string
- $languageResolvedTitle = $this->getLanguageInstance()->getMessage('link_' . $languageId . '_title');
+ $languageResolvedTitle = FrameworkBootstrap::getLanguageInstance()->getMessage('link_' . $languageId . '_title');
// Now add the link
$linkContent = $this->renderLinkContentWithTextExtraContent($languageResolvedText, $languageResolvedTitle);
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Real name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
use Org\Mxchange\CoreFramework\Registry\Registerable;
+use Org\Mxchange\CoreFramework\Traits\Template\CompileableTemplateTrait;
/**
* A general image class
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseImage extends BaseFrameworkSystem implements Registerable {
+ // Load traits
+ use CompileableTemplateTrait;
+
/**
* Image type
*/
/**
* Width of the image
*/
- private $width = '';
+ private $width = 0;
/**
* Height of the image
*/
- private $height = '';
+ private $height = 0;
/**
* X/Y
*/
- private $x = '';
- private $y = '';
+ private $x = 0;
+ private $y = 0;
/**
* Font size
*/
- private $fontSize = '';
+ private $fontSize = 0;
/**
* Image string
/**
* Background color in RGB
*/
- private $backgroundColor = array(
+ private $backgroundColor = [
'red' => '',
'green' => '',
'blue' => ''
- );
+ ];
/**
* Foreground color in RGB
*/
- private $foregroundColor = array(
+ private $foregroundColor = [
'red' => '',
'green' => '',
'blue' => ''
- );
+ ];
/**
* Current choosen color array
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
* @param $colorChannel Red, green or blue channel?
* @param $colorValue Value to set
*/
- private final function setColor ($colorMode, $colorChannel, $colorValue) {
+ private final function setColor (string $colorMode, string $colorChannel, $colorValue) {
// Construct the eval() command
$eval = sprintf("\$this->%s['%s'] = \"%s\";",
$colorMode,
* @param $width Width of the image
* @return void
*/
- public final function setWidth ($width) {
+ public final function setWidth (int $width) {
$this->width = $width;
}
* @param $height Height of the image
* @return void
*/
- public final function setHeight ($height) {
+ public final function setHeight (int $height) {
$this->height = $height;
}
* @return void
* @todo Find something usefull for this method.
*/
- public function initImageString ($groupable = 'single') {
+ public function initImageString (string $groupable = 'single') {
$this->groupable = $groupable;
}
* @return void
*/
public final function setRed ($red) {
- // Get array name
- $arrayName = $this->colorMode;
-
// Set image color
- $this->setColor($arrayName, 'red', $red);
+ $this->setColor($this->colorMode, 'red', $red);
}
/**
* @return void
*/
public final function setGreen ($green) {
- // Get array name
- $arrayName = $this->colorMode;
-
// Set image color
- $this->setColor($arrayName, 'green', $green);
+ $this->setColor($this->colorMode, 'green', $green);
}
/**
* @return void
*/
public final function setBlue ($blue) {
- // Get array name
- $arrayName = $this->colorMode;
-
// Set image color
- $this->setColor($arrayName, 'blue', $blue);
+ $this->setColor($this->colorMode, 'blue', $blue);
}
/**
* @param $string String to set in image
* @return void
*/
- public final function setString ($string) {
- $this->imageString = (string) $string;
+ public final function setString (string $string) {
+ $this->imageString = $string;
}
/**
* @param $imageType Type to set in image
* @return void
*/
- protected final function setImageType ($imageType) {
- $this->imageType = (string) $imageType;
+ protected final function setImageType (string $imageType) {
+ $this->imageType = $imageType;
}
/**
* @param $name Name of the image
* @return void
*/
- public final function setImageName ($name) {
- $this->imageName = (string) $name;
+ public final function setImageName (string $name) {
+ $this->imageName = $name;
}
/**
* @param $x X coordinate
* @return void
*/
- public final function setX ($x) {
+ public final function setX (int $x) {
$this->x = $x;
}
* @param $y Y coordinate
* @return void
*/
- public final function setY ($y) {
+ public final function setY (int $y) {
$this->y = $y;
}
* @param $fontSize Font size for strings
* @return void
*/
- public final function setFontSize ($fontSize) {
+ public final function setFontSize (int $fontSize) {
$this->fontSize = $fontSize;
}
* @param $stringName String name to set
* @return void
*/
- public final function setStringName($stringName) {
+ public final function setStringName(string $stringName) {
$this->stringName = $stringName;
}
* @return void
*/
public function finishImage () {
- // Get template instance
- $templateInstance = $this->getTemplateInstance();
-
// Compile width and height
- $width = $templateInstance->compileRawCode($this->getWidth());
- $height = $templateInstance->compileRawCode($this->getHeight());
+ $width = $this->getTemplateInstance()->compileRawCode($this->getWidth());
+ $height = $this->getTemplateInstance()->compileRawCode($this->getHeight());
// Set both again
$this->setWidth($width);
$this->imageResource = imagecreatetruecolor($width, $height);
// Compile background colors
- $red = $templateInstance->compileRawCode($this->backgroundColor['red']);
- $green = $templateInstance->compileRawCode($this->backgroundColor['green']);
- $blue = $templateInstance->compileRawCode($this->backgroundColor['blue']);
+ $red = $this->getTemplateInstance()->compileRawCode($this->backgroundColor['red']);
+ $green = $this->getTemplateInstance()->compileRawCode($this->backgroundColor['green']);
+ $blue = $this->getTemplateInstance()->compileRawCode($this->backgroundColor['blue']);
// Set all back
$this->initBackgroundColor();
imagefill($this->getImageResource(), 0, 0, $backColor);
// Compile foreground colors
- $red = $templateInstance->compileRawCode($this->foregroundColor['red']);
- $green = $templateInstance->compileRawCode($this->foregroundColor['green']);
- $blue = $templateInstance->compileRawCode($this->foregroundColor['blue']);
+ $red = $this->getTemplateInstance()->compileRawCode($this->foregroundColor['red']);
+ $green = $this->getTemplateInstance()->compileRawCode($this->foregroundColor['green']);
+ $blue = $this->getTemplateInstance()->compileRawCode($this->foregroundColor['blue']);
// Set all fore
$this->initForegroundColor();
switch ($this->groupable) {
case 'single': // Single image string
// Compile image string
- $imageString = $templateInstance->compileRawCode($this->getString());
+ $imageString = $this->getTemplateInstance()->compileRawCode($this->getString());
// Set it back
$this->setString($imageString);
// Compile X/Y coordinates and font size
- $x = $templateInstance->compileRawCode($this->getX());
- $y = $templateInstance->compileRawCode($this->getY());
- $size = $templateInstance->compileRawCode($this->getFontSize());
+ $x = $this->getTemplateInstance()->compileRawCode($this->getX());
+ $y = $this->getTemplateInstance()->compileRawCode($this->getY());
+ $size = $this->getTemplateInstance()->compileRawCode($this->getFontSize());
// Set the image string
imagestring($this->getImageResource(), $size, $x, $y, $imageString, $foreColor);
case 'groupable': // More than one string allowed
// Walk through all groups
- foreach ($templateInstance->getVariableGroups() as $group => $set) {
+ foreach ($this->getTemplateInstance()->getVariableGroups() as $group => $set) {
// Set the group
- $templateInstance->setVariableGroup($group, false);
+ $this->getTemplateInstance()->setVariableGroup($group, false);
// Compile image string
- $imageString = $templateInstance->compileRawCode($this->getString());
+ $imageString = $this->getTemplateInstance()->compileRawCode($this->getString());
// Compile X/Y coordinates and font size
- $x = $templateInstance->compileRawCode($this->getX());
- $y = $templateInstance->compileRawCode($this->getY());
- $size = $templateInstance->compileRawCode($this->getFontSize());
+ $x = $this->getTemplateInstance()->compileRawCode($this->getX());
+ $y = $this->getTemplateInstance()->compileRawCode($this->getY());
+ $size = $this->getTemplateInstance()->compileRawCode($this->getFontSize());
// Set the image string
//* DEBUG: */ print __METHOD__.": size={$size}, x={$x}, y={$y}, string={$imageString}<br />\n";
imagestring($this->getImageResource(), $size, $x, $y, $imageString, $foreColor);
- } // END - foreach
+ }
break;
}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Image;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
-
-// Import SPL stuff
-use \SplFileInfo;
-
-/**
- * A PNG image generator
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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 PngImage extends BaseImage {
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of this image class
- *
- * @param $templateInstance A template instance
- * @return $imageInstance An instance of this image class
- */
- public static final function createPngImage(CompileableTemplate $templateInstance) {
- // Get a new instance
- $imageInstance = new PngImage();
-
- // Set template instance
- $imageInstance->setTemplateInstance($templateInstance);
-
- // Set image type
- $imageInstance->setImageType('png');
-
- // Return the instance
- return $imageInstance;
- }
-
- /**
- * Finish this image by producing it
- *
- * @return void
- * @todo Rewrite this to SplFileInfo/Object
- */
- public function finishImage () {
- $this->partialStub('Unfinished method.');
- return;
-
- // Call parent method
- parent::finishImage();
-
- // Get a file name for our image
- $cacheFile = $this->getTemplateInstance()->getImageCacheFile();
-
- // Does it exist?
- if (FrameworkBootstrap::isReadableFile($cacheFile)) {
- // Remove it
- unlink($cacheFile->getPathname());
- } // END - if
-
- // Finish the image and send it to a cache file
- imagepng($this->getImageResource(), $cacheFile->getPathname(), 9, PNG_ALL_FILTERS);
- }
-
-}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Image;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
+
+// Import SPL stuff
+use \SplFileInfo;
+
+/**
+ * A PNG image generator
+ *
+ * @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 PngImage extends BaseImage {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Creates an instance of this image class
+ *
+ * @param $templateInstance A template instance
+ * @return $imageInstance An instance of this image class
+ */
+ public static final function createPngImage(CompileableTemplate $templateInstance) {
+ // Get a new instance
+ $imageInstance = new PngImage();
+
+ // Set template instance
+ $imageInstance->setTemplateInstance($templateInstance);
+
+ // Set image type
+ $imageInstance->setImageType('png');
+
+ // Return the instance
+ return $imageInstance;
+ }
+
+ /**
+ * Finish this image by producing it
+ *
+ * @return void
+ * @todo Rewrite this to SplFileInfo/Object
+ */
+ public function finishImage () {
+ DebugMiddleware::getSelfInstance()->partialStub('Unfinished method.');
+ return;
+
+ // Call parent method
+ parent::finishImage();
+
+ // Get a file name for our image
+ $cacheFile = $this->getTemplateInstance()->getImageCacheFile();
+
+ // Does it exist?
+ if (FrameworkBootstrap::isReadableFile($cacheFile)) {
+ // Remove it
+ unlink($cacheFile->getPathname());
+ }
+
+ // Finish the image and send it to a cache file
+ imagepng($this->getImageResource(), $cacheFile->getPathname(), 9, PNG_ALL_FILTERS);
+ }
+
+}
<?php
// Own namespace
-namespace CoreFramework\Index\!!!;
+namespace Org\Mxchange\CoreFramework\Index\!!!;
// Import framework stuff
use Org\Mxchange\CoreFramework\Index\BaseIndex;
use Org\Mxchange\CoreFramework\Index\Indexable;
+// Import SPL stuff
+use \SplFileInfo;
+
/**
* A ??? index class
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @param $fileName Name of the file stack to create an index file for
* @return $indexInstance An instance of this Index class
*/
- public final static function create???Index ($fileName) {
+ public final static function create???Index (SplFileInfo $fileInfoInstance) {
// Get a new instance
$indexInstance = new ???Index();
// Initialize index
- $indexInstance->initIndex($fileName);
+ $indexInstance->initIndex($fileInfoInstance);
// Return the prepared instance
return $indexInstance;
namespace Org\Mxchange\CoreFramework\Index;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
-use Org\Mxchange\CoreFramework\Iterator\Filesystem\SeekableWritableFileIterator;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
+use Org\Mxchange\CoreFramework\Traits\Iterator\IteratorTrait;
// Import SPL stuff
use \SplFileInfo;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-abstract class BaseIndex extends BaseFrameworkSystem {
- /**
- * Magic for this index
- */
- const INDEX_MAGIC = 'INDEXv0.1';
-
- /**
- * Separator group->hash
- */
- const SEPARATOR_GROUP_HASH = 0x01;
-
- /**
- * Separator hash->gap position
- */
- const SEPARATOR_HASH_GAP_POSITION = 0x02;
-
- /**
- * Separator gap position->length
- */
- const SEPARATOR_GAP_LENGTH = 0x03;
+abstract class BaseIndex extends BaseFrameworkSystem implements Indexable {
+ // Load traits
+ use IteratorTrait;
/**
* Protected constructor
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
- /**
- * Reads the file header
- *
- * @return void
- */
- public function readFileHeader () {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
-
- // First rewind to beginning as the header sits at the beginning ...
- $this->getIteratorInstance()->rewind();
-
- // Then read it (see constructor for calculation)
- $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
-
- // Have all requested bytes been read?
- assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
-
- // Last character must be the separator
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
- assert(substr($data, -1, 1) == chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES));
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
-
- // Okay, then remove it
- $data = substr($data, 0, -1);
-
- // And update seek position
- $this->getIteratorInstance()->updateSeekPosition();
-
- /*
- * Now split it:
- *
- * 0 => magic
- * 1 => total entries
- */
- $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
-
- // Set it here
- $this->getIteratorInstance()->setHeader($header);
-
- // Check if the array has only 3 elements
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, true)));
- assert(count($header) == 2);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
-
- // Check magic
- assert($header[0] == self::INDEX_MAGIC);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
-
- // Check length of count
- assert(strlen($header[1]) == BaseBinaryFile::LENGTH_COUNT);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
-
- // Decode count
- $header[1] = hex2bin($header[1]);
-
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
- }
-
- /**
- * Flushes the file header
- *
- * @return void
- */
- public function flushFileHeader () {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
-
- // Put all informations together
- $header = sprintf('%s%s%s%s',
- // Magic
- self::INDEX_MAGIC,
-
- // Separator header data
- chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
-
- // Total entries
- str_pad($this->dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
-
- // Separator header<->entries
- chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
- );
-
- // Write it to disk (header is always at seek position 0)
- $this->getIteratorInstance()->writeData(0, $header, false);
-
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
- }
-
- /**
- * Initializes this index
- *
- * @param $fileInfoInstance An instance of a SplFileInfo class
- * @return void
- * @todo Currently the index file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole index file.
- */
- protected function initIndex (SplFileInfo $fileInfoInstance) {
- // Get a file i/o pointer instance for index file
- $fileInstance = ObjectFactory::createObjectByConfiguredName('index_file_class', array($fileInfoInstance, $this));
-
- // Get iterator instance
- $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
-
- // Is the instance implementing the right interface?
- assert($iteratorInstance instanceof SeekableWritableFileIterator);
-
- // Set iterator here
- $this->setIteratorInstance($iteratorInstance);
-
- // Calculate header size
- $this->getIteratorInstance()->setHeaderSize(
- strlen(self::INDEX_MAGIC) +
- strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
- BaseBinaryFile::LENGTH_COUNT +
- strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
- );
-
- // Init counters and gaps array
- $this->getIteratorInstance()->initCountersGapsArray();
-
- // Is the file's header initialized?
- if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
- // No, then create it (which may pre-allocate the index)
- $this->getIteratorInstance()->createFileHeader();
-
- // And pre-allocate a bit
- $this->getIteratorInstance()->preAllocateFile('index');
- } // END - if
-
- // Load the file header
- $this->readFileHeader();
-
- // Count all entries in file
- $this->getIteratorInstance()->analyzeFile();
- }
-
- /**
- * Calculates minimum length for one entry/block
- *
- * @return $length Minimum length for one entry/block
- */
- public function calculateMinimumBlockLength () {
- // Calulcate it
- $length = BaseBinaryFile::LENGTH_TYPE + strlen(chr(BaseBinaryFile::SEPARATOR_TYPE_POSITION)) + BaseBinaryFile::LENGTH_POSITION + strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
-
- // Return it
- return $length;
- }
-
- /**
- * Determines whether the EOF has been reached
- *
- * @return $isEndOfFileReached Whether the EOF has been reached
- * @throws UnsupportedOperationException If this method is called
- */
- public function isEndOfFileReached () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Initializes counter for valid entries, arrays for damaged entries and
- * an array for gap seek positions. If you call this method on your own,
- * please re-analyze the file structure. So you are better to call
- * analyzeFile() instead of this method.
- *
- * @return void
- * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
- */
- public function initCountersGapsArray () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Getter for header size
- *
- * @return $totalEntries Size of file header
- * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
- */
- public final function getHeaderSize () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Setter for header size
- *
- * @param $headerSize Size of file header
- * @return void
- * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
- */
- public final function setHeaderSize ($headerSize) {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Getter for header array
- *
- * @return $totalEntries Size of file header
- * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
- */
- public final function getHeader () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Setter for header
- *
- * @param $header Array for a file header
- * @return void
- * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
- */
- public final function setHeader (array $header) {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Updates seekPosition attribute from file to avoid to much access on file.
- *
- * @return void
- * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
- */
- public function updateSeekPosition () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Getter for total entries
- *
- * @return $totalEntries Total entries in this file
- * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
- */
- public final function getCounter () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * "Getter" for file size
- *
- * @return $fileSize Size of currently loaded file
- */
- public function getFileSize () {
- // Call iterator's method
- return $this->getIteratorInstance()->getFileSize();
- }
-
- /**
- * Writes data at given position
- *
- * @param $seekPosition Seek position
- * @param $data Data to be written
- * @param $flushHeader Whether to flush the header (default: flush)
- * @return void
- * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
- */
- public function writeData ($seekPosition, $data, $flushHeader = true) {
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data[]=%s,flushHeader=%d', __METHOD__, __LINE__, $seekPosition, gettype($data), intval($flushHeader)));
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Writes given value to the file and returns a hash and gap position for it
- *
- * @param $groupId Group identifier
- * @param $value Value to be added to the stack
- * @return $data Hash and gap position
- * @throws UnsupportedOperationException If this method is called
- */
- public function writeValueToFile ($groupId, $value) {
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',value[' . gettype($value) . ']=' . print_r($value, true));
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Writes given raw data to the file and returns a gap position and length
- *
- * @param $groupId Group identifier
- * @param $hash Hash from encoded value
- * @param $encoded Encoded value to be written to the file
- * @return $data Gap position and length of the raw data
- */
- public function writeDataToFreeGap ($groupId, $hash, $encoded) {
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',hash=' . $hash . ',encoded()=' . strlen($encoded));
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Index\File;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
+use Org\Mxchange\CoreFramework\Filesystem\File\BinaryFile;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Index\BaseIndex;
+use Org\Mxchange\CoreFramework\Index\Indexable;
+use Org\Mxchange\CoreFramework\Utils\Arrays\ArrayUtils;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
+
+// Import SPL stuff
+use \OutOfBoundsException;
+use \SplFileInfo;
+use \UnexpectedValueException;
+
+/**
+ * A general file-based index class
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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/>.
+ */
+abstract class BaseFileIndex extends BaseIndex implements FileIndexer {
+ /**
+ * Minimum block length
+ */
+ private static $minimumBlockLength = 0;
+
+ /**
+ * Protected constructor
+ *
+ * @param $className Name of class
+ * @return void
+ */
+ protected function __construct (string $className) {
+ // Call parent constructor
+ parent::__construct($className);
+ }
+
+ /**
+ * Reads the file header
+ *
+ * @return void
+ * @throws UnexpectedValueException If header length or count of elements is invalid
+ */
+ public function readIndexHeader () {
+ // First rewind to beginning as the header sits at the beginning ...
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
+ $this->getIteratorInstance()->rewind();
+
+ // Get header size
+ $headerSize = $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize();
+
+ // Then read it (see constructor for calculation)
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: headerSize=%d', $headerSize));
+ $data = $this->getIteratorInstance()->getBinaryFileInstance()->read($headerSize);
+
+ // Have all requested bytes been read?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Read %d bytes (%d wanted).', strlen($data), $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize()));
+ if (strlen($data) != $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize()) {
+ // Invalid header length
+ throw new UnexpectedValueException(sprintf('data(%d)=%s is not expected length %d',
+ strlen($data),
+ $data,
+ $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize()
+ ), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ } elseif (empty(trim($data, chr(0)))) {
+ // Empty file header
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: File header is empty - EXIT!');
+ return;
+ } elseif (substr($data, -1, 1) != chr(BinaryFile::SEPARATOR_HEADER_ENTRIES)) {
+ // Bad last character
+ throw new UnexpectedValueException(sprintf('data=%s does not end with "%s"',
+ $data,
+ chr(BinaryFile::SEPARATOR_HEADER_ENTRIES)
+ ), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
+
+ // Okay, then remove it
+ $data = substr($data, 0, -1);
+
+ // And update seek position
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Invoking this->iteratorInstance->binaryFileInstance->updateSeekPosition() ...');
+ $this->getIteratorInstance()->getBinaryFileInstance()->updateSeekPosition();
+
+ /*
+ * Now split it:
+ *
+ * 0 => magic
+ * 1 => total entries
+ */
+ $header = explode(chr(BinaryFile::SEPARATOR_HEADER_DATA), $data);
+
+ // Map numeric entries to associative (alpha-numeric) elements
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Invoking ArrayUtils::mapNumericKeysToAssociative(%d) ...', count($header)));
+ //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: header(%d)=%s', count($header), print_r($header, true)));
+ $header = ArrayUtils::mapNumericKeysToAssociative($header, [
+ BinaryFile::HEADER_NAME_MAGIC,
+ BinaryFile::HEADER_NAME_TOTAL_ENTRIES,
+ ]);
+
+ // Check if the array has only 2 elements
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: HEADER_INDEX_ELEMENT_COUNT=%d,header()=%d', BinaryFile::HEADER_INDEX_ELEMENT_COUNT, count($header)));
+ if (count($header) != BinaryFile::HEADER_INDEX_ELEMENT_COUNT) {
+ // Bad header
+ throw new UnexpectedValueException(sprintf('header()=%d is not expected value %d', count($header), BinaryFile::HEADER_INDEX_ELEMENT_COUNT), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ } elseif ($header[BinaryFile::HEADER_NAME_MAGIC] !== Indexable::INDEX_MAGIC) {
+ // Magic must be in first element
+ throw new UnexpectedValueException(sprintf('header[%s]=%s is not the expected magic (%s)', BinaryFile::HEADER_NAME_MAGIC, $header[BinaryFile::HEADER_NAME_MAGIC], Indexable::INDEX_MAGIC), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ } elseif (strlen($header[BinaryFile::HEADER_NAME_TOTAL_ENTRIES]) != BinaryFile::LENGTH_COUNT) {
+ // Length of total entries not matching
+ throw new UnexpectedValueException(sprintf('header[%s](%d)=%s does not have expected length %d', BinaryFile::HEADER_NAME_TOTAL_ENTRIES, strlen($header[BinaryFile::HEADER_NAME_TOTAL_ENTRIES]), $header[BinaryFile::HEADER_NAME_TOTAL_ENTRIES], BinaryFile::LENGTH_COUNT), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
+
+ // Decode count
+ $header[BinaryFile::HEADER_NAME_TOTAL_ENTRIES] = hex2bin($header[BinaryFile::HEADER_NAME_TOTAL_ENTRIES]);
+
+ // Set it here
+ $this->getIteratorInstance()->getBinaryFileInstance()->setHeader($header);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: EXIT!');
+ }
+
+ /**
+ * Flushes the file header
+ *
+ * @return void
+ */
+ public function flushFileHeader () {
+ // Put all informations together
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
+ $header = sprintf('%s%s%s%s',
+ // Magic
+ Indexable::INDEX_MAGIC,
+
+ // Separator header data
+ chr(BinaryFile::SEPARATOR_HEADER_DATA),
+
+ // Total entries
+ str_pad(StringUtils::dec2hex($this->getIteratorInstance()->getBinaryFileInstance()->getCounter()), BinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
+
+ // Separator header<->entries
+ chr(BinaryFile::SEPARATOR_HEADER_ENTRIES)
+ );
+
+ // Write it to disk (header is always at seek position 0)
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Invoking this->iteratorInstance->binaryFileInstance->writeAtPosition(0, header=%s) ...', $header));
+ $this->getIteratorInstance()->getBinaryFileInstance()->writeAtPosition(0, $header);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: EXIT!');
+ }
+
+ /**
+ * Initializes this file-based index
+ *
+ * @param $fileInfoInstance An instance of a SplFileInfo class
+ * @return void
+ * @todo Currently the index file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole index file.
+ */
+ protected function initFileIndex (SplFileInfo $fileInfoInstance) {
+ // Get a file i/o pointer instance for index file
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: fileInfoInstance[%s]=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance));
+ $fileInstance = ObjectFactory::createObjectByConfiguredName('index_file_class', array($fileInfoInstance, $this));
+
+ // Get iterator instance
+ $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', [$fileInstance]);
+
+ // Set iterator here
+ $this->setIteratorInstance($iteratorInstance);
+
+ // Calculate header size
+ $headerSize = (
+ strlen(Indexable::INDEX_MAGIC) +
+ strlen(chr(BinaryFile::SEPARATOR_HEADER_DATA)) +
+ BinaryFile::LENGTH_COUNT +
+ strlen(chr(BinaryFile::SEPARATOR_HEADER_ENTRIES))
+ );
+
+ // Set it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Setting headerSize=%d ...', $headerSize));
+ $this->getIteratorInstance()->getBinaryFileInstance()->setHeaderSize($headerSize);
+
+ // Init counters and gaps array
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Invoking this->iteratorInstance->binaryFileInstance->initCountersGapsArray() ...');
+ $this->getIteratorInstance()->getBinaryFileInstance()->initCountersGapsArray();
+
+ // Default is not created
+ $created = false;
+
+ // Is the file's header initialized?
+ if (!$this->getIteratorInstance()->getBinaryFileInstance()->isFileHeaderInitialized()) {
+ // First pre-allocate a bit
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Invoking this->iteratorInstance->binaryFileInstance->preAllocateFile(index) ...');
+ $this->getIteratorInstance()->getBinaryFileInstance()->preAllocateFile('index');
+
+ // Then write file header
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Invoking this->iteratorInstance->binaryFileInstance->createFileHeader() ...');
+ $this->getIteratorInstance()->getBinaryFileInstance()->createFileHeader();
+
+ // Mark as freshly created
+ $created = true;
+ }
+
+ // Load the file header
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Invoking this->readIndexHeader() ...');
+ $this->readIndexHeader();
+
+ // Freshly created?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: created=%d', intval($created)));
+ if (!$created) {
+ // Analyze file structure
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Invoking this->iteratorInstance->binaryFileInstance->analyzeFileStructure() ...');
+ $this->getIteratorInstance()->getBinaryFileInstance()->analyzeFileStructure();
+ }
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: EXIT!');
+ }
+
+ /**
+ * Calculates minimum length for one entry/block
+ *
+ * @return $length Minimum length for one entry/block
+ */
+ public function calculateMinimumBlockLength () {
+ // Is it "cached"?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
+ if (self::$minimumBlockLength == 0) {
+ // Calulcate it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Calculating ...');
+ self::$minimumBlockLength = (
+ // Type
+ BinaryFile::LENGTH_TYPE + strlen(chr(BinaryFile::SEPARATOR_TYPE_POSITION)) +
+ // Position
+ BinaryFile::LENGTH_POSITION + strlen(chr(BinaryFile::SEPARATOR_ENTRIES))
+ );
+ }
+
+ // Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: self::minimumBlockLength=%d - EXIT!', self::$minimumBlockLength));
+ return self::$minimumBlockLength;
+ }
+
+ /**
+ * "Getter" for file size
+ *
+ * @return $fileSize Size of currently loaded file
+ */
+ public function getFileSize () {
+ // Call iterator's method
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
+ $fileSize = $this->getIteratorInstance()->getBinaryFileInstance()->getFileSize();
+
+ // Return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: fileSize=%d - EXIT!', $fileSize));
+ return $fileSize;
+ }
+
+ /**
+ * Searches for next suitable gap the given length of data can fit in
+ * including padding bytes.
+ *
+ * @param $length Length of raw data
+ * @return $seekPosition Found next gap's seek position
+ * @throws InvalidArgumentException If the parameter is not valid
+ * @todo Unfinished work
+ */
+ public function searchNextGap (int $length) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: length=%d - CALLED!', $length));
+ if ($length <= 0) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('length=%d is not valid', $length));
+ }
+
+ // Debug message
+ /* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: length=%d,this=%s', __METHOD__, __LINE__, $length, print_r($this, true)));
+ }
+
+ /**
+ * Writes at given position by seeking to it.
+ *
+ * @param $seekPosition Seek position in file
+ * @param $dataStream Data to be written
+ * @return mixed Number of writes bytes or false on error
+ * @throws OutOfBoundsException If the position is not seekable
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ public function writeAtPosition (int $seekPosition, string $dataStream) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: seekPosition=%d,dataStream(%d)=%s - CALLED!', $seekPosition, strlen($dataStream), $dataStream));
+ if ($seekPosition < 0) {
+ // Invalid seek position
+ throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid.', $seekPosition));
+ } elseif (empty($dataStream)) {
+ // Empty dataStream
+ throw new InvalidArgumentException('Parameter "dataStream" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Call iterated object's method
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: Invoking this->iteratorInstance->binaryFileInstance->writeAtPosition(%d, %s) ...', $seekPosition, $dataStream));
+ $status = $this->getIteratorInstance()->getBinaryFileInstance()->writeAtPosition($seekPosition, $dataStream);
+
+ // Return status
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-INDEX: status[%s]=%d - EXIT!', gettype($status), $status));
+ return $status;
+ }
+
+ /**
+ * Checks if this index has been fully and properly loaded.
+ *
+ * @return $isLoaded Whether this index has been loaded
+ */
+ public function isIndexLoaded () {
+ // Is the file gaps-only?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: CALLED!');
+ if ($this->getIteratorInstance()->getBinaryFileInstance()->isFileGapsOnly()) {
+ // Then skip below code as this implies the file has been fully analyzed and "loaded"
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-INDEX: Underlaying file is gaps-only: Returning TRUE ... - EXIT!');
+ return TRUE;
+ }
+
+ // Debug message
+ /* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this=%s', __METHOD__, __LINE__, print_r($this, true)));
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Index\File\Stack;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Index\File\BaseFileIndex;
+use Org\Mxchange\CoreFramework\Index\File\Stack\IndexableStack;
+use Org\Mxchange\CoreFramework\Index\Indexable;
+use Org\Mxchange\CoreFramework\Registry\Registerable;
+use Org\Mxchange\CoreFramework\Stack\File\StackableFile;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+use \SplFileInfo;
+use \UnexpectedValueException;
+
+/**
+ * A FileStack index class
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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 FileStackIndex extends BaseFileIndex implements IndexableStack, Registerable {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Creates an instance of this Index class and prepares it for usage
+ *
+ * @param $fileInfoInstance An instance of a SplFileInfo class
+ * @return $indexInstance An instance of this Index class
+ */
+ public final static function createFileStackIndex (SplFileInfo $fileInfoInstance) {
+ // Get a new instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-STACK-INDEX: fileInfoInstance[%s]=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance));
+ $indexInstance = new FileStackIndex();
+
+ // Initialize index
+ $indexInstance->initFileIndex($fileInfoInstance);
+
+ // Return the prepared instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-STACK-INDEX: indexInstance=%s - EXIT!', $indexInstance->__toString()));
+ return $indexInstance;
+ }
+
+ /**
+ * Adds given data's hash to an index file
+ *
+ * @param $stackName Name of stack to add hash for
+ * @param $data Hash and gap position to be added to the index
+ * @return void
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws UnexpectedValueException If an invalid gap position is being returned
+ */
+ public function addHashedDataToIndex (string $stackName, array $data) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-STACK-INDEX: stackName=%s,data()=%d - CALLED!', $stackName, count($data)));
+ if (empty($stackName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "stackName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (count($data) == 0) {
+ // Throw it again
+ throw new InvalidArgumentException('Parameter "data" is an empty array');
+ } elseif (!isset($data[StackableFile::ARRAY_NAME_HASH])) {
+ // Important array element missing
+ throw new InvalidArgumentException(sprintf('data[%s] not found', StackableFile::ARRAY_NAME_HASH));
+ } elseif (!isset($data[StackableFile::ARRAY_NAME_GAP_POSITION])) {
+ // Important array element missing
+ throw new InvalidArgumentException(sprintf('data[%s] not found', StackableFile::ARRAY_NAME_GAP_POSITION));
+ } elseif (!isset($data[StackableFile::ARRAY_NAME_DATA_LENGTH])) {
+ // Important array element missing
+ throw new InvalidArgumentException(sprintf('data[%s] not found', StackableFile::ARRAY_NAME_DATA_LENGTH));
+ }
+
+ // Raw data been written to the file
+ $rawData = sprintf('%s%s%s%s%s%s%s',
+ $stackName,
+ Indexable::SEPARATOR_GROUP_HASH,
+ $data[StackableFile::ARRAY_NAME_HASH],
+ Indexable::SEPARATOR_HASH_GAP_POSITION,
+ $data[StackableFile::ARRAY_NAME_GAP_POSITION],
+ Indexable::SEPARATOR_GAP_LENGTH,
+ $data[StackableFile::ARRAY_NAME_DATA_LENGTH]
+ );
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-STACK-INDEX: stackName=%s,hash{}=0x%s,rawData(%d)=%s', $stackName, bin2hex($data[StackableFile::ARRAY_NAME_HASH]), strlen($rawData), $rawData));
+
+ // Search for next free gap
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-STACK-INDEX: Invoking this->iteratorInstance->binaryFileInstance->searchNextGap(%d) ...', strlen($rawData)));
+ $gapPosition = $this->getIteratorInstance()->getBinaryFileInstance()->searchNextGap(strlen($rawData));
+
+ // Gap position cannot be smaller or equal than header length
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-STACK-INDEX: stackName=%s,hash{}=0x%s,gapPosition=%s', $stackName, bin2hex($data[StackableFile::ARRAY_NAME_HASH]), $gapPosition));
+ if ($gapPosition <= ($this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize() + 1)) {
+ // Not valid gap position returned
+ throw new UnexpectedValueException(sprintf('gapPosition[%s]=%d is smaller or equal headerSize+1=%d', gettype($gapPosition), $gapPosition, ($this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize() + 1)), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
+
+ // Then write the data at that gap
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-STACK-INDEX: Invoking this->iteratorInstance->binaryFileInstance->writeData(%d,%s) ...', $gapPosition, $rawData));
+ $this->getIteratorInstance()->getBinaryFileInstance()->writeData($gapPosition, $rawData);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-STACK-INDEX: stackName=%s,hash{}=0x%s,rawData()=%d - EXIT!', $stackName, bin2hex($data[StackableFile::ARRAY_NAME_HASH]), strlen($rawData)));
+ }
+
+}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Index\Stack;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Index\BaseIndex;
-use Org\Mxchange\CoreFramework\Index\Indexable;
-use Org\Mxchange\CoreFramework\Registry\Registerable;
-use Org\Mxchange\CoreFramework\Stacker\Filesystem\BaseFileStack;
-use Org\Mxchange\CoreFramework\Stacker\Index\IndexableStack;
-
-// Import SPL stuff
-use \SplFileInfo;
-
-/**
- * A FileStack index class
- *
- * @author Roland Haeder <webmaster@ship-simu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.ship-simu.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 FileStackIndex extends BaseIndex implements IndexableStack, Registerable {
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of this Index class and prepares it for usage
- *
- * @param $fileInfoInstance An instance of a SplFileInfo class
- * @return $indexInstance An instance of this Index class
- */
- public final static function createFileStackIndex (SplFileInfo $fileInfoInstance) {
- // Get a new instance
- $indexInstance = new FileStackIndex();
-
- // Initialize index
- $indexInstance->initIndex($fileInfoInstance);
-
- // Return the prepared instance
- return $indexInstance;
- }
-
- /**
- * Adds given hash to an index file
- *
- * @param $groupId Name of stack to add hash for
- * @param $data Hash and gap position to be added to the index
- * @return void
- */
- public function addHashToIndex ($groupId, array $data) {
- // Debug message
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,gap=%d,length=%d - CALLED!', __METHOD__, __LINE__, $groupId, $data[BaseFileStack::ARRAY_INDEX_HASH], $data[BaseFileStack::ARRAY_INDEX_GAP_POSITION], $data[BaseFileStack::ARRAY_INDEX_DATA_LENGTH]));
-
- // Raw data been written to the file
- $rawData = sprintf('%s%s%s%s%s%s%s',
- $groupId,
- self::SEPARATOR_GROUP_HASH,
- hex2bin($data[BaseFileStack::ARRAY_INDEX_HASH]),
- self::SEPARATOR_HASH_GAP_POSITION,
- $data[BaseFileStack::ARRAY_INDEX_GAP_POSITION],
- self::SEPARATOR_GAP_LENGTH,
- $data[BaseFileStack::ARRAY_INDEX_DATA_LENGTH]
- );
-
- // Debug message
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d', __METHOD__, __LINE__, $groupId, $data[BaseFileStack::ARRAY_INDEX_HASH], strlen($rawData)));
-
- // Search for next free gap
- $gapPosition = $this->getIteratorInstance()->searchNextGap(strlen($rawData));
-
- // Gap position cannot be smaller than header length + 1
- assert($gapPosition > $this->getIteratorInstance()->getHeaderSize());
-
- // Debug message
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,gapPosition=%s', __METHOD__, __LINE__, $groupId, $data[BaseFileStack::ARRAY_INDEX_HASH], $gapPosition));
-
- // Then write the data at that gap
- $this->getIteratorInstance()->writeData($gapPosition, $rawData);
-
- // Debug message
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d - EXIT!', __METHOD__, __LINE__, $groupId, $data[BaseFileStack::ARRAY_INDEX_HASH], strlen($rawData)));
- }
-
- /**
- * Searches for next suitable gap the given length of data can fit in
- * including padding bytes.
- *
- * @param $length Length of raw data
- * @return $seekPosition Found next gap's seek position
- */
- public function searchNextGap ($length) {
- $this->partialStub('length=' . $length);
- }
-
-}
<?php
// Own namespace
-namespace CoreFramework\Iterator\!!!;
+namespace Org\Mxchange\CoreFramework\Iterator\!!!;
// Import framework stuff
use Org\Mxchange\CoreFramework\Iterator\BaseIterator;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
// Import SPL stuff
use \Iterator;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Default is null
$current = null;
- $this->partialStub('Please implement this method.');
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this method.');
// Return it
return $current;
// Default is null
$key = null;
- $this->partialStub('Please implement this method.');
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this method.');
// Return it
return $key;
* @return void
*/
public function next () {
- $this->partialStub('Please implement this method.');
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this method.');
}
/**
* @return void
*/
public function rewind () {
- $this->partialStub('Please implement this method.');
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this method.');
}
/**
* @return void
*/
public function valid () {
- $this->partialStub('Please implement this method.');
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this method.');
}
}
namespace Org\Mxchange\CoreFramework\Iterator;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Lists\Listable;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+use Org\Mxchange\CoreFramework\Traits\Lists\ListableTrait;
// Import SPL stuff
use \Iterator;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseIterator extends BaseFrameworkSystem implements Iterator {
+ // Load traits
+ use ListableTrait;
+
/**
* Protected constructor
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
if (!$this->valid()) {
// Throw an exception here
throw new IndexOutOfBoundsException($this->key(), self::EXCEPTION_INDEX_OUT_OF_BOUNDS);
- } // END - if
+ }
// Now get the entry
- $current = $this->getListInstance()->getEntry($this->key());
+ $current = $this->getListInstance()->getEntryByIndex($this->key());
// Return it
return $current;
namespace Org\Mxchange\CoreFramework\Iterator\File;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Filesystem\Block;
+use Org\Mxchange\CoreFramework\Filesystem\File\BinaryFile;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Iterator\BaseIterator;
-use Org\Mxchange\CoreFramework\Iterator\Filesystem\SeekableWritableFileIterator;
+use Org\Mxchange\CoreFramework\Traits\File\BinaryFileTrait;
+
+// Import SPL stuff
+use \BadMethodCallException;
+use \InvalidArgumentException;
+use \OutOfBoundsException;
+use \SeekableIterator;
/**
* A file iterator
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* 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 FileIterator extends BaseIterator implements SeekableWritableFileIterator {
+class FileIterator extends BaseIterator implements SeekableIterator {
+ // Load traits
+ use BinaryFileTrait;
+
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
/**
* Creates an instance of this class
*
- * @param $pointerInstance An instance of a Block class
+ * @param $binaryFileInstance An instance of a BinaryFile class
* @return $iteratorInstance An instance of a Iterator class
*/
- public final static function createFileIterator (Block $blockInstance) {
+ public final static function createFileIterator (BinaryFile $binaryFileInstance) {
// Get new instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-ITERATOR: binaryFileInstance=%s - CALLED!', $binaryFileInstance->__toString()));
$iteratorInstance = new FileIterator();
// Set the instance here
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d] Setting blockInstance=%s ...', __METHOD__, __LINE__, $blockInstance->__toString()));
- $iteratorInstance->setBlockInstance($blockInstance);
+ $iteratorInstance->setBinaryFileInstance($binaryFileInstance);
// Return the prepared instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-ITERATOR: iteratorInstance=%s - EXIT!', $iteratorInstance->__toString()));
return $iteratorInstance;
}
* Gets currently read data
*
* @return $current Currently read data
+ * @throws BadMethodCallException If valid() is FALSE
*/
public function current () {
- // Call block instance
- return $this->getBlockInstance()->current();
+ // Is condition given?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-ITERATOR: CALLED!');
+ if (!$this->valid()) {
+ // Throw BMCE
+ throw new BadMethodCallException('Current key cannot be valid, forgot to invoke valid()?', FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
+
+ // Call file instance
+ $current = $this->getBinaryFileInstance()->current();
+
+ // Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-ITERATOR: current[]=%s - EXIT!', gettype($current)));
+ return $current;
}
/**
* Gets current seek position ("key").
*
* @return $key Current key in iteration
+ * @throws BadMethodCallException If valid() is FALSE
*/
public function key () {
- // Return it
- return $this->getBlockInstance()->determineSeekPosition();
+ // Is condition given?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-ITERATOR: CALLED!');
+ if (!$this->valid()) {
+ // Throw BMCE
+ throw new BadMethodCallException('Current key cannot be valid, forgot to invoke valid()?', FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
+
+ // Get key from file instance
+ $key = $this->getBinaryFileInstance()->determineSeekPosition();
+
+ // Return key
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-ITERATOR: key[%s]=%s - EXIT!', gettype($key), $key));
+ return $key;
}
/**
- * Advances to next "block" of bytes
+ * Advances to next "file" of bytes
*
* @return void
*/
public function next () {
- // Call block instance
- $this->getBlockInstance()->next();
+ // Call file instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-ITERATOR: CALLED!');
+ $this->getBinaryFileInstance()->next();
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-ITERATOR: EXIT!');
}
/**
* @return $status Status of this operation
*/
public function rewind () {
- // Call block instance
- return $this->getBlockInstance()->rewind();
+ // Call file instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-ITERATOR: CALLED!');
+ $this->getBinaryFileInstance()->rewind();
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-ITERATOR: EXIT!');
}
/**
* @return $isValid Whether the next entry is valid
*/
public function valid () {
- // Call block instance
- return $this->getBlockInstance()->valid();
+ // Call file instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-ITERATOR: CALLED!');
+ $isValid = $this->getBinaryFileInstance()->valid();
+
+ // Return flag
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-ITERATOR: isValid=%d - EXIT!', intval($isValid)));
+ return $isValid;
}
/**
* Seeks to given position
*
* @param $seekPosition Seek position in file
- * @return $status Status of this operation
- */
- public function seek ($seekPosition) {
- // Call block instance
- return $this->getBlockInstance()->seek($seekPosition);
- }
-
- /**
- * Size of file stack
- *
- * @return $size Size (in bytes) of file
- */
- public function size () {
- // Call the block object
- $size = $this->getBlockInstance()->size();
-
- // Return result
- return $size;
- }
-
- /**
- * Reads given amount of bytes from file.
- *
- * @param $bytes Amount of bytes to read
- * @return $data Data read from file
- */
- public function read ($bytes = NULL) {
- // Call block instance
- return $this->getBlockInstance()->read($bytes);
- }
-
- /**
- * Analyzes entries in index file. This will count all found (and valid)
- * entries, mark invalid as damaged and count gaps ("fragmentation"). If
- * only gaps are found, the file is considered as "virgin" (no entries).
- *
- * @return void
- */
- public function analyzeFile () {
- // Just call the block instance
- $this->getBlockInstance()->analyzeFile();
- }
-
- /**
- * Checks whether the file header is initialized
- *
- * @return $isInitialized Whether the file header is initialized
- */
- public function isFileHeaderInitialized () {
- // Just call the block instance
- return $this->getBlockInstance()->isFileHeaderInitialized();
- }
-
- /**
- * Creates the assigned file
- *
- * @return void
- */
- public function createFileHeader () {
- // Just call the block instance
- $this->getBlockInstance()->createFileHeader();
- }
-
- /**
- * Pre-allocates file (if enabled) with some space for later faster write access.
- *
- * @param $type Type of the file
- * @return void
- */
- public function preAllocateFile ($type) {
- // Just call the block instance
- $this->getBlockInstance()->preAllocateFile($type);
- }
-
- /**
- * Initializes counter for valid entries, arrays for damaged entries and
- * an array for gap seek positions. If you call this method on your own,
- * please re-analyze the file structure. So you are better to call
- * analyzeFile() instead of this method.
- *
- * @return void
- */
- public function initCountersGapsArray () {
- // Call block instance
- $this->getBlockInstance()->initCountersGapsArray();
- }
-
- /**
- * Getter for header size
- *
- * @return $totalEntries Size of file header
- */
- public final function getHeaderSize () {
- // Call block instance
- return $this->getBlockInstance()->getHeaderSize();
- }
-
- /**
- * Setter for header size
- *
- * @param $headerSize Size of file header
- * @return void
- */
- public final function setHeaderSize ($headerSize) {
- // Call block instance
- $this->getBlockInstance()->setHeaderSize($headerSize);
- }
-
- /**
- * Getter for header array
- *
- * @return $totalEntries Size of file header
- */
- public final function getHeader () {
- // Call block instance
- return $this->getBlockInstance()->getHeader();
- }
-
- /**
- * Setter for header
- *
- * @param $header Array for a file header
- * @return void
- */
- public final function setHeader (array $header) {
- // Call block instance
- $this->getBlockInstance()->setHeader($header);
- }
-
- /**
- * Updates seekPosition attribute from file to avoid to much access on file.
- *
- * @return void
- */
- public function updateSeekPosition () {
- // Call block instance
- $this->getBlockInstance()->updateSeekPosition();
- }
-
- /**
- * Getter for total entries
- *
- * @return $totalEntries Total entries in this file
- */
- public final function getCounter () {
- // Call block instance
- return $this->getBlockInstance()->getCounter();
- }
-
- /**
- * "Getter" for file size
- *
- * @return $fileSize Size of currently loaded file
- */
- public function getFileSize () {
- // Call block instance
- return $this->getBlockInstance()->getFileSize();
- }
-
- /**
- * Writes data at given position
- *
- * @param $seekPosition Seek position
- * @param $data Data to be written
- * @param $flushHeader Whether to flush the header (default: flush)
* @return void
+ * @throws OutOfBoundsException If the position is not seekable
*/
- public function writeData ($seekPosition, $data, $flushHeader = true) {
- // Call block instance
- $this->getBlockInstance()->writeData($seekPosition, $data, $flushHeader);
- }
-
- /**
- * Getter for seek position
- *
- * @return $seekPosition Current seek position (stored here in object)
- */
- public function getSeekPosition () {
- // Call block instance
- return $this->getBlockInstance()->getSeekPosition();
- }
-
- /**
- * Writes given value to the file and returns a hash and gap position for it
- *
- * @param $groupId Group identifier
- * @param $value Value to be added to the stack
- * @return $data Hash and gap position
- */
- public function writeValueToFile ($groupId, $value) {
- // Call block instance
- return $this->getBlockInstance()->writeValueToFile($groupId, $value);
- }
+ public function seek (int $seekPosition) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-ITERATOR: seekPosition=%d,whence=%d - CALLED!', $seekPosition, $whence));
+ if ($seekPosition < 0) {
+ // Throw IAE
+ throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid', $seekPosition));
+ }
- /**
- * Writes given raw data to the file and returns a gap position and length
- *
- * @param $groupId Group identifier
- * @param $hash Hash from encoded value
- * @param $encoded Encoded value to be written to the file
- * @return $data Gap position and length of the raw data
- */
- public function writeDataToFreeGap ($groupId, $hash, $encoded) {
- // Call block instance
- return $this->getBlockInstance()->writeDataToFreeGap($groupId, $hash, $encoded);
- }
+ // Call file instance
+ $this->getBinaryFileInstance()->seek($seekPosition);
- /**
- * Searches for next suitable gap the given length of data can fit in
- * including padding bytes.
- *
- * @param $length Length of raw data
- * @return $seekPosition Found next gap's seek position
- */
- public function searchNextGap ($length) {
- // Call block instance
- print $this->getBlockInstance()->__toString() . PHP_EOL;
- return $this->getBlockInstance()->searchNextGap($length);
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-ITERATOR: EXIT!');
}
}
namespace Org\Mxchange\CoreFramework\Iterator\Registry;
// Import framework stuff
+use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
use Org\Mxchange\CoreFramework\Iterator\BaseIterator;
+use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
use Org\Mxchange\CoreFramework\Registry\Register;
use Org\Mxchange\CoreFramework\Registry\Registerable;
-use Org\Mxchange\CoreFramework\Registry\Sub\SubRegistry;
+use Org\Mxchange\CoreFramework\Traits\Registry\RegisterTrait;
// Import SPL stuff
+use \BadMethodCallException;
use \LogicException;
+use \UnexpectedValueException;
/**
- * A Registry iterator
+ * A registry iterator
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class RegistryIterator extends BaseIterator implements IteratableRegistry {
+ // Load traits
+ use RegisterTrait;
+
/**
* All found registry keys
*/
private $registryKeys = [];
/**
- * Current array key
+ * An array containing keys ob sub-registries which keys should only be
+ * included in the iterator.
*/
- private $key = NULL;
+ private $onlyRegistries = [];
/**
- * Valid status (default: not valid)
+ * Current array key
*/
- private $valid = FALSE;
+ private $key = NULL;
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
+
+ // Init registry keys array
+ $this->registryKeys = [
+ // Generic registry
+ 'generic' => [],
+ // Instance registry
+ 'instance' => [],
+ ];
}
/**
*/
public final static function createRegistryIterator (Register $registryInstance) {
// Get new instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR: registryInstance=%s - CALLED!', $registryInstance->__toString()));
$iteratorInstance = new RegistryIterator();
// Set registry here
$iteratorInstance->setRegistryInstance($registryInstance);
// Return the prepared instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR: iteratorInstance=%s - EXIT!', $iteratorInstance->__toString()));
return $iteratorInstance;
}
+ /**
+ * Setter for only-registries array
+ *
+ * @param $onlyRegistries Array with keys only being iterated over
+ * @return void
+ */
+ private function setOnlyRegistries (array $onlyRegistries) {
+ $this->onlyRegistries = $onlyRegistries;
+ }
+
/**
* Initializes this iterator by scanning over the registry for all keys.
*
- * @param $callbackInstance An instance of a FrameworkInterface class to call back (optional)
- * @param $criteriaKey Criteria key (optional)
- * @param $criteriaMethod Method to call back (optional)
+ * @param $onlyRegistries Only iterate on these sub-registry keys, default is all
* @return void
* @throws LogicException If a registry entry does not implement Registerable
* @throws NullPointerException If criteriaKey or criteriaMethod is not set but a call-back instance is set
*/
- public function initIterator (FrameworkInterface $callbackInstance = NULL, $criteriaKey = NULL, $criteriaMethod = NULL) {
- // Is the call-back instance set?
- if ($callbackInstance instanceof FrameworkInterface) {
- // Then also criteria key and method name must be given
- if (is_null($criteriaKey)) {
- // Throw NPE
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } elseif (is_null($criteriaMethod)) {
- // Throw NPE
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- }
-
- // Set all
- $iteratorInstance->setCallbackInstance($callbackInstance);
- $iteratorInstance->setCriteriaKey($criteriaKey);
- } // END - if
+ public function initIterator (array $onlyRegistries = []) {
+ // Set it in this registry
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR: onlyRegistries()=%d - CALLED!', count($onlyRegistries)));
+ $this->setOnlyRegistries($onlyRegistries);
// Get generic registry entries from it
$entries = $this->getRegistryInstance()->getGenericRegistry();
- // Init registry keys array
- $this->registryKeys['generic'] = [];
-
// Anything in there?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR: entries()=%d', count($entries)));
if (count($entries) > 0) {
// Debugging:
- /* DEBUG-DIE: */ die(sprintf('[%s:%d]: entries=%s', __METHOD__, __LINE__, print_r($entries, TRUE)));
- } // END - if
+ /* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: UNFINISHED: entries=%s', __METHOD__, __LINE__, print_r($entries, TRUE)));
+ }
// Get instance registry entries from it
$entries = $this->getRegistryInstance()->getInstanceRegistry();
- // Init registry keys array
- $this->registryKeys['instance'] = [];
-
// Anything in there?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR: entries()=%d', count($entries)));
if (count($entries) > 0) {
// Then run over all
foreach ($entries as $key => $entry) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('REGISTRY-ITERATOR[instance]: key=%s,entry[]=%s', $key, gettype($entry)));
-
- // Is it 'socket_registry' ?
- if ($key == 'socket_registry') {
- // Skip this entry
+ // Is an unwanted registry found?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR: key=%s,entry[%s]=%s', $key, gettype($entry), $entry->__toString()));
+ if (substr($key, -8, 8) == 'registry') {
+ // Skip this!
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR: key=%s is a registry key, skipping ...', $key));
continue;
- } // END - if
+ }
// Is it an instance of a sub-registry?
- if ($entry instanceof SubRegistry) {
+ if (count($onlyRegistries) > 0 && !in_array($key, $onlyRegistries, TRUE)) {
+ // Not in requested registries
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR: key=%s is not wanted, skipping ...', $key));
+ continue;
+ } elseif ($entry instanceof ObjectRegistry) {
// Get iterator from this instance
- $iteratorInstance = $entry->getIterator();
-
- // Debugging:
- //* DEBUG-DIE: */ die(sprintf('[%s:%d]: key=%s,iteratorInstance=%s', __METHOD__, __LINE__, $key, print_r($iteratorInstance, TRUE)));
-
- // Get all keys
- $keys = $iteratorInstance->getRegistryKeys();
-
- // Should be there
- if (!isset($keys['instance'])) {
- // Should not happen
- throw new LogicException(sprintf('key=%s,keys[instance] is not set.', $key));
- } // END - if
+ $objectRegistryInstances = $entry->getInstanceRegistry();
// Add all sub-registry keys to this registry keys array
- $this->registryKeys['instance'][$key] = $keys['instance'];
-
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('REGISTRY-ITERATOR[instance]: key=%s,keys=%s', $key, print_r($this->registryKeys['instance'][$key], TRUE)));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR: objectRegistryInstances()=%d', count($objectRegistryInstances)));
+ //* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: key=%s,objectRegistryInstances=%s', __METHOD__, __LINE__, $key, print_r($objectRegistryInstances, TRUE)));
+ foreach (array_keys($objectRegistryInstances) as $subKey) {
+ // Add it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR: Adding key=%s,subKey=%s ...', $key, $subKey));
+ array_push($this->registryKeys['instance'], $subKey);
+
+ // Is the current key set?
+ if (is_null($this->key)) {
+ // Init key
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR: Setting this->key=%s as first key (subKey) ...', $subKey));
+ $this->key = $subKey;
+ }
+ }
// Skip below code
continue;
} elseif (!($entry instanceof Registerable)) {
// Not registerable?!
- throw new LogicException(sprintf('entry[]=%s does not implement Registerable.', gettype($entry)));
- } elseif (is_null($this->key)) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('REGISTRY-ITERATOR[instance]: Setting key=%s ...', $key));
+ throw new LogicException(sprintf('entry[]=%s does not implement Registerable.', gettype($entry)), FrameworkInterface::EXCEPTION_LOGIC_EXCEPTION);
+ }
- // Init key/valid
+ // Is the current key set?
+ if (is_null($this->key)) {
+ // Init key
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR: Setting this->key=%s as first key (key) ...', $key));
$this->key = $key;
- $this->valid = TRUE;
}
- // Debugging:
- //* DEBUG-DIE: */ die(sprintf('[%s:%d]: key=%s,entry=%s', __METHOD__, __LINE__, $key, print_r($entry, TRUE)));
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('REGISTRY-ITERATOR[instance]: key=%s,entry[]=%s - Adding ...', $key, gettype($entry)));
-
// Add key to array
- $this->registryKeys['instance'][$key] = [];
- } // END - foreach
- } // END - if
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR: key=%s - Adding ...', $key));
+ //* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: key=%s,entry=%s', __METHOD__, __LINE__, $key, print_r($entry, TRUE)));
+ array_push($this->registryKeys['instance'], $key);
+ }
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('REGISTRY-ITERATOR: EXIT!');
}
/**
* Getter for current value from group or generic
*
* @return $current Current value in iteration
+ * @throws NullPointerException If current key points to a non-existing entry in searched registries
*/
public function current () {
// Default is null
- $current = null;
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR[%s]: CALLED!', $this->key()));
+ //* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this->key(%d)[%s]=%s,this->valid=%d,this->registryKeys=%s', __METHOD__, __LINE__, strlen($this->key()), gettype($this->key()), $this->key(), intval($this->valid()), print_r($this->registryKeys, TRUE)));
+ $current = NULL;
+ $entries = [];
+
+ // Get all registries
+ $allRegistries = $this->getRegistryInstance()->getInstanceRegistry();
+
+ // Loop through all sub-sets
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: allRegistries()=%d', $this->key(), count($allRegistries)));
+ foreach ($allRegistries as $registryKey => $registryInstance) {
+ // Is this key wanted?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: registryKey=%s', $this->key(), $registryKey));
+ if (count($this->onlyRegistries) == 0 || in_array($registryKey, $this->onlyRegistries)) {
+ // Yes, then loop through them only
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: registryKey=%s,this->onlyRegistries()=%d', $this->key(), $registryKey, count($this->onlyRegistries)));
+ $instances = $registryInstance->getInstanceRegistry();
+
+ // The key should be there
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: Handling instances()=%d,registryKey=%s ...', $this->key(), count($instances), $registryKey));
+ if (!isset($instances[$this->key()])) {
+ // Not found
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->warningMessage(sprintf('REGISTRY-ITERATOR[%s]: registryKey=%s has no this->key=%s - CONTINUE!', $this->key(), $registryKey, $this->key()));
+ continue;
+ }
+
+ // Set as current
+ $current = $instances[$this->key()];
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: current=%s', $this->key(), $current->__toString()));
+ break;
+ }
+ }
- $this->partialStub('Please implement this method.');
+ // Is current still NULL?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: registryKey=%s,current[]=%s', $this->key(), $registryKey, gettype($current)));
+ if (is_null($current)) {
+ // This cannot happen and indicates a logic error
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
+ }
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR[%s]: current[%s]=%s - EXIT!', $this->key(), gettype($current), $current));
return $current;
}
*/
public function key () {
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR: this->key=%s EXIT!', $this->key));
return $this->key;
}
* Advances to the next entry
*
* @return void
+ * @throws BadMethodCallException If $this->valid() returns FALSE
+ * @throws UnexpectedValueException If $registryType is not changed
*/
public function next () {
- $this->partialStub('Please implement this method.');
+ // Is valid() still TRUE?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR[%s]: CALLED!', $this->key()));
+ //* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this->key(%d)[%s]=%s,this->valid=%d,this->registryKeys=%s', __METHOD__, __LINE__, strlen($this->key()), gettype($this->key()), $this->key(), intval($this->valid()), print_r($this->registryKeys, TRUE)));
+ if (!$this->valid()) {
+ // Bad method call!
+ throw new BadMethodCallException(sprintf('this->key[%s]=%s is no longer valid, but method was called.', gettype($this->key()), $this->key()), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ } elseif ((count($this->registryKeys['generic']) == 0) && (count($this->registryKeys['instance']) == 0)) {
+ // Both arrays are empty
+ throw new BadMethodCallException('No array elements in "generic" and "instance" found but method called.', FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
+
+ // Default is not valid
+ $nextIndex = -1;
+ $isNextValid = FALSE;
+ $registryType = 'invalid';
+
+ // Get first array element ...
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: this->registryKeys[generic]()=%d,this->registryKeys[instance]()=%d', $this->key(), count($this->registryKeys['generic']), count($this->registryKeys['instance'])));
+ if (count($this->registryKeys['generic']) > 0) {
+ // First generic array
+ /* UNFINISHED */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this->key(%d)[%s]=%s,this->valid=%d,this->registryKeys=%s', __METHOD__, __LINE__, strlen($this->key()), gettype($this->key()), $this->key(), intval($this->valid()), print_r($this->registryKeys, TRUE)));
+ } elseif (count($this->registryKeys['instance']) > 0) {
+ // Second instance, current key's index + 1
+ $nextIndex = array_search($this->key(), $this->registryKeys['instance']) + 1;
+ $isNextValid = isset($this->registryKeys['instance'][$nextIndex]);
+ $registryType = 'instance';
+ }
+
+ // Is it still valid?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: isNextValid=%d', $this->key(), intval($isNextValid)));
+ if (!$isNextValid) {
+ // Throw exception
+ throw new BadMethodCallException(sprintf('this->key=%s is last key in this iteration. Forgot to invoke valid() before?', $this->key()), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ } elseif ($registryType == 'invalid') {
+ // Not changed!
+ throw new UnexpectedValueException('registryType has not been changed.', FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
+
+ // Yes, then advance to that entry
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR: Setting this->key from this->registryKeys[%s][%d] ...', $registryType, $nextIndex));
+ $this->key = $this->registryKeys[$registryType][$nextIndex];
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR[%s]: EXIT!', $this->key()));
}
/**
* Rewinds to the beginning of the iteration
*
* @return void
+ * @throws BadMethodCallException If $this->key is already the first element
*/
public function rewind () {
- // Is the registry empty?
- if (count($this->registryKeys) == 0) {
- // Then no need to continue
- return;
- } // END - if
-
- // Debugging:
- /* DEBUG-DIE: */ die(sprintf('[%s:%d]: this->key(%d)[%s]=%s,this->valid=%d,this->registryKeys=%s', __METHOD__, __LINE__, strlen($this->key()), gettype($this->key()), $this->key(), intval($this->valid()), print_r($this->registryKeys, TRUE)));
+ // Is current key first key?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR[%s]: CALLED!', $this->key()));
+ //* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this->key(%d)[%s]=%s,this->valid=%d,this->registryKeys=%s', __METHOD__, __LINE__, strlen($this->key()), gettype($this->key()), $this->key(), intval($this->valid()), print_r($this->registryKeys, TRUE)));
+ if (array_search($this->key(), $this->getRegistryKeys()) === 0) {
+ // rewind() cannot rewind first entry!
+ throw new BadMethodCallException(sprintf('this->key=%s is already first element, but method was called.', $this->key()), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ } elseif ((count($this->registryKeys['generic']) == 0) && (count($this->registryKeys['instance']) == 0)) {
+ // Both arrays are empty
+ throw new BadMethodCallException('No array elements in "generic" and "instance" found but method called.', FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
+
+ // Get first array element ...
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('REGISTRY-ITERATOR[%s]: this->registryKeys[generic]()=%d,this->registryKeys[instance]()=%d', $this->key(), count($this->registryKeys['generic']), count($this->registryKeys['instance'])));
+ if (count($this->registryKeys['generic']) > 0) {
+ // First generic array
+ /* UNFINISHED */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this->key(%d)[%s]=%s,this->valid=%d,this->registryKeys=%s', __METHOD__, __LINE__, strlen($this->key()), gettype($this->key()), $this->key(), intval($this->valid()), print_r($this->registryKeys, TRUE)));
+ } elseif (count($this->registryKeys['instance']) > 0) {
+ // Second instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('REGISTRY-ITERATOR: Setting this->key from this->registryKeys[instance][0] ...');
+ $this->key = $this->registryKeys['instance'][0];
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR[%s]: EXIT!', $this->key()));
}
/**
* @return $valid Whether the current key is still valid
*/
public function valid () {
+ // Is the element there?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR[%s]: CALLED!', $this->key()));
+ //* DEBUG-DIE: */ ApplicationEntryPoint::exitApplication(sprintf('[%s:%d]: this->key(%d)[%s]=%s,this->registryKeys=%s', __METHOD__, __LINE__, strlen($this->key()), gettype($this->key()), $this->key(), print_r($this->registryKeys, TRUE)));
+ $valid = (in_array($this->key(), $this->registryKeys['instance']) || in_array($this->key(), $this->registryKeys['generic']));
+
// Return flag
- return $this->valid;
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('REGISTRY-ITERATOR[%s]: valid=%d - EXIT!', $this->key(), intval($valid)));
+ return $valid;
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
use Org\Mxchange\CoreFramework\ObjectArray\FrameworkArrayObject;
use Org\Mxchange\CoreFramework\Registry\Registerable;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
// Import SPL stuff
use \InvalidArgumentException;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @param $languageBasePath The local base path for all language strings or emty for auto-detection
* @return $langInstance An instance of LanguageSystem
* @throws InvalidArgumentException If languageBasePath remains empty (@TODO Get rid of that old-lost code)
- * @throws InvalidLanguagePathStringException If $languageBasePath is no string
- * @throws LanguagePathIsNoDirectoryException If $languageBasePath is no
+ * @throws InvalidArgumentException If $languageBasePath is no string
+ * @throws InvalidArgumentException If $languageBasePath is no
* directory or not found
- * @throws LanguagePathReadProtectedException If $languageBasePath is
+ * @throws InvalidArgumentException If $languageBasePath is
* read-protected
*/
- public static final function createLanguageSystem ($languageBasePath = '') {
+ public static final function createLanguageSystem (string $languageBasePath = '') {
// Get a new instance
$langInstance = new LanguageSystem();
if (empty($languageBasePath)) {
// No, then attempt "auto-dection":
// 1) Get application
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// 2) Try to build it
$languageBasePath = sprintf('%s%s/language/',
- $langInstance->getConfigInstance()->getConfigEntry('application_base_path'),
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path'),
$applicationInstance->getAppShortName()
);
- } // END - if
+ }
// Is the base path valid?
if (empty($languageBasePath)) {
// Language path is empty
- throw new InvalidArgumentException('languageBasePath is still empty');
- } elseif (!is_string($languageBasePath)) {
- // Is not a string
- throw new InvalidLanguagePathStringException(array($langInstance, $languageBasePath), self::EXCEPTION_INVALID_STRING);
+ throw new InvalidArgumentException('languageBasePath is still empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif (!is_dir($languageBasePath)) {
// Is not a path
- throw new LanguagePathIsNoDirectoryException(array($langInstance, $languageBasePath), self::EXCEPTION_INVALID_PATH_NAME);
+ throw new InvalidArgumentException(sprintf('languageBasePath=%s not found', $languageBasePath), self::EXCEPTION_INVALID_PATH_NAME);
} elseif (!is_readable($languageBasePath)) {
// Is not readable
- throw new LanguagePathReadProtectedException(array($langInstance, $languageBasePath), self::EXCEPTION_READ_PROTECED_PATH);
+ throw new InvalidArgumentException(sprintf('Cannot read from languageBasePath=%s', $languageBasePath), self::EXCEPTION_READ_PROTECED_PATH);
}
// Set the base path
* @param $languageBasePath The relative base path for all language files
* @return void
*/
- protected final function setLanguageBasePath ($languageBasePath) {
+ protected final function setLanguageBasePath (string $languageBasePath) {
// And set it
- $this->languageBasePath = (string) $languageBasePath;
+ $this->languageBasePath = $languageBasePath;
}
/**
* @param $langCode The language code for the current application
* @return void
*/
- protected final function setLanguageCode ($langCode) {
- // Cast it
- $langCode = (string) $langCode;
-
+ protected final function setLanguageCode (string $langCode) {
// And set it (only 2 chars)
$this->langCode = substr($langCode, 0, 2);
}
*
* Origin: StatusNet's lib/language.php
*/
- $localeCategories = array(
+ foreach ([
'LC_CTYPE',
'LC_NUMERIC',
'LC_TIME',
'LC_MONETARY',
'LC_MESSAGES',
'LC_ALL'
- );
-
- // Set all, if not defined
- foreach ($localeCategories as $key => $name) {
+ ] as $key => $name) {
// Is it set?
if (!defined($name)) {
// No, then set it
define($name, $key);
- } // END - if
- } // END - foreach
+ }
+ }
// Init language strings array
$this->langStrings = new FrameworkArrayObject('FakedLanguageStrings');
* @param $messageId The message id we shall find in the cache variable
* @return $messageText The plain message text
*/
- public function getMessage ($messageId) {
+ public function getMessage (string $messageId) {
// Default is missing message text
$messageText = sprintf('!%s!',
$messageId
if ($this->langStrings->offsetExists($messageId)) {
// Return the message string
$messageText = $this->langStrings->offsetGet($messageId);
- } // END - if
+ }
// Return the text
return $messageText;
<?php
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+
/**
* A ??? list
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @todo 0% done
*/
public function getListIterator () {
- $this->partialStub('Please implement this method.');
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this method.');
}
/**
* @todo 0% done
*/
public function clearList () {
- $this->partialStub('Please implement this method.');
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this method.');
}
}
namespace Org\Mxchange\CoreFramework\Lists;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+use Org\Mxchange\CoreFramework\Traits\Iterator\IteratorTrait;
use Org\Mxchange\CoreFramework\Visitor\Visitable;
// Import SPL stuff
+use \BadMethodCallException;
+use \InvalidArgumentException;
use \IteratorAggregate;
use \Countable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseList extends BaseFrameworkSystem implements IteratorAggregate, Countable {
+ // Load traits
+ use IteratorTrait;
+
// Exception constants
const EXCEPTION_GROUP_ALREADY_ADDED = 0xf20;
const EXCEPTION_GROUP_NOT_FOUND = 0xf21;
/**
* List groups array
*/
- private $listGroups = array();
+ private $listGroups = [];
/**
* List entries array
*/
- private $listEntries = array();
+ private $listEntries = [];
/**
* List index array
*/
- private $listIndex = array();
+ private $listIndex = [];
+
+ /**
+ * Cached values from "expensive" method calls
+ */
+ private $cache = [
+ // Cached isValidHash() calls
+ 'is_valid' => [],
+ ];
/**
* Protected constructor
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
// Is the instance set?
if (is_null($iteratorInstance)) {
// Prepare a default iterator
- $iteratorInstance = ObjectFactory::createObjectByConfiguredName('default_iterator_class', array($this));
+ $iteratorInstance = ObjectFactory::createObjectByConfiguredName('default_iterator_class', [$this]);
// Set it here
$this->setIteratorInstance($iteratorInstance);
- } // END - if
+ }
// And return it
return $iteratorInstance;
* @param $groupName Group to check if found in list
* @return $isset Whether the group is valid
*/
- public function isGroupSet ($groupName) {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName);
+ public function isGroupSet (string $groupName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-LIST: groupName=%s - CALLED!', $groupName));
+ if (empty($groupName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "groupName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Check on existence ...
return isset($this->listGroups[$groupName]);
}
/**
- * Adds the given group or if already added issues a ListGroupAlreadyAddedException
+ * Adds the given group or if already added issues a BadMethodCallException
*
* @param $groupName Group to add
* @return void
- * @throws ListGroupAlreadyAddedException If the given group is already added
+ * @throws BadMethodCallException If the given group is already added
*/
- public function addGroup ($groupName) {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ' - CALLED!');
- // Is the group already added?
- if ($this->isGroupSet($groupName)) {
+ public function addGroup (string $groupName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-LIST: groupName=%s - CALLED!', $groupName));
+ if (empty($groupName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "groupName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($this->isGroupSet($groupName)) {
// Throw the exception here
- throw new ListGroupAlreadyAddedException(array($this, $groupName), self::EXCEPTION_GROUP_ALREADY_ADDED);
- } // END - if
+ throw new BadMethodCallException(sprintf('groupName=%s is already set', $groupName), self::EXCEPTION_GROUP_ALREADY_ADDED);
+ }
// Add the group which is a simple array
$this->listGroups[$groupName] = ObjectFactory::createObjectByConfiguredName('list_group_class');
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ' - EXIT!');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: groupName=' . $groupName . ' - EXIT!');
}
/**
* @param $subGroup Sub group to add instance to
* @param $visitableInstance An instance of Visitable
* @return void
- * @throws NoListGroupException If the given group is not found
+ * @throws BadMethodCallException If the given group is not found
*/
- public function addInstance ($groupName, $subGroup, Visitable $visitableInstance) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ',subGroup=' . $subGroup . ',visitableInstance=' . $visitableInstance->__toString() . ' - CALLED!');
-
- // Is the group there?
- if (!$this->isGroupSet($groupName)) {
+ public function addInstance (string $groupName, string $subGroup, Visitable $visitableInstance) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: groupName=' . $groupName . ',subGroup=' . $subGroup . ',visitableInstance=' . $visitableInstance->__toString() . ' - CALLED!');
+ if (empty($groupName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "groupName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($subGroup)) {
+ // Throw it again
+ throw new InvalidArgumentException('Parameter "subGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isGroupSet($groupName)) {
// Throw the exception here
- throw new NoListGroupException(array($this, $groupName), self::EXCEPTION_GROUP_NOT_FOUND);
- } // END - if
+ throw new BadMethodCallException(sprintf('groupName=%s is not a valid group', $groupName), self::EXCEPTION_GROUP_NOT_FOUND);
+ }
// Is the sub group there?
if (!$this->listGroups[$groupName]->isGroupSet($subGroup)) {
// Automatically add it
$this->listGroups[$groupName]->addGroup($subGroup);
- } // END - if
+ }
// Generate the hash
$hash = $this->generateHash($groupName, $subGroup, $visitableInstance);
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',this->listGroups[' . $groupName . ']=' . $this->listGroups[$groupName]->__toString());
-
// Add the hash to the index
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: this->listGroups[' . $groupName . ']=' . $this->listGroups[$groupName]->__toString());
array_push($this->listIndex, $hash);
// Add the instance itself to the list
$this->listEntries[$hash] = $visitableInstance;
// Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ',subGroup=' . $subGroup . ' - EXIT!');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: groupName=' . $groupName . ',subGroup=' . $subGroup . ' - EXIT!');
}
/**
* Gets an array from given list
*
- * @param $list The requested list
+ * @param $groupName The requested list
* @return $array The requested array
- * @throws NoListGroupException If the given group is not found
+ * @throws BadMethodCallException If the given group is not found
*/
- public final function getArrayFromList ($list) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',list[' . gettype($list) . ']=' . $list . ' - CALLED!');
-
+ public final function getArrayFromList (string $groupName) {
// Is the group there?
- if ((!is_null($list)) && (!$this->isGroupSet($list))) {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: groupName[' . gettype($groupName) . ']=' . $groupName . ' - CALLED!');
+ if (empty($groupName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "groupName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isGroupSet($groupName)) {
// Throw the exception here
- throw new NoListGroupException(array($this, $list), self::EXCEPTION_GROUP_NOT_FOUND);
- } // END - if
+ throw new BadMethodCallException(sprintf('groupName=%s is not a valid group', $groupName), self::EXCEPTION_GROUP_NOT_FOUND);
+ }
// Init array
- $array = array();
+ $array = [];
// Is there another list?
- if (!is_null($list)) {
+ if ($this->listGroups[$groupName]->isGroupSet($groupName)) {
// Then get it as well
- $array = $this->listGroups[$list]->getArrayFromList(NULL);
- } // END - if
+ //* DEBUG-DIE: */ die(sprintf('[%s:%d]: groupName=%s,this=%s', __METHOD__, __LINE__, $groupName, print_r($this, TRUE)));
+ $array = $this->listGroups[$groupName]->getArrayFromList($groupName);
+ }
// Walk through all entries
foreach ($this->listIndex as $hash) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: hash=' . $hash);
-
// Is the list entry set?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: hash=' . $hash);
if ($this->isHashValid($hash)) {
// Add it
array_push($array, $this->listEntries[$hash]);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: hash=' . $hash . ',array(' . count($array) . ')=' . print_r($array, true) . ' - ADDED!');
- } // END - if
- } // END - foreach
-
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',list[' . gettype($list) . ']=' . $list . ',array()=' . count($array) . ' - EXIT!');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: hash=' . $hash . ',array(' . count($array) . ')=' . print_r($array, true) . ' - ADDED!');
+ }
+ }
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: groupName[' . gettype($groupName) . ']=' . $groupName . ',[]=' . count($array) . ' - EXIT!');
return $array;
}
* @param $groupName Group to add instance to
* @param $entry An entry of any type
* @return void
- * @throws NoListGroupException If the given group is not found
+ * @throws BadMethodCallException If the given group is not found
*/
- public function addEntry ($groupName, $entry) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ' - CALLED!');
-
+ public function addEntry (string $groupName, $entry) {
// Is the group already added?
- if (!$this->isGroupSet($groupName)) {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: groupName=' . $groupName . ' - CALLED!');
+ if (empty($groupName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "groupName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isGroupSet($groupName)) {
// Throw the exception here
- throw new NoListGroupException(array($this, $groupName), self::EXCEPTION_GROUP_NOT_FOUND);
- } // END - if
+ throw new BadMethodCallException(sprintf('groupName=%s is not a valid group', $groupName), self::EXCEPTION_GROUP_NOT_FOUND);
+ }
// Generate hash
$hash = $this->generateHash($groupName, $groupName, $entry);
// Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ',entry=' . print_r($entry, true) . ', hash=' . $hash);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: groupName=' . $groupName . ',entry=' . print_r($entry, true) . ', hash=' . $hash);
// Add the hash to the index
array_push($this->listIndex, $hash);
// Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ',listEntries()=' . count($this->listEntries));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: groupName=' . $groupName . ',listEntries()=' . count($this->listEntries));
// Now add the entry to the list
$this->listEntries[$hash] = $entry;
// Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ',listEntries()=' . count($this->listEntries) . ' - EXIT!');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: groupName=' . $groupName . ',listEntries()=' . count($this->listEntries) . ' - EXIT!');
}
/**
* @param $groupName Group where we should remove the entry from
* @param $entry The entry we should remove
* @return void
- * @throws NoListGroupException If the given group is not found
+ * @throws BadMethodCallException If the given group is not found
*/
- public function removeEntry ($groupName, $entry) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ' - CALLED!');
-
+ public function removeEntry (string $groupName, $entry) {
// Is the group already added?
- if (!$this->isGroupSet($groupName)) {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: groupName=' . $groupName . ' - CALLED!');
+ if (empty($groupName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "groupName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isGroupSet($groupName)) {
// Throw the exception here
- throw new NoListGroupException(array($this, $groupName), self::EXCEPTION_GROUP_NOT_FOUND);
- } // END - if
+ throw new BadMethodCallException(sprintf('groupName=%s is not a valid group', $groupName), self::EXCEPTION_GROUP_NOT_FOUND);
+ }
// Generate hash
$hash = $this->generateHash($groupName, $groupName, $entry);
// Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ',entry=' . $entry . ', hash=' . $hash);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: groupName=' . $groupName . ',entry=' . $entry . ', hash=' . $hash);
// Remove it from the list ...
unset($this->listEntries[$hash]);
unset($this->listIndex[array_search($hash, $this->listIndex)]);
// Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: this=' . $this->__toString() . ',groupName=' . $groupName . ' - EXIT!');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: groupName=' . $groupName . ' - EXIT!');
}
/**
* @param $entry An entry of any type
* @return $hash The generated
*/
- private function generateHash ($groupName, $subGroup, $entry) {
+ private function generateHash (string $groupName, string $subGroup, $entry) {
// Created entry, 'null' is default
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: groupName=' . $groupName . ',subGroup=' . $subGroup . ',entry[]=' . gettype($entry) . ' - CALLED!');
$entry2 = 'null';
// Determine type of entry
$entry2 = $this->getCallbackInstance()->generateListHashFromEntry($entry);
} else {
// Unsupported type detected
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST[' . __METHOD__ . ':' . __LINE__ . ']: Entry type ' . gettype($entry) . ' is unsupported (this->callbackInstance=' . $this->getCallbackInstance() . ').');
+ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: Entry type ' . gettype($entry) . ' is unsupported (this->callbackInstance=' . $this->getCallbackInstance() . ').');
// At least take all keys from array
$entry2 = gettype($entry) . ':' . implode(':', array_keys($entry));
}
// Construct string which we shall hash
- $hashString = $groupName . ':' . $subGroup . ':' . $entry2;
+ $hashString = sprintf('%s:%s:%s', $groupName, $subGroup, $entry2);
// Hash it with fastest hasher
$hash = crc32($hashString);
// And return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-LIST: hash=%s - EXIT!', $hash));
return $hash;
}
foreach ($groupNames as $groupName) {
// Clear this group
$this->clearGroup($groupName);
- } // END - foreach
+ }
}
/**
* @param $groupName Name of an existing group to clear
* @return void
*/
- protected function clearGroup ($groupName) {
+ protected function clearGroup (string $groupName) {
// Does this group exist?
- if (!$this->isGroupSet($groupName)) {
+ if (empty($groupName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "groupName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isGroupSet($groupName)) {
// Throw the exception here
- throw new NoListGroupException(array($this, $groupName), self::EXCEPTION_GROUP_NOT_FOUND);
- } // END - if
+ throw new BadMethodCallException(sprintf('groupName=%s is not a valid group', $groupName), self::EXCEPTION_GROUP_NOT_FOUND);
+ }
// Then clear this group list
$this->listGroups[$groupName]->clearList();
// Clear this list
- $this->listIndex = array();
- $this->listEntries = array();
+ $this->listIndex = [];
+ $this->listEntries = [];
}
/**
* @param $hash The hash we should validate
* @return $isValid Whether the given hash is valid
*/
- public final function isHashValid ($hash) {
- // Check it
- $isValid = ((in_array($hash, $this->listIndex)) && (isset($this->listEntries[$hash])));
+ public final function isHashValid (string $hash) {
+ // Validate parameter
+ if (empty($hash)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "hash" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!isset($this->cache['is_valid'][$hash])) {
+ // Check it
+ $this->cache['is_valid'][$hash] = ((in_array($hash, $this->listIndex)) && (isset($this->listEntries[$hash])));
+ }
// Return the result
- return $isValid;
+ return $this->cache['is_valid'][$hash];
}
/**
* @param $hashIndex Index holding the hash
* @return $hash The hash
*/
- public final function getHash ($hashIndex) {
+ public final function getHashByIndex (int $hashIndex) {
// Get it ...
$hash = $this->listIndex[$hashIndex];
* @return $entry Solved entry from list
* @throws InvalidListHashException If the solved hash index is invalid
*/
- public function getEntry ($hashIndex) {
+ public function getEntryByIndex (int $hashIndex) {
// Get the hash value
- $hash = $this->getHash($hashIndex);
+ $hash = $this->getHashByIndex($hashIndex);
// Is the hash valid?
if (!$this->isHashValid($hash)) {
// Throw an exception here
throw new InvalidListHashException(array($this, $hash, $hashIndex), self::EXCEPTION_INVALID_HASH);
- } // END - if
+ }
// Now copy the entry
$entry = $this->listEntries[$hash];
*
* @param $groupName The group name to get a list for
* @return $entries The array with all entries
- * @throws NoListGroupException If the specified group is invalid
+ * @throws BadMethodCallException If the specified group is invalid
*/
- public function getArrayFromProtocolInstance ($groupName) {
+ public function getArrayFromProtocolInstance (string $groupName) {
// Is the group valid?
- if (!$this->isGroupSet($groupName)) {
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-LIST: groupName=%s - CALLED!', $groupName));
+ if (empty($groupName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "groupName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isGroupSet($groupName)) {
// Throw the exception here
- throw new NoListGroupException(array($this, $groupName), self::EXCEPTION_GROUP_NOT_FOUND);
- } // END - if
+ throw new BadMethodCallException(sprintf('groupName=%s is not a valid group', $groupName), self::EXCEPTION_GROUP_NOT_FOUND);
+ }
// Init the entries' array
- $entries = array();
+ $entries = [];
// Get an iterator
$iteratorInstance = $this->listGroups[$groupName]->getIterator();
$entryIndex = $iteratorInstance->key();
// ... and the final entry which is the stored instance
- $entry = $this->getEntry($entryIndex);
-
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('LIST: Adding entry ' . $entry . ' ...');
+ $entry = $this->getEntryByIndex($entryIndex);
// Add it to the list
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-LIST: Adding entry ' . $entry . ' ...');
$entries[$iteratorInstance->current()] = $entry;
// Skip to next one
$iteratorInstance->next();
- } // END - while
+ }
// Return the list
return $entries;
* @return void
* @throws InvalidListHashException If the solved hash index is invalid
*/
- public function updateCurrentEntryByHash ($hash, array $entryArray) {
+ public function updateCurrentEntryByHash (string $hash, array $entryArray) {
// Is the hash valid?
- if (!$this->isHashValid($hash)) {
+ if (empty($hash)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "hash" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isHashValid($hash)) {
// Throw an exception here, hashIndex is unknown at this point
throw new InvalidListHashException(array($this, $hash, -999), self::EXCEPTION_INVALID_HASH);
- } // END - if
+ }
// Set the entry
$this->listEntries[$hash] = $entryArray;
// Import framework stuff
use Org\Mxchange\CoreFramework\Lists\BaseList;
use Org\Mxchange\CoreFramework\Lists\Listable;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
/**
* A ListGroup list
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @todo 0% done
*/
public function clearList () {
- $this->partialStub('Please implement this method.');
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this method.');
}
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
<?php
// Own namespace
-namespace CoreFramework\Mailer\!!!;
+namespace Org\Mxchange\CoreFramework\Mailer\!!!;
// Import framwork stuff
use Org\Mxchange\CoreFramework\Mailer\BaseMailer;
use Org\Mxchange\CoreFramework\Mailer\DeliverableMail;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
/**
* A ??? mailer class
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @todo 0% done
*/
public function deliverEmail() {
- $this->partialStub("You have to implement this method.");
+ DebugMiddleware::getSelfInstance()->partialStub("You have to implement this method.");
}
/**
* @todo 0% done
*/
public function sendAdminNotification() {
- $this->partialStub("You have to implement this method.");
+ DebugMiddleware::getSelfInstance()->partialStub("You have to implement this method.");
}
}
namespace Org\Mxchange\CoreFramework\Mailer;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Manager\Login\ManageableMember;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+use Org\Mxchange\CoreFramework\Traits\Template\CompileableTemplateTrait;
/**
* A general mailer class for all other mailers
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseMailer extends BaseFrameworkSystem {
+ // Load traits
+ use CompileableTemplateTrait;
+
/**
* Template name
*/
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
* @param $templateName Name of the template we shall load
* @return void
*/
- protected final function loadTemplate ($templateName) {
+ protected final function loadTemplate (string $templateName) {
// Set template name
$this->setTemplateName($templateName);
// Get configuration entry
- $templatePrefix = $this->getConfigInstance()->getConfigEntry('email_tpl_' . $templateName);
+ $templatePrefix = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('email_tpl_' . $templateName);
// Load this email template
$this->getTemplateInstance()->loadEmailTemplate($templatePrefix . '_' . $templateName);
* @param $valueInstance An object instance which can provide "field values"
* @return void
*/
- public final function addValueInstance ($variableName, FrameworkInterface $valueInstance) {
+ public final function addValueInstance (string $variableName, FrameworkInterface $valueInstance) {
$this->setGenericArrayElement('recipients', $this->getTemplateName(), 'values', $variableName, $valueInstance);
}
* @param $templateName Name of email template
* @return void
*/
- public final function setTemplateName ($templateName) {
- $this->templateName = (string) $templateName;
+ public final function setTemplateName (string $templateName) {
+ $this->templateName = $templateName;
}
/**
* @param $subjectLine Subject line to set
* @return void
*/
- public final function setSubjectLine ($subjectLine) {
+ public final function setSubjectLine (string $subjectLine) {
$this->setGenericArrayElement('recipients', $this->getTemplateName(), 'generic', 'subject', $subjectLine);
}
if ((!empty($templateName)) && ($this->isGenericArrayElementSet('recipients', $templateName, 'generic', 'subject'))) {
// Then use it
$subjectLine = $this->getGenericArrayElement('recipients', $templateName, 'generic', 'subject');
- } // END - if
+ }
// Return it
return $subjectLine;
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Mailer\BaseMailer;
use Org\Mxchange\CoreFramework\Mailer\DeliverableMail;
use Org\Mxchange\CoreFramework\Manager\Login\ManageableMember;
use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
+// Import SPL stuff
+use \UnexpectedValueException;
+
/**
* A mailer class for debugging purposes only. This class will print the
* prepared mail out and will not send it to the recipient.
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @param $templateName Name of email template to set
* @return $mailerInstance An instance of this mailer class
*/
- public static final function createDebugMailer (CompileableTemplate $templateInstance, $templateName) {
+ public static final function createDebugMailer (CompileableTemplate $templateInstance, string $templateName) {
// Get a new instance
$mailerInstance = new DebugMailer();
* Deliver email to the recipient(s)
*
* @return void
- * @throws InvalidInterfaceException If the recipient instance does not implement ManageableMember
+ * @throws UnexpectedValueException If the recipient instance does not implement ManageableMember
*/
public function deliverEmail () {
// Get template instance
// The recipient should be a user instance, right?
if (!$recipientInstance instanceof ManageableMember) {
// Invalid entry found!
- throw new InvalidInterfaceException(array($this, 'ManageableMember'), self::EXCEPTION_REQUIRED_INTERFACE_MISSING);
- } // END - if
+ throw new UnexpectedValueException(sprintf('recipientInstance[]=%s does not implement ManageableMember', gettype($recipientInstance)), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// User class found, so entry is valid, first load the template
$this->loadTemplate($templateName);
foreach ($recipientList['config_vars'] as $variable => $dummy) {
// Load the config value and set it
$templateInstance->assignConfigVariable($variable);
- } // END - if
+ }
// Now do the same with the values but ask the "value instance" instead!
foreach ($recipientList['value_vars'] as $variable => $dummy) {
// Is the value instance there?
if (!isset($recipientList['values'][$variable])) {
// Throw exception
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } // END - if
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
+ }
// Get the field from the value instance
$fieldValue = $recipientList['values'][$variable]->getField($variable);
// Transfer the data to the response
$templateInstance->transferToResponse($responseInstance);
- } // END - foreach
- } // END - foreach
+ }
+ }
}
/**
$templateInstance->assignTemplateWithVariable('footer', 'footer');
// Get master template name
- $masterTemplateName = GenericRegistry::getRegistry()->getInstance('application')->buildMasterTemplateName();
+ $masterTemplateName = ApplicationHelper::getSelfInstance()->buildMasterTemplateName();
// Load the master template
$templateInstance->loadCodeTemplate($masterTemplateName);
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
+use Org\Mxchange\CoreFramework\Traits\Template\CompileableTemplateTrait;
/**
* A general menu system class
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseMenu extends BaseFrameworkSystem {
+ // Load traits
+ use CompileableTemplateTrait;
+
/**
* Protected constructor
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
*/
public function renderMenu () {
// Initialize the menu system by preparing it's template instance
- $templateInstance = ObjectFactory::createObjectByConfiguredName('menu_template_class', array($this));
+ $templateInstance = ObjectFactory::createObjectByConfiguredName('menu_template_class', [$this]);
// Set it for later use
$this->setTemplateInstance($templateInstance);
// If page is empty, choose default
if (empty($command)) {
// Use default page as none has been specified
- $command = $this->getConfigInstance()->getConfigEntry('default_' . GenericRegistry::getRegistry()->getInstance('application')->getAppShortName() . '_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_command');
- } // END - if
+ $command = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('default_' . ApplicationHelper::getSelfInstance()->getAppShortName() . '_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_command');
+ }
// Load the menu template for this page
try {
$templateInstance->loadMenuTemplate($command . '_menu_entries');
} catch (FileNotFoundException $e) {
// Log exception @TODO Maybe to intrusive?
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: Exception caught: ' . $e->__toString() . ', with message: ' . $e->getMessage());
+ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-MENU: Exception caught: ' . $e->__toString() . ', with message: ' . $e->getMessage());
}
// Render template data here
<?php
// Own namespace
-namespace CoreFramework\Output\;
+namespace Org\Mxchange\CoreFramework\Output\;
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
/**
* A ??? output class
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
self::$!!!Instance = new WebOutput();
// Get the content type
- $contentType = self::$!!!Instance->getConfigInstance()->getConfigEntry('!!!_content_type');
+ $contentType = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('!!!_content_type');
// Set the content type
if (!empty($contentType)) {
// Set the header
FrameworkBootstrap::getResponseInstance()->addHeader('Content-type', $contentType);
- } // END - if
- } // END - if
+ }
+ }
// Return instance
return self::$!!!Instance;
* @todo 0% done
*/
public final function output ($outStream = false, $stripTags = false) {
- $this->partialStub('Please implement this method. outStream()=' . strlen($outStream) . ',stripTags=' . intval($stripTags));
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this method. outStream()=' . strlen($outStream) . ',stripTags=' . intval($stripTags));
}
/**
* @throws UnsupportedOperationException If this method is called
*/
public function seek ($offset, $whence = SEEK_SET) {
- self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] offset=' . $offset . ',whence=' . $whence);
+ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('OUTPUT: offset=' . $offset . ',whence=' . $whence);
throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @param $contentType A valid content-type
* @return $debugInstance An instance of this middleware class
*/
- public static final function createConsoleOutput ($contentType) {
+ public static final function createConsoleOutput (string $contentType) {
// Cast the content-type to string
- $contentType = (string) $contentType;
$contentType = trim($contentType);
// Get instance
@header(sprintf('Content-type: %s',
$contentType
));
- } // END - if
+ }
// Return instance
return self::$consoleInstance;
if (is_null(self::$consoleInstance)) {
$contentType = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('web_content_type');
self::$consoleInstance = ConsoleOutput::createConsoleOutput($contentType);
- } // END - if
+ }
// Return the instance
return self::$consoleInstance;
* @param $stripTags Whether HTML tags shall be stripped out
* @return void
*/
- public final function output ($outStream = false, $stripTags = false) {
+ public final function output (string $outStream = '', bool $stripTags = false) {
print trim($outStream) . PHP_EOL;
}
- /**
- * Determines seek position
- *
- * @return $seekPosition Current seek position
- * @throws UnsupportedOperationException If this method is called
- */
- public function determineSeekPosition () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Seek to given offset (default) or other possibilities as fseek() gives.
- *
- * @param $offset Offset to seek to (or used as "base" for other seeks)
- * @param $whence Added to offset (default: only use offset to seek to)
- * @return $status Status of file seek: 0 = success, -1 = failed
- * @throws UnsupportedOperationException If this method is called
- */
- public function seek ($offset, $whence = SEEK_SET) {
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] offset=' . $offset . ',whence=' . $whence);
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Size of file stack
- *
- * @return $size Size (in bytes) of file
- * @throws UnsupportedOperationException If this method is called
- */
- public function size () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
* @param $loggerClassName Class name this output class is being used for logging
* @return void
*/
- public final function setLoggerClassName ($loggerClassName) {
+ public final function setLoggerClassName (string $loggerClassName) {
$this->loggerClassName = $loggerClassName;
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Debug\Debugger;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
use Org\Mxchange\CoreFramework\Output\Debug\BaseDebugOutput;
use Org\Mxchange\CoreFramework\Registry\Registerable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class DebugConsoleOutput extends BaseDebugOutput implements Debugger, OutputStreamer, Registerable {
+ /**
+ * Cached configuration entry 'debug_*_output_timings'
+ */
+ private $isDebugOutputTimingsEnabled = FALSE;
+
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
- // Call parent constructor
+ private function __construct () {
+ // Call parent constructor first
parent::__construct(__CLASS__);
+
+ // Cache configuration entry
+ $this->isDebugOutputTimingsEnabled = FrameworkBootstrap::getConfigurationInstance()->isEnabled('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings');
}
/**
* @param $stripTags Whether HTML tags shall be stripped out
* @return void
*/
- public final function outputStream ($output, $stripTags = false) {
+ public final function outputStream (string $output, bool $stripTags = false) {
// Strip HTML tags out?
if ($stripTags === true) {
// Prepare the output without HTML tags
$output = trim(html_entity_decode(strip_tags(stripslashes($output))));
- } // END - if
+ }
// Are debug times enabled?
- if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
+ if ($this->isDebugOutputTimingsEnabled) {
// Output it first
$output = $this->getPrintableExecutionTime() . $output;
- } // END - if
+ }
// And print it out...
printf('%s%s', str_replace('->', '->', $output), PHP_EOL);
* @param $stripTags Whether HTML tags shall be stripped out
* @return void
*/
- public final function output ($outStream = false, $stripTags = false) {
+ public final function output (string $outStream = '', bool $stripTags = false) {
// Empty output will be silently ignored
- if ($outStream !== false) {
+ if (!empty($outStream)) {
$this->outputStream($outStream, $stripTags);
- } // END - if
+ }
}
/**
* @return $data The data (string mostly) to "stream"
* @throws UnsupportedOperationException If this method is called
*/
- public function streamData ($data) {
+ public function streamData (string $data) {
self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Determines seek position
- *
- * @return $seekPosition Current seek position
- * @throws UnsupportedOperationException If this method is called
- */
- public function determineSeekPosition () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Seek to given offset (default) or other possibilities as fseek() gives.
- *
- * @param $offset Offset to seek to (or used as "base" for other seeks)
- * @param $whence Added to offset (default: only use offset to seek to)
- * @return $status Status of file seek: 0 = success, -1 = failed
- * @throws UnsupportedOperationException If this method is called
- */
- public function seek ($offset, $whence = SEEK_SET) {
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] offset=' . $offset . ',whence=' . $whence);
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Size of file stack
- *
- * @return $size Size (in bytes) of file
- * @throws UnsupportedOperationException If this method is called
- */
- public function size () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Debug\Debugger;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
use Org\Mxchange\CoreFramework\Output\Debug\BaseDebugOutput;
use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @param $stripTags Whether HTML tags shall be stripped out
* @return void
*/
- public final function outputStream ($output, $stripTags = false) {
+ public final function outputStream (string $output, bool $stripTags = false) {
// Split multiple lines into and array to put them out line-by-line
$errorLines = explode(chr(10), $output);
if (!empty($err)) {
// Log this line
error_log(html_entity_decode(strip_tags($err)), 0);
- } // END - if
- } // END - foreach
+ }
+ }
}
/**
* @param $stripTags Whether HTML tags shall be stripped out
* @return void
*/
- public final function output ($outStream = false, $stripTags = false) {
+ public final function output (string $outStream = '', bool $stripTags = false) {
// Empty output will be silently ignored
- if ($outStream !== false) {
+ if (!empty($outStream)) {
$this->outputStream($outStream);
- } // END - if
+ }
}
/**
* @return $data The data (string mostly) to "stream"
* @throws UnsupportedOperationException If this method is called
*/
- public function streamData ($data) {
+ public function streamData (string $data) {
self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Determines for seek position
- *
- * @return $seekPosition Current seek position
- * @throws UnsupportedOperationException If this method is called
- */
- public function determineSeekPosition () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Seek to given offset (default) or other possibilities as fseek() gives.
- *
- * @param $offset Offset to seek to (or used as "base" for other seeks)
- * @param $whence Added to offset (default: only use offset to seek to)
- * @return $status Status of file seek: 0 = success, -1 = failed
- * @throws UnsupportedOperationException If this method is called
- */
- public function seek ($offset, $whence = SEEK_SET) {
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] offset=' . $offset . ',whence=' . $whence);
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Size of file stack
- *
- * @return $size Size (in bytes) of file
- * @throws UnsupportedOperationException If this method is called
- */
- public function size () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Debug\Debugger;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
use Org\Mxchange\CoreFramework\Output\Debug\BaseDebugOutput;
use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @param $stripTags Whether HTML tags shall be stripped out
* @return void
*/
- public final function outputStream ($output, $stripTags = false) {
+ public final function outputStream (string $output, bool $stripTags = false) {
// Strip out any <br />
$output = str_replace('<br />', '', $output);
printf('<!-- %s -->' . PHP_EOL, stripslashes($output));
* @param $stripTags Whether HTML tags shall be stripped out
* @return void
*/
- public final function output ($outStream = false, $stripTags = false) {
+ public final function output (string $outStream = '', bool $stripTags = false) {
// Empty output will be silently ignored
- if ($outStream !== false) {
+ if (!empty($outStream)) {
$this->outputStream($outStream, $stripTags);
- } // END - if
+ }
}
/**
* @return $data The data (string mostly) to "stream"
* @throws UnsupportedOperationException If this method is called
*/
- public function streamData ($data) {
+ public function streamData (string $data) {
self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Determines seek position
- *
- * @return $seekPosition Current seek position
- * @throws UnsupportedOperationException If this method is called
- */
- public function determineSeekPosition () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Seek to given offset (default) or other possibilities as fseek() gives.
- *
- * @param $offset Offset to seek to (or used as "base" for other seeks)
- * @param $whence Added to offset (default: only use offset to seek to)
- * @return $status Status of file seek: 0 = success, -1 = failed
- * @throws UnsupportedOperationException If this method is called
- */
- public function seek ($offset, $whence = SEEK_SET) {
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] offset=' . $offset . ',whence=' . $whence);
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Size of file stack
- *
- * @return $size Size (in bytes) of file
- * @throws UnsupportedOperationException If this method is called
- */
- public function size () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
-use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
use Org\Mxchange\CoreFramework\Output\BaseOutput;
use Org\Mxchange\CoreFramework\Registry\Registerable;
use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
/**
* Create a new web output system and set the content type
*
- * @param $applicationInstance An instance of a ManageableApplication class
- * @return $debugInstance An instance of this middleware class
+ * @return $webInstance An instance of an OutputStreamer class
*/
- public static final function createWebOutput (ManageableApplication $applicationInstance) {
+ public static final function createWebOutput () {
// Is the self-instance already set?
if (is_null(self::$webInstance)) {
// Get a new instance and set it
self::$webInstance = new WebOutput();
// Get the content type
- $contentType = self::$webInstance->getConfigInstance()->getConfigEntry('web_content_type');
+ $contentType = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('web_content_type');
// Set the content type
if (!empty($contentType)) {
// Set the header
FrameworkBootstrap::getResponseInstance()->addHeader('Content-type', $contentType);
- } // END - if
- } // END - if
+ }
+ }
// Return instance
return self::$webInstance;
* @param $stripTags Whether HTML tags shall be stripped out
* @return void
*/
- public final function output ($outStream = false, $stripTags = false) {
+ public final function output (string $outStream = '', bool $stripTags = false) {
print(stripslashes($outStream));
}
- /**
- * Determines seek position
- *
- * @return $seekPosition Current seek position
- * @throws UnsupportedOperationException If this method is called
- */
- public function determineSeekPosition () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Seek to given offset (default) or other possibilities as fseek() gives.
- *
- * @param $offset Offset to seek to (or used as "base" for other seeks)
- * @param $whence Added to offset (default: only use offset to seek to)
- * @return $status Status of file seek: 0 = success, -1 = failed
- * @throws UnsupportedOperationException If this method is called
- */
- public function seek ($offset, $whence = SEEK_SET) {
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] offset=' . $offset . ',whence=' . $whence);
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Size of file stack
- *
- * @return $size Size (in bytes) of file
- * @throws UnsupportedOperationException If this method is called
- */
- public function size () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+use Org\Mxchange\CoreFramework\Traits\Template\CompileableTemplateTrait;
/**
* A general Parser
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseParser extends BaseFrameworkSystem {
+ // Load traits
+ use CompileableTemplateTrait;
+
/**
* Protected constructor
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
namespace Org\Mxchange\CoreFramework\Parser\Xml;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
use Org\Mxchange\CoreFramework\Parser\BaseParser;
use Org\Mxchange\CoreFramework\Parser\Parseable;
use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
+// Import SPL stuff
+use \InvalidArgumentException;
+
/**
* A Xml Parser class
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class XmlParser extends BaseParser implements Parseable {
- // Exception constants
- const EXCEPTION_XML_PARSER_ERROR = 0x1e0;
- const EXCEPTION_XML_NODE_UNKNOWN = 0x1e1;
- const EXCEPTION_XML_NODE_MISMATCH = 0x1e2;
-
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @return void
* @throws XmlParserException If an XML error was found
*/
- public function parseXmlContent ($content) {
+ public function parseXmlContent (string $content) {
// Convert all to UTF8
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('XML-PARSER: content()=%d - CALLED!', strlen($content)));
if (empty($content)) {
- // No empty content!
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Empty content! Backtrace: <pre>');
- debug_print_backtrace();
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('</pre>');
- exit();
+ // No empty content
+ throw new InvalidArgumentException('content is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif (function_exists('recode')) {
// Recode found, so use it
$content = recode('html..utf8', $content);
$content = mb_convert_encoding($content, 'UTF-8', 'auto');
} else {
// @TODO We need to find a fallback solution here
- $this->partialStub('Cannot find recode/mbstring extension!');
- } // END - if
+ DebugMiddleware::getSelfInstance()->partialStub('Cannot find recode/mbstring extension!');
+ }
// Get an XML parser
$xmlParser = xml_parser_create();
// Force case-folding to on
- xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, true);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('XML-PARSER: Created xmlParser=%s ...', $xmlParser));
+ xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, TRUE);
// Set UTF-8
xml_parser_set_option($xmlParser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
- // Get instance (we need this :( )
- $templateInstance = $this->getTemplateInstance();
-
// Set object
- xml_set_object($xmlParser, $templateInstance);
+ xml_set_object($xmlParser, $this->getTemplateInstance());
// Set handler call-backs
xml_set_element_handler($xmlParser, 'startElement', 'finishElement');
xml_set_character_data_handler($xmlParser, 'characterHandler');
// Now parse the XML tree
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('XML-PARSER: Invoking xml_parse(%s, content()=%d) ...', $xmlParser, strlen($content)));
if (!xml_parse($xmlParser, $content)) {
- // Error found in XML!
+ // Error found in XML
//* DEBUG: */ exit(__METHOD__ . ':<pre>'.htmlentities($content).'</pre>');
- throw new XmlParserException(array($this, $xmlParser), self::EXCEPTION_XML_PARSER_ERROR);
- } // END - if
+ throw new XmlParserException([$this, $xmlParser], Parseable::EXCEPTION_XML_PARSER_ERROR);
+ }
// Free the parser
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('XML-PARSER: Freeing xmlParser=%s ...', $xmlParser));
xml_parser_free($xmlParser);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('XML-PARSER: EXIT!');
}
}
namespace Org\Mxchange\CoreFramework\User\Points;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
-use Org\Mxchange\CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Database\Frontend\DatabaseFrontendFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
use Org\Mxchange\CoreFramework\Registry\Registerable;
+use Org\Mxchange\CoreFramework\Traits\Manager\Account\ManageableAccountTrait;
+use Org\Mxchange\CoreFramework\Traits\Result\Search\SearchableResultTrait;
use Org\Mxchange\CoreFramework\User\ManageableAccount;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class UserPoints extends BaseFrameworkSystem implements Registerable, BookablePoints {
+ // Load traits
+ use ManageableAccountTrait;
+ use SearchableResultTrait;
+
/**
* Amount of points
*/
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
// Add search criteria
- $searchInstance->addCriteria(UserPointsDatabaseWrapper::DB_COLUMN_POINTS_UID, $userInstance->getUserId());
+ $searchInstance->addCriteria(UserPointsDatabaseFrontend::DB_COLUMN_POINTS_UID, $userInstance->getUserId());
$searchInstance->setLimit(1);
- // Get a wrapper instance
- $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName('user_points_db_wrapper_class');
+ // Get a frontend instance
+ $frontendInstance = DatabaseFrontendFactory::createFrontendByConfiguredName('user_points_db_frontend_class');
// Get result back
- $resultInstance = $wrapperInstance->doSelectByCriteria($searchInstance);
+ $resultInstance = $frontendInstance->doSelectByCriteria($searchInstance);
// Advance to first entry by default
$resultInstance->next();
* @param $amount Amount of points to store
* @return void
*/
- public final function setAmount ($amount) {
+ public final function setAmount (float $amount) {
$this->amount = (float) $amount;
}
* @return $hasRequired Whether the user has the required points
* @todo Finish loading part of points
*/
- public function ifUserHasRequiredPoints ($action) {
+ public function ifUserHasRequiredPoints (string $action) {
// Default is that everyone is poor... ;-)
$hasRequired = false;
// Get the required points entry
- $requiredPoints = $this->getConfigInstance()->getConfigEntry($action . '_action_points');
+ $requiredPoints = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($action . '_action_points');
// Rewind always
$this->getResultInstance()->rewind();
// Do we have an entry?
- if ($this->getResultInstance()->next()) {
+ if ($this->getResultInstance()->valid()) {
// Get the entry
$currEntry = $this->getResultInstance()->current();
// Has he enought points?
$hasRequired = ($currEntry['points'] >= $requiredPoints);
- } // END - if
+ }
// Return the result
return $hasRequired;
* @param $amount Amount of points we shall book
* @return void
*/
- public function bookPointsDirectly ($amount) {
+ public function bookPointsDirectly (float $amount) {
// Rewind always
$this->getResultInstance()->rewind();
// Do we have an entry?
- if ($this->getResultInstance()->next()) {
+ if ($this->getResultInstance()->valid()) {
// Get the entry
- $entry = $this->getResultInstance()->current();
+ $currentEntry = $this->getResultInstance()->current();
// Add the points
- $amount += $entry[UserPointsDatabaseWrapper::DB_COLUMN_POINTS];
+ $amount += $currentEntry[UserPointsDatabaseFrontend::DB_COLUMN_POINTS];
// Now get another criteria
$updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
// And add our both entries
- $updateInstance->addCriteria(UserPointsDatabaseWrapper::DB_COLUMN_POINTS, $amount);
+ $updateInstance->addCriteria(UserPointsDatabaseFrontend::DB_COLUMN_POINTS, $amount);
// Add the search criteria for searching for the right entry
$updateInstance->setSearchInstance($searchInstance);
- // Set wrapper class name
- $updateInstance->setWrapperConfigEntry('user_points_db_wrapper_class');
+ // Set frontend class name
+ $updateInstance->setFrontendConfigEntry('user_points_db_frontend_class');
// Remember the update in database result
$this->getResultInstance()->add2UpdateQueue($updateInstance);
$this->setAmount($amount);
// Create the new entry
- $wrapperInstance->insertUserPoints($this);
+ $frontendInstance->insertUserPoints($this);
}
}
*/
public function addElementsToDataSet (StoreableCriteria $criteriaInstance) {
// Add user id
- $criteriaInstance->addCriteria(UserPointsDatabaseWrapper::DB_COLUMN_POINTS_UID, $this->getUserInstance()->getUserId());
+ $criteriaInstance->addCriteria(UserPointsDatabaseFrontend::DB_COLUMN_POINTS_UID, $this->getUserInstance()->getUserId());
// Add amount
- $criteriaInstance->addCriteria(UserPointsDatabaseWrapper::DB_COLUMN_POINTS, $this->getAmount());
+ $criteriaInstance->addCriteria(UserPointsDatabaseFrontend::DB_COLUMN_POINTS, $this->getAmount());
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Database\Frontend\DatabaseFrontendFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
use Org\Mxchange\CoreFramework\Reader\News\ReadableNews;
use Org\Mxchange\CoreFramework\Registry\Registerable;
use Org\Mxchange\CoreFramework\Request\Requestable;
+use Org\Mxchange\CoreFramework\Traits\Result\Search\SearchableResultTrait;
/**
* A console news reader class reads news from database layer
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class ConsoleNewsReader extends BaseFrameworkSystem implements ReadableNews, Registerable {
+ // Load traits
+ use SearchableResultTrait;
+
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Get 'command' for saving some calls
$command = FrameworkBootstrap::getRequestInstance()->getRequestElement('command');
- // First get a wrapper instance
- $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName('news_db_wrapper_class');
+ // First get a frontend instance
+ $frontendInstance = DatabaseFrontendFactory::createFrontendByConfiguredName('news_db_frontend_class');
// Next create a searchable criteria instance
$criteriaInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
$criteriaInstance->setConfiguredLimit('news_' . $command . '_limit');
// Get a resultInstance back from the database
- $resultInstance = $wrapperInstance->doSelectByCriteria($criteriaInstance);
+ $resultInstance = $frontendInstance->doSelectByCriteria($criteriaInstance);
// Save that resultInstance in this class
$this->setResultInstance($resultInstance);
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Database\Frontend\DatabaseFrontendFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
use Org\Mxchange\CoreFramework\Registry\Registerable;
use Org\Mxchange\CoreFramework\Request\Requestable;
+use Org\Mxchange\CoreFramework\Traits\Result\Search\SearchableResultTrait;
/**
* A default news reader class reads news from database layer
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class DefaultNewsReader extends BaseFrameworkSystem implements ReadableNews, Registerable {
+ // Load traits
+ use SearchableResultTrait;
+
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
// Get 'command' for saving some calls
$command = FrameworkBootstrap::getRequestInstance()->getRequestElement('command');
- // First get a wrapper instance
- $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName('news_db_wrapper_class');
+ // First get a frontend instance
+ $frontendInstance = DatabaseFrontendFactory::createFrontendByConfiguredName('news_db_frontend_class');
// Next create a searchable criteria instance
$criteriaInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
$criteriaInstance->setConfiguredLimit('news_' . $command . '_limit');
// Get a resultInstance back from the database
- $resultInstance = $wrapperInstance->doSelectByCriteria($criteriaInstance);
+ $resultInstance = $frontendInstance->doSelectByCriteria($criteriaInstance);
// Save that resultInstance in this class
$this->setResultInstance($resultInstance);
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filter\Filterable;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
<?php
// Own namespace
-namespace CoreFramework\Registry\!!!;
+namespace Org\Mxchange\CoreFramework\Registry\!!!;
// Import framework stuff
use Org\Mxchange\CoreFramework\Registry\BaseRegistry;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
/**
* Instance of this class
*/
- private static $registryInstance = null;
+ private static $registryInstances = [];
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*
* @return $registryInstance Instance of this class
*/
- public final static function getRegistry () {
+ public final static function getRegistry (string $key) {
// Is an instance there?
- if (is_null(self::$registryInstance)) {
+ if (is_null(self::$registryInstances[$key])) {
// Not yet, so create one
- self::$registryInstance = new ???Registry();
- } // END - if
+ self::$registryInstances[$key] = new ???Registry();
+ }
// Return the instance
- return self::$registryInstance;
+ return self::$registryInstances[$key];
}
}
namespace Org\Mxchange\CoreFramework\Registry;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Generic\NullPointerException;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+use Org\Mxchange\CoreFramework\Traits\Iterator\IteratorTrait;
// Import SPL stuff
+use \InvalidArgumentExeption;
use \IteratorAggregate;
+use \UnexpectedValueException;
/**
* A general Registry
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseRegistry extends BaseFrameworkSystem implements Register, Registerable, IteratorAggregate {
+ // Load traits
+ use IteratorTrait;
+
/**
* Glue for generating a registry key
*/
const REGISTRY_KEY_GLUE = '_';
- /**
- * Instance of this class
- */
- private static $registryInstance = NULL;
-
/**
* Protected constructor
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-REGISTRY: className=%s - CONSTRUCTED!', $className));
parent::__construct($className);
// Init generic arrays
$this->initGenericArrayGroup('registry', 'generic');
- $this->initGenericArrayGroup('registry', 'instance');
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-REGISTRY: EXIT!');
}
/**
* Returns an iterator for this whole registry.
*
+ * @param $onlyRegistries Only iterate on these sub-registry keys, default is all
* @return $iteratorInstance An instance of a Iterator class
*/
- public function getIterator () {
+ public function getIterator (array $onlyRegistries = []) {
+ // Get iterator
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-REGISTRY: onlyRegistries()=%d - CALLED!', count($onlyRegistries)));
+ $iteratorInstance = $this->getIteratorInstance();
+
// Is it set?
- if (is_null($this->getIteratorInstance())) {
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-REGISTRY: iteratorInstance[]=%s', gettype($iteratorInstance)));
+ if (is_null($iteratorInstance)) {
// Then instance it
- $iteratorInstance = ObjectFactory::createObjectByConfiguredName('registry_iterator_class', array($this));
+ $iteratorInstance = ObjectFactory::createObjectByConfiguredName('registry_iterator_class', [$this]);
// ... and set it here
$this->setIteratorInstance($iteratorInstance);
- } else {
- // Use set iterator
- $iteratorInstance = $this->getIteratorInstance();
}
+ // Init iterator instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-REGISTRY: Invoking iteratorInstance->initIterator(onlyRegistries()=%d) ...', count($onlyRegistries)));
+ $iteratorInstance->initIterator($onlyRegistries);
+
// Return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-REGISTRY: iteratorInstance=%s - EXIT!', $iteratorInstance->__toString()));
return $iteratorInstance;
}
- /**
- * Checks whether an instance key was found
- *
- * @param $instanceKey The key holding an instance in registry
- * @return $exists Whether the key exists in registry
- */
- public function instanceExists ($instanceKey) {
- // Does this key exists?
- $exists = $this->isGenericArrayKeySet('registry', 'instance', $instanceKey);
-
- // Return the result
- return $exists;
- }
-
- /**
- * Adds/overwrites a new instance to the registry at the given key
- *
- * @param $instanceKey The key to identify the instance
- * @param $objectInstance An instance we shall store
- * @return void
- */
- public function addInstance ($instanceKey, Registerable $objectInstance) {
- $this->setGenericArrayKey('registry', 'instance', $instanceKey, $objectInstance);
- }
-
/**
* Getter for whole generic registry
*
return $this->getGenericSubArray('registry', 'generic');
}
- /**
- * Getter for whole instance registry
- *
- * @return $instanceRegistry The whole instance registry array
- */
- public final function getInstanceRegistry () {
- return $this->getGenericSubArray('registry', 'instance');
- }
-
/**
* Adds a new entry to the given list name. If you want to add objects
* please use addInstance() and getInstance() instead.
* @param $key The key to identify the whole list
* @param $value The value to be stored
* @return void
+ * @throws InvalidArgumentException If a paramter has an invalid value
*/
- public final function addEntry ($key, $value) {
- // Key must not be an array
- assert(!is_array($key));
+ public final function addEntry (string $key, $value) {
+ // Check parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-REGISTRY: key=%s,value[]=%s - CALLED!', $key, gettype($value)));
+ if (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentExeption('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Push it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-REGISTRY: Invoking this->pushValueToGenericArrayKey(registry,generic,%s,value[]=%s) ...', $key, gettype($value)));
$this->pushValueToGenericArrayKey('registry', 'generic', $key, $value);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-REGISTRY: EXIT!');
}
/**
* Getter for entries or "sub entries"
*
+ * @param $key Key
* @return $entries An array with entries from this registry
+ * @throws InvalidArgumentException If a paramter has an invalid value
*/
- public final function getEntries ($key = NULL) {
- // Key must not be an array
- assert(!is_array($key));
+ public final function getEntries (string $key = NULL) {
+ // Check parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-REGISTRY: key[%s]=%s - CALLED!', gettype($key), $key));
+ if (!is_null($key) && empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentExeption('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Default is whole array
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-REGISTRY: Invoking this->getGenericArray(registry) ...');
$entries = $this->getGenericArray('registry');
// Is $key set?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-REGISTRY: key[]=%s,entries()=%d', $key, count($entries)));
if (!is_null($key)) {
// Then use this entry
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-REGISTRY: Invoking this->getGenericArrayKey(registry,generic,%s) ...', $key));
$entries = $this->getGenericArrayKey('registry', 'generic', $key);
- } // END - if
+ }
// Return the array
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-REGISTRY: entries()=%d - EXIT!', count($entries)));
return $entries;
}
* @param $arrayKey The array (key) to look in
* @param $lookFor The key to look for
* @return $entry An array with all keys
+ * @throws InvalidArgumentException If a paramter has an invalid value
+ * @throws UnexpectedValueException If $value3 is not an array
*/
- public function getArrayFromKey ($arrayKey, $lookFor) {
- // Key must not be an array
- assert(!is_array($arrayKey));
+ public function getArrayFromKey (string $arrayKey, string $lookFor) {
+ // Check parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-REGISTRY: arrayKey=%s,lookFor=%s - CALLED!', $arrayKey, $lookFor));
+ if (empty($arrayKey)) {
+ // Throw IAE
+ throw new InvalidArgumentExeption('Parameter "arrayKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($lookFor)) {
+ // Throw IAE
+ throw new InvalidArgumentExeption('Parameter "lookFor" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Init array
- $entry = array();
-
- // Debug message
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('REGISTRY[' . __METHOD__ . ':' . __LINE__ . ']: Checking arrayKey=' . $arrayKey . ',lookFor=' . $lookFor);
+ $entry = [];
// "Walk" over all entries
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-REGISTRY: Checking arrayKey=%s,lookFor=%s', $arrayKey, $lookFor));
foreach ($this->getEntries($arrayKey) as $key => $value) {
- // Debug message
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('REGISTRY[' . __METHOD__ . ':' . __LINE__ . ']: Checking key=' . $key . ',value=' . $value . ',lookFor=' . $lookFor);
-
// If $value matches the $lookFor, we need to look for more entries for this!
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-REGISTRY: Checking key=%s,value=%s,lookFor=%s', $key, $value, $lookFor));
if ($lookFor == $value) {
// Look for more entries
foreach ($this->getEntries() as $key2 => $value2) {
// Now "walk" through all entries, if an array is returned
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-REGISTRY: key2=%s,value2[]=%s', $key2, gettype($value2)));
if (is_array($value2)) {
- // Debug message
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('REGISTRY[' . __METHOD__ . ':' . __LINE__ . ']: Checking key2=' . $key2 . ',value2()=' . count($value2) . ',lookFor=' . $lookFor);
-
// "Walk" through all of them
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-REGISTRY: Checking key2=%s,value2()=%s,lookFor=%s', $key2, count($value2), $lookFor));
foreach ($value2 as $key3 => $value3) {
// $value3 needs to be an array
- assert(is_array($value3));
-
- // Debug message
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('REGISTRY[' . __METHOD__ . ':' . __LINE__ . ']: Checking key=' . $key . ',key3=' . $key3 . ',isset()=' . isset($value3[$key]) . ' ...');
+ if (!is_array($value3)) {
+ // Throw exception
+ throw new UnexpectedValueException(sprintf('arrayKey=%s,key=%s,value=%s,key2=%s,key3=%s has unexpected value3[]=%s', $arrayKey, $key, $value, $key2, $key3, gettype($value3)), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// Both keys must match!
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-REGISTRY: Checking key=%s,key3=%s,isset()=%s ...', $key, $key3, intval(isset($value3[$key]))));
if (($key == $key3) || (isset($value3[$key]))) {
- // Debug message
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('REGISTRY[' . __METHOD__ . ':' . __LINE__ . ']: Adding ' . $value3[$key] . ' ...');
-
// Then add it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-REGISTRY: Adding value3[%s]=%s ...', $key, $value3[$key]));
$entry[$key3] = $value3[$key];
- } // END - if
- } // END - foreach
- } // END - if
- } // END - foreach
+ }
+ }
+ }
+ }
// Skip further lookups
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('BASE-REGISTRY: BREAK!');
break;
- } // END - if
- } // END - foreach
-
- // Debug message
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('REGISTRY[' . __METHOD__ . ':' . __LINE__ . ']: Returning entry(' . count($entry) . ')=' . print_r($entry, true));
+ }
+ }
// Return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-REGISTRY: entry()=%d - EXIT!', count($entry)));
return $entry;
}
- /**
- * Gets a registered instance or null if not found
- *
- * @param $instanceKey The key to identify the instance
- * @return $objectInstance An instance we shall store
- * @throws NullPointerException If the requested key is not found
- */
- public function getInstance ($instanceKey) {
- // Is the instance there?
- if (!$this->instanceExists($instanceKey)) {
- // This might happen if a non-registered key was requested
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } // END - if
-
- // Get the instance
- $objectInstance = $this->getGenericArrayKey('registry', 'instance', $instanceKey);
-
- // Return the result
- return $objectInstance;
- }
-
/**
* "Getter" for a registry key for given prefix and array. This method
* calls implode() to get a suitable key. This method does not care about
* @param $data An array with data
* @return $registryKey A registry key
*/
- public static function getRegistryKeyFromArray ($prefix, array $data) {
+ public static function getRegistryKeyFromArray (string $prefix, array $data) {
+ // Check parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-REGISTRY: prefix=%s,data()=%d - CALLED!', $prefix, count($data)));
+ if (empty($prefix)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "prefix" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (count($data) == 0) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "data" is an empty array', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// "Generate" the key
$registryKey = $prefix . self::REGISTRY_KEY_GLUE . implode(self::REGISTRY_KEY_GLUE, $data);
// Return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-REGISTRY: registryKey=%s - EXIT!', $registryKey));
return $registryKey;
}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
if (is_null(self::$registryInstance)) {
// Not yet, so create one
self::$registryInstance = new ???FormatUpgradeRegistry();
- } // END - if
+ }
// Return the instance
return self::$registryInstance;
}
-}
-// [EOF]
-?>
+}
namespace Org\Mxchange\CoreFramework\Registry\Upgrade\Format\Lfdb;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
use Org\Mxchange\CoreFramework\Registry\BaseRegistry;
use Org\Mxchange\CoreFramework\Upgrade\Format\Database\UpgradeableDatabaseFormat;
use Org\Mxchange\CoreFramework\Upgrade\Format\RegisterableFormatUpgrade;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
if (is_null(self::$registryInstance)) {
// Not yet, so create one
self::$registryInstance = new LocalFileDatabaseFormatUpgradeRegistry();
- } // END - if
+ }
// Return the instance
return self::$registryInstance;
* @todo 0% done
*/
public function registerFormatUpgrader (UpgradeableDatabaseFormat $upgradeInstance) {
- $this->partialStub();
+ DebugMiddleware::getSelfInstance()->partialStub();
}
}
// Own namespace
namespace Org\Mxchange\CoreFramework\Registry;
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+
/**
* A registry for several data types and objects. Objects should be added by
* addInstance() and therefore must implement the interface Registerable.
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* Singleton getter for self instance. This class has no factory pattern
* because here is no need for special parameters.
*
+ * @param $key Key for for this instance
* @return $registryInstance Instance of this class
+ * @throws InvalidArgumentException If a parameter has an invalid value
*/
- public static final function getRegistry () {
+ public static final function getRegistry (string $key) {
+ // Check parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('OBJECT-REGISTRY: key=%s - CALLED!', $key));
+ if (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Is an instance there?
- if (is_null(self::$registryInstance)) {
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('OBJECT-REGISTRY: self::registryInstance[%s]?=%d', $key, intval(isset((self::$registryInstances[$key])))));
+ if (!isset(self::$registryInstances[$key])) {
// Not yet, so create one
- self::$registryInstance = new GenericRegistry();
- } // END - if
+ self::$registryInstances[$key] = new ObjectRegistry();
+ }
// Return the instance
- return self::$registryInstance;
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('OBJECT-REGISTRY: self::registryInstance[%s]=%s - EXIT!', $key, self::$registryInstances[$key]->__toString()));
+ return self::$registryInstances[$key];
}
}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Registry\Object;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Generic\NullPointerException;
+use Org\Mxchange\CoreFramework\Registry\BaseRegistry;
+use Org\Mxchange\CoreFramework\Registry\Registerable;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+
+/**
+ * A registry for several data types and objects. Objects should be added by
+ * addInstance() and therefore must implement the interface Registerable.
+ *
+ * @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 ObjectRegistry extends BaseRegistry implements ObjectRegister {
+ /**
+ * Instances of this class
+ */
+ private static $registryInstances = [];
+
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('OBJECT-REGISTRY: CONSTRUCTED!');
+ parent::__construct(__CLASS__);
+
+ // Init own array
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('OBJECT-REGISTRY: Invoking this->initGenericArrayGroup(registry,instance) ...');
+ $this->initGenericArrayGroup('registry', 'instance');
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('OBJECT-REGISTRY: EXIT!');
+ }
+
+ /**
+ * Singleton getter for self instance. This class has no factory pattern
+ * because here is no need for special parameters.
+ *
+ * @param $key Key for for this instance
+ * @return $registryInstance Instance of this class
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ */
+ public static final function getRegistry (string $key) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('OBJECT-REGISTRY: key=%s - CALLED!', $key));
+ if (empty($key)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "key" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Is an instance there?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('OBJECT-REGISTRY: self::registryInstance[%s]?=%d', $key, intval(isset(self::$registryInstances[$key]))));
+ if (!isset(self::$registryInstances[$key])) {
+ // Not yet, so create one
+ self::$registryInstances[$key] = new ObjectRegistry();
+ }
+
+ // Return the instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('OBJECT-REGISTRY: self::registryInstance[%s]=%s - EXIT!', $key, self::$registryInstances[$key]->__toString()));
+ return self::$registryInstances[$key];
+ }
+
+ /**
+ * Checks whether an instance key was found
+ *
+ * @param $instanceKey The key holding an instance in registry
+ * @return $exists Whether the key exists in registry
+ * @throws InvalidArgumentException If a paramter has an invalid value
+ */
+ public function instanceExists (string $instanceKey) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('OBJECT-REGISTRY: instanceKey=%s - CALLED!', $instanceKey));
+ if (empty($instanceKey)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "instanceKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Does this key exists?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('OBJECT-REGISTRY: Invoking this->isGenericArrayKeySet(registry, instance, %s) ...', $instanceKey));
+ $exists = $this->isGenericArrayKeySet('registry', 'instance', $instanceKey);
+
+ // Return the result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('OBJECT-REGISTRY: exists=%d - EXIT!', intval($exists)));
+ return $exists;
+ }
+
+ /**
+ * Getter for whole instance registry
+ *
+ * @return $instanceRegistry The whole instance registry array
+ */
+ public final function getInstanceRegistry () {
+ return $this->getGenericSubArray('registry', 'instance');
+ }
+
+ /**
+ * Adds/overwrites a new instance to the registry at the given key
+ *
+ * @param $instanceKey The key to identify the instance
+ * @param $objectInstance An instance we shall store
+ * @return void
+ * @throws InvalidArgumentException If a paramter has an invalid value
+ */
+ public function addInstance (string $instanceKey, Registerable $objectInstance) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('OBJECT-REGISTRY: instanceKey=%s,objectInstance=%s - CALLED!', $instanceKey, $objectInstance->__toString()));
+ if (empty($instanceKey)) {
+ // Throw IAE
+ throw new InvalidArgumentExeption('Parameter "instanceKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Set entry in generic array
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('OBJECT-REGISTRY: Invoking this->setGenericArrayKey(registry,instance,%s,%s) ...', $instanceKey, $objectInstance->__toString()));
+ $this->setGenericArrayKey('registry', 'instance', $instanceKey, $objectInstance);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('OBJECT-REGISTRY: EXIT!');
+ }
+
+ /**
+ * Gets a registered instance or null if not found
+ *
+ * @param $instanceKey The key to identify the instance
+ * @return $objectInstance An instance we shall store
+ * @throws InvalidArgumentException If a paramter has an invalid value
+ * @throws NullPointerException If the requested key is not found
+ */
+ public function getInstance (string $instanceKey) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('OBJECT-REGISTRY: instanceKey=%s - CALLED!', $instanceKey));
+ if (empty($instanceKey)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "instanceKey" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Is the instance there?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('OBJECT-REGISTRY: Invoking this->instanceExists(%s) ...', $instanceKey));
+ if (!$this->instanceExists($instanceKey)) {
+ // This might happen if a non-registered key was requested
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
+ }
+
+ // Get the instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('OBJECT-REGISTRY: Invoking this->getGenericArrayKey(registry,instance,%s) ...', $instanceKey));
+ $objectInstance = $this->getGenericArrayKey('registry', 'instance', $instanceKey);
+
+ // Return the result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('OBJECT-REGISTRY: objectInstance=%s - EXIT!', $objectInstance->__toString()));
+ return $objectInstance;
+ }
+
+}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
<?php
// Own namespace
-namespace CoreFramework\Request;
+namespace Org\Mxchange\CoreFramework\Request;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
/**
* A concrete request class
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @todo Needs to be implemented
*/
protected function prepareRequestData () {
- $this->partialStub("Please implement this method.");
+ DebugMiddleware::getSelfInstance()->partialStub("Please implement this method.");
}
/**
* @return $headerValue Value of the header or 'null' if not found
*/
public function getHeaderElement ($headerName) {
- $this->partialStub("Please implement this method.");
+ DebugMiddleware::getSelfInstance()->partialStub("Please implement this method.");
}
/**
* @return $requestMethod Used request method
*/
public final function getRequestMethod () {
- $this->partialStub("Please implement this method.");
+ DebugMiddleware::getSelfInstance()->partialStub("Please implement this method.");
return $_SERVER['REQUEST_METHOD'];
}
* @return $cookieValue Value of cookie or null if not found
*/
public final function readCookie ($cookieName) {
- $this->partialStub("Please implement this method.");
+ DebugMiddleware::getSelfInstance()->partialStub("Please implement this method.");
}
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* Array for the request data
*/
- private $requestData = array();
+ private $requestData = [];
/**
* Whether this request is valid and can be further processed. The default is
* valid so make sure your intercepting filters sets this attribute to false
* when they need to intercept the data flow.
*/
- private $requestIsValid = true;
+ private $isRequestValid = true;
/**
* Protected constructor
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
* @param $element Name of the request element we want to check
* @return $isSet Whether the request element is set
*/
- public function isRequestElementSet ($element) {
+ public function isRequestElementSet (string $element) {
// Is this element found?
$isSet = isset($this->requestData[$element]);
* @return $value Value of the found request element or 'null' if the
* element was not found
*/
- public function getRequestElement ($element) {
+ public function getRequestElement (string $element) {
// Initialize value
$value = NULL;
// Secure it against attacks
$value = htmlentities(strip_tags($value), ENT_QUOTES);
- } // END - if
+ }
// Return the element's value
return $value;
* @param $value Value to set
* @return void
*/
- public function setRequestElement ($element, $value) {
+ public function setRequestElement (string $element, $value) {
$this->requestData[$element] = $value;
}
}
/**
- * Sets whether the request was valid (default: true)
+ * Sets whether the request was valid
*
* @param $isValid Whether the request is valid
* @return void
*/
- public final function requestIsValid ($isValid = true) {
- $this->requestIsValid = (bool) $isValid;
+ public final function setIsRequestValid (bool $isValid) {
+ $this->isRequestValid = $isValid;
}
/**
* Returns whether this request is valid
*
- * @return $requestIsValid Whether this request is valid
+ * @return $isRequestValid Whether this request is valid
*/
public final function isRequestValid () {
- return $this->requestIsValid;
+ return $this->isRequestValid;
}
}
namespace Org\Mxchange\CoreFramework\Request;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
use Org\Mxchange\CoreFramework\Request\Requestable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
if ((!isset($_SERVER['argv'])) || (!isset($_SERVER['argc']))) {
// Maybe not right PHP mode? (needs CLI?)
trigger_error(sprintf('[%s:%d]: argv/argc not set: %s', __METHOD__, __LINE__, print_r($_SERVER, true)), E_USER_ERROR);
- } // END - if
+ }
// Get the "request data" from the command-line argument list
$args = $_SERVER['argv'];
if ($_SERVER['argc'] < 2) {
// Skip this
return;
- } // END - if
+ }
// Is the first element "index.php" ?
if ($args[0] == 'index.php') {
// Then remove it
array_shift($args);
- } // END - if
+ }
// Try to determine next parameters
foreach ($args as $arg) {
// Set a name=value pair escaped and secured
$this->setRequestElement($argArray[0], escapeshellcmd($argArray[1]));
}
- } // END - foreach
+ }
}
/**
* @return $headerValue Value of the header or 'null' if not found
* @throws UnsupportedOperationException This method should never be called
*/
- public function getHeaderElement ($headerName) {
+ public function getHeaderElement (string $headerName) {
// Console doesn't have any headers
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $executorInstance), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $executorInstance), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @return $cookieValue Value of cookie or null if not found
* @throws UnsupportedOperationException This method should never be called
*/
- public final function readCookie ($cookieName) {
+ public final function readCookie (string $cookieName) {
// There are no cookies on console
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $executorInstance), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $executorInstance), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
*/
public function isGetRequestMethod () {
// Not support method
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $executorInstance), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $executorInstance), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
*/
public function isHeadRequestMethod () {
// Not support method
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $executorInstance), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $executorInstance), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
*/
public function isPostRequestMethod () {
// Not support method
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $executorInstance), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $executorInstance), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Request\Requestable;
-use Org\Mxchange\CoreFramework\String\Utils\StringUtils;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
/**
* A concrete and secured HTML request class to make HTML requests more abstract
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @todo Move out the cookie part to a seperate class, e.g. Cookie
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @param $headerName Name of the header
* @return $headerValue Value of the header or 'null' if not found
*/
- public function getHeaderElement ($headerName) {
+ public function getHeaderElement (string $headerName) {
// Default return value on error
$headerValue = NULL;
// Does this header exist?
if (isset($_SERVER[$name])) {
$headerValue = $_SERVER[$name];
- } // END - if
+ }
// Return the value
return $headerValue;
* @param $cookieName Name of cookie we shall read
* @return $cookieValue Value of cookie or null if not found
*/
- public final function readCookie ($cookieName) {
+ public final function readCookie (string $cookieName) {
// Default is no cookie with that name found
$cookieValue = NULL;
if (isset($_COOKIE[$cookieName])) {
// Then get it
$cookieValue = $_COOKIE[$cookieName];
- } // END - if
+ }
// Return the value
return $cookieValue;
namespace Org\Mxchange\CoreFramework\Resolver\Action;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Resolver\BaseResolver;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
// Import SPL stuff
use \InvalidArgumentException;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
* @param $actionName Last validated action name
* @return void
*/
- protected final function setActionName ($actionName) {
- $this->actionName = (string) $actionName;
+ protected final function setActionName (string $actionName) {
+ $this->actionName = $actionName;
}
/**
* @return $isValid Whether the given action is valid
* @throws InvalidArgumentException Thrown if given action is not set
*/
- public function isActionValid ($namespace, $actionName) {
- // By default nothing shall be valid
- $isValid = false;
-
+ public function isActionValid (string $namespace, string $actionName) {
// Is a action set?
if (empty($namespace)) {
// Then thrown an exception here
- throw new InvalidArgumentException('Parameter "namespace" is empty');
+ throw new InvalidArgumentException('Parameter "namespace" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif (empty($actionName)) {
// Then thrown an exception here
- throw new InvalidArgumentException('Parameter "actionName" is empty');
+ throw new InvalidArgumentException('Parameter "actionName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
}
// Create class name
'%s\%s%sAction',
$namespace,
$this->getCapitalizedClassPrefix(),
- self::convertToClassName($actionName)
+ StringUtils::convertToClassName($actionName)
);
// Now, let us create the full name of the action class
$this->setClassName($className);
// Is this class already loaded?
- if (class_exists($this->getClassName())) {
- // This class does exist. :-)
- $isValid = true;
- } // END - if
+ $isValid = class_exists($this->getClassName());
- // Set action name
- $this->setActionName($actionName);
+ // Is it valid?
+ if ($isValid) {
+ // Set action name
+ $this->setActionName($actionName);
+ }
// Return the result
return $isValid;
'%s\%s%sAction',
$this->getNamespace(),
$this->getCapitalizedClassPrefix(),
- self::convertToClassName($actionName)
+ StringUtils::convertToClassName($actionName)
);
// ... and set it
$this->setClassName($className);
// Initiate the action
- $actionInstance = ObjectFactory::createObjectByName($this->getClassName(), array($this));
+ $actionInstance = ObjectFactory::createObjectByName($this->getClassName(), [$this]);
// Return the result
return $actionInstance;
namespace Org\Mxchange\CoreFramework\Resolver\Action;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Request\Requestable;
// Import SPL stuff
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
// Is the variable $actionName set and the action is valid?
if (empty($actionName)) {
// Then thrown an exception here
- throw new InvalidArgumentException('Parameter "actionName" is empty');
+ throw new InvalidArgumentException('Parameter "actionName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif ($resolverInstance->isActionValid($actionName) === false) {
// Invalid action found
throw new InvalidActionException(array($resolverInstance, $actionName), self::EXCEPTION_INVALID_ACTION);
// Is the action empty? Then fall back to default action
if (empty($actionName)) {
- $actionName = $this->getConfigInstance()->getConfigEntry('default_action');
- } // END - if
+ $actionName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('default_action');
+ }
// Check if action is valid
if ($this->isActionValid($actionName) === false) {
// This action is invalid!
throw new InvalidActionException(array($this, $actionName), self::EXCEPTION_INVALID_ACTION);
- } // END - if
+ }
// Get the action
$actionInstance = $this->loadAction();
if ((!is_object($actionInstance)) || (!$actionInstance instanceof Actionable)) {
// This action has an invalid instance!
throw new InvalidActionInstanceException(array($this, $actionName), self::EXCEPTION_INVALID_ACTION);
- } // END - if
+ }
// Set last action
$this->setResolvedInstance($actionInstance);
// Is the action empty? Then fall back to default action
if (empty($actionName)) {
- $actionName = $this->getConfigInstance()->getConfigEntry('default_action');
- } // END - if
+ $actionName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('default_action');
+ }
// Check if action is valid
if ($this->isActionValid($actionName) === false) {
// This action is invalid!
throw new InvalidActionException(array($this, $actionName), self::EXCEPTION_INVALID_ACTION);
- } // END - if
+ }
// Get the action
$actionInstance = $this->loadAction();
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
$!!!Name = $requestInstance->getRequestElement('action');
// Is the action empty? Then fall back to default action
- if (empty($!!!Name)) $!!!Name = $this->getConfigInstance()->getConfigEntry('default_action');
+ if (empty($!!!Name)) $!!!Name = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('default_action');
// Check if action is valid
if ($this->is|||Valid($!!!Name) === false) {
// This action is invalid!
throw new Invalid|||Exception(array($this, $!!!Name), self::EXCEPTION_INVALID_ACTION);
- } // END - if
+ }
// Get the action
$!!!Instance = $this->load|||();
if ((!is_object($!!!Instance)) || (!$!!!Instance instanceof |||able)) {
// This action has an invalid instance!
throw new Invalid|||InstanceException(array($this, $!!!Name), self::EXCEPTION_INVALID_ACTION);
- } // END - if
+ }
// Set last action
$this->setResolvedInstance($!!!Instance);
// Is the action empty? Then fall back to default action
if (empty($!!!Name)) {
- $!!!Name = $this->getConfigInstance()->getConfigEntry('default_action');
- } // END - if
+ $!!!Name = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('default_action');
+ }
// Check if action is valid
if ($this->is|||Valid($!!!Name) === false) {
// This action is invalid!
throw new Invalid|||Exception(array($this, $!!!Name), self::EXCEPTION_INVALID_ACTION);
- } // END - if
+ }
// Get the action
$!!!Instance = $this->load|||();
// Import framework stuff
use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
/**
* A generic resolver class
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseResolver extends BaseFrameworkSystem {
+ // Exception constants
+ const EXCEPTION_INVALID_COMMAND = 0x1d0;
+ const EXCEPTION_INVALID_CONTROLLER = 0x1d1;
+ const EXCEPTION_INVALID_ACTION = 0x1d2;
+ const EXCEPTION_INVALID_STATE = 0x1d3;
+
/**
* Namespace
*/
*/
private $resolvedInstance = NULL;
- // Exception constants
- const EXCEPTION_INVALID_COMMAND = 0x1d0;
- const EXCEPTION_INVALID_CONTROLLER = 0x1d1;
- const EXCEPTION_INVALID_ACTION = 0x1d2;
- const EXCEPTION_INVALID_STATE = 0x1d3;
-
/**
* Protected constructor
*
* @param $className Real name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
* @param $namespace Namespace to look in
* @return void
*/
- protected final function setNamespace ($namespace) {
- $this->namespace = (string) $namespace;
+ protected final function setNamespace (string $namespace) {
+ $this->namespace = $namespace;
}
/**
* @param $className Name of the class
* @return void
*/
- protected final function setClassName ($className) {
- $this->className = (string) $className;
+ protected final function setClassName (string $className) {
+ $this->className = $className;
}
/**
$className = $this->getClassPrefix();
// And capitalize it
- $className = self::convertToClassName($className);
+ $className = StringUtils::convertToClassName($className);
// Return it
return $className;
* @param $classPrefix Last validated classPrefix
* @return void
*/
- protected final function setClassPrefix ($classPrefix) {
- $this->classPrefix = (string) $classPrefix;
+ protected final function setClassPrefix (string $classPrefix) {
+ $this->classPrefix = $classPrefix;
}
/**
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Command\Commandable;
use Org\Mxchange\CoreFramework\Command\InvalidCommandException;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Resolver\BaseResolver;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
// Import SPL stuff
use \InvalidArgumentException;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseCommandResolver extends BaseResolver {
+ /**
+ * Command name
+ */
+ private $commandName = '';
+
/**
* Protected constructor
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
+ /**
+ * Setter for command name
+ *
+ * @param $commandName Last validated command name
+ * @return void
+ */
+ protected final function setCommandName (string $commandName) {
+ $this->commandName = $commandName;
+ }
+
+ /**
+ * Getter for command name
+ *
+ * @return $commandName Last validated command name
+ */
+ public final function getCommandName () {
+ return $this->commandName;
+ }
+
/**
* "Loads" a given command and instances it if not yet cached
*
* @throws InvalidCommandException Thrown if even the default
* command class is missing (bad!)
*/
- protected function loadCommand ($commandName) {
+ protected function loadCommand (string $commandName) {
// Init command instance
$commandInstance = NULL;
'%s\%s%sCommand',
$this->getNamespace(),
$this->getCapitalizedClassPrefix(),
- self::convertToClassName($commandName)
+ StringUtils::convertToClassName($commandName)
);
// Create command class name
if (!class_exists($this->getClassName())) {
// Class not found, so throw an exception
throw new InvalidCommandException(array($this, $commandName), self::EXCEPTION_INVALID_COMMAND);
- } // END - if
+ }
// Initiate the command
- $commandInstance = ObjectFactory::createObjectByName($this->getClassName(), array($this));
+ $commandInstance = ObjectFactory::createObjectByName($this->getClassName(), [$this]);
// Return the result
return $commandInstance;
*/
public function resolveCommandByRequest (Requestable $requestInstance) {
// Init variables
- $commandName = '';
- $commandInstance = NULL;
-
- // This goes fine so let's resolve the command
$commandName = $requestInstance->getRequestElement('command');
+ $commandType = FrameworkBootstrap::getRequestTypeFromSystem();
+ $commandInstance = NULL;
// Is the command empty? Then fall back to default command
if (empty($commandName)) {
- $commandName = $this->getConfigInstance()->getConfigEntry('default_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_command');
- } // END - if
+ // Fall back to default command
+ $commandName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry(sprintf('default_%s_command', $commandType));
+ }
// Check if command is valid
if ($this->isCommandValid($this->getNamespace(), $commandName) === false) {
// This command is invalid!
throw new InvalidCommandException(array($this, $commandName), self::EXCEPTION_INVALID_COMMAND);
- } // END - if
+ }
// Get the command
$commandInstance = $this->loadCommand($commandName);
// And validate it
if ((!is_object($commandInstance)) || (!$commandInstance instanceof Commandable)) {
// This command has an invalid instance!
- throw new UnexpectedValueException(sprintf('commandInstance for commandName=%s is not object (%s) or does not implement Commandable.', $commandName, gettype($commandInstance)), self::EXCEPTION_INVALID_COMMAND);
- } // END - if
+ throw new UnexpectedValueException(sprintf('commandInstance for commandName=%s is not object (%s) or does not implement Commandable.', $commandName, gettype($commandInstance)), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// Set last command
$this->setResolvedInstance($commandInstance);
+ // Init template engine
+ $commandInstance->initTemplateEngine($commandType);
+
// Return the resolved command instance
return $commandInstance;
}
/**
* Resolves the command by its direct name and returns an instance of its class
*
+ * @param $namespace Namespace to look in
* @param $commandName The direct command name we shall resolve
* @return $commandInstance An instance of the command class
* @throws InvalidCommandException Thrown if $commandName is invalid
*/
- public function resolveCommand ($commandName) {
+ public function resolveCommand (string $namespace, string $commandName) {
+ // Is a action set?
+ if (empty($namespace)) {
+ // Then thrown an exception here
+ throw new InvalidArgumentException('Parameter "namespace" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($commandName)) {
+ // Then thrown an exception here
+ throw new InvalidArgumentException('Parameter "commandName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Initiate the instance variable
$commandInstance = NULL;
+ $commandType = FrameworkBootstrap::getRequestTypeFromSystem();
// Is the command empty? Then fall back to default command
if (empty($commandName)) {
- $commandName = $this->getConfigInstance()->getConfigEntry('default_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_command');
- } // END - if
+ // Init default command
+ $commandName = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry(sprintf('default_%s_command', $commandType));
+ }
// Check if command is valid
- if ($this->isCommandValid($commandName) === false) {
+ if ($this->isCommandValid($namespace, $commandName) === false) {
// This command is invalid!
throw new InvalidCommandException(array($this, $commandName), self::EXCEPTION_INVALID_COMMAND);
- } // END - if
+ }
// Get the command
$commandInstance = $this->loadCommand($commandName);
+ // Init template engine
+ $commandInstance->initTemplateEngine($commandType);
+
// Return the instance
return $commandInstance;
}
* @return $isValid Whether the given command is valid
* @throws InvalidArgumentException Thrown if given command is not set
*/
- protected function isCommandValid ($namespace, $commandName) {
- // By default nothing shall be valid
- $isValid = false;
-
+ protected function isCommandValid (string $namespace, string $commandName) {
// Is namespace and command name set?
if (empty($namespace)) {
// Then thrown an exception here
- throw new InvalidArgumentException('Parameter "namespace" is empty');
+ throw new InvalidArgumentException('Parameter "namespace" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif (empty($commandName)) {
// Then thrown an exception here
- throw new InvalidArgumentException('Parameter "commandName" is empty');
- } // END - if
+ throw new InvalidArgumentException('Parameter "commandName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // By default nothing shall be valid
+ $isValid = false;
// Create the full class name
$className = sprintf(
'%s\%s%sCommand',
$namespace,
$this->getCapitalizedClassPrefix(),
- self::convertToClassName($commandName)
+ StringUtils::convertToClassName($commandName)
);
// Now, let us create the full name of the command class
if (class_exists($this->getClassName())) {
// This class does exist. :-)
$isValid = true;
- } // END - if
+ }
// Set command name
$this->setCommandName($commandName);
// Import framework stuff
use Org\Mxchange\CoreFramework\Command\BaseCommand;
use Org\Mxchange\CoreFramework\Command\InvalidCommandException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
// Import SPL stuff
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
/**
* Creates an instance of a Console command resolver with a given default command
*
+ * @param $namespace Namespace of the command's class file
* @param $commandName The default command we shall execute
* @return $resolverInstance The prepared command resolver instance
* @throws InvalidArgumentException Thrown if default command is not set
* @throws InvalidCommandException Thrown if default command is invalid
*/
- public static final function createConsoleCommandResolver ($commandName) {
+ public static final function createConsoleCommandResolver (string $namespace, string $commandName) {
// Create the new instance
$resolverInstance = new ConsoleCommandResolver();
// Is the variable $commandName set and the command is valid?
- if (empty($commandName)) {
+ if (empty($namespace)) {
// Then thrown an exception here
- throw new InvalidArgumentException('Parameter "commandName" is empty');
- } elseif ($resolverInstance->isCommandValid($commandName) === false) {
+ throw new InvalidArgumentException('Parameter "namespace" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($commandName)) {
+ // Then thrown an exception here
+ throw new InvalidArgumentException('Parameter "commandName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$resolverInstance->isCommandValid($namespace, $commandName)) {
// Invalid command found
throw new InvalidCommandException(array($resolverInstance, $commandName), self::EXCEPTION_INVALID_COMMAND);
}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
// Import framework stuff
use Org\Mxchange\CoreFramework\Command\InvalidCommandException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
// Import SPL stuff
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
* @throws InvalidArgumentException Thrown if default command is not set
* @throws InvalidCommandException Thrown if default command is invalid
*/
- public static final function createHtmlCommandResolver ($commandName) {
+ public static final function createHtmlCommandResolver (string $commandName) {
// Create the new instance
$resolverInstance = new HtmlCommandResolver();
// Is the variable $commandName set and the command is valid?
if (empty($commandName)) {
// Then thrown an exception here
- throw new InvalidArgumentException('Parameter "commandName" is empty');
+ throw new InvalidArgumentException('Parameter "commandName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif ($resolverInstance->isCommandValid($commandName) === false) {
// Invalid command found
+ // @TODO Missing namespace!
throw new InvalidCommandException(array($resolverInstance, $commandName), self::EXCEPTION_INVALID_COMMAND);
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Command\InvalidCommandException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
// Import SPL stuff
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
* @throws InvalidArgumentException Thrown if default command is not set
* @throws InvalidCommandException Thrown if default command is invalid
*/
- public static final function createImageCommandResolver ($commandName) {
+ public static final function createImageCommandResolver (string $commandName) {
// Create the new instance
$resolverInstance = new ImageCommandResolver();
// Is the variable $commandName set and the command is valid?
if (empty($commandName)) {
// Then thrown an exception here
- throw new InvalidArgumentException('Parameter "commandName" is empty');
+ throw new InvalidArgumentException('Parameter "commandName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif ($resolverInstance->isCommandValid($commandName) === false) {
+ // @TODO Missing namespace!
// Invalid command found
throw new InvalidCommandException(array($resolverInstance, $commandName), self::EXCEPTION_INVALID_COMMAND);
}
namespace Org\Mxchange\CoreFramework\Resolver\Controller;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Controller\Controller;
use Org\Mxchange\CoreFramework\Controller\DefaultControllerException;
use Org\Mxchange\CoreFramework\Controller\InvalidControllerException;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Resolver\BaseResolver;
use Org\Mxchange\CoreFramework\Resolver\Controller\ControllerResolver;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
// Import SPL stuff
use \InvalidArgumentException;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseControllerResolver extends BaseResolver {
+ /**
+ * Controller name
+ */
+ private $controllerName = '';
+
/**
* Protected constructor
*
* @param $className Name of the real class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
+ /**
+ * Setter for controller name
+ *
+ * @param $controllerName Last validated controller name
+ * @return void
+ */
+ protected final function setControllerName (string $controllerName) {
+ $this->controllerName = $controllerName;
+ }
+
+ /**
+ * Getter for controller name
+ *
+ * @return $controllerName Last validated controller name
+ */
+ protected final function getControllerName () {
+ return $this->controllerName;
+ }
+
/**
* "Loads" a given controller and instances it if not yet cached. If the
* controller was not found one of the default controllers will be used
* @throws InvalidControllerException Thrown if even the requested
* controller class is missing (bad!)
*/
- protected function loadController ($controllerName) {
+ protected function loadController (string $controllerName) {
// Cache default controller
- $defaultController = $this->getConfigInstance()->getConfigEntry('default_' . strtolower($this->getClassPrefix()) . '_controller');
-
- // Init controller instance
- $controllerInstance = NULL;
+ $defaultController = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('default_' . strtolower($this->getClassPrefix()) . '_controller');
// Create full class name
$className = sprintf(
'%s\%s%sController',
$this->getNamespace(),
$this->getCapitalizedClassPrefix(),
- self::convertToClassName($controllerName)
+ StringUtils::convertToClassName($controllerName)
);
// ... and set it
// No news at main controller or non-news controller
$this->setClassName($className);
}
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('AFTER: controller=' . $this->getClassName());
// Is this class loaded?
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('AFTER: controller=' . $this->getClassName());
if (!class_exists($this->getClassName())) {
// Throw an exception here
throw new InvalidControllerException(array($this, $controllerName), self::EXCEPTION_INVALID_CONTROLLER);
- } // END - if
-
- // Set default resolver config name
- $resolverConfigEntry = '';
+ }
// Try to read a config entry for our resolver including controller name... ;-)
$resolverConfigEntry = sprintf('%s_cmd_%s_resolver_class', strtolower($this->getClassPrefix()), strtolower($controllerName));
// Get the config, this will throw an exception if there is no special controller resolver
- $resolverClass = $this->getConfigInstance()->getConfigEntry($resolverConfigEntry);
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-CONTROLLER-RESOLVER: resolverConfigEntry=%s', $resolverConfigEntry));
+ $resolverClass = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($resolverConfigEntry);
// Initiate the resolver and controller
$resolverInstance = ObjectFactory::createObjectByConfiguredName(
$resolverConfigEntry,
array(
$controllerName,
- GenericRegistry::getRegistry()->getInstance('application')
+ ApplicationHelper::getSelfInstance()
)
);
+
+ // Get controller instance
$controllerInstance = ObjectFactory::createObjectByName(
$this->getClassName(),
array($resolverInstance)
* @throws InvalidArgumentException Thrown if given controller is not set
* @throws DefaultControllerException Thrown if default controller was not found
*/
- protected function isControllerValid ($namespace, $controllerName) {
- // By default nothing shall be valid
- $isValid = false;
-
- // Is namespace and controller name set?
+ protected function isControllerValid (string $namespace, string $controllerName) {
+ // Is a action set?
if (empty($namespace)) {
// Then thrown an exception here
- throw new InvalidArgumentException('Parameter "namespace" is empty');
+ throw new InvalidArgumentException('Parameter "namespace" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif (empty($controllerName)) {
// Then thrown an exception here
- throw new InvalidArgumentException('Parameter "controllerName" is empty');
+ throw new InvalidArgumentException('Parameter "controllerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
}
+ // By default nothing shall be valid
+ $isValid = false;
+
// Create class name
$className = sprintf(
- '%s\%sController',
+ '%s\%s%sController',
$namespace,
- $this->getCapitalizedClassPrefix() . self::convertToClassName($controllerName)
+ $this->getCapitalizedClassPrefix(),
+ StringUtils::convertToClassName($controllerName)
);
- $newsControllerName = sprintf(
+
+ // Application's default news controller
+ $appDefaultControllerName = sprintf(
'%s\%sDefaultNewsController',
$namespace,
$this->getCapitalizedClassPrefix()
);
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('className=%s', $className));
+ // Framework's default news controller
+ $defaultControllerName = sprintf(
+ 'Org\Mxchange\CoreFramework\Controller\News\%sDefaultNewsController',
+ $this->getCapitalizedClassPrefix()
+ );
// Now, let us create the full name of the controller class
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('className=%s', $className));
$this->setClassName($className);
// Try it hard to get an controller
if (class_exists($this->getClassName())) {
// This class does exist. :-)
$isValid = true;
- } elseif ($this->getClassName() != $newsControllerName) {
- // Set default controller
- $this->setClassName($newsControllerName);
+ } elseif ($this->getClassName() != $appDefaultControllerName) {
+ // Set application's default controller
+ $this->setClassName($appDefaultControllerName);
+ } elseif ($this->getClassName() != $defaultControllerName) {
+ // Set framework's default controller
+ $this->setClassName($defaultControllerName);
} else {
// All is tried, give it up here
throw new DefaultControllerException($this, self::EXCEPTION_DEFAULT_CONTROLLER_GONE);
}
- } // END - while
+ }
// Return the result
return $isValid;
*/
public function resolveController () {
// Init variables
- $controllerName = '';
- $controllerInstance = NULL;
-
- // Get namespace and controller name
$controllerName = $this->getControllerName();
// Get the controller
if ((!is_object($controllerInstance)) || (!$controllerInstance instanceof Controller)) {
// This controller has an invalid instance!
throw new InvalidControllerInstanceException(array($this, $controllerName), self::EXCEPTION_INVALID_CONTROLLER);
- } // END - if
+ }
// Set last controller
$this->setResolvedInstance($controllerInstance);
// Import framework stuff
use Org\Mxchange\CoreFramework\Controller\BaseController;
use Org\Mxchange\CoreFramework\Controller\InvalidControllerException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Resolver\Controller\ControllerResolver;
use Org\Mxchange\CoreFramework\Resolver\Controller\BaseControllerResolver;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
* @throws InvalidArgumentException Thrown if default controller is not set
* @throws InvalidControllerException Thrown if default controller is invalid
*/
- public static final function createConsoleControllerResolver ($namespace, $controllerName) {
+ public static final function createConsoleControllerResolver (string $namespace, string $controllerName) {
// Create the new instance
$resolverInstance = new ConsoleControllerResolver();
// Is the variable $controllerName set and the controller is valid?
if (empty($namespace)) {
// Then thrown an exception here
- throw new InvalidArgumentException('Parameter "namespace" is empty');
+ throw new InvalidArgumentException('Parameter "namespace" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif (empty($controllerName)) {
// Then thrown an exception here
- throw new InvalidArgumentException('Parameter "controllerName" is empty');
+ throw new InvalidArgumentException('Parameter "controllerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif ($resolverInstance->isControllerValid($namespace, $controllerName) === false) {
// Invalid controller found
throw new InvalidControllerException(array($resolverInstance, $controllerName), self::EXCEPTION_INVALID_CONTROLLER);
// Import framework stuff
use Org\Mxchange\CoreFramework\Controller\BaseController;
use Org\Mxchange\CoreFramework\Controller\InvalidControllerException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Resolver\Controller\ControllerResolver;
use Org\Mxchange\CoreFramework\Resolver\Controller\BaseControllerResolver;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
* @throws InvalidArgumentException Thrown if default controller is not set
* @throws InvalidControllerException Thrown if default controller is invalid
*/
- public static final function createHtmlControllerResolver ($namespace, $controllerName) {
+ public static final function createHtmlControllerResolver (string $namespace, string $controllerName) {
// Create the new instance
$resolverInstance = new HtmlControllerResolver();
// Are all parameter set and the controller is valid?
if (empty($namespace)) {
// Then thrown an exception here
- throw new InvalidArgumentException('Parameter "namespace" is empty');
+ throw new InvalidArgumentException('Parameter "namespace" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif (empty($controllerName)) {
// Then thrown an exception here
- throw new InvalidArgumentException('Parameter "controllerName" is empty');
+ throw new InvalidArgumentException('Parameter "controllerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif ($resolverInstance->isControllerValid($namespace, $controllerName) === false) {
// Invalid controller found
throw new InvalidControllerException(array($resolverInstance, $controllerName), self::EXCEPTION_INVALID_CONTROLLER);
// Import framework stuff
use Org\Mxchange\CoreFramework\Controller\BaseController;
use Org\Mxchange\CoreFramework\Controller\InvalidControllerException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Resolver\Controller\ControllerResolver;
use Org\Mxchange\CoreFramework\Resolver\Controller\BaseControllerResolver;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
* @throws InvalidArgumentException Thrown if default controller is not set
* @throws InvalidControllerException Thrown if default controller is invalid
*/
- public static final function createImageControllerResolver ($namespace, $controllerName) {
+ public static final function createImageControllerResolver (string $namespace, string $controllerName) {
// Create the new instance
$resolverInstance = new ImageControllerResolver();
// Are all parameter set and the controller is valid?
if (empty($namespace)) {
// Then thrown an exception here
- throw new InvalidArgumentException('Parameter "namespace" is empty');
+ throw new InvalidArgumentException('Parameter "namespace" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif (empty($controllerName)) {
// Then thrown an exception here
- throw new InvalidArgumentException('Parameter "controllerName" is empty');
+ throw new InvalidArgumentException('Parameter "controllerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif ($resolverInstance->isControllerValid($namespace, $controllerName) === false) {
// Invalid controller found
throw new InvalidControllerException(array($resolverInstance, $controllerName), self::EXCEPTION_INVALID_CONTROLLER);
namespace Org\Mxchange\CoreFramework\Response;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
/**
* A generic request class
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* Array with all headers
*/
- private $responseHeaders = array();
+ private $responseHeaders = [];
/**
* Cookies we shall sent out
*/
- private $cookies = array();
+ private $cookies = [];
/**
* Body of the response
*/
private $responseBody = '';
- /**
- * Instance of the template engine
- */
- private $templateInstance = NULL;
-
/**
* Response type
*/
* @param $className Name of the concrete response
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
* @param $status New response status
* @return void
*/
- public final function setResponseStatus ($status) {
- $this->responseStatus = (string) $status;
+ public final function setResponseStatus (string $status) {
+ $this->responseStatus = $status;
}
/**
* @param $value Value of header element
* @return void
*/
- public final function addHeader ($name, $value) {
+ public final function addHeader (string $name, $value) {
$this->responseHeaders[$name] = $value;
}
* @return void
*/
public final function resetResponseHeaders () {
- $this->responseHeaders = array();
+ $this->responseHeaders = [];
}
/**
* @param $output Output we shall sent in the HTTP response
* @return void
*/
- public final function writeToBody ($output) {
+ public final function writeToBody (string $output) {
$this->responseBody .= $output;
}
* @param $responseType Response type
* @return void
*/
- protected final function setResponseType ($responseType) {
+ protected final function setResponseType (string $responseType) {
$this->responseType = $responseType;
}
* @param $messageId The message id we shall add
* @return void
*/
- public final function addFatalMessage ($messageId) {
- // Get application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
-
+ public final function addFatalMessage (string $messageId) {
// Adds the resolved message id to the fatal message list
- $this->addFatalMessagePlain($applicationInstance->getLanguageInstance()->getMessage($messageId));
+ $this->addFatalMessagePlain(FrameworkBootstrap::getLanguageInstance()->getMessage($messageId));
}
/**
* @param $message The plain message we shall add
* @return void
*/
- public final function addFatalMessagePlain ($message) {
+ public final function addFatalMessagePlain (string $message) {
// Adds the resolved message id to the fatal message list
$this->pushValueToGenericArrayKey('fatal_messages', 'generic', 'message', $message);
}
* @throws ResponseHeadersAlreadySentException Thrown if headers are
* already sent
*/
- public function flushBuffer ($force = false) {
+ public function flushBuffer (bool $force = false) {
// Get application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Headers already sent?
if ((headers_sent()) && ($force === false)) {
$this->addHeader('Pragma', 'no-cache'); // HTTP/1.0
// Define the charset to be used
- //$this->addHeader('Content-type:', sprintf("text/html; charset=%s", $this->getConfigInstance()->getConfigEntry('header_charset')));
+ //$this->addHeader('Content-type:', sprintf("text/html; charset=%s", FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('header_charset')));
// Send all headers
foreach ($this->responseHeaders as $name => $value) {
header($name . ': ' . $value);
//* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('name=' . $name . ',value=' . $value);
- } // END - foreach
+ }
// Send cookies out?
if (count($this->cookies) > 0) {
header('Set-Cookie: ' . $cookieString);
// Remove them all
- $this->cookies = array();
- } // END - if
+ $this->cookies = [];
+ }
}
// Are there some error messages?
*/
public function determineDefaultCommand () {
// Get application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Generate config key
$configKey = sprintf('default_%s_%s_command',
);
// Get default command response
- $defaultCommand = $this->getConfigInstance()->getConfigEntry($configKey);
+ $defaultCommand = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($configKey);
// Return it
return $defaultCommand;
namespace Org\Mxchange\CoreFramework\Response;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
use Org\Mxchange\CoreFramework\Response\Responseable;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
return $responseInstance;
}
- /**
- * Initializes the template engine instance
- *
- * @param $applicationInstance An instance of a manageable application
- * @return void
- */
- public final function initTemplateEngine (ManageableApplication $applicationInstance) {
- $this->setTemplateInstance($this->prepareTemplateInstance($applicationInstance));
- }
-
/**
* Adds a cookie to the response
*
* @return void
* @throws ResponseHeadersAlreadySentException If headers are already sent
*/
- public function addCookie ($cookieName, $cookieValue, $encrypted = false, $expires = NULL) {
+ public function addCookie (string $cookieName, $cookieValue, bool $encrypted = FALSE, int $expires = NULL) {
//* DEBUG: */ echo $cookieName.'='.$cookieValue."<br />\n";
- $this->partialStub('Naturally unimplemented in console response.');
+ DebugMiddleware::getSelfInstance()->partialStub('Naturally unimplemented in console response.');
}
/**
* @throws ResponseHeadersAlreadySentException If headers are already sent
*/
public function redirectToConfiguredUrl ($configEntry) {
- $this->partialStub('Naturally unimplemented in console response.');
+ DebugMiddleware::getSelfInstance()->partialStub('Naturally unimplemented in console response.');
}
/**
* @return void
*/
public function expireCookie ($cookieName) {
- $this->partialStub('Naturally unimplemented in console response.');
+ DebugMiddleware::getSelfInstance()->partialStub('Naturally unimplemented in console response.');
}
/**
* @return void
*/
public function refreshCookie ($cookieName) {
- $this->partialStub('Naturally unimplemented in console response.');
+ DebugMiddleware::getSelfInstance()->partialStub('Naturally unimplemented in console response.');
}
/**
* @throws ResponseHeadersAlreadySentException Thrown if headers are already sent
*/
public function flushBuffer ($force = false) {
- $this->partialStub('Please implement this class.');
+ DebugMiddleware::getSelfInstance()->partialStub('Please implement this class.');
}
}
namespace Org\Mxchange\CoreFramework\Response;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
+use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
use Org\Mxchange\CoreFramework\Response\Responseable;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
return $responseInstance;
}
- /**
- * Initializes the template engine instance
- *
- * @param $applicationInstance An instance of a manageable application
- * @return void
- */
- public final function initTemplateEngine (ManageableApplication $applicationInstance) {
- $this->setTemplateInstance($this->prepareTemplateInstance($applicationInstance));
- }
-
/**
* Adds a cookie to the response
*
* @return void
* @throws ResponseHeadersAlreadySentException If headers are already sent
* @todo Encryption of cookie data not yet supported.
- * @todo Why are these parameters conflicting?
* @todo If the return statement is removed and setcookie() commented out,
* @todo this will send only one cookie out, the first one.
*/
- public function addCookie ($cookieName, $cookieValue, $encrypted = false, $expires = NULL) {
+ public function addCookie (string $cookieName, $cookieValue, bool $encrypted = FALSE, int $expires = NULL) {
//* DEBUG: */ echo $cookieName.'='.$cookieValue."<br />\n";
// Are headers already sent?
if (headers_sent()) {
// Throw an exception here
//* DEBUG: */ return;
throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
- } // END - if
+ }
// Shall we encrypt the cookie?
- if ($encrypted === true) {
+ if ($encrypted) {
// Unsupported at the moment
- $this->partialStub('Encryption is unsupported at the moment.');
- } // END - if
+ DebugMiddleware::getSelfInstance()->partialStub('Encryption is unsupported at the moment.');
+ }
// For slow browsers set the cookie array element first
$_COOKIE[$cookieName] = $cookieValue;
// Get all config entries
if (is_null($expires)) {
- $expires = (time() + $this->getConfigInstance()->getConfigEntry('cookie_expire'));
- } // END - if
+ $expires = (time() + FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('cookie_expire'));
+ }
- $path = $this->getConfigInstance()->getConfigEntry('cookie_path');
- $domain = $this->getConfigInstance()->getConfigEntry('cookie_domain');
+ $path = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('cookie_path');
+ $domain = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('cookie_domain');
setcookie($cookieName, $cookieValue, $expires);
//, $path, $domain, (isset($_SERVER['HTTPS']))
*/
public function redirectToConfiguredUrl ($configEntry) {
// Get application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Is the header not yet sent?
if (headers_sent()) {
// Throw an exception here
throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
- } // END - if
+ }
// Assign application data
$this->getTemplateInstance()->assignApplicationData($applicationInstance);
// Get the url from config
- $url = $this->getConfigInstance()->getConfigEntry($configEntry . '_url');
+ $url = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($configEntry . '_url');
// Compile the URL
$url = $this->getTemplateInstance()->compileRawCode($url);
// Is there a / in front of the relative URL?
if (substr($url, 0, 1) == '/') {
$url = substr($url, 1);
- } // END - if
+ }
// No, then extend it with our base URL
- $url = $this->getConfigInstance()->getConfigEntry('base_url') . '/' . $url;
- } // END - if
+ $url = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('base_url') . '/' . $url;
+ }
// Add redirect header
$this->addHeader('Location', str_replace('&', '&', $url));
* @param $cookieName Cookie to expire
* @return void
*/
- public function expireCookie ($cookieName) {
+ public function expireCookie (string $cookieName) {
// Is the cookie there?
if (isset($_COOKIE[$cookieName])) {
// Then expire it with 20 minutes past
// Remove it from array
unset($_COOKIE[$cookieName]);
- } // END - if
+ }
}
/**
* @param $cookieName Cookie to refresh
* @return void
*/
- public function refreshCookie ($cookieName) {
+ public function refreshCookie (string $cookieName) {
// Only update existing cookies
if (isset($_COOKIE[$cookieName])) {
// Update the cookie
$this->addCookie($cookieName, $_COOKIE[$cookieName], false);
- } // END - if
+ }
}
}
namespace Org\Mxchange\CoreFramework\Response;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
+use Org\Mxchange\CoreFramework\Image\BaseImage;
+use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
use Org\Mxchange\CoreFramework\Response\Responseable;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* Michal Cihar <michal@cihar.com>, licensed under GNU GPL 2.0.
*/
class ImageResponse extends BaseResponse implements Responseable {
+ /**
+ * Instance of the image
+ */
+ private $imageInstance = NULL;
+
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
/**
- * Initializes the template engine instance
+ * Setter for image instance
*
- * @param $applicationInstance An instance of a manageable application
+ * @param $imageInstance An instance of an image
* @return void
*/
- public final function initTemplateEngine (ManageableApplication $applicationInstance) {
- // Get config instance
- $cfg = $this->getConfigInstance();
-
- // Set new template engine
- $cfg->setConfigEntry('html_template_class' , $cfg->getConfigEntry('image_template_class'));
- $cfg->setConfigEntry('raw_template_extension' , '.img');
- $cfg->setConfigEntry('code_template_extension', '.xml');
- $cfg->setConfigEntry('tpl_base_path' , 'templates/images/');
- // @TODO Please fix this
- $cfg->setConfigEntry('code_template_type' , 'image');
-
- // Get a prepared instance
- $this->setTemplateInstance($this->prepareTemplateInstance($applicationInstance));
+ public final function setImageInstance (BaseImage $imageInstance) {
+ $this->imageInstance = $imageInstance;
+ }
+
+ /**
+ * Getter for image instance
+ *
+ * @return $imageInstance An instance of an image
+ */
+ public final function getImageInstance () {
+ return $this->imageInstance;
}
/**
* @return void
* @throws ResponseHeadersAlreadySentException If headers are already sent
* @todo Encryption of cookie data not yet supported.
- * @todo Why are these parameters conflicting?
* @todo If the return statement is removed and setcookie() commented out,
* @todo this will send only one cookie out, the first one.
*/
- public function addCookie ($cookieName, $cookieValue, $encrypted = false, $expires = NULL) {
+ public function addCookie (string $cookieName, $cookieValue, bool $encrypted = FALSE, int $expires = NULL) {
// Are headers already sent?
if (headers_sent()) {
// Throw an exception here
throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
- } // END - if
+ }
// Shall we encrypt the cookie?
- if ($encrypted === true) {
+ if ($encrypted) {
// Unsupported at the moment
- $this->partialStub('Encryption is unsupported at the moment.');
- } // END - if
+ DebugMiddleware::getSelfInstance()->partialStub('Encryption is unsupported at the moment.');
+ }
// For slow browsers set the cookie array element first
$_COOKIE[$cookieName] = $cookieValue;
// Get all config entries
if (is_null($expires)) {
- $expires = (time() + $this->getConfigInstance()->getConfigEntry('cookie_expire'));
- } // END - if
+ $expires = (time() + FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('cookie_expire'));
+ }
- $path = $this->getConfigInstance()->getConfigEntry('cookie_path');
- $domain = $this->getConfigInstance()->getConfigEntry('cookie_domain');
+ $path = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('cookie_path');
+ $domain = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('cookie_domain');
setcookie($cookieName, $cookieValue, $expires);
//, $path, $domain, (isset($_SERVER['HTTPS']))
* @return void
* @throws ResponseHeadersAlreadySentException If headers are already sent
*/
- public function redirectToConfiguredUrl ($configEntry) {
+ public function redirectToConfiguredUrl (string $configEntry) {
// Get application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Is the header not yet sent?
if (headers_sent()) {
// Throw an exception here
throw new ResponseHeadersAlreadySentException($this, self::EXCEPTION_HEADERS_ALREADY_SENT);
- } // END - if
+ }
// Assign application data
$this->getTemplateInstance()->assignApplicationData($applicationInstance);
// Get the url from config
- $url = $this->getConfigInstance()->getConfigEntry($configEntry . '_url');
+ $url = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($configEntry . '_url');
// Compile the URL
$url = $this->getTemplateInstance()->compileRawCode($url);
if (substr($url, 0, 1) == '/') $url = substr($url, 1);
// No, then extend it with our base URL
- $url = $this->getConfigInstance()->getConfigEntry('base_url') . '/' . $url;
- } // END - if
+ $url = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('base_url') . '/' . $url;
+ }
// Add redirect header
$this->addHeader('Location', str_replace('&', '&', $url));
* already sent with an exception
* @return void
*/
- public function flushBuffer ($force = false) {
+ public function flushBuffer (bool $force = false) {
// Finish the image
$this->getImageInstance()->finishImage();
* @param $cookieName Cookie to expire
* @return void
*/
- public function expireCookie ($cookieName) {
+ public function expireCookie (string $cookieName) {
// Is the cookie there?
if (isset($_COOKIE[$cookieName])) {
// Then expire it with 20 minutes past
// Remove it from array
unset($_COOKIE[$cookieName]);
- } // END - if
+ }
}
/**
* @param $cookieName Cookie to refresh
* @return void
*/
- public function refreshCookie ($cookieName) {
+ public function refreshCookie (string $cookieName) {
// Only update existing cookies
if (isset($_COOKIE[$cookieName])) {
// Update the cookie
$this->addCookie($cookieName, $_COOKIE[$cookieName], false);
- } // END - if
+ }
}
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Name of this class
* @return void
*/
- protected function __construct ($className = __CLASS__) {
+ private function __construct () {
// Call parent constructor
- parent::__construct($className);
+ parent::__construct(__CLASS__);
}
/**
*/
protected function initRng ($extraInstance) {
// Get the prime number from config
- $this->prime = $this->getConfigInstance()->getConfigEntry('math_prime');
+ $this->prime = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('math_prime');
// Calculate the extra number which is always the same unless you give
// a better prime number
$serverIp = 'cluster';
// Do we have a single server?
- if ($this->getConfigInstance()->getConfigEntry('is_single_server') == 'Y') {
+ if (FrameworkBootstrap::getConfigurationInstance()->isEnabled('single_server')) {
// Then use that IP for extra security
$serverIp = FrameworkBootstrap::detectServerAddress();
- } // END - if
+ }
// Yet-another fixed salt. This is not dependend on server software or date
if ($extraInstance instanceof FrameworkInterface) {
$this->extraSalt = sha1(
$this->fixedSalt . ':' .
getenv('SERVER_SOFTWARE') . ':' .
- $this->getConfigInstance()->getConfigEntry('date_key') . ':' .
- $this->getConfigInstance()->getConfigEntry('base_url')
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('date_key') . ':' .
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('base_url')
);
// Get config entry for max salt length
- $this->rndStrLen = $this->getConfigInstance()->getConfigEntry('rnd_str_length');
+ $this->rndStrLen = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('rnd_str_length');
}
/**
// Is the number <1, then fix it to default length
if ($length < 1) {
$length = $this->rndStrLen;
- } // END - if
+ }
// Initialize the string
$randomString = '';
for ($idx = 0; $idx < $length; $idx++) {
// Add a random character and add it to our string
$randomString .= chr($this->randomNumber(0, 255));
- } // END - for
+ }
// Return the random string a little mixed up
return str_shuffle($randomString);
$key = md5($this->getExtraSalt());
// Get key
- if ($this->getConfigInstance()->getConfigEntry('crypt_fixed_salt') == 'Y') {
+ if (FrameworkBootstrap::getConfigurationInstance()->isEnabled('crypt_fixed_salt')) {
$key = md5($this->getFixedSalt());
- } // END - if
+ }
// Return it
return $key;
<?php
// Own namespace
-namespace CoreFramework\Stacker\!!!;
+namespace Org\Mxchange\CoreFramework\Stack\!!!;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Stacker\BaseStacker;
-use Org\Mxchange\CoreFramework\Stacker\Stackable;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+use Org\Mxchange\CoreFramework\Stack\BaseStacker;
+use Org\Mxchange\CoreFramework\Stack\Stackable;
/**
* A ??? Stacker class
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @throws StackerFullException If the stack is full
*/
public function pushNamed ($stackerName, $value) {
- $this->partialStub('stackerName=' . $stackerName . ',value[' . gettype($value) . ']=' . $value);
+ DebugMiddleware::getSelfInstance()->partialStub('stackerName=' . $stackerName . ',value[' . gettype($value) . ']=' . $value);
}
/**
* @throws EmptyStackerException If the named stacker is empty
*/
public function popNamed ($stackerName) {
- $this->partialStub('stackerName=' . $stackerName);
+ DebugMiddleware::getSelfInstance()->partialStub('stackerName=' . $stackerName);
}
/**
* @throws EmptyStackerException If the named stacker is empty
*/
public function getNamed ($stackerName) {
- $this->partialStub('stackerName=' . $stackerName);
+ DebugMiddleware::getSelfInstance()->partialStub('stackerName=' . $stackerName);
}
}
<?php
// Own namespace
-namespace Org\Mxchange\CoreFramework\Stacker;
+namespace Org\Mxchange\CoreFramework\Stack;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+// Import SPL stuff
+use \BadMethodCallException;
+use \InvalidArgumentException;
+
/**
* A general Stacker
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseStacker extends BaseFrameworkSystem {
- // Exception codes
- const EXCEPTION_STACKER_ALREADY_INITIALIZED = 0x050;
- const EXCEPTION_STACKER_IS_FULL = 0x051;
- const EXCEPTION_NO_STACKER_FOUND = 0x052;
- const EXCEPTION_STACKER_IS_EMPTY = 0x053;
+ /**
+ * Array "caches" configuration entries for saving "expensive" method
+ * invocations
+ */
+ private $cachedMaxStackSizes = [];
/**
* Protected constructor
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
* @param $stackerName Name of the stack
* @param $forceReInit Force re-initialization
* @return void
- * @throws AlreadyInitializedStackerException If the stack is already initialized
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If the stack is already initialized
*/
- public function initStack ($stackerName, $forceReInit = false) {
- // Is the stack already initialized?
- if (($forceReInit === false) && ($this->isStackInitialized($stackerName))) {
+ public function initStack (string $stackerName, bool $forceReInit = false) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: stackerName=%s,forceReInit=%d - CALLED!', $stackerName, intval($forceReInit)));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (($forceReInit === false) && ($this->isStackInitialized($stackerName))) {
// Then throw the exception
- throw new AlreadyInitializedStackerException(array($this, $stackerName, $forceReInit), self::EXCEPTION_STACKER_ALREADY_INITIALIZED);
- } // END - if
+ throw new BadMethodCallException(array($this, $stackerName, $forceReInit), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
- // Initialize the given stack
+ // Initialize the given stack and "cache" configuration entry
$this->initGenericArrayKey('stacks', $stackerName, 'entries', $forceReInit);
+ $this->cachedMaxStackSizes[$stackerName] = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry(sprintf('stacker_%s_max_size', $stackerName));
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-STACKER: EXIT!');
}
/**
* Initializes all stacks
*
* @return void
+ * @throws InvalidArgumentException If a parameter is invalid
*/
- public function initStacks (array $stacks, $forceReInit = false) {
+ public function initStacks (array $stacks, bool $forceReInit = false) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: stacks()=%d,forceReInit=%d - CALLED!', count($stacks), intval($forceReInit)));
+ if (count($stacks) == 0) {
+ // No empty stack name
+ throw new InvalidArgumentException('Array "stacks" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// "Walk" through all (more will be added as needed
foreach ($stacks as $stackerName) {
// Init this stack
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: Invoking this->initStack(%s,%d) ...', $stackerName, intval($forceReInit)));
$this->initStack($stackerName, $forceReInit);
- } // END - foreach
+ }
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-STACKER: EXIT!');
}
/**
*
* @param $stackerName Name of the stack
* @return $isInitialized Whether the stack is initialized
+ * @throws InvalidArgumentException If a parameter is invalid
*/
- public function isStackInitialized ($stackerName) {
+ public function isStackInitialized (string $stackerName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Is is there?
$isInitialized = ($this->isValidGenericArrayKey('stacks', $stackerName, 'entries'));
// Return result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: isInitialized=%d - EXIT!', intval($isInitialized)));
return $isInitialized;
}
*
* @param $stackerName Name of the stack
* @return $isFull Whether the stack is full
- * @throws NoStackerException If given stack is missing
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If given stack is missing
*/
- protected function isStackFull ($stackerName) {
- // Is the stack not yet initialized?
- if (!$this->isStackInitialized($stackerName)) {
+ protected function isStackFull (string $stackerName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isStackInitialized($stackerName)) {
// Throw an exception
- throw new NoStackerException(array($this, $stackerName), self::EXCEPTION_NO_STACKER_FOUND);
- } // END - if
+ throw new BadMethodCallException(sprintf('stackerName=%s not yet initialized but method called.', $stackerName), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// So, is the stack full?
- $isFull = (($this->getStackCount($stackerName)) == $this->getConfigInstance()->getConfigEntry('stacker_' . $stackerName . '_max_size'));
+ $isFull = (($this->getStackCount($stackerName)) == $this->cachedMaxStackSizes[$stackerName]);
// Return result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: isFull=%d - EXIT!', intval($isFull)));
return $isFull;
}
*
* @param $stackerName Name of the stack
* @return $isEmpty Whether the stack is empty
- * @throws NoStackerException If given stack is missing
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If given stack is missing
*/
- public function isStackEmpty ($stackerName) {
- // Is the stack not yet initialized?
- if (!$this->isStackInitialized($stackerName)) {
+ public function isStackEmpty (string $stackerName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isStackInitialized($stackerName)) {
// Throw an exception
- throw new NoStackerException(array($this, $stackerName), self::EXCEPTION_NO_STACKER_FOUND);
- } // END - if
+ throw new BadMethodCallException(sprintf('stackerName=%s not yet initialized but method called.', $stackerName), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// So, is the stack empty?
$isEmpty = (($this->getStackCount($stackerName)) == 0);
// Return result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: isEmpty=%d - EXIT!', intval($isEmpty)));
return $isEmpty;
}
*
* @param $stackerName Name of the stack
* @return $count Size of stack (array count)
- * @throws NoStackerException If given stack is missing
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If given stack is missing
*/
- public function getStackCount ($stackerName) {
- // Is the stack not yet initialized?
- if (!$this->isStackInitialized($stackerName)) {
+ public function getStackCount (string $stackerName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isStackInitialized($stackerName)) {
// Throw an exception
- throw new NoStackerException(array($this, $stackerName), self::EXCEPTION_NO_STACKER_FOUND);
- } // END - if
+ throw new BadMethodCallException(sprintf('stackerName=%s not yet initialized but method called.', $stackerName), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Now, count the array of entries
$count = $this->countGenericArrayElements('stacks', $stackerName, 'entries');
// Return result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: count=%d - EXIT!', $count));
return $count;
}
* @param $stackerName Name of the stack
* @param $value Value to add to this stacker
* @return void
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If given stack is missing
* @throws FullStackerException Thrown if the stack is full
*/
- protected function addValue ($stackerName, $value) {
- // Is the stack not yet initialized or full?
- if (!$this->isStackInitialized($stackerName)) {
- // Then do it here
- $this->initStack($stackerName);
+ protected function addValueToStack (string $stackerName, $value) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: stackerName=%s,value[]=%s - CALLED!', $stackerName, gettype($value)));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isStackInitialized($stackerName)) {
+ // Throw an exception
+ throw new BadMethodCallException(sprintf('stackerName=%s not yet initialized but method called.', $stackerName), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
} elseif ($this->isStackFull($stackerName)) {
// Stacker is full
- throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
+ throw new BadMethodCallException(sprintf('stackerName=%s is full but method called.', $stackerName), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
}
// Now add the value to the stack
$this->pushValueToGenericArrayKey('stacks', $stackerName, 'entries', $value);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-STACKER: EXIT!');
}
/**
*
* @param $stackerName Name of the stack
* @return $value Value of last added value
- * @throws NoStackerException If the named stacker was not found
- * @throws EmptyStackerException If the named stacker is empty
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If the named stacker was not found
+ * @throws BadMethodCallException If the named stacker is empty
*/
- protected function getLastValue ($stackerName) {
- // Is the stack not yet initialized or full?
- if (!$this->isStackInitialized($stackerName)) {
+ protected function getLastValue (string $stackerName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isStackInitialized($stackerName)) {
// Throw an exception
- throw new NoStackerException(array($this, $stackerName), self::EXCEPTION_NO_STACKER_FOUND);
+ throw new BadMethodCallException(sprintf('stackerName=%s not yet initialized but method called.', $stackerName), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
} elseif ($this->isStackEmpty($stackerName)) {
// Throw an exception
- throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
+ throw new BadMethodCallException(sprintf('stackerName=%s not yet initialized but method called.', $stackerName), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
}
+ // Calculate last index
+ $lastIndex = $this->getStackCount($stackerName) - 1;
+
// Now get the last value
- $value = $this->getGenericArrayElement('stacks', $stackerName, 'entries', $this->getStackCount($stackerName) - 1);
+ $value = $this->getGenericArrayElement('stacks', $stackerName, 'entries', $lastIndex);
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: value[]=%s - EXIT!', gettype($value)));
return $value;
}
*
* @param $stackerName Name of the stack
* @return $value Value of last added value
- * @throws NoStackerException If the named stacker was not found
- * @throws EmptyStackerException If the named stacker is empty
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If the named stacker was not found
+ * @throws BadMethodCallException If the named stacker is empty
*/
- protected function getFirstValue ($stackerName) {
- // Is the stack not yet initialized or full?
- if (!$this->isStackInitialized($stackerName)) {
+ protected function getFirstValue (string $stackerName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isStackInitialized($stackerName)) {
// Throw an exception
- throw new NoStackerException(array($this, $stackerName), self::EXCEPTION_NO_STACKER_FOUND);
+ throw new BadMethodCallException(sprintf('stackerName=%s not yet initialized but method called.', $stackerName), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
} elseif ($this->isStackEmpty($stackerName)) {
// Throw an exception
- throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
+ throw new BadMethodCallException(sprintf('stackerName=%s not yet initialized but method called.', $stackerName), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
}
// Now get the first value
- $value = $this->getGenericArrayElement('stacks', $stackerName, 'entries', 0);
+ $value = $this->getGenericArrayElement('stacks', $stackerName, 'entries', '0');
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: value[]=%s - EXIT!', gettype($value)));
return $value;
}
*
* @param $stackerName Name of the stack
* @return $value Value "poped" from array
- * @throws NoStackerException If the named stacker was not found
- * @throws EmptyStackerException If the named stacker is empty
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If the named stacker was not found
+ * @throws BadMethodCallException If the named stacker is empty
*/
- protected function popLast ($stackerName) {
- // Is the stack not yet initialized or full?
- if (!$this->isStackInitialized($stackerName)) {
+ protected function popLast (string $stackerName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isStackInitialized($stackerName)) {
// Throw an exception
- throw new NoStackerException(array($this, $stackerName), self::EXCEPTION_NO_STACKER_FOUND);
+ throw new BadMethodCallException(sprintf('stackerName=%s not yet initialized but method called.', $stackerName), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
} elseif ($this->isStackEmpty($stackerName)) {
// Throw an exception
- throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
+ throw new BadMethodCallException(sprintf('stackerName=%s is empty but method called.', $stackerName), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
}
// Now, remove the last entry, we don't care about the return value here, see elseif() block above
- return $this->popGenericArrayElement('stacks', $stackerName, 'entries');
+ $value = $this->popGenericArrayElement('stacks', $stackerName, 'entries');
+
+ // Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: value[]=%s - EXIT!', gettype($value)));
+ return $value;
}
/**
*
* @param $stackerName Name of the stack
* @return $value Value "shifted" from array
- * @throws NoStackerException If the named stacker was not found
- * @throws EmptyStackerException If the named stacker is empty
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If the named stacker was not found
+ * @throws BadMethodCallException If the named stacker is empty
*/
- protected function popFirst ($stackerName) {
- // Is the stack not yet initialized or full?
- if (!$this->isStackInitialized($stackerName)) {
+ protected function popFirst (string $stackerName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!$this->isStackInitialized($stackerName)) {
// Throw an exception
- throw new NoStackerException(array($this, $stackerName), self::EXCEPTION_NO_STACKER_FOUND);
+ throw new BadMethodCallException(sprintf('stackerName=%s not yet initialized but method called.', $stackerName), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
} elseif ($this->isStackEmpty($stackerName)) {
// Throw an exception
- throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
+ throw new BadMethodCallException(sprintf('stackerName=%s not yet initialized but method called.', $stackerName), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
}
// Now, remove the last entry, we don't care about the return value here, see elseif() block above
- return $this->shiftGenericArrayElement('stacks', $stackerName, 'entries');
+ $value = $this->shiftGenericArrayElement('stacks', $stackerName, 'entries');
+
+ // Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: value[]=%s - EXIT!', gettype($value)));
+ return $value;
}
}
<?php
// Own namespace
-namespace Org\Mxchange\CoreFramework\Stacker;
+namespace Org\Mxchange\CoreFramework\Stack;
+
+// Import framework-specific stuff
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+
+// Import SPL stuff
+use \InvalidArgumentException;
/**
* A FiFo Stacker class
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @param $stackerName Name of the stack
* @param $value Value to push on it
* @return void
- * @throws StackerFullException If the stack is full
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If the stack is full
*/
- public function pushNamed ($stackerName, $value) {
+ public function pushNamed (string $stackerName, $value) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: stackerName=%s,value[]=%s - CALLED!', $stackerName, gettype($value)));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Call the protected method
- parent::addValue($stackerName, $value);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: Invoking parent::addValueToStack(%s,%s) ...', $stackerName, gettype($value)));
+ parent::addValueToStack($stackerName, $value);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-STACKER: EXIT!');
}
/**
*
* @param $stackerName Name of the stack
* @return $value Value of the current stack entry
- * @throws NoStackerException If the named stacker was not found
- * @throws EmptyStackerException If the named stacker is empty
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If the named stacker was not found
+ * @throws BadMethodCallException If the named stacker is empty
*/
- public function popNamed ($stackerName) {
+ public function popNamed (string $stackerName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get the value
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: Invoking this->getNamed(%s) ...', $stackerName));
$value = $this->getNamed($stackerName);
// Call the protected method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: Invoking parent::popFirst(%s) ...', $stackerName));
parent::popFirst($stackerName);
// Return the value
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: value[]=%s - EXIT!', gettype($value)));
return $value;
}
*
* @param $stackerName Name of the stack
* @return $value Value of last added value
- * @throws NoStackerException If the named stacker was not found
- * @throws EmptyStackerException If the named stacker is empty
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If the named stacker was not found
+ * @throws BadMethodCallException If the named stacker is empty
*/
- public function getNamed ($stackerName) {
+ public function getNamed (string $stackerName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Call the protected method
- return parent::getFirstValue($stackerName);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: Invoking parent::getFirstValue(%s) ...', $stackerName));
+ $value = parent::getFirstValue($stackerName);
+
+ // Return value
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-STACKER: value[]=%s - EXIT!', gettype($value)));
+ return $value;
}
}
<?php
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+
/**
* A ??? file-based stack
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2017 Core Developer Team
+ * @copyright Copyright (c) 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @throws StackerFullException If the stack is full
*/
public function pushNamed ($stackerName, $value) {
- $this->partialStub('stackerName=' . $stackerName . ',value[' . gettype($value) . ']=' . $value);
+ DebugMiddleware::getSelfInstance()->partialStub('stackerName=' . $stackerName . ',value[' . gettype($value) . ']=' . $value);
}
/**
* @throws EmptyStackerException If the named stacker is empty
*/
public function popNamed ($stackerName) {
- $this->partialStub('stackerName=' . $stackerName);
+ DebugMiddleware::getSelfInstance()->partialStub('stackerName=' . $stackerName);
}
/**
* @throws EmptyStackerException If the named stacker is empty
*/
public function getNamed ($stackerName) {
- $this->partialStub('stackerName=' . $stackerName);
+ DebugMiddleware::getSelfInstance()->partialStub('stackerName=' . $stackerName);
}
/**
* @return void
*/
public function seek ($seekPosition) {
- $this->partialStub('seekPosition=' . $seekPosition);
+ DebugMiddleware::getSelfInstance()->partialStub('seekPosition=' . $seekPosition);
}
/**
* @return $size Size (in bytes) of file
*/
public function size () {
- $this->partialStub();
+ DebugMiddleware::getSelfInstance()->partialStub();
}
}
<?php
// Own namespace
-namespace Org\Mxchange\CoreFramework\Stacker\Filesystem;
+namespace Org\Mxchange\CoreFramework\Stack\File;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\Filesystem\Stack\FileStackIndexFactory;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Stack\File\FileStackIndexFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
+use Org\Mxchange\CoreFramework\Filesystem\File\BinaryFile;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
-use Org\Mxchange\CoreFramework\Iterator\Filesystem\SeekableWritableFileIterator;
-use Org\Mxchange\CoreFramework\Stacker\BaseStacker;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+use Org\Mxchange\CoreFramework\Stack\BaseStacker;
+use Org\Mxchange\CoreFramework\Traits\Index\IndexableTrait;
+use Org\Mxchange\CoreFramework\Traits\Iterator\IteratorTrait;
+use Org\Mxchange\CoreFramework\Utils\Arrays\ArrayUtils;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
// Import SPL stuff
+use \InvalidArgumentException;
use \SplFileInfo;
+use \UnexpectedValueException;
/**
* A general file-based stack class
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseFileStack extends BaseStacker {
- /**
- * Magic for this stack
- */
- const STACK_MAGIC = 'STACKv0.1';
+ // Load traits
+ use IndexableTrait;
+ use IteratorTrait;
- /**
- * Name of array index for gap position
- */
- const ARRAY_INDEX_GAP_POSITION = 'gap';
+ // Exception codes
+ const EXCEPTION_BAD_MAGIC = 0xe100;
/**
- * Name of array index for hash
+ * Minimum block length
*/
- const ARRAY_INDEX_HASH = 'hash';
-
- /**
- * Name of array index for length of raw data
- */
- const ARRAY_INDEX_DATA_LENGTH = 'length';
+ private static $minimumBlockLength = 0;
/**
* Protected constructor
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
*
* @return void
* @todo To hard assertions here, better rewrite them to exceptions
+ * @throws UnexpectedValueException If header is not proper length
+ * @throws InvalidMagicException If a bad magic was found
*/
- public function readFileHeader () {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
-
+ public function readStackHeader () {
// First rewind to beginning as the header sits at the beginning ...
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: CALLED!');
$this->getIteratorInstance()->rewind();
+ // Get header size
+ $headerSize = $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize();
+
// Then read it (see constructor for calculation)
- $data = $this->getIteratorInstance()->read($this->getIteratorInstance()->getHeaderSize());
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Read %d bytes (%d wanted).', __METHOD__, __LINE__, strlen($data), $this->getIteratorInstance()->getHeaderSize()));
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: headerSize=%d', $headerSize));
+ $data = $this->getIteratorInstance()->getBinaryFileInstance()->read($headerSize);
// Have all requested bytes been read?
- assert(strlen($data) == $this->getIteratorInstance()->getHeaderSize());
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Read %d bytes (%d wanted).', strlen($data), $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize()));
+ if (strlen($data) != $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize()) {
+ // Bad data length
+ throw new UnexpectedValueException(sprintf('data(%d)=%s does not match iteratorInstance->headerSize=%d',
+ strlen($data),
+ $data,
+ $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize()
+ ), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ } elseif (empty(trim($data, chr(0)))) {
+ // Empty header, file is freshly pre-allocated
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Empty file header detected - EXIT!');
+ return;
+ }
// Last character must be the separator
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] data(-1)=%s', __METHOD__, __LINE__, dechex(ord(substr($data, -1, 1)))));
- assert(substr($data, -1, 1) == chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES));
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: data(-1)=0x%s', dechex(ord(substr($data, -1, 1)))));
+ if (substr($data, -1, 1) !== chr(BinaryFile::SEPARATOR_HEADER_ENTRIES)) {
+ // Not valid separator
+ throw new UnexpectedValueException(sprintf('data=%s does not have separator=0x%s at the end.',
+ $data,
+ dechex(BinaryFile::SEPARATOR_HEADER_ENTRIES)
+ ), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// Okay, then remove it
$data = substr($data, 0, -1);
// And update seek position
- $this->getIteratorInstance()->updateSeekPosition();
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Invoking this->iteratorInstance->binaryFileInstance->updateSeekPosition() ...');
+ $this->getIteratorInstance()->getBinaryFileInstance()->updateSeekPosition();
/*
* Now split it:
* 1 => total entries
* 2 => current seek position
*/
- $header = explode(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA), $data);
+ $header = explode(chr(BinaryFile::SEPARATOR_HEADER_DATA), $data);
- // Set header here
- $this->getIteratorInstance()->setHeader($header);
+ // Map numeric indexes to associative indexes
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Invoking ArrayUtils::mapNumericKeysToAssociative(%d) ...', count($header)));
+ $header = ArrayUtils::mapNumericKeysToAssociative($header, [
+ BinaryFile::HEADER_NAME_MAGIC,
+ BinaryFile::HEADER_NAME_TOTAL_ENTRIES,
+ BinaryFile::HEADER_NAME_SEEK_POSITION,
+ ]);
// Check if the array has only 3 elements
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] header(%d)=%s', __METHOD__, __LINE__, count($header), print_r($header, true)));
- assert(count($header) == 3);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
-
- // Check magic
- assert($header[0] == self::STACK_MAGIC);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
-
- // Check length of count and seek position
- assert(strlen($header[1]) == BaseBinaryFile::LENGTH_COUNT);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
- assert(strlen($header[2]) == BaseBinaryFile::LENGTH_POSITION);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] Passed assert().', __METHOD__, __LINE__));
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: HEADER_STACK_ELEMENT_COUNT=%d,header()=%d', BinaryFile::HEADER_STACK_ELEMENT_COUNT, count($header)));
+ //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: HEADER_STACK_ELEMENT_COUNT=%d,header(%d)=%s', BinaryFile::HEADER_STACK_ELEMENT_COUNT, count($header), print_r($header, true)));
+ if (count($header) != BinaryFile::HEADER_STACK_ELEMENT_COUNT) {
+ // Header array count is not expected
+ throw new UnexpectedValueException(sprintf('data=%s has %d elements, but expected is %d',
+ $data,
+ count($header),
+ BinaryFile::HEADER_STACK_ELEMENT_COUNT
+ ), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ } elseif ($header[BinaryFile::HEADER_NAME_MAGIC] != StackableFile::STACK_MAGIC) {
+ // Bad magic
+ throw new InvalidMagicException($data, self::EXCEPTION_BAD_MAGIC);
+ } elseif (strlen($header[BinaryFile::HEADER_NAME_TOTAL_ENTRIES]) != BinaryFile::LENGTH_COUNT) {
+ // Count length not valid
+ throw new UnexpectedValueException(sprintf('header[%s](%d)=%s is not expected %d length',
+ BinaryFile::HEADER_NAME_TOTAL_ENTRIES,
+ strlen($header[BinaryFile::HEADER_NAME_TOTAL_ENTRIES]),
+ $header[BinaryFile::HEADER_NAME_TOTAL_ENTRIES],
+ BinaryFile::LENGTH_COUNT
+ ), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ } elseif (strlen($header[BinaryFile::HEADER_NAME_SEEK_POSITION]) != BinaryFile::LENGTH_POSITION) {
+ // Position length not valid
+ throw new UnexpectedValueException(sprintf('header[%s](%d)=%s is not expected %d length',
+ BinaryFile::HEADER_NAME_SEEK_POSITION,
+ strlen($header[BinaryFile::HEADER_NAME_SEEK_POSITION]),
+ $header[BinaryFile::HEADER_NAME_SEEK_POSITION],
+ BinaryFile::LENGTH_POSITION
+ ), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// Decode count and seek position
- $header[1] = hex2bin($header[1]);
- $header[2] = hex2bin($header[2]);
+ $header[BinaryFile::HEADER_NAME_TOTAL_ENTRIES] = hex2bin($header[BinaryFile::HEADER_NAME_TOTAL_ENTRIES]);
+ $header[BinaryFile::HEADER_NAME_SEEK_POSITION] = hex2bin($header[BinaryFile::HEADER_NAME_SEEK_POSITION]);
+
+ // Set header here
+ $this->getIteratorInstance()->getBinaryFileInstance()->setHeader($header);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: EXIT!');
}
/**
* @return void
*/
public function flushFileHeader () {
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
-
// Put all informations together
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: CALLED!');
$header = sprintf('%s%s%s%s%s%s',
// Magic
- self::STACK_MAGIC,
+ StackableFile::STACK_MAGIC,
// Separator magic<->count
- chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
+ chr(BinaryFile::SEPARATOR_HEADER_DATA),
- // Total entries (will be zero) and pad it to 20 chars
- str_pad($this->dec2hex($this->getIteratorInstance()->getCounter()), BaseBinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
+ // Padded total entries
+ str_pad(StringUtils::dec2hex($this->getIteratorInstance()->getBinaryFileInstance()->getCounter()), BinaryFile::LENGTH_COUNT, '0', STR_PAD_LEFT),
// Separator count<->seek position
- chr(BaseBinaryFile::SEPARATOR_HEADER_DATA),
+ chr(BinaryFile::SEPARATOR_HEADER_DATA),
- // Position (will be zero)
- str_pad($this->dec2hex($this->getIteratorInstance()->getSeekPosition(), 2), BaseBinaryFile::LENGTH_POSITION, '0', STR_PAD_LEFT),
+ // Padded seek position
+ str_pad(StringUtils::dec2hex($this->getIteratorInstance()->getBinaryFileInstance()->getSeekPosition(), 2), BinaryFile::LENGTH_POSITION, '0', STR_PAD_LEFT),
// Separator position<->entries
- chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES)
+ chr(BinaryFile::SEPARATOR_HEADER_ENTRIES)
);
// Write it to disk (header is always at seek position 0)
- $this->getIteratorInstance()->writeData(0, $header, false);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Invoking this->iteratorInstance->writeAtPosition(0, header=%s) ...', $header));
+ $this->getIteratorInstance()->getBinaryFileInstance()->writeAtPosition(0, $header);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: EXIT!');
}
/**
* @param $fileInfoInstance An instance of a SplFileInfo class
* @param $type Type of this stack (e.g. url_source for URL sources)
* @return void
+ * @throws InvalidArgumentException If a parameter is invalid
* @todo Currently the stack file is not cached, please implement a memory-handling class and if enough RAM is found, cache the whole stack file.
*/
- protected function initFileStack (SplFileInfo $fileInfoInstance, $type) {
+ protected function initFileStack (SplFileInfo $fileInfoInstance, string $type) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: fileInfoInstance[%s]=%s,type=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance, $type));
+ if (empty($type)) {
+ // Invalid parameter
+ throw new InvalidArgumentException('Parameter "type" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get a stack file instance
- $fileInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileInfoInstance, $this));
+ $stackInstance = ObjectFactory::createObjectByConfiguredName('stack_file_class', array($fileInfoInstance, $this));
// Get iterator instance
- $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($fileInstance));
-
- // Is the instance implementing the right interface?
- assert($iteratorInstance instanceof SeekableWritableFileIterator);
+ $iteratorInstance = ObjectFactory::createObjectByConfiguredName('file_iterator_class', array($stackInstance));
// Set iterator here
$this->setIteratorInstance($iteratorInstance);
// Calculate header size
- $this->getIteratorInstance()->setHeaderSize(
- strlen(self::STACK_MAGIC) +
- strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
- BaseBinaryFile::LENGTH_COUNT +
- strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_DATA)) +
- BaseBinaryFile::LENGTH_POSITION +
- strlen(chr(BaseBinaryFile::SEPARATOR_HEADER_ENTRIES))
+ $headerSize = (
+ strlen(StackableFile::STACK_MAGIC) +
+ strlen(chr(BinaryFile::SEPARATOR_HEADER_DATA)) +
+ BinaryFile::LENGTH_COUNT +
+ strlen(chr(BinaryFile::SEPARATOR_HEADER_DATA)) +
+ BinaryFile::LENGTH_POSITION +
+ strlen(chr(BinaryFile::SEPARATOR_HEADER_ENTRIES))
);
- // Init counters and gaps array
- $this->getIteratorInstance()->initCountersGapsArray();
-
- // Is the file's header initialized?
- if (!$this->getIteratorInstance()->isFileHeaderInitialized()) {
- // No, then create it (which may pre-allocate the stack)
- $this->getIteratorInstance()->createFileHeader();
+ // Setting it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Setting headerSize=%d ...', $headerSize));
+ $this->getIteratorInstance()->getBinaryFileInstance()->setHeaderSize($headerSize);
- // And pre-allocate a bit
- $this->getIteratorInstance()->preAllocateFile('file_stack');
- } // END - if
-
- // Load the file header
- $this->readFileHeader();
-
- // Count all entries in file
- $this->getIteratorInstance()->analyzeFile();
+ // Init counters and gaps array
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Invoking this->iteratorInstance->initCountersGapsArray() ...');
+ $this->getIteratorInstance()->getBinaryFileInstance()->initCountersGapsArray();
/*
* Get stack index instance. This can be used for faster
* "defragmentation" and startup.
*/
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Creating index instance for fileInfoInstance[%s]=%s,type=%s ...', get_class($fileInfoInstance), $fileInfoInstance, $type));
$indexInstance = FileStackIndexFactory::createFileStackIndexInstance($fileInfoInstance, $type);
// And set it here
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: indexInstance=%s', $indexInstance->__toString()));
$this->setIndexInstance($indexInstance);
+
+ // Is the file's header initialized?
+ if (!$this->getIteratorInstance()->getBinaryFileInstance()->isFileHeaderInitialized()) {
+ // First pre-allocate a bit
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Invoking this->iteratorInstance->preAllocateFile(file_stack) ...');
+ $this->getIteratorInstance()->getBinaryFileInstance()->preAllocateFile('file_stack');
+
+ // Then create file header
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: this->iteratorInstance->createFileHeader() ...');
+ $this->getIteratorInstance()->getBinaryFileInstance()->createFileHeader();
+ }
+
+ // Load the file header
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Invoking this->readStackHeader() ...');
+ $this->readStackHeader();
+
+ // Is the index loaded correctly, e.g. the stack file is just created?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Invoking this->indexInstance->isIndexLoaded() ...');
+ if (!$this->getIndexInstance()->isIndexLoaded()) {
+ /*
+ * Something horrible has happened to the index as it should be
+ * loaded at this point. The stack's file structure then needs to
+ * be analyzed and the index rebuild.
+ */
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Invoking this->iteratorInstance->analyzeFileStructure() ...');
+ $this->getIteratorInstance()->getBinaryFileInstance()->analyzeFileStructure();
+
+ // Rebuild index from file
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Invoking this->iteratorInstance->rebuildIndexFromStack(%s) ...', $this->__toString()));
+ $this->getIndexInstance()->rebuildIndexFromStack($this);
+ }
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: EXIT!');
}
/**
* @param $value Value to add to this stacker
* @return void
* @throws FullStackerException If the stack is full
- */
- protected function addValue ($stackerName, $value) {
- // Do some tests
- if ($this->isStackFull($stackerName)) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws InvalidArgumentException Not all variable types are wanted here
+ */
+ protected function addValueToStack (string $stackerName, $value) {
+ // Validate parameter
+ /* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s,value[]=%s - CALLED!', $stackerName, gettype($value)));
+ //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s,value[%s]=%s', $stackerName, gettype($value), print_r($value, true)));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($this->isStackFull($stackerName)) {
// Stacker is full
- throw new FullStackerException(array($this, $stackerName, $value), self::EXCEPTION_STACKER_IS_FULL);
- } // END - if
-
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName . ',value[' . gettype($value) . ']=' . print_r($value, true));
-
- // No objects/resources are allowed as their serialization takes to long
- assert(!is_object($value));
- assert(!is_resource($value));
+ throw new BadMethodCallException(sprintf('stackerName=%s is full but method call.', $stackerName), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ } elseif (is_resource($value) || is_object($value)) {
+ // Not wanted type
+ throw new InvalidArgumentException(sprintf('value[]=%s is not supported', gettype($value)));
+ }
/*
* Now add the value to the file stack which returns gap position, a
* hash and length of the raw data.
*/
- $data = $this->getIteratorInstance()->writeValueToFile($stackerName, $value);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Invoking this->iteratorInstance->binaryFileInstance->writeValueToFile(%s,value[]=%s) ...', $stackerName, gettype($value)));
+ $data = $this->getIteratorInstance()->getBinaryFileInstance()->writeValueToFile($stackerName, $value);
// Add the hash and gap position to the index
- $this->getIndexInstance()->addHashToIndex($stackerName, $data);
+ //* PRINTR-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: data=%s', print_r($data, true));
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: Invoking this->indexInstance->addHashedDataToIndex(%s,data()=%d) ...', $stackerName, count($data)));
+ $this->getIndexInstance()->addHashedDataToIndex($stackerName, $data);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: EXIT!');
}
/**
*
* @param $stackerName Name of the stack
* @return $value Value of last added value
- * @throws EmptyStackerException If the stack is empty
- */
- protected function getLastValue ($stackerName) {
- // Is the stack not yet initialized or full?
- if ($this->isStackEmpty($stackerName)) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If the stack is empty
+ */
+ protected function getLastValue (string $stackerName) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($this->isStackEmpty($stackerName)) {
// Throw an exception
- throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
- } // END - if
+ throw new BadMethodCallException([$this, $stackerName], FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Now get the last value
- /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
+ /* NOISY-DEBUG: */ DebugMiddleware::getSelfInstance()->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
$value = NULL;
// Return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: value[]=%s - EXIT!', gettype($value)));
return $value;
}
*
* @param $stackerName Name of the stack
* @return $value Value of last added value
- * @throws EmptyStackerException If the stack is empty
- */
- protected function getFirstValue ($stackerName) {
- // Is the stack not yet initialized or full?
- if ($this->isStackEmpty($stackerName)) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If the stack is empty
+ */
+ protected function getFirstValue (string $stackerName) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($this->isStackEmpty($stackerName)) {
// Throw an exception
- throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
- } // END - if
+ throw new BadMethodCallException([$this, $stackerName], FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Now get the first value
- /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
+ /* NOISY-DEBUG: */ DebugMiddleware::getSelfInstance()->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
$value = NULL;
// Return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: value[]=%s - EXIT!', gettype($value)));
return $value;
}
*
* @param $stackerName Name of the stack
* @return $value Value "poped" from array
- * @throws EmptyStackerException If the stack is empty
- */
- protected function popLast ($stackerName) {
- // Is the stack not yet initialized or full?
- if ($this->isStackEmpty($stackerName)) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If the stack is empty
+ */
+ protected function popLast (string $stackerName) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($this->isStackEmpty($stackerName)) {
// Throw an exception
- throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
- } // END - if
+ throw new BadMethodCallException([$this, $stackerName], FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Now, remove the last entry, we don't care about the return value here, see elseif() block above
- /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
+ /* NOISY-DEBUG: */ DebugMiddleware::getSelfInstance()->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
return NULL;
}
*
* @param $stackerName Name of the stack
* @return $value Value "shifted" from array
- * @throws EmptyStackerException If the named stacker is empty
- */
- protected function popFirst ($stackerName) {
- // Is the stack not yet initialized or full?
- if ($this->isStackEmpty($stackerName)) {
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If the named stacker is empty
+ */
+ protected function popFirst (string $stackerName) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($this->isStackEmpty($stackerName)) {
// Throw an exception
- throw new EmptyStackerException(array($this, $stackerName), self::EXCEPTION_STACKER_IS_EMPTY);
- } // END - if
+ throw new BadMethodCallException([$this, $stackerName], FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Now, remove the last entry, we don't care about the return value here, see elseif() block above
- /* NOISY-DEBUG: */ $this->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
+ /* NOISY-DEBUG: */ DebugMiddleware::getSelfInstance()->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
return NULL;
}
*
* @param $stackerName Name of the stack
* @return $isFull Whether the stack is full
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- protected function isStackFull ($stackerName) {
- // File-based stacks will only run full if the disk space is low.
+ protected function isStackFull (string $stackerName) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// @TODO Please implement this, returning false
+ /* NOISY-DEBUG: */ DebugMiddleware::getSelfInstance()->partialStub('[' . __METHOD__ . ':' . __LINE__ . '] stackerName=' . $stackerName);
$isFull = false;
// Return result
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: isFull=%d - EXIT!', intval($isFull)));
return $isFull;
}
*
* @param $stackerName Name of the stack
* @return $isEmpty Whether the stack is empty
- * @throws NoStackerException If given stack is missing
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws BadMethodCallException If given stack is missing
*/
- public function isStackEmpty ($stackerName) {
+ public function isStackEmpty (string $stackerName) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// So, is the stack empty?
$isEmpty = (($this->getStackCount($stackerName)) == 0);
// Return result
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: isEmpty=%d - EXIT!', intval($isEmpty)));
return $isEmpty;
}
- /**
- * Initializes given stacker
- *
- * @param $stackerName Name of the stack
- * @param $forceReInit Force re-initialization
- * @return void
- * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
- */
- public function initStack ($stackerName, $forceReInit = false) {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
- /**
- * Initializes all stacks
- *
- * @return void
- * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
- */
- public function initStacks (array $stacks, $forceReInit = false) {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
/**
* Checks whether the given stack is initialized (set in array $stackers)
*
* @return $isInitialized Whether the stack is initialized
* @throws UnsupportedOperationException This method is not (and maybe never will be) supported
*/
- public function isStackInitialized ($stackerName) {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
+ public function isStackInitialized (string $stackerName) {
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException This method is not (and maybe never will be) supported
*/
public function isEndOfFileReached () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @param $stackerName Name of the stack
* @return $count Size of stack (array count)
*/
- public function getStackCount ($stackerName) {
+ public function getStackCount (string $stackerName) {
// Now, simply return the found count value, this must be up-to-date then!
- return $this->getIteratorInstance()->getCounter();
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
+ $count = $this->getIteratorInstance()->getBinaryFileInstance()->getCounter();
+
+ // Return count
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: count=%d - EXIT!', $count));
+ return $count;
}
/**
* @return $length Minimum length for one entry/block
*/
public function calculateMinimumBlockLength () {
- // Calulcate it
- $length =
- // Length of entry group
- BaseBinaryFile::LENGTH_GROUP + strlen(chr(BaseBinaryFile::SEPARATOR_GROUP_HASH)) +
- // Hash + value
- self::getHashLength() + strlen(chr(BaseBinaryFile::SEPARATOR_HASH_VALUE)) + 1 +
- // Final separator
- strlen(chr(BaseBinaryFile::SEPARATOR_ENTRIES));
+ // Is the value "cached"?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: CALLED!');
+ if (self::$minimumBlockLength == 0) {
+ // Calulcate it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: Calculating ...');
+ self::$minimumBlockLength =
+ // Length of entry group
+ BinaryFile::LENGTH_GROUP + strlen(chr(BinaryFile::SEPARATOR_GROUP_HASH)) +
+ // Hash + value
+ self::getHashLength() + strlen(chr(BinaryFile::SEPARATOR_HASH_VALUE)) + 1 +
+ // Final separator
+ strlen(chr(BinaryFile::SEPARATOR_ENTRIES));
+ }
// Return it
- return $length;
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: self::minimumBlockLength=%d - EXIT!', self::$minimumBlockLength));
+ return self::$minimumBlockLength;
}
/**
* Initializes counter for valid entries, arrays for damaged entries and
* an array for gap seek positions. If you call this method on your own,
* please re-analyze the file structure. So you are better to call
- * analyzeFile() instead of this method.
+ * analyzeFileStructure() instead of this method.
*
* @return void
* @throws UnsupportedOperationException This method is not (and maybe never will be) supported
*/
public function initCountersGapsArray () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException This method is not (and maybe never will be) supported
*/
public final function getHeaderSize () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @return void
* @throws UnsupportedOperationException This method is not (and maybe never will be) supported
*/
- public final function setHeaderSize ($headerSize) {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
+ public final function setHeaderSize (int $headerSize) {
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException This method is not (and maybe never will be) supported
*/
public final function getHeader () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException This method is not (and maybe never will be) supported
*/
public final function setHeader (array $header) {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException This method is not (and maybe never will be) supported
*/
public function updateSeekPosition () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @throws UnsupportedOperationException This method is not (and maybe never will be) supported
*/
public final function getCounter () {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @return void
* @throws UnsupportedOperationException This method is not (and maybe never will be) supported
*/
- public function writeData ($seekPosition, $data, $flushHeader = true) {
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] seekPosition=%s,data[]=%s,flushHeader=%d', __METHOD__, __LINE__, $seekPosition, gettype($data), intval($flushHeader)));
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
+ public function writeData (int $seekPosition, string $data, bool $flushHeader = true) {
+ // Not supported
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
+ }
+
+ /**
+ * Writes at given position by seeking to it.
+ *
+ * @param $seekPosition Seek position in file
+ * @param $dataStream Data to be written
+ * @return mixed Number of writes bytes or false on error
+ * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
+ */
+ public function writeAtPosition (int $seekPosition, string $dataStream) {
+ // Not supported
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* Writes given value to the file and returns a hash and gap position for it
*
- * @param $groupId Group identifier
+ * @param $stackName Group identifier
* @param $value Value to be added to the stack
* @return $data Hash and gap position
* @throws UnsupportedOperationException This method is not (and maybe never will be) supported
*/
- public function writeValueToFile ($groupId, $value) {
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,value[%s]=%s', __METHOD__, __LINE__, $groupId, gettype($value), print_r($value, true)));
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
+ public function writeValueToFile (string $stackName, $value) {
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @return $seekPosition Found next gap's seek position
* @throws UnsupportedOperationException This method is not (and maybe never will be) supported
*/
- public function searchNextGap ($length) {
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] length=%s', __METHOD__, __LINE__, $length));
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getPointerInstance()), self::EXCEPTION_UNSPPORTED_OPERATION);
+ public function searchNextGap (int $length) {
+ // Not supported here
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $this->getIteratorInstance()->getBinaryFileInstance()), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
*/
public function getFileSize () {
// Call iterator's method
- return $this->getIteratorInstance()->getFileSize();
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FILE-STACK: CALLED!');
+ $size = $this->getIteratorInstance()->getBinaryFileInstance()->getFileSize();
+
+ // Return size
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: size=%d - EXIT!', $size));
+ return $size;
}
/**
* Writes given raw data to the file and returns a gap position and length
*
- * @param $groupId Group identifier
+ * @param $stackName Group identifier
* @param $hash Hash from encoded value
* @param $encoded Encoded value to be written to the file
* @return $data Gap position and length of the raw data
- */
- public function writeDataToFreeGap ($groupId, $hash, $encoded) {
- // Debug message
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,encoded()=%d - CALLED!', __METHOD__, __LINE__, $groupId, $hash, strlen($encoded)));
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ */
+ public function writeDataToFreeGap (string $stackName, string $hash, string $encoded) {
+ // Check parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackName=%s,hash{}=0x%s,encoded()=%d - CALLED!', $stackName, bin2hex($hash), strlen($encoded)));
+ if (empty($stackName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "stackName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($hash)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "hash" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($encoded)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "encoded" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
// Raw data been written to the file
$rawData = sprintf('%s%s%s%s%s',
- $groupId,
- BaseBinaryFile::SEPARATOR_GROUP_HASH,
- hex2bin($hash),
- BaseBinaryFile::SEPARATOR_HASH_VALUE,
+ $stackName,
+ BinaryFile::SEPARATOR_GROUP_HASH,
+ $hash,
+ BinaryFile::SEPARATOR_HASH_VALUE,
$encoded
);
- // Debug message
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
-
// Search for next free gap
- $gapPosition = $this->getIteratorInstance()->searchNextGap(strlen($rawData));
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackName=%s,hash{}=0x%s,rawData()=%d', $stackName, bin2hex($hash), strlen($rawData)));
+ $gapPosition = $this->getIteratorInstance()->getBinaryFileInstance()->searchNextGap(strlen($rawData));
// Gap position cannot be smaller than header length + 1
- assert($gapPosition > $this->getIteratorInstance()->getHeaderSize());
-
- // Debug message
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,gapPosition=%s', __METHOD__, __LINE__, $groupId, $hash, $gapPosition));
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: gapPosition=%d', $gapPosition));
+ if ($gapPosition <= $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize()) {
+ // Improper gap position
+ throw new UnexpectedValueException(sprintf('gapPosition[%s]=%d is not larger than headerSize=%d',
+ gettype($gapPosition),
+ $gapPosition,
+ $this->getIteratorInstance()->getBinaryFileInstance()->getHeaderSize()
+ ), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// Then write the data at that gap
- $this->getIteratorInstance()->writeData($gapPosition, $rawData);
-
- // Debug message
- /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:%d:] groupId=%s,hash=%s,rawData()=%d - EXIT!', __METHOD__, __LINE__, $groupId, $hash, strlen($rawData)));
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackName=%s,hash{}=0x%s,gapPosition=%s', $stackName, bin2hex($hash), $gapPosition));
+ $this->getIteratorInstance()->getBinaryFileInstance()->writeData($gapPosition, $rawData);
// Return gap position, hash and length of raw data
- return array(
- self::ARRAY_INDEX_GAP_POSITION => $gapPosition,
- self::ARRAY_INDEX_HASH => $hash,
- self::ARRAY_INDEX_DATA_LENGTH => strlen($rawData)
- );
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-FILE-STACK: stackName=%s,hash{}=0x%s,rawData()=%d - EXIT!', $stackName, bin2hex($hash), strlen($rawData)));
+ return [
+ StackableFile::ARRAY_NAME_GAP_POSITION => $gapPosition,
+ StackableFile::ARRAY_NAME_HASH => $hash,
+ StackableFile::ARRAY_NAME_DATA_LENGTH => strlen($rawData),
+ ];
}
}
<?php
// Own namespace
-namespace Org\Mxchange\CoreFramework\Stacker\Filesystem;
+namespace Org\Mxchange\CoreFramework\Stack\File;
// Import framework stuff
use Org\Mxchange\CoreFramework\Filesystem\Block\CalculatableBlock;
-use Org\Mxchange\CoreFramework\Filesystem\Stack\StackableFile;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
use Org\Mxchange\CoreFramework\Registry\Registerable;
-use Org\Mxchange\CoreFramework\Stacker\Filesystem\BaseFileStack;
+use Org\Mxchange\CoreFramework\Stack\File\BaseFileStack;
+use Org\Mxchange\CoreFramework\Stack\File\StackableFile;
// Import SPL stuff
+use \InvalidArgumentException;
+use \OutOfBoundsException;
use \SplFileInfo;
/**
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2017 Core Developer Team
+ * @copyright Copyright (c) 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @param $fileInfoInstance An instance of a SplFileInfo class
* @param $type Type of this stack (e.g. url_source for URL sources)
* @return $stackInstance An instance of a StackableFile class
+ * @throws InvalidArgumentException If a parameter is invalid
*/
- public final static function createFiFoFileStack (SplFileInfo $fileInfoInstance, $type) {
+ public final static function createFiFoFileStack (SplFileInfo $fileInfoInstance, string $type) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FIFO-FILE-STACK: fileInfoInstance[%s]=%s,type=%s - CALLED!', get_class($fileInfoInstance), $fileInfoInstance, $type));
+ if (empty($type)) {
+ // No empty type
+ throw new InvalidArgumentException('Parameter "type" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get new instance
$stackInstance = new FiFoFileStack();
// Init this stack
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FIFO-FILE-STACK: Invoking stackInstance->initFileStack([%s]=%s,%s) ...', get_class($fileInfoInstance), $fileInfoInstance, $type));
$stackInstance->initFileStack($fileInfoInstance, $type);
// Return the prepared instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FIFO-FILE-STACK: stackInstance=%s - EXIT!', $stackInstance->__toString()));
return $stackInstance;
}
* @param $stackerName Name of the stack
* @param $value Value to push on it
* @return void
- * @throws StackerFullException If the stack is full
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If the stack is full
*/
- public function pushNamed ($stackerName, $value) {
+ public function pushNamed (string $stackerName, $value) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FIFO-FILE-STACK: stackerName=%s,value[]=%s - CALLED!', $stackerName, gettype($value)));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (is_object($value) || is_resource($value)) {
+ // Those types for $value are not allowed
+ throw new InvalidArgumentException(sprintf('value[]=%s is not valid', gettype($value)));
+ }
+
// Call the protected method
- parent::addValue($stackerName, $value);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FIFO-FILE-STACK: Invoking parent::addValueToStack(%s,%s) ...', $stackerName, gettype($value)));
+ parent::addValueToStack($stackerName, $value);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FIFO-FILE-STACK: EXIT!');
}
/**
*
* @param $stackerName Name of the stack
* @return $value Value of the current stack entry
- * @throws NoStackerException If the named stacker was not found
- * @throws EmptyStackerException If the named stacker is empty
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If the named stacker was not found
+ * @throws BadMethodCallException If the named stacker is empty
*/
- public function popNamed ($stackerName) {
+ public function popNamed (string $stackerName) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FIFO-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get the value
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FIFO-FILE-STACK: this->getNamed(%s) ...', $stackerName));
$value = $this->getNamed($stackerName);
// Call the protected method
parent::popFirst($stackerName);
// Return the value
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FIFO-FILE-STACK: value[]=%s - EXIT!', gettype($value)));
return $value;
}
*
* @param $stackerName Name of the stack
* @return $value Value of last added value
- * @throws NoStackerException If the named stacker was not found
- * @throws EmptyStackerException If the named stacker is empty
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If the named stacker was not found
+ * @throws BadMethodCallException If the named stacker is empty
*/
- public function getNamed ($stackerName) {
+ public function getNamed (string $stackerName) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FIFO-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Call the protected method
- return parent::getFirstValue($stackerName);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FIFO-FILE-STACK: parent::getFirstValue(%s) ...', $stackerName));
+ $value = parent::getFirstValue($stackerName);
+
+ // Return the value
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FIFO-FILE-STACK: value[]=%s - EXIT!', gettype($value)));
+ return $value;
}
/**
* Seeks to given position
*
* @param $seekPosition Seek position in file
+ * @param $whence Added to offset (default: only use offset to seek to)
* @return $status Status of this operation
+ * @throws OutOfBoundsException If the position is not seekable
*/
- public function seek ($seekPosition) {
- $this->partialStub('seekPosition=' . $seekPosition);
+ public function seek (int $seekPosition, int $whence = SEEK_SET) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FIFO-FILE-STACK: seekPosition=%d,whence=%d - CALLED!', $seekPosition, $whence));
+ if ($seekPosition < 0) {
+ // Invalid seek position
+ throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid', $seekPosition));
+ }
+
+ // @TODO Unfinished method or invoke inner iterator's method?
+ DebugMiddleware::getSelfInstance()->partialStub('seekPosition=' . $seekPosition);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FIFO-FILE-STACK: EXIT!');
}
/**
*/
public function size () {
// Call the iterator instance
- return $this->getIteratorInstance()->size();
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FIFO-FILE-STACK: CALLED!');
+ $size = $this->getIteratorInstance()->size();
+
+ // Return size
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FIFO-FILE-STACK: size=%d - EXIT!', $size));
+ return $size;
}
}
<?php
// Own namespace
-namespace Org\Mxchange\CoreFramework\Stacker;
+namespace Org\Mxchange\CoreFramework\Stack;
+
+// Import framework-specific stuff
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
/**
* A FiLo Stacker class
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
*/
public static final function createFiLoStacker () {
// Get a new instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILO-FILE-STACK: CALLED!');
$stackInstance = new FiLoStacker();
// Init the generic stacker
$stackInstance->initStack('generic');
// Return the prepared instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILO-FILE-STACK: stackInstance=%s - EXIT!', $stackInstance->__toString()));
return $stackInstance;
}
* @param $stackerName Name of the stack
* @param $value Value to push on it
* @return void
- * @throws StackerFullException If the stack is full
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If the stack is full
*/
- public function pushNamed ($stackerName, $value) {
+ public function pushNamed (string $stackerName, $value) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILO-FILE-STACK: stackerName=%s,value[]=%s - CALLED!', $stackerName, gettype($value)));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Call the protected method
- parent::addValue($stackerName, $value);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILO-FILE-STACK: Invoking parent::addValueToStack(%s,%s) ...', $stackerName, gettype($value)));
+ parent::addValueToStack($stackerName, $value);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILO-FILE-STACK: EXIT!');
}
/**
*
* @param $stackerName Name of the stack
* @return $value Value of the current stack entry
- * @throws NoStackerException If the named stacker was not found
- * @throws EmptyStackerException If the named stacker is empty
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If the named stacker was not found
+ * @throws BadMethodCallException If the named stacker is empty
*/
- public function popNamed ($stackerName) {
+ public function popNamed (string $stackerName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILO-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get the value
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILO-FILE-STACK: this->getNamed(%s) ...', $stackerName));
$value = $this->getNamed($stackerName);
// Call the protected method
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILO-FILE-STACK: parent::popLast(%s) ...', $stackerName));
parent::popLast($stackerName);
// Return the value
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILO-FILE-STACK: value[]=%s - EXIT!', gettype($value)));
return $value;
}
*
* @param $stackerName Name of the stack
* @return $value Value of last added value
- * @throws NoStackerException If the named stacker was not found
- * @throws EmptyStackerException If the named stacker is empty
+ * @throws InvalidArgumentException If a parameter is invalid
+ * @throws BadMethodCallException If the named stacker was not found
+ * @throws BadMethodCallException If the named stacker is empty
*/
- public function getNamed ($stackerName) {
+ public function getNamed (string $stackerName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILO-FILE-STACK: stackerName=%s - CALLED!', $stackerName));
+ if (empty($stackerName)) {
+ // No empty stack name
+ throw new InvalidArgumentException('Parameter "stackerName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Call the protected method
- return parent::getLastValue($stackerName);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILO-FILE-STACK: parent::getLastValue(%s) ...', $stackerName));
+ $value = parent::getLastValue($stackerName);
+
+ // Return the value
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILO-FILE-STACK: value[]=%s - EXIT!', gettype($value)));
+ return $value;
}
}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
// Import framework stuff
use Org\Mxchange\CoreFramework\Executor\Executor;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
use Org\Mxchange\CoreFramework\State\Stateable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
* @param $stateName Name of this state in a printable maner
* @return void
*/
- protected final function setStateName ($stateName) {
+ protected final function setStateName (string $stateName) {
$this->stateName = $stateName;
}
* @throws UnsupportedOperationException This method should be overwritten
*/
public function executeState (Executor $executorInstance) {
- throw new UnsupportedOperationException(array($this, __FUNCTION__, $executorInstance), self::EXCEPTION_UNSPPORTED_OPERATION);
+ throw new UnsupportedOperationException(array($this, __FUNCTION__, $executorInstance), FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
}
<?php
// Own namespace
-namespace CoreFramework\Stream\;
+namespace Org\Mxchange\CoreFramework\Stream\;
// Import framework stuff
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @throws UnsupportedOperationException If this method is called
*/
public function streamData ($data) {
- self::createDebugInstance(__CLASS__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
+ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Stream\Crypto;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
+use Org\Mxchange\CoreFramework\Stream\BaseStream;
+
+/**
+ * A general crypto stream class
+ *
+ * @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/>.
+ */
+abstract class BaseCryptoStream extends BaseStream {
+ /**
+ * Instance of a RNG
+ */
+ private $rngInstance = NULL;
+
+ /**
+ * Protected constructor
+ *
+ * @param $className Name of the class
+ * @return void
+ */
+ protected function __construct (string $className) {
+ // Call parent constructor
+ parent::__construct($className);
+ }
+
+ /**
+ * Setter for RNG instance
+ *
+ * @param $rngInstance An instance of a random number generator (RNG)
+ * @return void
+ */
+ protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
+ $this->rngInstance = $rngInstance;
+ }
+
+ /**
+ * Getter for RNG instance
+ *
+ * @return $rngInstance An instance of a random number generator (RNG)
+ */
+ protected final function getRngInstance () {
+ return $this->rngInstance;
+ }
+
+}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Stream\Crypto;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
-use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
-use Org\Mxchange\CoreFramework\Stream\BaseStream;
-
-/**
- * A mcrypt-based encryption stream
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.shipsimu.org
- * @todo mcrypt will become deprecated, rewrite to OpenSSL
- *
- * 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 McryptStream extends BaseStream implements EncryptableStream {
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of this node class
- *
- * @param $rngInstance An RNG instance
- * @return $streamInstance An instance of this node class
- */
- public static final function createMcryptStream (RandomNumberGenerator $rngInstance) {
- // Get a new instance
- $streamInstance = new McryptStream();
-
- // Set the RNG instance
- $streamInstance->setRngInstance($rngInstance);
-
- // Return the instance
- return $streamInstance;
- }
-
- /**
- * Encrypt the string with fixed salt
- *
- * @param $str The unencrypted string
- * @param $key Optional key, if none provided, a random key will be generated
- * @return $encrypted Encrypted string
- */
- public function encryptStream ($str, $key = NULL) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: key[' . gettype($key) . ']=' . $key);
-
- // Init crypto module
- $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
- $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
-
- // Generate key, if none provided
- if (is_null($key)) {
- // None provided
- $key = $this->getRngInstance()->generateKey();
- } // END - if
-
- // Add some "payload" to the string
- switch ($this->getRngInstance()->randomNumber(0, 8)) {
- case 0:
- $payloadString = crc32($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . crc32($this->getRngInstance()->randomString(20));
- break;
-
- case 1:
- $payloadString = crc32($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . md5($this->getRngInstance()->randomString(20));
- break;
-
- case 2:
- $payloadString = crc32($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . sha1($this->getRngInstance()->randomString(20));
- break;
-
- case 3:
- $payloadString = md5($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . crc32($this->getRngInstance()->randomString(20));
- break;
-
- case 4:
- $payloadString = md5($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . md5($this->getRngInstance()->randomString(20));
- break;
-
- case 5:
- $payloadString = md5($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . sha1($this->getRngInstance()->randomString(20));
- break;
-
- case 6:
- $payloadString = sha1($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . crc32($this->getRngInstance()->randomString(20));
- break;
-
- case 7:
- $payloadString = sha1($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . md5($this->getRngInstance()->randomString(20));
- break;
-
- case 8:
- $payloadString = sha1($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . sha1($this->getRngInstance()->randomString(20));
- break;
- }
-
- // Encrypt the string
- $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $payloadString, MCRYPT_MODE_ECB, $iv);
-
- // Return the string
- return $encrypted;
- }
-
- /**
- * Decrypt the string with fixed salt
- *
- * @param $encrypted Encrypted string
- * @param $key Optional key, if none provided, a random key will be generated
- * @return $str The unencrypted string
- */
- public function decryptStream ($encrypted, $key = NULL) {
- // Init crypto module
- $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
- $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
-
- // Shall we use a default key or custom?
- if (is_null($key)) {
- // Generate (default) key
- $key = $this->getRngInstance()->generateKey();
- } // END - if
-
- // Decrypt the string
- $payloadString = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, MCRYPT_MODE_ECB, $iv);
-
- // Get the real string out
- $strArray = explode(EncryptableStream::DATA_PAYLOAD_SEPARATOR, $payloadString);
-
- // Does the element count match?
- assert(count($strArray) == 3);
-
- // Decode the string
- $str = base64_decode($strArray[1]);
-
- // Trim trailing nulls away
- $str = rtrim($str, "\0");
-
- // Return the string
- return $str;
- }
-
- /**
- * Streams the data and maybe does something to it
- *
- * @param $data The data (string mostly) to "stream"
- * @return $data The data (string mostly) to "stream"
- * @throws UnsupportedOperationException If this method is called (which is a mistake)
- */
- public function streamData ($data) {
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Stream\Crypto;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
-use Org\Mxchange\CoreFramework\Stream\BaseStream;
-
-/**
- * A null-encryption stream does not encrypt anything but can be used if e.e.
- * mcrypt is not installed.
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 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 NullCryptoStream extends BaseStream implements EncryptableStream {
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of this node class
- *
- * @return $streamInstance An instance of this node class
- */
- public static final function createNullCryptoStream () {
- // Get a new instance
- $streamInstance = new NullCryptoStream();
-
- // Return the instance
- return $streamInstance;
- }
-
- /**
- * Encrypt the string with fixed salt
- *
- * @param $str The unencrypted string
- * @param $key Optional key, if none provided, a random key will be generated
- * @return $encrypted Encrypted string
- */
- public function encryptStream ($str, $key = NULL) {
- // Just handle it over
- $encrypted = (string) $str;
-
- // Return it
- return $encrypted;
- }
-
- /**
- * Decrypt the string with fixed salt
- *
- * @param $encrypted Encrypted string
- * @return $str The unencrypted string
- */
- public function decryptStream ($encrypted) {
- // Just handle it over
- $str = (string) $encrypted;
-
- // Return it
- return $str;
- }
-
- /**
- * Streams the data and maybe does something to it
- *
- * @param $data The data (string mostly) to "stream"
- * @return $data The data (string mostly) to "stream"
- * @throws UnsupportedOperationException If this method is called (which is a mistake)
- */
- public function streamData ($data) {
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Stream\Crypto;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
-use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
-use Org\Mxchange\CoreFramework\Stream\BaseStream;
-
-/**
- * An OpenSSL-based encryption stream
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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 OpenSslStream extends BaseStream implements EncryptableStream {
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of this node class
- *
- * @param $rngInstance An RNG instance
- * @return $streamInstance An instance of this node class
- */
- public static final function createOpenSslStream (RandomNumberGenerator $rngInstance) {
- // Get a new instance
- $streamInstance = new OpenSslStream();
-
- // Set the RNG instance
- $streamInstance->setRngInstance($rngInstance);
-
- // Return the instance
- return $streamInstance;
- }
-
- /**
- * Encrypt the string with fixed salt
- *
- * @param $str The unencrypted string
- * @param $key Optional key, if none provided, a random key will be generated
- * @return $encrypted Encrypted string
- */
- public function encryptStream ($str, $key = NULL) {
- // @TODO unfinished
- return $str;
-
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: key[' . gettype($key) . ']=' . $key);
-
- // Init crypto module
- $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
- $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
-
- // Generate key, if none provided
- if (is_null($key)) {
- // None provided
- $key = $this->getRngInstance()->generateKey();
- } // END - if
-
- // Add some "payload" to the string
- switch ($this->getRngInstance()->randomNumber(0, 8)) {
- case 0:
- $payloadString = crc32($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . crc32($this->getRngInstance()->randomString(20));
- break;
-
- case 1:
- $payloadString = crc32($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . md5($this->getRngInstance()->randomString(20));
- break;
-
- case 2:
- $payloadString = crc32($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . sha1($this->getRngInstance()->randomString(20));
- break;
-
- case 3:
- $payloadString = md5($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . crc32($this->getRngInstance()->randomString(20));
- break;
-
- case 4:
- $payloadString = md5($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . md5($this->getRngInstance()->randomString(20));
- break;
-
- case 5:
- $payloadString = md5($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . sha1($this->getRngInstance()->randomString(20));
- break;
-
- case 6:
- $payloadString = sha1($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . crc32($this->getRngInstance()->randomString(20));
- break;
-
- case 7:
- $payloadString = sha1($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . md5($this->getRngInstance()->randomString(20));
- break;
-
- case 8:
- $payloadString = sha1($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . sha1($this->getRngInstance()->randomString(20));
- break;
- }
-
- // Encrypt the string
- $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $payloadString, MCRYPT_MODE_ECB, $iv);
-
- // Return the string
- return $encrypted;
- }
-
- /**
- * Decrypt the string with fixed salt
- *
- * @param $encrypted Encrypted string
- * @param $key Optional key, if none provided, a random key will be generated
- * @return $str The unencrypted string
- */
- public function decryptStream ($encrypted, $key = NULL) {
- // @TODO unfinished
- return $encrypted;
-
- // Init crypto module
- $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
- $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
-
- // Shall we use a default key or custom?
- if (is_null($key)) {
- // Generate (default) key
- $key = $this->getRngInstance()->generateKey();
- } // END - if
-
- // Decrypt the string
- $payloadString = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, MCRYPT_MODE_ECB, $iv);
-
- // Get the real string out
- $strArray = explode(EncryptableStream::DATA_PAYLOAD_SEPARATOR, $payloadString);
-
- // Does the element count match?
- assert(count($strArray) == 3);
-
- // Decode the string
- $str = base64_decode($strArray[1]);
-
- // Trim trailing nulls away
- $str = rtrim($str, "\0");
-
- // Return the string
- return $str;
- }
-
- /**
- * Streams the data and maybe does something to it
- *
- * @param $data The data (string mostly) to "stream"
- * @return $data The data (string mostly) to "stream"
- * @throws UnsupportedOperationException If this method is called (which is a mistake)
- */
- public function streamData ($data) {
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
- }
-
-}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Stream\Crypto\Null;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
+use Org\Mxchange\CoreFramework\Stream\Crypto\BaseCryptoStream;
+use Org\Mxchange\CoreFramework\Stream\Crypto\EncryptableStream;
+
+/**
+ * A null-encryption stream does not encrypt anything but can be used if e.g.
+ * openssl is not installed.
+ *
+ * @author Roland Haeder <webmaster@shipsimu.org>
+ * @version 0.0.0
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 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 NullCryptoStream extends BaseCryptoStream implements EncryptableStream {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Creates an instance of this node class
+ *
+ * @return $streamInstance An instance of this node class
+ */
+ public static final function createNullCryptoStream () {
+ // Get a new instance
+ $streamInstance = new NullCryptoStream();
+
+ // Return the instance
+ return $streamInstance;
+ }
+
+ /**
+ * Encrypt the string with fixed salt
+ *
+ * @param $str The unencrypted string
+ * @param $key Ignored
+ * @return $encrypted Encrypted string
+ */
+ public function encryptStream (string $str, string $key = NULL) {
+ // Return it
+ return $str;
+ }
+
+ /**
+ * Decrypt the string with fixed salt
+ *
+ * @param $encrypted Encrypted string
+ * @param $key Ignored
+ * @return $str The unencrypted string
+ */
+ public function decryptStream (string $encrypted, string $key = NULL) {
+ // Return it
+ return $encrypted;
+ }
+
+ /**
+ * Streams the data and maybe does something to it
+ *
+ * @param $data The data (string mostly) to "stream"
+ * @return $data The data (string mostly) to "stream"
+ * @throws UnsupportedOperationException If this method is called (which is a mistake)
+ */
+ public function streamData (string $data) {
+ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Stream\Crypto\OpenSsl;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
+use Org\Mxchange\CoreFramework\Stream\Crypto\BaseCryptoStream;
+use Org\Mxchange\CoreFramework\Stream\Crypto\EncryptableStream;
+
+/**
+ * An OpenSSL-based encryption stream
+ *
+ * @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 OpenSslStream extends BaseCryptoStream implements EncryptableStream {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Creates an instance of this node class
+ *
+ * @param $rngInstance An RNG instance
+ * @return $streamInstance An instance of this node class
+ */
+ public static final function createOpenSslStream (RandomNumberGenerator $rngInstance) {
+ // Get a new instance
+ $streamInstance = new OpenSslStream();
+
+ // Set the RNG instance
+ $streamInstance->setRngInstance($rngInstance);
+
+ // Return the instance
+ return $streamInstance;
+ }
+
+ /**
+ * Encrypt the string with fixed salt
+ *
+ * @param $str The unencrypted string
+ * @param $key Optional key, if none provided, a random key will be generated
+ * @return $encrypted Encrypted string
+ */
+ public function encryptStream (string $str, string $key = NULL) {
+ // @TODO unfinished
+ return $str;
+
+ // Debug message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('OPENSSL-STREAM: key[' . gettype($key) . ']=' . $key);
+
+ // Init crypto module
+ $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
+ $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
+
+ // Generate key, if none provided
+ if (is_null($key)) {
+ // None provided
+ $key = $this->getRngInstance()->generateKey();
+ }
+
+ // Add some "payload" to the string
+ switch ($this->getRngInstance()->randomNumber(0, 8)) {
+ case 0:
+ $payloadString = crc32($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . crc32($this->getRngInstance()->randomString(20));
+ break;
+
+ case 1:
+ $payloadString = crc32($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . md5($this->getRngInstance()->randomString(20));
+ break;
+
+ case 2:
+ $payloadString = crc32($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . sha1($this->getRngInstance()->randomString(20));
+ break;
+
+ case 3:
+ $payloadString = md5($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . crc32($this->getRngInstance()->randomString(20));
+ break;
+
+ case 4:
+ $payloadString = md5($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . md5($this->getRngInstance()->randomString(20));
+ break;
+
+ case 5:
+ $payloadString = md5($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . sha1($this->getRngInstance()->randomString(20));
+ break;
+
+ case 6:
+ $payloadString = sha1($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . crc32($this->getRngInstance()->randomString(20));
+ break;
+
+ case 7:
+ $payloadString = sha1($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . md5($this->getRngInstance()->randomString(20));
+ break;
+
+ case 8:
+ $payloadString = sha1($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . sha1($this->getRngInstance()->randomString(20));
+ break;
+ }
+
+ // Encrypt the string
+ $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $payloadString, MCRYPT_MODE_ECB, $iv);
+
+ // Return the string
+ return $encrypted;
+ }
+
+ /**
+ * Decrypt the string with fixed salt
+ *
+ * @param $encrypted Encrypted string
+ * @param $key Optional key, if none provided, a random key will be generated
+ * @return $str The unencrypted string
+ */
+ public function decryptStream (string $encrypted, string $key = NULL) {
+ // @TODO unfinished
+ return $encrypted;
+
+ // Init crypto module
+ $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
+ $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
+
+ // Shall we use a default key or custom?
+ if (is_null($key)) {
+ // Generate (default) key
+ $key = $this->getRngInstance()->generateKey();
+ }
+
+ // Decrypt the string
+ $payloadString = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, MCRYPT_MODE_ECB, $iv);
+
+ // Get the real string out
+ $strArray = explode(EncryptableStream::DATA_PAYLOAD_SEPARATOR, $payloadString);
+
+ // Does the element count match?
+ assert(count($strArray) == 3);
+
+ // Decode the string
+ $str = base64_decode($strArray[1]);
+
+ // Trim trailing nulls away
+ $str = rtrim($str, "\0");
+
+ // Return the string
+ return $str;
+ }
+
+ /**
+ * Streams the data and maybe does something to it
+ *
+ * @param $data The data (string mostly) to "stream"
+ * @return $data The data (string mostly) to "stream"
+ * @throws UnsupportedOperationException If this method is called (which is a mistake)
+ */
+ public function streamData (string $data) {
+ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
+ }
+
+}
<?php
// Own namespace
-namespace CoreFramework\Stream\Input\;
+namespace Org\Mxchange\CoreFramework\Stream\Input\;
// Import framework stuff
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @throws UnsupportedOperationException If this method is called
*/
public function streamData ($data) {
- self::createDebugInstance(__CLASS__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
+ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
}
<?php
// Own namespace
-namespace CoreFramework\Stream\Output\;
+namespace Org\Mxchange\CoreFramework\Stream\Output\;
// Import framework stuff
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @throws UnsupportedOperationException If this method is called
*/
public function streamData ($data) {
- self::createDebugInstance(__CLASS__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
+ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
}
<?php
// Own namespace
-namespace CoreFramework\Task\___;
+namespace Tld\Domain\Project\Task\___;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
use Org\Mxchange\CoreFramework\Task\BaseTask;
use Org\Mxchange\CoreFramework\Task\Taskable;
use Org\Mxchange\CoreFramework\Visitor\Visitable;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @todo 0%
*/
public function executeTask () {
- $this->partialStub('Unimplemented task.');
+ DebugMiddleware::getSelfInstance()->partialStub('Unimplemented task.');
}
/**
* @todo 0% done
*/
public function doShutdown () {
- self::createDebugInstance(__CLASS__)->debugOutput('TASK[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down...');
+ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK: Shutting down...');
}
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
namespace Org\Mxchange\CoreFramework\Task\IdleLoop;
// Import Framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Task\BaseTask;
use Org\Mxchange\CoreFramework\Task\Taskable;
use Org\Mxchange\CoreFramework\Visitor\Visitable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
// Init idle loop time from config ("cache" it here)
- $this->idleTime = $this->getConfigInstance()->getConfigEntry('idle_loop_time');
+ $this->idleTime = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('idle_loop_time');
}
/**
*/
public function doShutdown () {
// Debug message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down...');
+ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TASK: Shutting down...');
}
}
<?php
// Own namespace
-namespace CoreFramework\Template\Engine\;
+namespace Org\Mxchange\CoreFramework\Template\Engine\;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Template\Engine\BaseTemplateEngine;
/**
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$templateInstance = new ???TemplateEngine();
// Determine base path
- $templateBasePath = $templateInstance->getConfigInstance()->getConfigEntry('application_base_path') . $applicationInstance->getRequestInstance()->getRequestElement('application') . DIRECTORY_SEPARATOR;
+ $templateBasePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . $applicationInstance->getRequestInstance()->getRequestElement('application') . DIRECTORY_SEPARATOR;
// Is the base path valid?
if (empty($templateBasePath)) {
$templateInstance->setTemplateBasePath($templateBasePath);
// Set template extensions
- $templateInstance->setRawTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('raw_template_extension'));
- $templateInstance->setCodeTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('code_template_extension'));
+ $templateInstance->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
+ $templateInstance->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_template_extension'));
// Absolute output path for compiled templates
- $templateInstance->setCompileOutputPath($templateInstance->getConfigInstance()->getConfigEntry('application_base_path') . $templateInstance->getConfigInstance()->getConfigEntry('compile_output_path'));
+ $templateInstance->setCompileOutputPath(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path'));
// Return the prepared instance
return $templateInstance;
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
use Org\Mxchange\CoreFramework\Response\Responseable;
-use Org\Mxchange\CoreFramework\String\Utils\StringUtils;
+use Org\Mxchange\CoreFramework\Traits\Handler\Io\IoHandlerTrait;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
// Import SPL stuff
+use \BadMethodCallException;
use \InvalidArgumentException;
use \SplFileInfo;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseTemplateEngine extends BaseFrameworkSystem {
+ // Load traits
+ use IoHandlerTrait;
+
+ // Exception codes for the template engine
+ const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
+ const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
+ const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
+ const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
+
+ /**
+ * HTML template type
+ */
+ private static $htmlTemplateType = 'invalid';
+
/**
* The local path name where all templates and sub folders for special
* templates are stored. We will internally determine the language plus
/**
* The variable stack for the templates
*/
- private $varStack = array();
+ private $varStack = [];
/**
* Loaded templates for recursive protection and detection
*/
- private $loadedTemplates = array();
+ private $loadedTemplates = [];
/**
* Compiled templates for recursive protection and detection
*/
- private $compiledTemplates = array();
+ private $compiledTemplates = [];
/**
* Loaded raw template data
/**
* Loaded helpers
*/
- private $helpers = array();
+ private $helpers = [];
/**
* Current variable group
/**
* All template groups except "general"
*/
- private $variableGroups = array();
+ private $variableGroups = [];
/**
* Code begin
*/
private $languageSupport = true;
- /**
- * XML compacting is disabled by default
- */
- private $xmlCompacting = false;
-
- // Exception codes for the template engine
- const EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED = 0x110;
- const EXCEPTION_TEMPLATE_CONTAINS_INVALID_VAR = 0x111;
- const EXCEPTION_INVALID_VIEW_HELPER = 0x112;
- const EXCEPTION_VARIABLE_IS_MISSING = 0x113;
-
/**
* Protected constructor
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: className=%s - CONSTRUCTED!', $className));
parent::__construct($className);
// Init file I/O instance
$ioInstance = ObjectFactory::createObjectByConfiguredName('file_io_class');
// Set it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: ioInstance=%s', $ioInstance->__toString()));
$this->setFileIoInstance($ioInstance);
+
+ // "Cache" config entry
+ self::$htmlTemplateType = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('html_template_type');
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: self::htmlTemplateType=%s - EXIT!', self::$htmlTemplateType));
}
/**
* @param $variableGroup Optional variable group to look in
* @return $index false means not found, >=0 means found on a specific index
*/
- private function getVariableIndex ($variableName, $variableGroup = NULL) {
+ private function getVariableIndex (string $variableName, string $variableGroup = NULL) {
// Replace all dashes to underscores to match variables with configuration entries
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: variableName=%s,variableGroup[%s]=%s - CALLED!', $variableName, gettype($variableGroup), $variableGroup));
$variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
// First everything is not found
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: variableName=%s', $variableName));
$found = false;
// If the stack is NULL, use the current group
if (is_null($variableGroup)) {
// Use current group
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: this->currGroup=%s set as stack!', $this->currGroup));
$variableGroup = $this->currGroup;
- } // END - if
+ }
// Is the group there?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: variableGroup=%s', $variableGroup));
if ($this->isVarStackSet($variableGroup)) {
// Now search for it
foreach ($this->getVarStack($variableGroup) as $index => $currEntry) {
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':currGroup=' . $variableGroup . ',idx=' . $index . ',currEntry=' . $currEntry['name'] . ',variableName=' . $variableName);
// Is the entry found?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: index=%d,currGroup=%s,currEntry[name]=%s,variableName=%s', $index, $variableGroup, $currEntry['name'], $variableName));
if ($currEntry['name'] == $variableName) {
// Found!
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.':FOUND!');
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: index=%d - BREAK!', $index));
$found = $index;
break;
- } // END - if
- } // END - foreach
- } // END - if
+ }
+ }
+ }
// Return the current position
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: found=%d - EXIT!', $found));
return $found;
}
*
* @param $variableGroup Variable group to check
* @return $isSet Whether the given variable group is set
+ * @throws InvalidArgumentException If the variable name is left empty
*/
- protected final function isVarStackSet ($variableGroup) {
+ protected final function isVarStackSet (string $variableGroup) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: variableGroup=%s - CALLED!', $variableGroup));
+ if (empty($variableGroup)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "variableGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Check it
- $isSet = isset($this->varStack[$variableGroup]);
+ $isset = isset($this->varStack[$variableGroup]);
// Return result
- return $isSet;
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: isset=%d - EXIT!', intval($isset)));
+ return $isset;
}
/**
*
* @param $variableGroup Variable group to check
* @return $varStack Found variable group
+ * @throws InvalidArgumentException If the variable name is left empty
*/
- public final function getVarStack ($variableGroup) {
+ public final function getVarStack (string $variableGroup) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: variableGroup=%s - CALLED!', $variableGroup));
+ if (empty($variableGroup)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "variableGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Return value
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: this->varStack[%s]()=%d - EXIT!', $variableGroup, count($this->varStack[$variableGroup])));
return $this->varStack[$variableGroup];
}
* @param $variableGroup Variable group to check
* @param $varStack Variable stack to check
* @return void
+ * @throws InvalidArgumentException If the variable name is left empty
*/
- protected final function setVarStack ($variableGroup, array $varStack) {
+ protected final function setVarStack (string $variableGroup, array $varStack) {
+ // Validate parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: variableGroup=%s,varStack()=%d - CALLED!', $variableGroup, count($varStack)));
+ if (empty($variableGroup)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "variableGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Set var stack
$this->varStack[$variableGroup] = $varStack;
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: EXIT!');
}
/**
* @param $variableName The variable we are looking for
* @param $variableGroup Optional variable group to look in
* @return $content Content of the variable or null if not found
+ * @throws InvalidArgumentException If the variable name is left empty
*/
- protected function readVariable ($variableName, $variableGroup = NULL) {
+ protected function readVariable (string $variableName, string $variableGroup = NULL) {
+ // Check parameters
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: variableName=%s,variableGroup[%s]=%s - CALLED!', $variableName, gettype($variableGroup), $variableGroup));
+ if (empty($variableName)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "variableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!is_null($variableGroup) && empty($variableGroup)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "variableGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Replace all dashes to underscores to match variables with configuration entries
$variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
// First everything is not found
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: variableName=%s', $variableName));
$content = NULL;
// If the stack is NULL, use the current group
if (is_null($variableGroup)) {
// Use current group
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.' currGroup=' . $this->currGroup . ' set as stack!');
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: this->currGroup=%s set as stack!', $this->currGroup));
$variableGroup = $this->currGroup;
- } // END - if
+ }
// Get variable index
$found = $this->getVariableIndex($variableName, $variableGroup);
// Is the variable found?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: found[]=%s', gettype($found)));
if ($found !== false) {
// Read it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking this->getVariableValue(%s,%s) ...', $variableGroup, $found));
$content = $this->getVariableValue($variableGroup, $found);
- } // END - if
+ }
// Return the current position
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': variableGroup=' . $variableGroup . ',variableName=' . $variableName . ', content[' . gettype($content) . ']=' . $content);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: content()=%d - EXIT!', strlen($content)));
return $content;
}
* @param $value Value we want to store in the variable
* @return void
*/
- private function addVariable ($variableName, $value) {
+ private function addVariable (string $variableName, $value) {
// Set general variable group
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: variableName=%s,value[]=%s - CALLED!', $variableName, gettype($value)));
$this->setVariableGroup('general');
// Add it to the stack
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking this->addVariableGroup(%s,value[]=%s) ...', $variableName, gettype($value)));
$this->addGroupVariable($variableName, $value);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: EXIT!');
}
/**
*/
private function readCurrentGroup () {
// Default is not found
- $result = array();
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: CALLED!');
+ $result = [];
// Is the group there?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: this->currGroup=%s', $this->currGroup));
if ($this->isVarStackSet($this->currGroup)) {
// Then use it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking this->getVarStack(%s) ...', $this->currGroup));
$result = $this->getVarStack($this->currGroup);
- } // END - if
+ }
// Return result
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: result()=%d - EXIT!', count($result)));
return $result;
}
* @param $groupName Name of variable group
* @param $add Whether add this group
* @return void
+ * @throws InvalidArgumentException If the variable name is left empty
*/
- public function setVariableGroup ($groupName, $add = true) {
+ public function setVariableGroup (string $groupName, bool $add = true) {
+ // Check parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: groupName=%s,add=%d - CALLED!', $groupName, intval($add)));
+ if (empty($groupName)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "groupName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Set group name
- //* DEBIG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': currGroup=' . $groupName);
$this->currGroup = $groupName;
// Skip group 'general'
if (($groupName != 'general') && ($add === true)) {
+ // Mark as 'OK'
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: Marking groupName=%s as OK ...', $groupdName));
$this->variableGroups[$groupName] = 'OK';
- } // END - if
- }
+ }
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: EXIT!');
+ }
/**
* Adds a variable to current group
* @param $variableName Variable to set
* @param $value Value to store in variable
* @return void
+ * @throws InvalidArgumentException If the variable name is left empty
*/
- public function addGroupVariable ($variableName, $value) {
+ public function addGroupVariable (string $variableName, $value) {
+ // Check parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: variableName=%s,value[]=%s - CALLED!', $variableName, gettype($value)));
+ if (empty($variableName)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "variableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (is_object($value) || is_resource($value)) {
+ // Throw an exception
+ throw new InvalidArgumentException(sprintf('value[]=%s is not supported', gettype($value)), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Replace all dashes to underscores to match variables with configuration entries
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking StringUtils::convertDashesToUnderscores(%s) ...', $variableName));
$variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
- // Debug message
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': group=' . $this->currGroup . ', variableName=' . $variableName . ', value=' . $value);
-
// Get current variables in group
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: this->currGroup=%s,variableName=%s,value[]=%s', $this->currGroup, $variableName, gettype($value)));
$currVars = $this->readCurrentGroup();
// Append our variable
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: currVars()=%d - BEFORE!', count($currVars)));
array_push($currVars, $this->generateVariableArray($variableName, $value));
// Add it to the stack
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking this->setVarStack(%s,currVars()=%d) - AFTER!', $this->currGroup, count($currVars)));
$this->setVarStack($this->currGroup, $currVars);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: EXIT!');
}
/**
* Getter for variable value, throws a NoVariableException if the variable is not found
*
* @param $variableGroup Variable group to use
- * @param $index Index in variable array
- * @return $value Value to set
+ * @param $index Index in variable array
+ * @return $value Value to set
*/
- private function getVariableValue ($variableGroup, $index) {
+ private function getVariableValue (string $variableGroup, int $index) {
// Return it
- return $this->varStack[$variableGroup][$index]['value'];
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: variableGroup=%s,index[]=%d - CALLED!', $variableGroup, $index));
+ $value = $this->varStack[$variableGroup][$index]['value'];
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: value[]=%s - EXIT!', gettype($value)));
+ return $value;
}
/**
* @param $variableName The variable we are looking for
* @param $value The value we want to store in the variable
* @return void
- * @throws NoVariableException If the given variable is not found
*/
- private function modifyVariable ($variableName, $value) {
+ private function modifyVariable (string $variableName, $value) {
// Replace all dashes to underscores to match variables with configuration entries
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: variableName=%s,value[]=%s - CALLED!', $variableName, gettype($value)));
$variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
// Get index for variable
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: this->getVariableIndex(%s) ...', $variableName));
$index = $this->getVariableIndex($variableName);
- // Is the variable set?
- if ($index === false) {
- // Unset variables cannot be modified
- throw new NoVariableException(array($this, $variableName, $value), self::EXCEPTION_VARIABLE_IS_MISSING);
- } // END - if
-
// Then modify it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: this->setVariableValue(%s,%d,value[]=%s) ...', $this->currGroup, $index, gettype($value)));
$this->setVariableValue($this->currGroup, $index, $value);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: EXIT!');
}
/**
* @param $value Value to set
* @return void
*/
- private function setVariableValue ($variableGroup, $index, $value) {
+ private function setVariableValue (string $variableGroup, int $index, $value) {
+ // Set variable
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: variableGroup=%s,index[]=%d,value[]=%s - CALLED!', $variableGroup, $index, gettype($value)));
$this->varStack[$variableGroup][$index]['value'] = $value;
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: EXIT!');
}
/**
* @param $variableName Variable to set
* @param $value Value to set
* @return void
+ * @throws InvalidArgumentException If the variable name is left empty
*/
- protected function setVariable ($variableGroup, $variableName, $value) {
+ protected function setVariable (string $variableGroup, string $variableName, $value) {
+ // Check parameters
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: variableGroup=%s,variableName=%s,value[]=%s - CALLED!', $variableGroup, $variableName, gettype($value)));
+ if (empty($variableGroup)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "variableGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($variableName)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "variableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Replace all dashes to underscores to match variables with configuration entries
$variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
// Get index for variable
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: this->getVariableIndex(%s) ...', $variableName));
$index = $this->getVariableIndex($variableName);
// Is the variable set?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: index[]=%s', gettype($index)));
if ($index === false) {
// Is the stack there?
if (!isset($this->varStack[$variableGroup])) {
// Then initialize it here
- $this->varStack[$variableGroup] = array();
- } // END - if
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: Initializing this->varStack[%s] ...', $variableGroup));
+ $this->varStack[$variableGroup] = [];
+ }
// Not found, add it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: Pushing variableGroup=%s,variableName=%s,value[]=%s ...', $variableGroup, $variableName, gettype($value)));
array_push($this->varStack[$variableGroup], $this->generateVariableArray($variableName, $value));
} else {
// Then modify it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking this->setVariableValue(%s,%d,value[]=%s) ...', $this->currGroup, $index, gettype($value)));
$this->setVariableValue($this->currGroup, $index, $value);
}
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: EXIT!');
}
/**
* @param $value Value to set
* @return $varData Variable data array
*/
- private function generateVariableArray ($variableName, $value) {
+ private function generateVariableArray (string $variableName, $value) {
// Replace all dashes to underscores to match variables with configuration entries
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: variableName=%s,value[]=%s - CALLED!', $variableName, gettype($value)));
$variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
// Generate the temporary array
- $varData = array(
+ $varData = [
'name' => $variableName,
'value' => $value
- );
+ ];
// And return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: varData()=%d - EXIT!', count($varData)));
return $varData;
}
* @param $templateType The current template's type
* @return void
*/
- protected final function setTemplateType ($templateType) {
- $this->templateType = (string) $templateType;
+ protected final function setTemplateType (string $templateType) {
+ $this->templateType = $templateType;
}
/**
* @param $templateBasePath The relative base path for all templates
* @return void
*/
- protected final function setTemplateBasePath ($templateBasePath) {
+ protected final function setTemplateBasePath (string $templateBasePath) {
// And set it
- $this->templateBasePath = (string) $templateBasePath;
+ $this->templateBasePath = $templateBasePath;
}
/**
* templates
* @return void
*/
- protected final function setRawTemplateExtension ($templateExtension) {
+ protected final function setRawTemplateExtension (string $templateExtension) {
// And set it
- $this->templateExtension = (string) $templateExtension;
+ $this->templateExtension = $templateExtension;
}
/**
* templates
* @return void
*/
- protected final function setCodeTemplateExtension ($codeExtension) {
+ protected final function setCodeTemplateExtension (string $codeExtension) {
// And set it
- $this->codeExtension = (string) $codeExtension;
+ $this->codeExtension = $codeExtension;
}
/**
* templates
* @return void
*/
- protected final function setCompileOutputPath ($compileOutputPath) {
+ protected final function setCompileOutputPath (string $compileOutputPath) {
// And set it
- $this->compileOutputPath = (string) $compileOutputPath;
+ $this->compileOutputPath = $compileOutputPath;
}
/**
* @param $index Index to unset
* @param $variableGroup Variable group (default: currGroup)
* @return void
- */
- protected final function unsetVariableStackOffset ($index, $variableGroup = NULL) {
+ * @throws InvalidArgumentException If the variable name is left empty
+ * @throws BadMethodCallException If this method was called but combination of variableGroup/index isn't found
+ */
+ protected final function unsetVariableStackOffset (int $index, string $variableGroup = NULL) {
+ // Check variables
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: index=%d,variableGroup[%s]=%s - CALLED!', $index, gettype($variableGroup), $variableGroup));
+ if ($index < 0) {
+ // Invalid index
+ throw new InvalidArgumentException(sprintf('index=%d is below zero', $index), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!is_null($variableGroup) && empty($variableGroup)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "variableGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Is the variable group not set?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: variableGroup[]=%s', gettype($variableGroup)));
if (is_null($variableGroup)) {
// Then set it to current
$variableGroup = $this->currGroup;
- } // END - if
+ }
// Is the entry there?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: Checking variableGroup=%s,index=%d ...', $variableGroup, $index));
if (!isset($this->varStack[$variableGroup][$index])) {
// Abort here, we need fixing!
- $this->debugInstance();
- } // END - if
+ throw new BadMethodCallException(sprintf('variableGroup=%s,index=%d does not exist, but method was invoked', $variableGroup, $index), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
+ }
// Remove it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: Unsetting variableGroup=%s,index=%d ...', $variableGroup, $index));
unset($this->varStack[$variableGroup][$index]);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: EXIT!');
}
/**
* @param $rawTemplateData The raw data from the template
* @return void
*/
- protected final function setRawTemplateData ($rawTemplateData) {
+ protected final function setRawTemplateData (string $rawTemplateData) {
// And store it in this class
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . strlen($rawTemplateData) . ' Bytes set.');
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(__METHOD__.': ' . $this->currGroup . ' variables: ' . count($this->getVarStack($this->currGroup)) . ', groups=' . count($this->varStack));
- $this->rawTemplateData = (string) $rawTemplateData;
+ $this->rawTemplateData = $rawTemplateData;
}
/**
* @return $rawTemplateData The raw data from the template
*/
public final function getRawTemplateData () {
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->rawTemplateData) . ' Bytes read.');
return $this->rawTemplateData;
}
/**
* Private setter for compiled templates
*
+ * @param $compiledData Compiled template data
* @return void
*/
- private final function setCompiledData ($compiledData) {
+ private final function setCompiledData (string $compiledData) {
// And store it in this class
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($compiledData) . ' Bytes set.');
- $this->compiledData = (string) $compiledData;
+ $this->compiledData = $compiledData;
}
/**
* @return $compiledData Compiled template data
*/
public final function getCompiledData () {
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: ' . strlen($this->compiledData) . ' Bytes read.');
return $this->compiledData;
}
* @param $templateName The template we shall load
* @param $extOther An other extension to use
* @return void
+ * @throws InvalidArgumentException If the variable name is left empty
* @throws FileNotFoundException If the template was not found
*/
- protected function loadTemplate ($templateName, $extOther = '') {
+ protected function loadTemplate (string $templateName, string $extOther = '') {
+ // Check parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: templateName=%s,extOther=%s - CALLED!', $templateName, $extOther));
+ if (empty($templateName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "templateName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get extension for the template if empty
if (empty($extOther)) {
// None provided, so get the raw one
$ext = $this->getRawTemplateExtension();
} else {
// Then use it!
- $ext = (string) $extOther;
+ $ext = $extOther;
}
/*
* now entirely done by php_intl. These old thing with language-based
* template paths comes from an older time.
*/
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: ext=%s', $ext));
$fileInstance = new SplFileInfo(sprintf('%s%s%s%s%s%s',
$this->getTemplateBasePath(),
$this->getGenericBasePath(),
));
// First try this
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: fileInstance=%s', $fileInstance->__toString()));
try {
// Load the raw template data
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking this->loadRawTemplateData(%s) ...', $fileInstance->__toString()));
$this->loadRawTemplateData($fileInstance);
} catch (FileNotFoundException $e) {
// If we shall load a code-template we need to switch the file extension
- if (($this->getTemplateType() != $this->getConfigInstance()->getConfigEntry('html_template_type')) && (empty($extOther))) {
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: this->templateType=%s,self::htmlTemplateType=%s,extOther=%s', $this->getTemplateType(), self::$htmlTemplateType, $extOther));
+ if (($this->getTemplateType() != self::$htmlTemplateType) && (empty($extOther))) {
// Switch over to the code-template extension and try it again
$ext = $this->getCodeTemplateExtension();
// Try it again...
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking this->loadTemplate(%s,%s) ...', $templateName, $ex));
$this->loadTemplate($templateName, $ext);
} else {
// Throw it again
}
}
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: EXIT!');
}
/**
* @return void
*/
private function loadRawTemplateData (SplFileInfo $fileInstance) {
- // Some debug code to look on the file which is being loaded
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: fileInstance=' . $fileInstance);
-
// Load the raw template
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: fileInstance=%s - CALLED!', $fileInstance->__toString()));
$rawTemplateData = $this->getFileIoInstance()->loadFileContents($fileInstance);
// Store the template's contents into this class
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking this->setRawTemplateData(%d) ...', strlen($rawTemplateData)));
$this->setRawTemplateData($rawTemplateData);
// Remember the template's file instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking this->setLastTemplate(%s) ...', $fileInstance->__toString()));
$this->setLastTemplate($fileInstance);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: EXIT!');
}
/**
* Try to assign an extracted template variable as a "content" or 'config'
* variable.
*
- * @param $variableName The variable's name (shall be content or config)
+ * @param $variableName The variable's name (shall be content or config)
* by default
- * @param $variableName The variable we want to assign
+ * @param $configKey Possible configuration key
* @return void
*/
- private function assignTemplateVariable ($variableName, $var) {
+ private function assignTemplateVariable (string $variableName, string $configKey = '') {
// Replace all dashes to underscores to match variables with configuration entries
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: variableName=%s,configKey=%s - CALLED!', $variableName, $configKey));
$variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
- // Debug message
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',variableName=' . $variableName);
-
// Is it not a config variable?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: variableName=%s', $variableName));
if ($variableName != 'config') {
// Regular template variables
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking this->assignVariable(%s,"") ...', $variableName));
$this->assignVariable($variableName, '');
} else {
// Configuration variables
- $this->assignConfigVariable($var);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking this->assignConfigVariable(%s,"") ...', $configKey));
+ $this->assignConfigVariable($configKey);
}
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: EXIT!');
}
/**
* @param $rawData The raw template data we shall analyze
* @return void
*/
- private function extractVariablesFromRawData ($rawData) {
- // Cast to string
- $rawData = (string) $rawData;
-
+ private function extractVariablesFromRawData (string $rawData) {
// Search for variables
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: rawData(%d)=%s - CALLED!', strlen($rawData), $rawData));
preg_match_all('/\$(\w+)(\[(\w+)\])?/', $rawData, $variableMatches);
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawData(' . strlen($rawData) . ')=' . $rawData . ',variableMatches=' . print_r($variableMatches, true));
-
// Did we find some variables?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: variableMatches[]=%s', gettype($variableMatches)));
if ((is_array($variableMatches)) && (count($variableMatches) == 4) && (count($variableMatches[0]) > 0)) {
// Initialize all missing variables
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: variableMatches()=%d', count($variableMatches)));
foreach ($variableMatches[3] as $key => $var) {
// Variable name
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: key=%s,var=%s', $key, $var));
$variableName = $variableMatches[1][$key];
// Workarround: Do not assign empty variables
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: variableName=%s', $variableName));
if (!empty($var)) {
// Try to assign it, empty strings are being ignored
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking this->assignTemplateVariable(%s,%s) ...', $variableName, $var));
$this->assignTemplateVariable($variableName, $var);
- } // END - if
- } // END - foreach
- } // END - if
+ }
+ }
+ }
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: EXIT!');
}
/**
*/
private function analyzeTemplate (array $templateMatches) {
// Backup raw template data
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: templateMatches()=%d', count($templateMatches)));
$backup = $this->getRawTemplateData();
// Initialize some arrays
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: backup[%s]()=%d,this->loadedRawData[]=%s', gettype($backup), strlen($backup), gettype($this->loadedRawData)));
if (is_null($this->loadedRawData)) {
// Initialize both
- $this->loadedRawData = array();
- $this->rawTemplates = array();
- } // END - if
+ $this->loadedRawData = [];
+ $this->rawTemplates = [];
+ }
// Load all requested templates
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: templateMatches[1]()=%d', count($templateMatches[1])));
foreach ($templateMatches[1] as $template) {
// Load and compile only templates which we have not yet loaded
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: template=%s', $template));
// RECURSIVE PROTECTION! BE CAREFUL HERE!
if ((!isset($this->loadedRawData[$template])) && (!in_array($template, $this->loadedTemplates))) {
- // Debug message
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template);
-
// Template not found, but maybe variable assigned?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-TEMPLATE: template=%s not loaded yet', $template));
if ($this->getVariableIndex($template) !== false) {
// Use that content here
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-TEMPLATE: Assigning this->loadedTemplateData[%s] from variable template=%s ...', $template, $template));
$this->loadedRawData[$template] = $this->readVariable($template);
// Recursive protection:
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-TEMPLATE: Marking template=%s as loaded ...', $template));
array_push($this->loadedTemplates, $template);
} else {
// Then try to search for code-templates
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: template=%s is maybe name of code template?', $template));
try {
- // Load the code template and remember it's contents
+ // Load the code template ...
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking this->loadCodeTemplate(%s) ...', $template));
$this->loadCodeTemplate($template);
+
+ // ... and remember it's contents
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-TEMPLATE: Setting this->loadedRawData[%s] from this->rawTemplateData ...', $template));
$this->loadedRawData[$template] = $this->getRawTemplateData();
// Remember this template for recursion detection
// RECURSIVE PROTECTION!
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-TEMPLATE: Marking template=%s as loaded ...', $template));
array_push($this->loadedTemplates, $template);
} catch (FileNotFoundException $e) {
// Even this is not done... :/
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-TEMPLATE: Marking template=%s as loaded ...', $template));
array_push($this->rawTemplates, $template);
}
}
- } // END - if
- } // END - foreach
+ }
+ }
// Restore the raw template data
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking this->setRawTemplateData(backup()=%d) ...', strlen($backup)));
$this->setRawTemplateData($backup);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: EXIT!');
}
/**
* @param $template The template's name
* @return void
*/
- private function compileCode ($code, $template) {
+ private function compileCode (string $code, string $template) {
// Is this template already compiled?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: code=%s,template=%s - CALLED!', $code, $template));
if (in_array($template, $this->compiledTemplates)) {
// Abort here...
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Found template=%s in this->compiledTemplates - EXIT!', $template));
return;
- } // END - if
+ }
// Remember this template being compiled
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: Adding template=%s to this->compiledTemplates ...', $template));
array_push($this->compiledTemplates, $template);
// Compile the loaded code in five steps:
//
// 1. Backup current template data
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: this->compiledTemplates()=%d', count($this->compiledTemplates)));
$backup = $this->getRawTemplateData();
// 2. Set the current template's raw data as the new content
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking this->setRawTemplateData(code()=%d) ... - backup[%s]()=%d', strlen($code), gettype($backup), strlen($backup)));
$this->setRawTemplateData($code);
// 3. Compile the template data
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: Invoking this->compileTemplate() ...');
$this->compileTemplate();
// 4. Remember it's contents
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('BASE-TEMPLATE: Setting this->loadedRawData[%s] from this->rawTemplateData ...', $template));
$this->loadedRawData[$template] = $this->getRawTemplateData();
// 5. Restore the previous raw content from backup variable
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: Invoking this->setRawTemplateData(backup()=%d) ...', strlen($backup)));
$this->setRawTemplateData($backup);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: EXIT!');
}
/**
*/
private function insertAllTemplates (array $templateMatches) {
// Run through all loaded codes
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-TEMPLATE: templateMatches()=%d', count($templateMatches)));
foreach ($this->loadedRawData as $template => $code) {
-
// Search for the template
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: template=%s,code()=%d', $template, strlen($code)));
$foundIndex = array_search($template, $templateMatches[1]);
// Lookup the matching template replacement
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: foundIndex[%s]=d', gettype($foundIndex), $foundIndex));
if (($foundIndex !== false) && (isset($templateMatches[0][$foundIndex]))) {
-
// Get the current raw template
$rawData = $this->getRawTemplateData();
// Replace the space holder with the template code
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: rawData()=%s - BEFORE!', strlen($rawData)));
$rawData = str_replace($templateMatches[0][$foundIndex], $code, $rawData);
// Set the new raw data
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-TEMPLATE: rawData()=%s - AFTER!', strlen($rawData)));
$this->setRawTemplateData($rawData);
- } // END - if
- } // END - foreach
+ }
+ }
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-TEMPLATE: EXIT!');
}
/**
// This template was never found. We silently ignore it
unset($this->rawTemplates[$key]);
}
- } // END - foreach
- } // END - if
+ }
+ }
}
/**
* @todo Unfinished work or don't die here.
*/
private function assignAllVariables (array $varMatches) {
- // Debug message
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches()=' . count($varMatches));
-
// Search for all variables
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:varMatches()=' . count($varMatches));
foreach ($varMatches[1] as $key => $var) {
// Replace all dashes to underscores to match variables with configuration entries
$var = trim(StringUtils::convertDashesToUnderscores($var));
// Debug message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:key=' . $key . ',var=' . $var);
+ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:key=' . $key . ',var=' . $var);
// Detect leading equals
if (substr($varMatches[2][$key], 0, 1) == '=') {
// Remove and cast it
$varMatches[2][$key] = (string) substr($varMatches[2][$key], 1);
- } // END - if
+ }
// Do we have some quotes left and right side? Then it is free text
if ((substr($varMatches[2][$key], 0, 1) == '"') && (substr($varMatches[2][$key], -1, 1) == '"')) {
// @TODO Non-string found so we need some deeper analysis...
ApplicationEntryPoint::exitApplication('Deeper analysis not yet implemented!');
}
- } // END - foreach
+ }
}
/**
* @return void
*/
private function compileRawTemplateData (array $templateMatches) {
- // Debug message
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:loadedRawData()= ' .count($this->loadedRawData));
-
// Are some code-templates found which we need to compile?
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:loadedRawData()= ' .count($this->loadedRawData));
if (count($this->loadedRawData) > 0) {
// Then compile all!
foreach ($this->loadedRawData as $template => $code) {
// Debug message
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:template=' . $template . ',code(' . strlen($code) . ')=' . $code);
// Is this template already compiled?
if (in_array($template, $this->compiledTemplates)) {
// Then skip it
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Template ' . $template . ' already compiled. SKIPPED!');
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: Template ' . $template . ' already compiled. SKIPPED!');
continue;
- } // END - if
+ }
// Search for the template
$foundIndex = array_search($template, $templateMatches[1]);
if (($foundIndex !== false) && (isset($templateMatches[3][$foundIndex]))) {
// Split it up with another reg. exp. into variable=value pairs
preg_match_all($this->regExpVarValue, $templateMatches[3][$foundIndex], $varMatches);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varMatches=' . print_r($varMatches, true));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:varMatches=' . print_r($varMatches, true));
// Assign all variables
$this->assignAllVariables($varMatches);
- } // END - if (isset($templateMatches ...
+ }
// Compile the loaded template
$this->compileCode($code, $template);
- } // END - foreach ($this->loadedRawData ...
+ }
// Insert all templates
$this->insertAllTemplates($templateMatches);
- } // END - if (count($this->loadedRawData) ...
+ }
}
/**
private function finalizeVariableCompilation () {
// Get the content
$content = $this->getRawTemplateData();
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content before=' . strlen($content) . ' (' . md5($content) . ')');
-
- // Do we have the stack?
- if (!$this->isVarStackSet('general')) {
- // Abort here silently
- // @TODO This silent abort should be logged, maybe.
- return;
- } // END - if
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: content before=' . strlen($content) . ' (' . md5($content) . ')');
// Walk through all variables
foreach ($this->getVarStack('general') as $currEntry) {
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: name=' . $currEntry['name'] . ', value=<pre>' . htmlentities($currEntry['value']) . '</pre>');
// Replace all [$var] or {?$var?} with the content
// @TODO Old behaviour, will become obsolete!
$content = str_replace('$content[' . $currEntry['name'] . ']', $currEntry['value'], $content);
// The new behaviour
$content = str_replace('{?' . $currEntry['name'] . '?}', $currEntry['value'], $content);
- } // END - for
-
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: content after=' . strlen($content) . ' (' . md5($content) . ')');
+ }
// Set the content back
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: content after=' . strlen($content) . ' (' . md5($content) . ')');
$this->setRawTemplateData($content);
}
* @param $template The web template we shall load which is located in
* 'html' by default
* @return void
+ * @throws InvalidArgumentException If the variable name is left empty
*/
- public function loadHtmlTemplate ($template) {
+ public function loadHtmlTemplate (string $template) {
+ // Validate parameter
+ if (empty($template)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "template" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Set template type
- $this->setTemplateType($this->getConfigInstance()->getConfigEntry('html_template_type'));
+ $this->setTemplateType(self::$htmlTemplateType);
// Load the special template
$this->loadTemplate($template);
* @param $variableName The variable we are looking for
* @param $value The value we want to store in the variable
* @return void
- * @throws NullPointerException If $variableName is NULL
* @throws InvalidArgumentException If the variable name is left empty
*/
- public final function assignVariable ($variableName, $value) {
+ public final function assignVariable (string $variableName, $value) {
// Validate parameter
- if (is_null($variableName)) {
- // Throw NPE
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } elseif (empty($variableName)) {
+ if (empty($variableName)) {
// Throw an exception
- throw new InvalidArgumentException('Parameter "variableName" is empty');
+ throw new InvalidArgumentException('Parameter "variableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
}
// Replace all dashes to underscores to match variables with configuration entries
// Was it found?
if ($index === false) {
// Add it to the stack
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:ADD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
$this->addVariable($variableName, $value);
} elseif (!empty($value)) {
// Modify the stack entry
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:MOD: ' . $variableName . '[' . gettype($value) . ']=' . $value);
$this->modifyVariable($variableName, $value);
}
}
* @param $variableName The variable we are looking for
* @param $variableGroup Name of variable group (default: 'general')
* @return void
+ * @throws InvalidArgumentException If the variable name is left empty
*/
- public final function removeVariable ($variableName, $variableGroup = 'general') {
+ public final function removeVariable (string $variableName, string $variableGroup = 'general') {
+ // Validate parameter
+ if (empty($variableName)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "variableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($variableGroup)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "variableGroup" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// First search for the variable if it was already added
$index = $this->getVariableIndex($variableName, $variableGroup);
// Was it found?
if ($index !== false) {
// Remove this variable
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:UNSET: variableGroup=' . $variableGroup . ',variableName=' . $variableName . ',index=' . $index);
$this->unsetVariableStackOffset($index, $variableGroup);
- } // END - if
+ }
}
/**
* @param $templateName Name of the template we want to assign
* @param $variableName Name of the variable we want to assign
* @return void
+ * @throws InvalidArgumentException If the variable name is left empty
*/
- public function assignTemplateWithVariable ($templateName, $variableName) {
+ public function assignTemplateWithVariable (string $templateName, string $variableName) {
+ // Validate parameter
+ if (empty($templateName)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "templateName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($variableName)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "variableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get the content from last loaded raw template
$content = $this->getRawTemplateData();
*
* @param $variableName The configuration variable we want to assign
* @return void
+ * @throws InvalidArgumentException If the variable name is left empty
*/
- public function assignConfigVariable ($variableName) {
+ public function assignConfigVariable (string $variableName) {
+ // Validate parameter
+ if (empty($variableName)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "variableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Replace all dashes to underscores to match variables with configuration entries
$variableName = trim(StringUtils::convertDashesToUnderscores($variableName));
// Sweet and simple...
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: variableName=' . $variableName . ',getConfigEntry()=' . $this->getConfigInstance()->getConfigEntry($variableName));
- $this->assignVariable($variableName, $this->getConfigInstance()->getConfigEntry($variableName));
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: variableName=' . $variableName . ',getConfigEntry()=' . FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($variableName));
+ $this->assignVariable($variableName, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($variableName));
}
/**
foreach ($variables as $name => $value) {
// Set variable with name for 'config' group
$this->assignVariable($name, $value);
- } // END - foreach
+ }
}
/**
*/
public function assignApplicationData () {
// Get application instance
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Get long name and assign it
$this->assignVariable('app_full_name' , $applicationInstance->getAppName());
* @param $template The code template we shall load which is
* located in 'code' by default
* @return void
+ * @throws InvalidArgumentException If the variable name is left empty
*/
- public function loadCodeTemplate ($template) {
+ public function loadCodeTemplate (string $template) {
+ // Validate parameter
+ if (empty($template)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "template" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Set template type
- $this->setTemplateType($this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type'));
+ $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type'));
// Load the special template
$this->loadTemplate($template);
* @param $template The email template we shall load which is
* located in 'emails' by default
* @return void
+ * @throws InvalidArgumentException If the variable name is left empty
*/
- public function loadEmailTemplate ($template) {
+ public function loadEmailTemplate (string $template) {
+ // Validate parameter
+ if (empty($template)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "template" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Set template type
- $this->setTemplateType($this->getConfigInstance()->getConfigEntry('email_template_type'));
+ $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('email_template_type'));
// Load the special template
$this->loadTemplate($template);
// Do we have the stack?
if (!$this->isVarStackSet('general')) {
// Abort here silently
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: Aborted, variable stack general not found!');
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: Aborted, variable stack general not found!');
return;
- } // END - if
+ }
// Iterate through all general variables
foreach ($this->getVarStack('general') as $index => $currVariable) {
$value = $this->compileRawCode($this->readVariable($currVariable['name']), true);
// Debug message
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: name=' . $currVariable['name'] . ',value=' . $value);
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: name=' . $currVariable['name'] . ',value=' . $value);
// Remove it from stack
$this->removeVariable($currVariable['name'], 'general');
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: value='. $value . ',name=' . $currVariable['name'] . ',index=' . $index);
// Is it a configuration key?
- if ($this->getConfigInstance()->isConfigurationEntrySet($value)) {
+ if (FrameworkBootstrap::getConfigurationInstance()->isConfigurationEntrySet($value)) {
// The value itself is a configuration entry
$this->assignConfigVariable($value);
} else {
// Re-assign the value directly
$this->assignVariable($currVariable['name'], $value);
}
- } // END - foreach
+ }
}
/**
*/
public final function compileVariables () {
// Initialize the $content array
- $validVar = $this->getConfigInstance()->getConfigEntry('tpl_valid_var');
- $dummy = array();
+ $validVar = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('tpl_valid_var');
+ $dummy = [];
// Iterate through all general variables
foreach ($this->getVarStack('general') as $currVariable) {
// Transfer it's name/value combination to the $content array
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:' . $currVariable['name'] . '=<pre>' . htmlentities($currVariable['value']).'</pre>');
$dummy[$currVariable['name']] = $currVariable['value'];
- }// END - if
+ }
// Set the new variable (don't remove the second dollar!)
$$validVar = $dummy;
// And put all together
$eval = sprintf('%s<%%php %s %%>%s', $evalLeft, $evalMiddle, $evalRight);
- } // END - while
+ }
// Prepare PHP code for eval() command
$eval = str_replace(
// Output backtrace here
$this->debugBackTrace();
- } // END - if
+ }
// Set raw template data
$this->setRawTemplateData($result);
$cnt++;
- } // END - while
+ }
// Final variable assignment
$this->finalizeVariableCompilation();
*/
public function compileTemplate () {
// Get code type to make things shorter
- $codeType = $this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type');
+ $codeType = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type');
// We will only work with template type "code" from configuration
if (substr($this->getTemplateType(), 0, strlen($codeType)) != $codeType) {
// Abort here
- throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), $this->getConfigInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
- } // END - if
+ throw new UnexpectedTemplateTypeException(array($this, $this->getTemplateType(), FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_template_type')), self::EXCEPTION_TEMPLATE_TYPE_IS_UNEXPECTED);
+ }
// Get the raw data.
$rawData = $this->getRawTemplateData();
preg_match_all($this->regExpCodeTags, $rawData, $templateMatches);
// Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:templateMatches=' . print_r($templateMatches , true));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:templateMatches=' . print_r($templateMatches , true));
// Analyze the matches array
if ((is_array($templateMatches)) && (count($templateMatches) == 4) && (count($templateMatches[0]) > 0)) {
// Remove the raw template content as well
$this->setRawTemplateData('');
- } // END - if
- } // END - if($templateMatches ...
+ }
+ }
}
/**
*
* @param $helperName The helper's name
* @return void
+ * @throws InvalidArgumentException If the variable name is left empty
*/
- protected function loadViewHelper ($helperName) {
+ protected function loadViewHelper (string $helperName) {
+ // Validate parameter
+ if (empty($helperName)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "helperName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Is this view helper loaded?
if (!isset($this->helpers[$helperName])) {
// Create a class name
- $className = self::convertToClassName($helperName) . 'ViewHelper';
+ $className = StringUtils::convertToClassName($helperName) . 'ViewHelper';
// Generate new instance
$this->helpers[$helperName] = ObjectFactory::createObjectByName($className);
- } // END - if
+ }
// Return the requested instance
return $this->helpers[$helperName];
* @param $rawCode Raw code to compile
* @param $setMatchAsCode Sets $match if readVariable() returns empty result
* @return $rawCode Compile code with inserted variable value
+ * @throws InvalidArgumentException If the variable name is left empty
*/
- public function compileRawCode ($rawCode, $setMatchAsCode=false) {
+ public function compileRawCode (string $rawCode, bool $setMatchAsCode = false) {
+ // Validate parameter
+ if (empty($rawCode)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "rawCode" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Find the variables
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
preg_match_all($this->regExpVarValue, $rawCode, $varMatches);
// Compile all variables
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:<pre>' . print_r($varMatches, true) . '</pre>');
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:<pre>' . print_r($varMatches, true) . '</pre>');
foreach ($varMatches[0] as $match) {
// Add variable tags around it
$varCode = '{?' . $match . '?}';
// Debug message
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:varCode=' . $varCode);
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:varCode=' . $varCode);
// Is the variable found in code? (safes some calls)
if (strpos($rawCode, $varCode) !== false) {
// Debug message
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: match=' . $match . ',rawCode[' . gettype($rawCode) . ']=' . $rawCode);
// Use $match as new value or $value from read variable?
if ($setMatchAsCode === true) {
// Insert value
$rawCode = str_replace($varCode, $value, $rawCode);
}
- } // END - if
- } // END - foreach
+ }
+ }
// Return the compiled data
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE:rawCode=<pre>' . htmlentities($rawCode) . '</pre>');
return $rawCode;
}
* @param $oldName Old name of variable
* @param $newName New name of variable
* @return void
+ * @throws InvalidArgumentException If the variable name is left empty
*/
- public function renameVariable ($oldName, $newName) {
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE[' . __METHOD__ . ':' . __LINE__ . ']: oldName=' . $oldName . ', newName=' . $newName);
+ public function renameVariable (string $oldName, string $newName) {
+ // Validate parameter
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-TEMPLATE: oldName=' . $oldName . ', newName=' . $newName);
+ if (empty($oldName)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "oldName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($newName)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "newName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get raw template code
$rawData = $this->getRawTemplateData();
$this->setRawTemplateData($rawData);
}
- /**
- * Renders the given XML content
- *
- * @param $content Valid XML content or if not set the current loaded raw content
- * @return void
- * @throws XmlParserException If an XML error was found
- */
- public function renderXmlContent ($content = NULL) {
- // Is the content set?
- if (is_null($content)) {
- // Get current content
- $content = $this->getRawTemplateData();
- } // END - if
-
- // Get a XmlParser instance
- $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', array($this));
-
- // Check if XML compacting is enabled
- if ($this->isXmlCompactingEnabled()) {
- // Yes, so get a decorator class for transparent compacting
- $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', array($parserInstance));
- } // END - if
-
- // Parse the XML document
- $parserInstance->parseXmlContent($content);
- }
-
/**
* Enables or disables language support
*
* @param $languageSupport New language support setting
* @return void
*/
- public final function enableLanguageSupport ($languageSupport = true) {
- $this->languageSupport = (bool) $languageSupport;
+ public final function enableLanguageSupport (bool $languageSupport = true) {
+ $this->languageSupport = $languageSupport;
}
/**
return $this->languageSupport;
}
- /**
- * Enables or disables XML compacting
- *
- * @param $xmlCompacting New XML compacting setting
- * @return void
- */
- public final function enableXmlCompacting ($xmlCompacting = true) {
- $this->xmlCompacting = (bool) $xmlCompacting;
- }
-
- /**
- * Checks whether XML compacting is enabled
- *
- * @return $xmlCompacting Whether XML compacting is enabled or disabled
- */
- public final function isXmlCompactingEnabled () {
- return $this->xmlCompacting;
- }
-
/**
* Removes all commentd, tabs and new-line characters to compact the content
*
* @param $uncompactedContent The uncompacted content
* @return $compactedContent The compacted content
*/
- public function compactContent ($uncompactedContent) {
+ public function compactContent (string $uncompactedContent) {
+ // Validate parameter
+ if (empty($uncompactedContent)) {
+ // Throw an exception
+ throw new InvalidArgumentException('Parameter "uncompactedContent" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// First, remove all tab/new-line/revert characters
$compactedContent = str_replace(chr(9), '', str_replace(chr(10), '', str_replace(chr(13), '', $uncompactedContent)));
foreach ($matches[0] as $match) {
// Remove the match
$compactedContent = str_replace($match, '', $compactedContent);
- } // END - foreach
- } // END - if
+ }
+ }
// Set the content again
$this->setRawTemplateData($compactedContent);
namespace Org\Mxchange\CoreFramework\Template\Engine;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Filesystem\InvalidDirectoryException;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
use Org\Mxchange\CoreFramework\Template\Engine\BaseTemplateEngine;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @todo This template engine does not make use of setTemplateType()
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$templateInstance = new ConsoleTemplateEngine();
// Get the application instance from registry
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Determine base path
- $templateBasePath = $templateInstance->getConfigInstance()->getConfigEntry('application_base_path') . $applicationInstance->getAppShortName(). '/';
+ $templateBasePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . $applicationInstance->getAppShortName(). '/';
// Is the base path valid?
if (empty($templateBasePath)) {
// Base path is empty
- throw new UnexpectedValueException(sprintf('[%s:%d] Variable templateBasePath is empty.', $templateInstance->__toString(), __LINE__), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
- } elseif (!is_string($templateBasePath)) {
- // Is not a string
- throw new UnexpectedValueException(sprintf('[%s:%d] %s is not a string with a base path.', $templateInstance->__toString(), __LINE__, $templateBasePath), self::EXCEPTION_INVALID_STRING);
+ throw new UnexpectedValueException(sprintf('[%s:%d] Variable templateBasePath is empty.', $templateInstance->__toString(), __LINE__), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
} elseif (!is_dir($templateBasePath)) {
// Is not a path
throw new InvalidDirectoryException(array($templateInstance, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
$templateInstance->setTemplateBasePath($templateBasePath);
// Set template extensions
- $templateInstance->setRawTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('raw_template_extension'));
- $templateInstance->setCodeTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('code_template_extension'));
+ $templateInstance->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
+ $templateInstance->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_template_extension'));
// Absolute output path for compiled templates
$templateInstance->setCompileOutputPath(sprintf('%s%s/',
$templateBasePath,
- $templateInstance->getConfigInstance()->getConfigEntry('compile_output_path')
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
));
// Return the prepared instance
namespace Org\Mxchange\CoreFramework\Template\Engine;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Filesystem\InvalidDirectoryException;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
use Org\Mxchange\CoreFramework\Template\Engine\BaseTemplateEngine;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$templateInstance = new HtmlTemplateEngine();
// Get the application instance from registry
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Determine base path
- $templateBasePath = $templateInstance->getConfigInstance()->getConfigEntry('application_base_path') . $applicationInstance->getAppShortName(). '/';
+ $templateBasePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . $applicationInstance->getAppShortName(). '/';
// Is the base path valid?
if (empty($templateBasePath)) {
// Base path is empty
- throw new UnexpectedValueException(sprintf('[%s:%d] Variable templateBasePath is empty.', $templateInstance->__toString(), __LINE__), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
- } elseif (!is_string($templateBasePath)) {
- // Is not a string
- throw new UnexpectedValueException(sprintf('[%s:%d] %s is not a string with a base path.', $templateInstance->__toString(), __LINE__, $templateBasePath), self::EXCEPTION_INVALID_STRING);
+ throw new UnexpectedValueException(sprintf('[%s:%d] Variable templateBasePath is empty.', $templateInstance->__toString(), __LINE__), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
} elseif (!is_dir($templateBasePath)) {
// Is not a path
throw new InvalidDirectoryException(array($templateInstance, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
$templateInstance->setTemplateBasePath($templateBasePath);
// Set template extensions
- $templateInstance->setRawTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('raw_template_extension'));
- $templateInstance->setCodeTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('code_template_extension'));
+ $templateInstance->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
+ $templateInstance->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_template_extension'));
// Absolute output path for compiled templates
$templateInstance->setCompileOutputPath(sprintf('%s%s/',
$templateBasePath,
- $templateInstance->getConfigInstance()->getConfigEntry('compile_output_path')
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
));
// Return the prepared instance
namespace Org\Mxchange\CoreFramework\Template\Engine;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filesystem\InvalidDirectoryException;
-use Org\Mxchange\CoreFramework\Parser\Xml\XmlParser;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
+use Org\Mxchange\CoreFramework\Image\BaseImage;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+use Org\Mxchange\CoreFramework\Parser\Parseable;
use Org\Mxchange\CoreFramework\Response\Responseable;
use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
use Org\Mxchange\CoreFramework\Template\Engine\BaseTemplateEngine;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
// Import SPL stuff
use \SplFileInfo;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*/
private $currMainNode = '';
+ /**
+ * Instance of the image
+ */
+ private $imageInstance = NULL;
+
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$templateInstance = new ImageTemplateEngine();
// Get the application instance from registry
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Determine base path
- $templateBasePath = $templateInstance->getConfigInstance()->getConfigEntry('application_base_path') . $applicationInstance->getAppShortName(). '/';
+ $templateBasePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . $applicationInstance->getAppShortName(). '/';
// Is the base path valid?
if (empty($templateBasePath)) {
// Base path is empty
- throw new UnexpectedValueException(sprintf('[%s:%d] Variable templateBasePath is empty.', $templateInstance->__toString(), __LINE__), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
- } elseif (!is_string($templateBasePath)) {
- // Is not a string
- throw new UnexpectedValueException(sprintf('[%s:%d] %s is not a string with a base path.', $templateInstance->__toString(), __LINE__, $templateBasePath), self::EXCEPTION_INVALID_STRING);
+ throw new UnexpectedValueException(sprintf('[%s:%d] Variable templateBasePath is empty.', $templateInstance->__toString(), __LINE__), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
} elseif (!is_dir($templateBasePath)) {
// Is not a path
throw new InvalidDirectoryException(array($templateInstance, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
$templateInstance->setTemplateBasePath($templateBasePath);
// Set template extensions
- $templateInstance->setRawTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('raw_template_extension'));
- $templateInstance->setCodeTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('code_template_extension'));
+ $templateInstance->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
+ $templateInstance->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_template_extension'));
// Absolute output path for compiled templates
$templateInstance->setCompileOutputPath(sprintf('%s%s/',
$templateBasePath,
- $templateInstance->getConfigInstance()->getConfigEntry('compile_output_path')
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
));
// Return the prepared instance
return $this->subNodes;
}
+ /**
+ * Setter for image instance
+ *
+ * @param $imageInstance An instance of an image
+ * @return void
+ */
+ public final function setImageInstance (BaseImage $imageInstance) {
+ $this->imageInstance = $imageInstance;
+ }
+
+ /**
+ * Getter for image instance
+ *
+ * @return $imageInstance An instance of an image
+ */
+ public final function getImageInstance () {
+ return $this->imageInstance;
+ }
+
/**
* Handles the start element of an XML resource
*
* @return void
* @throws InvalidXmlNodeException If an unknown/invalid XML node name was found
*/
- public function startElement ($resource, $element, array $attributes) {
+ public function startElement ($resource, string $element, array $attributes) {
// Initial method name which will never be called...
$methodName = 'initImage';
//* DEBUG: */ echo "START: >".$element."<<br />\n";
if (in_array($element, $this->mainNodes)) {
// Okay, main node found!
- $methodName = 'setImage' . self::convertToClassName($element);
+ $methodName = 'setImage' . StringUtils::convertToClassName($element);
} elseif (in_array($element, $this->subNodes)) {
// Sub node found
- $methodName = 'setImageProperty' . self::convertToClassName($element);
+ $methodName = 'setImageProperty' . StringUtils::convertToClassName($element);
} elseif ($element != 'image') {
// Invalid node name found
- throw new InvalidXmlNodeException(array($this, $element, $attributes), XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
+ throw new InvalidXmlNodeException([$this, $element, $attributes], Parseable::EXCEPTION_XML_NODE_UNKNOWN);
}
// Call method
* @return void
* @throws XmlNodeMismatchException If current main node mismatches the closing one
*/
- public function finishElement ($resource, $nodeName) {
- // Make all lower-case
- $nodeName = strtolower($nodeName);
-
+ public function finishElement ($resource, string $nodeName) {
// Does this match with current main node?
//* DEBUG: */ echo "END: >".$nodeName."<<br />\n";
if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
// Did not match!
- throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), XmlParser::EXCEPTION_XML_NODE_MISMATCH);
+ throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), Parseable::EXCEPTION_XML_NODE_MISMATCH);
} elseif (in_array($nodeName, $this->getSubNodes())) {
// Silently ignore sub nodes
return;
}
// Construct method name
- $methodName = 'finish' . self::convertToClassName($nodeName);
+ $methodName = sprintf('finish%s', StringUtils::convertToClassName($nodeName));
// Call the corresponding method
- call_user_func_array(array($this->getImageInstance(), $methodName), array());
+ call_user_func_array(array($this->getImageInstance(), $methodName), []);
}
/**
* @return void
* @todo Find something usefull with this!
*/
- public function characterHandler ($resource, $characters) {
+ public function characterHandler ($resource, string $characters) {
// Trim all spaces away
$characters = trim($characters);
if (empty($characters)) {
// Then skip it silently
return;
- } // END - if
+ }
// Unfinished work!
- $this->partialStub('Handling extra characters is not yet supported!');
+ DebugMiddleware::getSelfInstance()->partialStub('Handling extra characters is not yet supported!');
}
/**
* @param $imageType Code fragment or direct value holding the image type
* @return void
*/
- private function setImageType ($imageType) {
+ private function setImageType (string $imageType) {
// Set group to general
$this->setVariableGroup('general');
$imageType = $this->compileRawCode($imageType);
// Now make a class name of it
- $className = self::convertToClassName($imageType.'_image');
+ $className = StringUtils::convertToClassName($imageType.'_image');
// And try to initiate it
- $this->setImageInstance(ObjectFactory::createObjectByName($className, array($this)));
+ $this->setImageInstance(ObjectFactory::createObjectByName($className, [$this]));
// Set current main node to type
$this->currMainNode = 'type';
* @return void
* @see ImageTemplateEngine::setImageResolution
*/
- private function setImageImageString ($groupable = 'single') {
+ private function setImageImageString (string $groupable = 'single') {
// Call the image class
$this->getImageInstance()->initImageString($groupable);
* @param $imageName Name of the image
* @return void
*/
- private function setImagePropertyName ($imageName) {
+ private function setImagePropertyName (string $imageName) {
// Call the image class
$this->getImageInstance()->setImageName($imageName);
}
* @param $width Width of the image or variable
* @return void
*/
- private function setImagePropertyWidth ($width) {
+ private function setImagePropertyWidth (int $width) {
// Call the image class
$this->getImageInstance()->setWidth($width);
}
* @param $height Height of the image or variable
* @return void
*/
- private function setImagePropertyHeight ($height) {
+ private function setImagePropertyHeight (int $height) {
// Call the image class
$this->getImageInstance()->setHeight($height);
}
* @param $stringName String name (identifier)
* @return void
*/
- private function setImagePropertyStringName ($stringName) {
+ private function setImagePropertyStringName (string $stringName) {
// Call the image class
$this->getImageInstance()->setStringName($stringName);
}
* @param $fontSize Size of the font
* @return void
*/
- private function setImagePropertyFontSize ($fontSize) {
+ private function setImagePropertyFontSize (int $fontSize) {
// Call the image class
$this->getImageInstance()->setFontSize($fontSize);
}
* @param $imageString Image string to set
* @return void
*/
- private function setImagePropertyText ($imageString) {
+ private function setImagePropertyText (string $imageString) {
// Call the image class
$this->getImageInstance()->setString($imageString);
}
* @param $x X coordinate
* @return void
*/
- private function setImagePropertyX ($x) {
+ private function setImagePropertyX (int $x) {
// Call the image class
$this->getImageInstance()->setX($x);
}
* @param $y Y coordinate
* @return void
*/
- private function setImagePropertyY ($y) {
+ private function setImagePropertyY (int $y) {
// Call the image class
$this->getImageInstance()->setY($y);
}
public function getImageCacheFile () {
// Get the instance ready
$fileInstance = new SplFileInfo(sprintf('%s%s%s/%s.%s',
- $this->getConfigInstance()->getConfigEntry('root_base_path'),
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('root_base_path'),
$this->getGenericBasePath(),
'images/_cache',
md5(
*
* @param $responseInstance An instance of a Responseable class
* @return void
+ * @todo Nothing to really "transfer" here?
*/
public function transferToResponse (Responseable $responseInstance) {
// Set the image instance
* located in 'image' by default
* @return void
*/
- public function loadImageTemplate ($template) {
+ public function loadImageTemplate (string $template) {
// Set template type
- $this->setTemplateType($this->getConfigInstance()->getConfigEntry('image_template_type'));
+ $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('image_template_type'));
// Load the special template
$this->loadTemplate($template);
namespace Org\Mxchange\CoreFramework\Template\Engine;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Filesystem\InvalidDirectoryException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Mailer\DeliverableMail;
-use Org\Mxchange\CoreFramework\Parser\Xml\XmlParser;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
+use Org\Mxchange\CoreFramework\Parser\Parseable;
use Org\Mxchange\CoreFramework\Response\Responseable;
use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
use Org\Mxchange\CoreFramework\Template\Engine\BaseTemplateEngine;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
// Import SPL stuff
use \UnexpectedValueException;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @todo This template engine does not make use of setTemplateType()
/**
* Main nodes in the XML tree
*/
- private $mainNodes = array(
+ private $mainNodes = [
'mail-data'
- );
+ ];
/**
* Sub nodes in the XML tree
*/
- private $subNodes = array(
+ private $subNodes = [
'subject-line',
'sender-address',
'recipient-address',
'message'
- );
+ ];
/**
* Mailer instance
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
+
+ // Set template type
+ $this->setTemplateType('mail');
}
/**
$templateInstance = new MailTemplateEngine();
// Get the application instance from registry
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Determine base path
- $templateBasePath = $templateInstance->getConfigInstance()->getConfigEntry('application_base_path') . $applicationInstance->getAppShortName(). '/';
+ $templateBasePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . $applicationInstance->getAppShortName(). '/';
// Is the base path valid?
if (empty($templateBasePath)) {
// Base path is empty
- throw new UnexpectedValueException(sprintf('[%s:%d] Variable templateBasePath is empty.', $templateInstance->__toString(), __LINE__), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
- } elseif (!is_string($templateBasePath)) {
- // Is not a string
- throw new UnexpectedValueException(sprintf('[%s:%d] %s is not a string with a base path.', $templateInstance->__toString(), __LINE__, $templateBasePath), self::EXCEPTION_INVALID_STRING);
+ throw new UnexpectedValueException(sprintf('[%s:%d] Variable templateBasePath is empty.', $templateInstance->__toString(), __LINE__), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
} elseif (!is_dir($templateBasePath)) {
// Is not a path
throw new InvalidDirectoryException(array($templateInstance, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
$templateInstance->setTemplateBasePath($templateBasePath);
// Set template extensions
- $templateInstance->setRawTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('raw_template_extension'));
- $templateInstance->setCodeTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('code_template_extension'));
+ $templateInstance->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
+ $templateInstance->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('code_template_extension'));
// Absolute output path for compiled templates
$templateInstance->setCompileOutputPath(sprintf('%s%s/',
$templateBasePath,
- $templateInstance->getConfigInstance()->getConfigEntry('compile_output_path')
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
));
// Return the prepared instance
* @return void
* @throws InvalidXmlNodeException If an unknown/invalid XML node name was found
*/
- public function startElement ($resource, $element, array $attributes) {
+ public function startElement ($resource, string $element, array $attributes) {
// Initial method name which will never be called...
$methodName = 'initEmail';
//* DEBUG: */ echo "START: >".$element."<<br />\n";
if (in_array($element, $this->getMainNodes())) {
// Okay, main node found!
- $methodName = 'setEmail' . self::convertToClassName($element);
+ $methodName = 'setEmail' . StringUtils::convertToClassName($element);
} elseif (in_array($element, $this->getSubNodes())) {
// Sub node found
- $methodName = 'setEmailProperty' . self::convertToClassName($element);
+ $methodName = 'setEmailProperty' . StringUtils::convertToClassName($element);
} elseif ($element != 'text-mail') {
// Invalid node name found
- throw new InvalidXmlNodeException(array($this, $element, $attributes), XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
+ throw new InvalidXmlNodeException([$this, $element, $attributes], Parseable::EXCEPTION_XML_NODE_UNKNOWN);
}
// Call method
* @return void
* @throws XmlNodeMismatchException If current main node mismatches the closing one
*/
- public function finishElement ($resource, $nodeName) {
- // Make all lower-case
- $nodeName = strtolower($nodeName);
-
+ public function finishElement ($resource, string $nodeName) {
// Does this match with current main node?
//* DEBUG: */ echo "END: >".$nodeName."<<br />\n";
if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
// Did not match!
- throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), XmlParser::EXCEPTION_XML_NODE_MISMATCH);
+ throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), Parseable::EXCEPTION_XML_NODE_MISMATCH);
} elseif (in_array($nodeName, $this->getSubNodes())) {
// Silently ignore sub nodes
return;
}
// Construct method name
- $methodName = 'finish' . self::convertToClassName($nodeName);
+ $methodName = 'finish' . StringUtils::convertToClassName($nodeName);
// Call the corresponding method
- call_user_func_array(array($this, $methodName), array());
+ call_user_func_array(array($this, $methodName), []);
}
/**
* @param $characters Characters to handle
* @return void
*/
- public function characterHandler ($resource, $characters) {
+ public function characterHandler ($resource, string $characters) {
// Trim all spaces away
$characters = trim($characters);
if (empty($characters)) {
// Then skip it silently
return;
- } // END - if
+ }
// Add the message now
$this->assignVariable('message', $characters);
* @param $senderAddress Sender address to set in email
* @return void
*/
- private function setEmailPropertySenderAddress ($senderAddress) {
+ private function setEmailPropertySenderAddress (string $senderAddress) {
// Set the template variable
$this->assignVariable('sender', $senderAddress);
}
* @param $recipientAddress Recipient address to set in email
* @return void
*/
- private function setEmailPropertyRecipientAddress ($recipientAddress) {
+ private function setEmailPropertyRecipientAddress (string $recipientAddress) {
// Set the template variable
$this->assignVariable('recipient', $recipientAddress);
}
namespace Org\Mxchange\CoreFramework\Template\Engine;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filesystem\InvalidDirectoryException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Menu\RenderableMenu;
-use Org\Mxchange\CoreFramework\Parser\Xml\XmlParser;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
-use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
+use Org\Mxchange\CoreFramework\Parser\Parseable;
use Org\Mxchange\CoreFramework\Template\Engine\BaseTemplateEngine;
+use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
+use Org\Mxchange\CoreFramework\Traits\Stack\StackableTrait;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
// Import SPL stuff
use \SplFileInfo;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class MenuTemplateEngine extends BaseTemplateEngine implements CompileableTemplate {
+ // Load traits
+ use StackableTrait;
+
/**
* Main nodes in the XML tree ('menu' is ignored)
*/
- private $mainNodes = array(
+ private $mainNodes = [
'block-list',
- );
+ ];
/**
* Sub nodes in the XML tree
*/
- private $subNodes = array(
+ private $subNodes = [
'entry-list',
'entry',
'entry-id',
'anchor-text',
'anchor-title',
'anchor-href',
- );
+ ];
/**
* Variables for a menu entry
*/
- private $menuEntryVariables = array(
+ private $menuEntryVariables = [
// List entry
'entry_id',
// Anchor
'anchor-text',
'anchor-title',
'anchor-href',
- );
+ ];
/**
* Variables for a menu block
*/
- private $menuBlockVariables = array(
+ private $menuBlockVariables = [
// Title
'title_id',
'title_class',
'footer_id',
'footer_class',
'footer_text',
- );
+ ];
/**
* Rendered menu entries
*/
- private $menuEntries = array();
+ private $menuEntries = [];
/**
* Rendered menu blocks
*/
- private $menuBlocks = array();
+ private $menuBlocks = [];
/**
- * Menu instance
+ * Current main node
*/
- private $menuInstance = NULL;
+ private $curr = [];
/**
- * Current main node
+ * Content from dependency
*/
- private $curr = array();
+ private $dependencyContent = [];
/**
- * Content from dependency
+ * Instance of a menu
*/
- private $dependencyContent = array();
+ private $menuInstance = NULL;
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
$templateInstance = new MenuTemplateEngine();
// Get the application instance from registry
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Determine base path
- $templateBasePath = $templateInstance->getConfigInstance()->getConfigEntry('application_base_path') . $applicationInstance->getAppShortName(). '/';
+ $templateBasePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path') . $applicationInstance->getAppShortName(). '/';
// Is the base path valid?
if (empty($templateBasePath)) {
// Base path is empty
- throw new UnexpectedValueException(sprintf('[%s:%d] Variable templateBasePath is empty.', $templateInstance->__toString(), __LINE__), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
- } elseif (!is_string($templateBasePath)) {
- // Is not a string
- throw new UnexpectedValueException(sprintf('[%s:%d] %s is not a string with a base path.', $templateInstance->__toString(), __LINE__, $templateBasePath), self::EXCEPTION_INVALID_STRING);
+ throw new UnexpectedValueException(sprintf('[%s:%d] Variable templateBasePath is empty.', $templateInstance->__toString(), __LINE__), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
} elseif (!is_dir($templateBasePath)) {
// Is not a path
throw new InvalidDirectoryException(array($templateInstance, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
$templateInstance->setTemplateBasePath($templateBasePath);
// Set template extensions
- $templateInstance->setRawTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('raw_template_extension'));
- $templateInstance->setCodeTemplateExtension($templateInstance->getConfigInstance()->getConfigEntry('menu_template_extension'));
+ $templateInstance->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
+ $templateInstance->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('menu_template_extension'));
// Absolute output path for compiled templates
$templateInstance->setCompileOutputPath(sprintf('%s%s/',
$templateBasePath,
- $templateInstance->getConfigInstance()->getConfigEntry('compile_output_path')
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
));
// Set the menu instance
return $templateInstance;
}
+ /**
+ * Setter for the menu instance
+ *
+ * @param $menuInstance A RenderableMenu instance
+ * @return void
+ */
+ protected final function setMenuInstance (RenderableMenu $menuInstance) {
+ $this->menuInstance = $menuInstance;
+ }
+
+ /**
+ * Getter for the menu instance
+ *
+ * @return $menuInstance A RenderableMenu instance
+ */
+ private final function getMenuInstance () {
+ return $this->menuInstance;
+ }
+
/**
* Load a specified menu template into the engine
*
* located in 'menu' by default
* @return void
*/
- public function loadMenuTemplate ($template) {
+ public function loadMenuTemplate (string $template) {
// Set template type
- $this->setTemplateType($this->getConfigInstance()->getConfigEntry('menu_template_type'));
+ $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('menu_template_type'));
// Load the special template
$this->loadTemplate($template);
* @param $element Element name to set as current main node
* @return $currMainNode Current main node
*/
- private final function setCurrMainNode ($element) {
- $this->curr['main_node'] = (string) $element;
+ private final function setCurrMainNode (string $element) {
+ $this->curr['main_node'] = $element;
}
/**
* @return void
* @throws InvalidXmlNodeException If an unknown/invalid XML node name was found
*/
- public function startElement ($resource, $element, array $attributes) {
+ public function startElement ($resource, string $element, array $attributes) {
// Initial method name which will never be called...
$methodName = 'initMenu';
//* DEBUG: */ echo "START: >".$element."<<br />\n";
if (in_array($element, $this->getMainNodes())) {
// Okay, main node found!
- $methodName = 'start' . self::convertToClassName($element);
+ $methodName = 'start' . StringUtils::convertToClassName($element);
// Set it
$this->setCurrMainNode($element);
} elseif (in_array($element, $this->getSubNodes())) {
// Sub node found
- $methodName = 'start' . self::convertToClassName($element);
+ $methodName = 'start' . StringUtils::convertToClassName($element);
} elseif ($element != 'menu') {
// Invalid node name found
- throw new InvalidXmlNodeException(array($this, $element, $attributes), XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
+ throw new InvalidXmlNodeException([$this, $element, $attributes], Parseable::EXCEPTION_XML_NODE_UNKNOWN);
}
// Call method
* @return void
* @throws XmlNodeMismatchException If current main node mismatches the closing one
*/
- public function finishElement ($resource, $nodeName) {
- // Make all lower-case
- $nodeName = strtolower($nodeName);
-
+ public function finishElement ($resource, string $nodeName) {
// Does this match with current main node?
//* DEBUG: */ echo "END: >".$nodeName."<<br />\n";
if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
// Did not match!
- throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), XmlParser::EXCEPTION_XML_NODE_MISMATCH);
- } // END - if
+ throw new XmlNodeMismatchException (array($this, $nodeName, $this->getCurrMainNode()), Parseable::EXCEPTION_XML_NODE_MISMATCH);
+ }
// Construct method name
- $methodName = 'finish' . self::convertToClassName($nodeName);
+ $methodName = 'finish' . StringUtils::convertToClassName($nodeName);
// Call the corresponding method
//* DEBUG: */ echo "call: ".$methodName."<br />\n";
- call_user_func_array(array($this, $methodName), array());
+ call_user_func_array(array($this, $methodName), []);
}
/**
* @return void
* @todo Find something useful with this!
*/
- public function characterHandler ($resource, $characters) {
+ public function characterHandler ($resource, string $characters) {
// Trim all spaces away
$characters = trim($characters);
if (empty($characters)) {
// Then skip it silently
return;
- } // END - if
+ }
// Assign the found characters to variable and use the last entry from
// stack as the name
* @param $templateDependency A template to load to satisfy dependencies
* @return void
*/
- private function handleTemplateDependency ($node, $templateDependency) {
+ private function handleTemplateDependency (string $node, string $templateDependency) {
// Is the template dependency set?
if ((!empty($templateDependency)) && (!isset($this->dependencyContent[$node]))) {
// Get a temporay menu template instance
// Save the parsed raw content in our dependency array
$this->dependencyContent[$node] = $templateInstance->getRawTemplateData();
- } // END - if
+ }
}
/**
* @return void
* @todo Add cache creation here
*/
- private function initMenu ($templateDependency = '') {
+ private function initMenu (string $templateDependency = '') {
// Get web template engine
- $this->setTemplateInstance(ObjectFactory::createObjectByConfiguredName('html_template_class', array(GenericRegistry::getRegistry()->getInstance('application'))));
+ $this->setTemplateInstance(ObjectFactory::createObjectByConfiguredName('html_template_class', array(ApplicationHelper::getSelfInstance())));
// Handle the dependency template
$this->handleTemplateDependency('menu', $templateDependency);
* @return void
*/
private function renderMenuEntry () {
- // Prepare template engine
- $templateInstance = $this->prepareTemplateInstance();
-
// Load menu entry template
- $templateInstance->loadCodeTemplate('menu_entry');
+ $this->getTemplateInstance()->loadCodeTemplate('menu_entry');
// Copy all variables over to it
foreach ($this->menuEntryVariables as $variableName) {
if ($variableName == 'anchor-href') {
// Expand variable with URL then
$variableValue = '{?base_url?}/' . $variableValue;
- } // END - if
+ }
// ... into the instance
- $templateInstance->assignVariable($variableName, $variableValue);
- } // END - foreach
+ $this->getTemplateInstance()->assignVariable($variableName, $variableValue);
+ }
// Compile template + variables
- $templateInstance->compileTemplate();
- $templateInstance->compileVariables();
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->compileVariables();
// Remember it here
- $this->menuEntries[$this->readVariable('entry_id')] = $templateInstance->getRawTemplateData();
+ $this->menuEntries[$this->readVariable('entry_id')] = $this->getTemplateInstance()->getRawTemplateData();
}
/**
// Init block content
$blockContent = implode('', $this->menuEntries);
- // Prepare template engine
- $templateInstance = $this->prepareTemplateInstance();
-
// Load menu entry template
- $templateInstance->loadCodeTemplate('menu_block');
+ $this->getTemplateInstance()->loadCodeTemplate('menu_block');
// Copy all variables over to it
foreach ($this->menuBlockVariables as $variableName) {
$variableValue = $this->readVariable($variableName);
// ... into the instance
- $templateInstance->assignVariable($variableName, $variableValue);
- } // END - foreach
+ $this->getTemplateInstance()->assignVariable($variableName, $variableValue);
+ }
// Assign block content
- $templateInstance->assignVariable('block_content', $blockContent);
+ $this->getTemplateInstance()->assignVariable('block_content', $blockContent);
// Compile template + variables
- $templateInstance->compileTemplate();
- $templateInstance->compileVariables();
+ $this->getTemplateInstance()->compileTemplate();
+ $this->getTemplateInstance()->compileVariables();
// Remember it here
- array_push($this->menuBlocks, $templateInstance->getRawTemplateData());
+ array_push($this->menuBlocks, $this->getTemplateInstance()->getRawTemplateData());
// Reset rendered menu entries array
- $this->menuEntries = array();
+ $this->menuEntries = [];
}
/**
$menuContent = implode('', $this->menuBlocks);
// Clean variable
- $this->menuBlocks = array();
+ $this->menuBlocks = [];
// And return it
return $menuContent;
*/
public function getMenuCacheFile () {
// Get the application instance from registry
- $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
+ $applicationInstance = ApplicationHelper::getSelfInstance();
// Get the file instance ready
$fileInstance = new SplFileInfo(sprintf('%s%smenus/_cache/%s.%s',
- $this->getConfigInstance()->getConfigEntry('application_base_path'),
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path'),
$applicationInstance->getAppShortName(),
md5(
$this->getMenuInstance()->getMenuName() . ':' .
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Template\Engine\Xml;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Template\XmlTemplateEngineFactory;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
+use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
+use Org\Mxchange\CoreFramework\Template\Engine\BaseTemplateEngine;
+use Org\Mxchange\CoreFramework\Template\Xml\CompileableXmlTemplate;
+use Org\Mxchange\CoreFramework\Traits\Stack\StackableTrait;
+use Org\Mxchange\CoreFramework\Traits\Template\CompileableTemplateTrait;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+
+/**
+ * A generic XML template engine class
+ *
+ * @author Roland Haeder <webmaster@shipsimu.org>
+ * @version 0.0.0
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2018 Hub Developer Team
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.shipsimu.org
+ * @todo This template engine does not make use of setTemplateType()
+ *
+ * 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/>.
+ */
+abstract class BaseXmlTemplateEngine extends BaseTemplateEngine implements CompileableXmlTemplate {
+ // Load traits
+ use CompileableTemplateTrait;
+ use StackableTrait;
+
+ /**
+ * Main nodes in the XML tree
+ */
+ private $mainNodes = [];
+
+ /**
+ * Sub nodes in the XML tree
+ */
+ private $subNodes = [];
+
+ /**
+ * Current main node
+ */
+ private $curr = [];
+
+ /**
+ * XML template type
+ */
+ private $xmlTemplateType = 'xml';
+
+ /**
+ * Type prefix
+ */
+ private $typePrefix = 'xml';
+
+ /**
+ * Name of stacker
+ */
+ private $stackerName = '';
+
+ /**
+ * Content from dependency
+ */
+ protected $dependencyContent = [];
+
+ /**
+ * XML compacting is disabled by default
+ */
+ private $xmlCompacting = false;
+
+ /**
+ * Method name for XML template type
+ */
+ private $initMethodName = 'invalid';
+
+ /**
+ * Protected constructor
+ *
+ * @param $className Name of the class
+ * @return void
+ */
+ protected function __construct (string $className) {
+ // Call parent constructor
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: className=%s - CONSTRUCTED!', $className));
+ parent::__construct($className);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!');
+ }
+
+ /**
+ * Does a generic initialization of the template engine
+ *
+ * @param $typePrefix Type prefix
+ * @param $xmlTemplateType Type of XML template
+ * @return $templateInstance An instance of TemplateEngine
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ * @throws BasePathIsEmptyException If the provided $templateBasePath is empty
+ * @throws InvalidBasePathStringException If $templateBasePath is no string
+ * @throws BasePathIsNoDirectoryException If $templateBasePath is no
+ * directory or not found
+ * @throws BasePathReadProtectedException If $templateBasePath is
+ * read-protected
+ */
+ protected function initXmlTemplateEngine (string $typePrefix, string $xmlTemplateType) {
+ // Check on parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: typePrefix=%s,xmlTemplateType=%s - CALLED!', $typePrefix, $xmlTemplateType));
+ if (empty($typePrefix)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "typePrefix" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($xmlTemplateType)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "xmlTemplateType" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Set XML template type and prefix
+ $this->xmlTemplateType = $xmlTemplateType;
+ $this->typePrefix = $typePrefix;
+ $this->initMethodName = sprintf('init%s', StringUtils::convertToClassName($this->xmlTemplateType));
+
+ // Get template instance
+ $applicationInstance = ApplicationHelper::getSelfInstance();
+
+ // Determine base path
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: applicationInstance=%s', $applicationInstance->__toString()));
+ $templateBasePath = sprintf('%s%s%s',
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('application_base_path'),
+ FrameworkBootstrap::getRequestInstance()->getRequestElement('app'),
+ DIRECTORY_SEPARATOR
+ );
+
+ // Is the base path valid?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: templateBasePath=%s', $templateBasePath));
+ if (empty($templateBasePath)) {
+ // Base path is empty
+ throw new BasePathIsEmptyException($this, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
+ } elseif (!is_dir($templateBasePath)) {
+ // Is not a path
+ throw new BasePathIsNoDirectoryException(array($this, $templateBasePath), self::EXCEPTION_INVALID_PATH_NAME);
+ } elseif (!is_readable($templateBasePath)) {
+ // Is not readable
+ throw new BasePathReadProtectedException(array($this, $templateBasePath), self::EXCEPTION_READ_PROTECED_PATH);
+ }
+
+ // Set the base path
+ $this->setTemplateBasePath($templateBasePath);
+
+ // Set template extensions
+ $this->setRawTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('raw_template_extension'));
+ $this->setCodeTemplateExtension(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($typePrefix . '_message_template_extension'));
+
+ // Absolute output path for compiled templates
+ $this->setCompileOutputPath(sprintf('%s%s',
+ $templateBasePath,
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compile_output_path')
+ ));
+
+ // Init a variable stacker
+ $stackInstance = ObjectFactory::createObjectByConfiguredName($typePrefix . '_' . $xmlTemplateType . '_stacker_class');
+
+ // Set name
+ $this->stackerName = $typePrefix . '_' . $xmlTemplateType;
+
+ // Init stacker
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: this->stackerName=%s', $this->stackerName));
+ $stackInstance->initStack($this->stackerName);
+
+ // Set it
+ $this->setStackInstance($stackInstance);
+
+ // Set it in main nodes
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Adding xmlTemplateType=%s to this->mainNodes ...', $xmlTemplateType));
+ array_push($this->mainNodes, str_replace('_', '-', $xmlTemplateType));
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!');
+ }
+
+ /**
+ * Load a specified XML template into the engine
+ *
+ * @param $templateName Optional name of template
+ * @return void
+ */
+ public function loadXmlTemplate (string $templateName = '') {
+ // Is the template name empty?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: templateName=%s - CALLED!', $templateName));
+ if (empty($templateName)) {
+ // Set generic template name
+ $templateName = $this->typePrefix . '_' . $this->xmlTemplateType . '_template_type';
+ }
+
+ // Set template type
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: templateName=%s', $templateName));
+ $this->setTemplateType(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry($templateName));
+
+ // Load the special template
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Invoking this->loadTemplate(%s) ...', $this->xmlTemplateType));
+ $this->loadTemplate($this->xmlTemplateType);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!');
+ }
+
+ /**
+ * Getter for current main node
+ *
+ * @return $currMainNode Current main node
+ */
+ public final function getCurrMainNode () {
+ return $this->curr['main_node'];
+ }
+
+ /**
+ * Setter for current main node
+ *
+ * @param $element Element name to set as current main node
+ * @return $currMainNode Current main node
+ */
+ private final function setCurrMainNode (string $element) {
+ $this->curr['main_node'] = $element;
+ }
+
+ /**
+ * Getter for main node array
+ *
+ * @return $mainNodes Array with valid main node names
+ */
+ public final function getMainNodes () {
+ return $this->mainNodes;
+ }
+
+ /**
+ * Getter for stacker name
+ *
+ * @return $stackerName Name of stacker of this class
+ */
+ protected final function getStackerName () {
+ return $this->stackerName;
+ }
+
+ /**
+ * Setter for sub node array
+ *
+ * @param $subNodes Array with valid sub node names
+ * @return void
+ */
+ public final function setSubNodes (array $subNodes) {
+ $this->subNodes = $subNodes;
+ }
+
+ /**
+ * Getter for sub node array
+ *
+ * @return $subNodes Array with valid sub node names
+ */
+ public final function getSubNodes () {
+ return $this->subNodes;
+ }
+
+ /**
+ * Read XML variables by calling readVariable() with 'general' as
+ * variable stack.
+ *
+ * @param $key Key to read from
+ * @return $value Value from variable
+ */
+ public function readXmlData (string $key) {
+ // Is key parameter valid?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: key=%s - CALLED!', $key));
+ if (empty($key)) {
+ // Throw exception
+ throw new InvalidArgumentException('Parameter key is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Read the variable
+ $value = parent::readVariable($key, 'general');
+
+ // Is this null?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: value[]=%s', gettype($value)));
+ if (is_null($value)) {
+ // Bah, needs fixing.
+ $this->debugInstance(sprintf('[%s:%d]: key=%s returns NULL', __METHOD__, __LINE__, $key));
+ }
+
+ // Return value
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: value[%s]=%s - EXIT!', gettype($value), $value));
+ return $value;
+ }
+
+ /**
+ * Handles the template dependency for given XML node
+ *
+ * @param $node The XML node we should load a dependency template
+ * @param $templateDependency A template to load to satisfy dependencies
+ * @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ */
+ protected function handleTemplateDependency (string $node, string $templateDependency) {
+ // Check parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: node=%s,templateDependency=%s - CALLED!', $node, $templateDependency));
+ if (empty($node)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "node" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($templateDependency)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "templateDependency" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Is the template dependency set?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: node=%s,templateDependency=%s', $node, $templateDependency));
+ if ((!empty($templateDependency)) && (!isset($this->dependencyContent[$node]))) {
+ // Create class name
+ $configKey = sprintf('%s_%s_%s_template_class', $this->typePrefix, self::convertDashesToUnderscores($node), $this->xmlTemplateType);
+
+ // Get a temporay template instance
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: configKey=%s', $configKey));
+ $templateInstance = XmlTemplateEngineFactory::createXmlTemplateEngineInstance();
+
+ // Then load it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: templateInstance=%s', $templateInstance->__toString()));
+ $templateInstance->loadXmlTemplate($templateDependency);
+
+ // Parse the XML content
+ $templateInstance->renderXmlContent();
+
+ // Save the parsed raw content in our dependency array
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Invoking templateInstance->getRawTemplateData() for this->dependencyContent[%s] ...', $node));
+ $this->dependencyContent[$node] = $templateInstance->getRawTemplateData();
+ }
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!');
+ }
+
+ /**
+ * Handles the start element of an XML resource
+ *
+ * @param $resource XML parser resource (currently ignored)
+ * @param $element The element we shall handle
+ * @param $attributes All attributes
+ * @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ * @throws InvalidXmlNodeException If an unknown/invalid XML node name was found
+ */
+ public final function startElement ($resource, string $element, array $attributes) {
+ // Check parameters
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: resource[%s]=%s,element=%s,attributes()=%d - CALLED!', gettype($resource), $resource, $element, count($attributes)));
+ if (!is_resource($resource)) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('Parameter resource has unexpected type %s', gettype($resource)), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($element)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "element" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Initial method name which will never be called...
+ $methodName = $this->initMethodName;
+
+ // Make the element name lower-case
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: methodName=%s', $methodName));
+ $element = strtolower($element);
+
+ // Is the element a main node?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: element=%s', $element));
+ if (in_array($element, $this->getMainNodes())) {
+ // Okay, main node found!
+ $methodName = 'start' . StringUtils::convertToClassName($element);
+
+ // Set it
+ $this->setCurrMainNode($element);
+ } elseif (in_array($element, $this->getSubNodes())) {
+ // Sub node found
+ $methodName = 'start' . StringUtils::convertToClassName($element);
+ } else {
+ // Invalid node name found
+ throw new InvalidXmlNodeException([$this, $element, $attributes], XmlParser::EXCEPTION_XML_NODE_UNKNOWN);
+ }
+
+ // Call method
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Invoking this->%s(attributes()=%d) ...', $methodName, count($attributes)));
+ call_user_func_array([$this, $methodName], $attributes);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!');
+ }
+
+ /**
+ * Ends the main or sub node by sending out the gathered data
+ *
+ * @param $resource An XML resource pointer (currently ignored)
+ * @param $nodeName Name of the node we want to finish
+ * @return void
+ * @throws XmlNodeMismatchException If current main node mismatches the closing one
+ */
+ public final function finishElement ($resource, string $nodeName) {
+ // Check parameters
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: resource[%s]=%s,nodeName=%s - CALLED!', gettype($resource), $resource, $nodeName));
+ if (!is_resource($resource)) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('Parameter resource has unexpected type %s', gettype($resource)), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($nodeName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "nodeName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Make all lower-case
+ $nodeName = strtolower($nodeName);
+
+ // Does this match with current main node?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: nodeName=%s', $nodeName));
+ if (($nodeName != $this->getCurrMainNode()) && (in_array($nodeName, $this->getMainNodes()))) {
+ // Did not match!
+ throw new XmlNodeMismatchException ([$this, $nodeName, $this->getCurrMainNode()], XmlParser::EXCEPTION_XML_NODE_MISMATCH);
+ }
+
+ // Construct method name
+ $methodName = 'finish' . StringUtils::convertToClassName($nodeName);
+
+ // Call the corresponding method
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Invoking this->%s() ...', $methodName));
+ call_user_func_array([$this, $methodName], []);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!');
+ }
+
+ /**
+ * Renders the given XML content
+ *
+ * @param $content Valid XML content or if not set the current loaded raw content
+ * @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ */
+ public function renderXmlContent (string $content = NULL) {
+ // Is the content set?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: content[%s]()=%d - CALLED!', gettype($content), strlen($content)));
+ if (is_null($content)) {
+ // Get current content
+ $content = $this->getRawTemplateData();
+ } elseif (empty($content)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "content" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Get a XmlParser instance
+ $parserInstance = ObjectFactory::createObjectByConfiguredName('xml_parser_class', [$this]);
+
+ // Check if XML compacting is enabled
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: parserInstance=%s', $parserInstance->__toString()));
+ if ($this->isXmlCompactingEnabled()) {
+ // Yes, so get a decorator class for transparent compacting
+ $parserInstance = ObjectFactory::createObjectByConfiguredName('deco_compacting_xml_parser_class', [$parserInstance]);
+ }
+
+ // Parse the XML document
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('BASE-XML-TEMPLATE-ENGINE: Invoking parserInstance->parseXmlContent(content()=%d) ...', strlen($content)));
+ $parserInstance->parseXmlContent($content);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('BASE-XML-TEMPLATE-ENGINE: EXIT!');
+ }
+
+ /**
+ * Enables or disables XML compacting
+ *
+ * @param $xmlCompacting New XML compacting setting
+ * @return void
+ */
+ public final function enableXmlCompacting (bool $xmlCompacting = true) {
+ $this->xmlCompacting = $xmlCompacting;
+ }
+
+ /**
+ * Checks whether XML compacting is enabled
+ *
+ * @return $xmlCompacting Whether XML compacting is enabled or disabled
+ */
+ public final function isXmlCompactingEnabled () {
+ return $this->xmlCompacting;
+ }
+
+}
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
use Org\Mxchange\CoreFramework\Generic\FrameworkException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
use Org\Mxchange\CoreFramework\Socket\InvalidSocketException;
// Import SPL stuff
+use \InvalidArgumentException;
use \SplFileInfo;
+use \UnexpectedValueException;
/**
* This class contains static helper functions for console applications
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Hub Developer Team
+ * @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
*
class ConsoleTools extends BaseFrameworkSystem {
// Constants
const HTTP_EOL = "\r\n";
- const HTTP_USER_AGENT = 'ConsoleTools/1.0';
+ const HTTP_USER_AGENT = 'ConsoleTools/1.0.1';
/**
* Default is that this class is noisy
*/
- private static $quietResolver = FALSE;
+ private static $isQuietResolver = FALSE;
+
+ /**
+ * Cached values
+ */
+ private static $cache = [];
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
// Cache configuration entry
- self::$quietResolver = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('quiet_dns_resolver');
+ self::$isQuietResolver = FrameworkBootstrap::getConfigurationInstance()->isEnabled('quiet_dns_resolver');
}
/**
*/
protected function isProxyUsed () {
// Do we have cache?
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!');
if (!isset($GLOBALS[__METHOD__])) {
// Determine it
- $GLOBALS[__METHOD__] = (($this->getConfigInstance()->getConfigEntry('proxy_host') != '') && ($this->getConfigInstance()->getConfigEntry('proxy_port') > 0));
- } // END - if
+ $GLOBALS[__METHOD__] = (
+ (
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_host') != ''
+ ) && (
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_port') > 0
+ )
+ );
+ }
// Return cache
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: isUsed=%d', $GLOBALS[__METHOD__]));
return $GLOBALS[__METHOD__];
}
* @param $port Port number to connect to
* @param $socketResource Resource of a socket
* @return $response Response array
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- protected function setupProxyTunnel ($host, $port, $socketResource) {
+ protected function setupProxyTunnel (string $host, int $port, $socketResource) {
+ // Validate parameter
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: host=%s,port=%d,socketResource=%s - CALLED!', $host, $port, $socketResource));
+ if (empty($host)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "host" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($port < 1) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('port=%d is not valid', $port));
+ } elseif (!is_resource($socketResource)) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('socketResource[]=%s is not valid', gettype($socketResource)));
+ }
+
// Initialize array
- $response = array('', '', '');
+ $response = ['', '', ''];
$proxyTunnel = '';
// Generate CONNECT request header
$proxyTunnel .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
// Use login data to proxy? (username at least!)
- if ($this->getConfigInstance()->getConfigEntry('proxy_username') != '') {
+ if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_username') != '') {
// Add it as well
- $encodedAuth = base64_encode($this->getConfigInstance()->getConfigEntry('proxy_username') . ':' . $this->getConfigInstance()->getConfigEntry('proxy_password'));
+ $encodedAuth = base64_encode(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_username') . ':' . FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_password'));
$proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
- } // END - if
+ }
// Add last new-line
$proxyTunnel .= self::HTTP_EOL;
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: proxyTunnel=' . $proxyTunnel);
// Write request
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: Sending %d bytes to socketResource=%s (proxy tunnel) ...', strlen($proxyTunnel), $socketResource));
fwrite($socketResource, $proxyTunnel);
// Got response?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: feof(%s)=%d', $socketResource, intval(feof($socketResource))));
if (feof($socketResource)) {
// No response received
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: response()=%d, feof! - EXIT!', count($response)));
return $response;
- } // END - if
+ }
// Read the first line
$resp = trim(fgets($socketResource, 10240));
if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
// Invalid response!
return $response;
- } // END - if
+ }
// All fine!
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: respArray()=%d - EXIT!', count($respArray)));
return $respArray;
}
*
* @param $rawData Raw data from /etc/hostname file
* @return $hostname Extracted host name
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- protected function extractHostnameFromRawData ($rawData) {
+ protected function extractHostnameFromRawData (string $rawData) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: rawData=%s - CALLED!', $rawData));
+ if (empty($rawData)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "rawData" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Default is invalid
$hostname = 'invalid';
$data = explode(PHP_EOL, $rawData);
// "Walk" through it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: data()=%d', count($data)));
foreach ($data as $line) {
// Trim it
$line = trim($line);
// Begins with a hash (#) = comment?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: line=%s', $line));
if (substr($line, 0, 1) == '#') {
// Then skip it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: line=%s - SKIPPED!', $line));
continue;
- } // END - if
+ }
// Has an equals sign?
if (strpos($line, '=') !== false) {
$hostData = explode('=', $line);
// Make sure only a key=value pair goes through
- assert(count($hostData) == 2);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostData()=%d', count($hostData)));
+ if (count($hostData) < 2) {
+ // Ops, wrong count
+ throw new UnexpectedValueException(sprintf('hostData()=%d is unexpected, line=%s', count($hostData), $line), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+ }
// Try to get it and abort
- $hostname = str_replace(array('"', chr(39)), array('', ''), $hostData[1]);
+ $hostname = str_replace(
+ ['"', chr(39)],
+ ['', ''],
+ $hostData[1]
+ );
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s from hostData - BREAK!', $hostname));
break;
} else {
// Use it directly
$hostname = $line;
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s from line - BREAK!', $line));
break;
}
- } // END - foreach
+ }
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: hostname=%s - EXIT!', $hostname));
return $hostname;
}
*
* @param $hostname Host name we shall resolve
* @return $ipAddress IPv4 address resolved from host name
+ * @throws InvalidArgumentException If a parameter is not valid
* @todo This should be connected to a caching class to cache DNS requests
*/
- public static function resolveIpAddress ($hostname) {
- // Quiet?
- if (self::$quietResolver !== TRUE) {
+ public static function resolveIpAddress (string $hostname) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: hostname=%s - CALLED!', $hostname));
+ if (empty($hostname)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "hostname" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (self::$isQuietResolver !== TRUE) {
// Debug message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s',
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('[%s:] Host name to resolve is: %s',
__CLASS__,
$hostname
));
- } // END - if
+ }
// Default is false
$ipAddress = false;
* other domain, basically.
*/
$hostname .= '.';
- } // END - if
+ }
// Resolve it
// @TODO Here should the cacher be implemented
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s', $hostname));
$ipResolved = gethostbyname($hostname);
// Was it fine?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: ipResolved[%s]=%s', gettype($ipResolved), $ipResolved));
if (($ipResolved !== false) && ($ipResolved != $hostname)) {
// Okay, this works!
$ipAddress = $ipResolved;
// Quiet?
- if (self::$quietResolver !== TRUE) {
+ if (self::$isQuietResolver !== TRUE) {
// Debug message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s',
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('[%s:] Resolved IP address is: %s',
__CLASS__,
$ipAddress
));
- } // END - if
+ }
} else {
// Problem while resolving IP address
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.',
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.',
__CLASS__,
$hostname
));
}
// Return resolved IP
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: ipAddress=%s - EXIT!', $ipAddress));
return $ipAddress;
}
/**
- * Aquires the IP address of this host by reading the /etc/hostname file
- * and solving it. It is now stored in configuration
+ * acquires this host's LAN name. It tries a varity of different source.
*
- * @return $ipAddress Aquired IPv4 address
+ * @return $hostName The acquired name of this host or something invalid
*/
- public static function acquireSelfIpAddress () {
- // Local IP by default
- $ipAddress = '127.0.0.1';
+ public static function acquireHostname () {
+ // Is cache there?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!');
+ if (!isset(self::$cache[__METHOD__])) {
+ // Get a new instance
+ $toolsInstance = new ConsoleTools();
- // Get a new instance
- $helperInstance = new ConsoleTools();
+ // Get SplFileInfo instance
+ $infoInstance = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('hostname_file'));
- // Get SplFileInfo instance
- $infoInstance = new SplFileInfo($helperInstance->getConfigInstance()->getConfigEntry('hostname_file'));
+ // Init host name
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: infoInstance=%s', $infoInstance->__toString()));
+ $hostname = 'host.invalid';
- try {
- // Get a file pointer
- $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($infoInstance));
+ // Try to check /etc/hostname first
+ try {
+ // Get a file pointer
+ $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', [$infoInstance]);
- // Read the file
- $rawData = trim($fileInstance->readFromFile());
+ // Read the file
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: fileInstance=%s', $fileInstance->__toString()));
+ $rawData = trim($fileInstance->readFromFile());
- // Close the file
- $fileInstance->closeFile();
+ // Close the file
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: rawData=%s', $rawData));
+ $fileInstance->closeFile();
- // Extract hostname from it
- $hostname = $helperInstance->extractHostnameFromRawData($rawData);
+ // Extract hostname from it
+ $hostname = $toolsInstance->extractHostnameFromRawData($rawData);
- // Resolve the IP number
- $ipAddress = self::resolveIpAddress($hostname);
- } catch (FileNotFoundException $e) {
- // Fall-back to 'SESSION_SVR' which found on my Sun Station
- if (isset($_SERVER['SESSION_SVR'])) {
- // Resolve it
- $ipAddress = self::resolveIpAddress($_SERVER['SESSION_SVR']);
- } elseif (isset($_SERVER['COMPUTERNAME'])) {
- // May happen on some Windows XP systems, so also try this
- $ipAddress = self::resolveIpAddress($_SERVER['COMPUTERNAME']);
- } else {
- // Could not find our hostname
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] WARNING: Cannot resolve my own IP address.',
- $helperInstance->__toString()
+ // Debug message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s from /etc/hostname', $hostname));
+ } catch (FileNotFoundException $e) {
+ // Fall-back to 'SESSION_SVR' which found on my Sun Station
+ if (isset($_SERVER['SESSION_SVR'])) {
+ // Resolve it
+ $hostname = $_SERVER['SESSION_SVR'];
+ } elseif (isset($_SERVER['COMPUTERNAME'])) {
+ // May happen on some Windows XP systems, so also try this
+ $hostname = $_SERVER['COMPUTERNAME'];
+ } else {
+ // Could not find our hostname
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('[%s:] WARNING: Cannot acquire my own host name.',
+ $toolsInstance->__toString()
+ ));
+ }
+
+ // Debug message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s from _SERVER array', $hostname));
+ } catch (FrameworkException $e) {
+ // Output debug message
+ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s',
+ $toolsInstance->__toString(),
+ $e->__toString(),
+ $e->getHexCode(),
+ $e->getMessage()
));
}
- } catch (FrameworkException $e) {
- // Output debug message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s',
- $helperInstance->__toString(),
- $e->__toString(),
- $e->getHexCode(),
- $e->getMessage()
- ));
+
+ // Set cache
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: Setting hostname=%s ...', $hostname));
+ self::$cache[__METHOD__] = $hostname;
+ } else {
+ // Get from cache
+ $hostname = self::$cache[__METHOD__];
}
// Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: hostname=%s - EXIT!', $hostname));
+ return $hostname;
+ }
+
+ /**
+ * acquires the IP address of this host by reading the /etc/hostname file
+ * and solving it. It is now stored in configuration
+ *
+ * @return $ipAddress acquired IPv4 address
+ */
+ public static function acquireSelfIpAddress () {
+ // Is cache there?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!');
+ if (!isset(self::$cache[__METHOD__])) {
+ // Get host name
+ $hostname = self::acquireHostname();
+
+ // Resolve the IP number
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s', $hostname));
+ $ipAddress = self::resolveIpAddress($hostname);
+
+ // Set cache
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: Setting ipAddress=%s ...', $ipAddress));
+ self::$cache[__METHOD__] = $ipAddress;
+ } else {
+ // Get it from cache
+ $ipAddress = self::$cache[__METHOD__];
+ }
+
+ // Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: ipAddress=%s - EXIT!', $ipAddress));
return $ipAddress;
}
*/
public static function determineExternalAddress () {
// Get helper instance
- $helperInstance = new ConsoleTools();
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!');
+ $toolsInstance = new ConsoleTools();
// First get a socket
// @TODO Add some DNS caching here
// Open connection
- if ($helperInstance->isProxyUsed() === true) {
+ if ($toolsInstance->isProxyUsed() === true) {
// Resolve hostname into IP address
- $ipAddress = self::resolveIpAddress($helperInstance->getConfigInstance()->getConfigEntry('proxy_host'));
+ $ipAddress = self::resolveIpAddress(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_host'));
// Connect to host through proxy connection
- $socketResource = fsockopen($ipAddress, $helperInstance->getConfigInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: ipAddress=%s', $ipAddress));
+ $socketResource = fsockopen($ipAddress, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
} else {
// Connect to host directly
$socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
}
// Check if there was an error else
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: socketResource[%s]=%s,errorNo=%d,errorStr=%s', gettype($socketResource), $socketResource, $errorNo, $errorStr));
if ($errorNo > 0) {
// Then throw again
- throw new InvalidSocketException(array($helperInstance, $socketResource, $errorNo, $errorStr), BaseFrameworkSystem::EXCEPTION_INVALID_SOCKET);
- } // END - if
+ throw new InvalidSocketException([$toolsInstance, $socketResource, $errorNo, $errorStr], BaseFrameworkSystem::EXCEPTION_INVALID_SOCKET);
+ }
// Prepare the GET request
- $request = 'GET ' . ($helperInstance->isProxyUsed() === true ? 'http://shipsimu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL;
+ $request = 'GET ' . ($toolsInstance->isProxyUsed() === true ? 'http://shipsimu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL;
$request .= 'Host: shipsimu.org' . self::HTTP_EOL;
$request .= 'User-Agent: ' . self::HTTP_USER_AGENT . self::HTTP_EOL;
$request .= 'Connection: close' . self::HTTP_EOL;
// Do we use proxy?
- if ($helperInstance->isProxyUsed() === true) {
+ if ($toolsInstance->isProxyUsed() === true) {
// CONNECT method?
- if ($helperInstance->getConfigInstance()->getConfigEntry('proxy_connect_method') == 'Y') {
+ if (FrameworkBootstrap::getConfigurationInstance()->isEnabled('proxy_connect_method')) {
// Setup proxy tunnel
- $response = $helperInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
+ $response = $toolsInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
// If the response is invalid, abort
if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
// Invalid response!
- $helperInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, true));
- } // END - if
+ $toolsInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, true));
+ }
} else {
// Add header for proxy
$request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
}
- } // END - if
+ }
// Add last HTTP_EOL
$request .= self::HTTP_EOL;
// Send it to the socket
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: Writing %d bytes to socketResource=%s ...', strlen($request), $socketResource));
fwrite($socketResource, $request);
// Init IP (this will always be the last line)
// And read the reply
while (!feof($socketResource)) {
// Get line
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: feof()=%d', intval(feof($socketResource))));
$externalAddress = trim(fgets($socketResource, 128));
// Detect HTTP response
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: externalAddress=%s', $externalAddress));
if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
// Stop processing
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('CONSOLE-TOOLS: BREAK!');
break;
- } // END - if
- } // END - while
+ }
+ }
// Close socket
fclose($socketResource);
-
- // Debug message
- /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Resolved external address: ' . $externalAddress);
-
// Return determined external address
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: externalAddress=%s - EXIT!', $externalAddress));
return $externalAddress;
}
*/
public static function analyzeEnvironmentForType () {
// Default is the console
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!');
$type = 'console';
// Now, do we have a request method, or query string set?
if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
// Possibly HTTP request
$type = 'http';
- } // END - if
+ }
// Return it
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: type=%s - EXIT!', $type));
return $type;
}
*/
public static function analyzeEnvironmentForClassType () {
// Default is the console
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!');
$type = 'console';
// Now, do we have a request method, or query string set?
if (self::analyzeEnvironmentForType() == 'http') {
// Possibly HTTP request
$type = 'web';
- } // END - if
+ }
// Return it
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: type=%s - EXIT!', $type));
return $type;
}
namespace Org\Mxchange\CoreFramework\User;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseWrapper;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseFrontend;
use Org\Mxchange\CoreFramework\Database\Updateable;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
+use Org\Mxchange\CoreFramework\Traits\Result\Search\SearchableResultTrait;
/**
* A general user class
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseUser extends BaseFrameworkSystem implements Updateable {
+ // Load traits
+ use SearchableResultTrait;
+
// Exception constances
const EXCEPTION_USERNAME_NOT_FOUND = 0x150;
const EXCEPTION_USER_EMAIL_NOT_FOUND = 0x151;
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
* @param $userName The username to set
* @return void
*/
- public final function setUserName ($userName) {
- $this->userName = (string) $userName;
+ public final function setUserName (string $userName) {
+ $this->userName = $userName;
}
/**
* @return void
* @todo Find a way of casting here. "(int)" might destroy the user id > 32766
*/
- public final function setUserId ($userId) {
+ public final function setUserId (int $userId) {
$this->userId = $userId;
}
* @param $email The email to set
* @return void
*/
- protected final function setEmail ($email) {
- $this->email = (string) $email;
+ protected final function setEmail (string $email) {
+ $this->email = $email;
}
/**
// Is a previous result there?
if (!$this->getResultInstance() instanceof SearchableResult) {
- // Get a UserDatabaseWrapper instance
- $wrapperInstance = ObjectFactory::createObjectByConfiguredName('user_db_wrapper_class');
+ // Get a UserDatabaseFrontend instance
+ $frontendInstance = ObjectFactory::createObjectByConfiguredName('user_db_frontend_class');
// Create a search criteria
$criteriaInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
// Add the username as a criteria and set limit to one entry
- $criteriaInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
+ $criteriaInstance->addCriteria(UserDatabaseFrontend::DB_COLUMN_USERNAME, $this->getUserName());
$criteriaInstance->setLimit(1);
// Get a search result
- $resultInstance = $wrapperInstance->doSelectByCriteria($criteriaInstance);
+ $resultInstance = $frontendInstance->doSelectByCriteria($criteriaInstance);
// Set the index "solver"
- $resultInstance->solveResultIndex(UserDatabaseWrapper::DB_COLUMN_USERID, $wrapperInstance, array($this, 'setUserId'));
+ $resultInstance->solveResultIndex(UserDatabaseFrontend::DB_COLUMN_USERID, $frontendInstance, array($this, 'setUserId'));
// And finally set it
$this->setResultInstance($resultInstance);
- } // END - if
+ }
// Rewind it
$this->getResultInstance()->rewind();
// Search for it
- if ($this->getResultInstance()->next()) {
+ if ($this->getResultInstance()->valid()) {
// Entry found
$exists = true;
- } // END - if
+ }
// Return the status
return $exists;
// Is a previous result there?
if (!$this->getResultInstance() instanceof SearchableResult) {
- // Get a UserDatabaseWrapper instance
- $wrapperInstance = ObjectFactory::createObjectByConfiguredName('user_db_wrapper_class');
+ // Get a UserDatabaseFrontend instance
+ $frontendInstance = ObjectFactory::createObjectByConfiguredName('user_db_frontend_class');
// Create a search criteria
$criteriaInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
// Add the username as a criteria and set limit to one entry
- $criteriaInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_EMAIL, $this->getEmail());
+ $criteriaInstance->addCriteria(UserDatabaseFrontend::DB_COLUMN_EMAIL, $this->getEmail());
$criteriaInstance->setLimit(1);
// Get a search result
- $resultInstance = $wrapperInstance->doSelectByCriteria($criteriaInstance);
+ $resultInstance = $frontendInstance->doSelectByCriteria($criteriaInstance);
// Set the index "solver"
- $resultInstance->solveResultIndex(UserDatabaseWrapper::DB_COLUMN_USERID, $wrapperInstance, array($this, 'setUserId'));
+ $resultInstance->solveResultIndex(UserDatabaseFrontend::DB_COLUMN_USERID, $frontendInstance, array($this, 'setUserId'));
// And finally set it
$this->setResultInstance($resultInstance);
- } // END - if
+ }
// Rewind it
$this->getResultInstance()->rewind();
// Search for it
- if ($this->getResultInstance()->next()) {
+ if ($this->getResultInstance()->valid()) {
// Entry found
$exists = true;
// Set the username
$this->setUserName($currEntry['username']);
- } // END - if
- } // END - if
+ }
+ }
// Return the status
return $exists;
// Is a previous result there?
if ((!$this->getResultInstance() instanceof SearchableResult) || ($this->getResultInstance()->count() == 0)) {
- // Get a UserDatabaseWrapper instance
- $wrapperInstance = ObjectFactory::createObjectByConfiguredName('user_db_wrapper_class');
+ // Get a UserDatabaseFrontend instance
+ $frontendInstance = ObjectFactory::createObjectByConfiguredName('user_db_frontend_class');
// Create a search criteria
$criteriaInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
// Add the username as a criteria and set limit to one entry
- $criteriaInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
+ $criteriaInstance->addCriteria(UserDatabaseFrontend::DB_COLUMN_USERNAME, $this->getUserName());
$criteriaInstance->setLimit(1);
// Get a search result
- $resultInstance = $wrapperInstance->doSelectByCriteria($criteriaInstance);
+ $resultInstance = $frontendInstance->doSelectByCriteria($criteriaInstance);
// Set the index "solver"
- $resultInstance->solveResultIndex(UserDatabaseWrapper::DB_COLUMN_USERID, $wrapperInstance, array($this, 'setUserId'));
+ $resultInstance->solveResultIndex(UserDatabaseFrontend::DB_COLUMN_USERID, $frontendInstance, array($this, 'setUserId'));
// And finally set it
$this->setResultInstance($resultInstance);
- } // END - if
+ }
// Rewind it and advance to first entry
$this->getResultInstance()->rewind();
// So does the hashes match?
//* DEBUG: */ echo $requestInstance->getRequestElement('pass_hash') . '<br />' . $this->getResultInstance()->getFoundValue() . '<br />';
$matches = ($requestInstance->getRequestElement('pass_hash') === $this->getResultInstance()->getFoundValue());
- } // END - if
+ }
// Return the status
return $matches;
if (isset($entry['pass_hash'])) {
// Get it
$passHash = $entry['pass_hash'];
- } // END - if
+ }
// And return the hash
return $passHash;
* @return $primaryValue Value of the primary key based on database type
*/
public final function getPrimaryKey () {
- // Get a user database wrapper
- $wrapperInstance = ObjectFactory::createObjectByConfiguredName('user_db_wrapper_class');
+ // Get a user database frontend
+ $frontendInstance = ObjectFactory::createObjectByConfiguredName('user_db_frontend_class');
- // Get the primary key back from the wrapper
- $primaryKey = $wrapperInstance->getPrimaryKeyValue();
+ // Get the primary key back from the frontend
+ $primaryKey = $frontendInstance->generatePrimaryKey();
// Get that field
$primaryValue = $this->getField($primaryKey);
* @return void
* @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, $fieldValue) {
// Get a critieria instance
$searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
// Add search criteria
- $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
+ $searchInstance->addCriteria(UserDatabaseFrontend::DB_COLUMN_USERNAME, $this->getUserName());
$searchInstance->setLimit(1);
// Now get another criteria
// Add the search criteria for searching for the right entry
$updateInstance->setSearchInstance($searchInstance);
- // Set wrapper class name
- $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
+ // Set frontend class name
+ $updateInstance->setFrontendConfigEntry('user_db_frontend_class');
// Remember the update in database result
$this->getResultInstance()->add2UpdateQueue($updateInstance);
*/
public function isConfirmed () {
// Determine it
- $isConfirmed = ($this->getField(UserDatabaseWrapper::DB_COLUMN_USER_STATUS) == $this->getConfigInstance()->getConfigEntry('user_status_confirmed'));
+ $isConfirmed = ($this->getField(UserDatabaseFrontend::DB_COLUMN_USER_STATUS) == FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('user_status_confirmed'));
// Return it
return $isConfirmed;
*/
public function isGuest () {
// Determine it
- $isGuest = ($this->getField(UserDatabaseWrapper::DB_COLUMN_USER_STATUS) == $this->getConfigInstance()->getConfigEntry('user_status_guest'));
+ $isGuest = ($this->getField(UserDatabaseFrontend::DB_COLUMN_USER_STATUS) == FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('user_status_guest'));
// Return it
return $isGuest;
namespace Org\Mxchange\CoreFramework\User\Guest;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Manager\Guest\ManageableGuest;
use Org\Mxchange\CoreFramework\Registry\Registerable;
use Org\Mxchange\CoreFramework\Request\Requestable;
use Org\Mxchange\CoreFramework\User\BaseUser;
+use Org\Mxchange\CoreFramework\User\UsernameMissingException;
+
+// Import SPL stuff
+use \InvalidArgumentException;
/**
* A generic class for handling guests
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @throws UsernameMissingException If the username does not exist
* @throws UserNoGuestException If the user is no guest account
*/
- public static final function createGuestByUsername ($userName) {
+ public static final function createGuestByUsername (string $userName) {
+ // Check parameter
+ if (empty($userName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Paramter "userName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get a new instance
$userInstance = new Guest();
* @param $email Email address of the user
* @return $userInstance An instance of this user class
*/
- public static final function createGuestByEmail ($email) {
+ public static final function createGuestByEmail (string $email) {
+ // Check parameter
+ if (empty($email)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Paramter "email" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get a new instance
$userInstance = new Guest();
/**
* Updates the last activity timestamp and last performed action in the
- * database result. You should call flushPendingUpdates() to flush these updates
- * to the database layer.
+ * database result.
*
* @param $requestInstance A requestable class instance
* @return void
// No activity will be logged for guest accounts
}
- /**
- * Flushs all pending updates to the database layer
- *
- * @return void
- */
- public function flushPendingUpdates () {
- // No updates will be flushed to database!
- }
-
}
namespace Org\Mxchange\CoreFramework\User\Login;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseWrapper;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseFrontend;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Manager\Login\ManageableMember;
use Org\Mxchange\CoreFramework\Registry\Registerable;
use Org\Mxchange\CoreFramework\User\BaseUser;
+use Org\Mxchange\CoreFramework\User\UsernameMissingException;
+
+// Import SPL stuff
+use \InvalidArgumentException;
/**
* A generic class for handling users
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
* @throws UsernameMissingException If the username does not exist
* @throws UnexpectedGuestAccountException If the user status is 'guest'
*/
- public static final function createMemberByUsername ($userName) {
+ public static final function createMemberByUsername (string $userName) {
+ // Check parameter
+ if (empty($userName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "userName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get a new instance
$userInstance = new Member();
* @param $email Email address of the user
* @return $userInstance An instance of this user class
*/
- public static final function createMemberByEmail ($email) {
+ public static final function createMemberByEmail (string $email) {
+ // Check parameter
+ if (empty($email)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "email" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Get a new instance
$userInstance = new Member();
/**
* Updates the last activity timestamp and last performed action in the
- * database result. You should call flushPendingUpdates() to flush these updates
- * to the database layer.
+ * database result.
*
* @param $requestInstance A requestable class instance
* @return void
// If there is no action use the default on
if (is_null($lastAction)) {
- $lastAction = $this->getConfigInstance()->getConfigEntry('login_default_action');
- } // END - if
+ $lastAction = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('login_default_action');
+ }
// Get a critieria instance
$searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
// Add search criteria
- $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
+ $searchInstance->addCriteria(UserDatabaseFrontend::DB_COLUMN_USERNAME, $this->getUserName());
$searchInstance->setLimit(1);
// Now get another criteria
// Add the search criteria for searching for the right entry
$updateInstance->setSearchInstance($searchInstance);
- // Set wrapper class name
- $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
+ // Set frontend class name
+ $updateInstance->setFrontendConfigEntry('user_db_frontend_class');
// Remember the update in database result
$this->getResultInstance()->add2UpdateQueue($updateInstance);
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Utils\Arrays;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+use \OutOfBoundsException;
+
+/**
+ * A number utility class
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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/>.
+ */
+final class ArrayUtils extends BaseFrameworkSystem {
+ /**
+ * Private constructor, no instance needed. If PHP would have a static initializer ...
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Maps numeric array keys to their corresponding associative
+ * (alpha-numberic) parts.
+ *
+ * @param $numericArray The array the mapping shall happen on
+ * @param $mapping Numeric array to map all elements from numeric keys to alpha-numeric keys
+ * @return $mappedArray An array with mapped values
+ * @throws InvalidArgumentException If a aparameter is not valid
+ */
+ public static function mapNumericKeysToAssociative (array $numericArray, array $mapping) {
+ // Validate parameters
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('ARRAY-UTILS: numericArray()=%d,mapping()=%d - CALLED!', count($numericArray), count($mapping)));
+ if (count($numericArray) == 0) {
+ // Throw IAE
+ throw new InvalidArgumentException('Array "numericArray" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (count($mapping) == 0) {
+ // Throw it again
+ throw new InvalidArgumentException('Array "mapping" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (count($numericArray) != count($mapping)) {
+ // Throw it yet again
+ throw new InvalidArgumentException(sprintf('numericArray()=%d does not match mapping()=%d', count($numericArray), count($mapping)));
+ }
+
+ // Init mapped array
+ $mappedArray = [];
+
+ // "Walk" over the mapping array
+ foreach ($mapping as $sourceIndex => $targetName) {
+ // Is the source index not there?
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('ARRAY-UTILS: sourceIndex=%d,targetName=%s', $sourceIndex, $targetName));
+ if (!array_key_exists($sourceIndex, $numericArray)) {
+ // Should always be there!
+ throw new OutOfBoundsException(sprintf('numericArray[%d] does not exist.', $sourceIndex), FrameworkInterface::EXCEPTION_OUT_OF_BOUNDS);
+ }
+
+ // "Map" (copy) it to new array
+ $mappedArray[$targetName] = $numericArray[$sourceIndex];
+ }
+
+ // Return fully mapped array
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('ARRAY-UTILS: mappedArray()=%d - EXIT!', count($mappedArray)));
+ return $mappedArray;
+ }
+
+}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\String\Utils;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Configuration\FrameworkConfiguration;
-use Org\Mxchange\CoreFramework\Generic\NullPointerException;
-use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
-
-// Import SPL stuff
-use \InvalidArgumentException;
-
-/**
- * A string utility class
- *
- * @author Roland Haeder <webmaster@ship-simu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.ship-simu.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/>.
- */
-final class StringUtils extends BaseFrameworkSystem {
- /**
- * Private constructor, no instance needed
- *
- * @return void
- */
- private function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Converts dashes to underscores, e.g. useable for configuration entries
- *
- * @param $str The string with maybe dashes inside
- * @return $str The converted string with no dashed, but underscores
- * @throws NullPointerException If $str is null
- * @throws InvalidArgumentException If $str is empty
- */
- public static function convertDashesToUnderscores ($str) {
- // Is it null?
- if (is_null($str)) {
- // Throw NPE
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } elseif (!is_string($str)) {
- // Entry is empty
- throw new InvalidArgumentException(sprintf('str[]=%s is not a string', gettype($str)), FrameworkConfiguration::EXCEPTION_CONFIG_KEY_IS_EMPTY);
- } elseif ((is_string($str)) && (empty($str))) {
- // Entry is empty
- throw new InvalidArgumentException('str is empty', FrameworkConfiguration::EXCEPTION_CONFIG_KEY_IS_EMPTY);
- }
-
- // Convert them all
- $str = str_replace('-', '_', $str);
-
- // Return converted string
- return $str;
- }
-
-}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Utils\Crypto;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+use \LogicException;
+
+/**
+ * Crypto utilities class
+ *
+ * @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/>.
+ */
+final class CryptoUtils extends BaseFrameworkSystem {
+ /**
+ * Length of output from hash()
+ */
+ private static $hashLength = NULL;
+
+ /**
+ * Hash function, will be overwritten, so don't set it here!
+ */
+ private static $hashFunction = '';
+
+ /**
+ * Private constructor, no instance needed. If PHP would have a static initializer ...
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Since PHP doesn't have static initializers, this method needs to be
+ * invoked by each public method here.
+ */
+ private static function staticInitializer () {
+ // Is $hashFunction set?
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CRYPRO-UTILS: self::hashFunction[]=%s - CALLED!', gettype(self::$hashFunction)));
+ if (empty(self::$hashFunction)) {
+ // Get instance
+ $dummyInstance = new CryptoUtils();
+
+ // Set hash function from configuration
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('CRYPRO-UTILS: Setting self::hashFunction from configuration entry ...');
+ self::$hashFunction = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('crypto_hash_function_name');
+ }
+
+ // Trace message
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CRYPRO-UTILS: EXIT!');
+ }
+
+ /**
+ * Hashes a given string with a simple but stronger hash function (no salt)
+ * and hex-encode it.
+ *
+ * @param $str The string to be hashed
+ * @return $hash The hash from string $str
+ * @throws InvalidArgumentException If a parameter is not valid
+ * @throws LogicException If proper extension hash is not loaded
+ */
+ public static final function hash (string $str) {
+ // Validate parameter/mhash extension
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CRYPTO-UTILS: str=%s - CALLED!', $str));
+ if (empty($str)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "str" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!extension_loaded('hash')) {
+ // Should be there
+ throw new LogicException('Extension ext-hash not loaded', FrameworkInterface::EXCEPTION_LOGIC_EXCEPTION);
+ }
+
+ // Invoke static initializer
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CRYPRO-UTILS: Invoking self::staticInitializier() ...');
+ self::staticInitializer();
+
+ // Hash given string with (better secure) hasher
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CRYPRO-UTILS: Invoking hash(self::%s,%s,true) ...', $hashFunction, $str));
+ $hash = hash(self::$hashFunction, $str, true);
+
+ // Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CRYPTO-UTILS: hash{}=0x%s - EXIT!', bin2hex($hash)));
+ return $hash;
+ }
+
+ /**
+ * "Getter" for length of hash() output. This will be "cached" to speed up
+ * things.
+ *
+ * @return $length Length of hash() output
+ */
+ public static final function getHashLength () {
+ // Invoke static initializer
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CRYPRO-UTILS: Invoking self::staticInitializer() ... - CALLED!');
+ self::staticInitializer();
+
+ // Is it cashed?
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CRYPRO-UTILS: self::hashLength[%s]=%d', gettype(self::$hashLength), self::$hashLength));
+ if (is_null(self::$hashLength)) {
+ // No, then hash a string and save its length.
+ self::$hashLength = strlen(self::hash('abc123'));
+ }
+
+ // Return it
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CRYPRO-UTILS: self::hashLength=%d - EXIT!', self::$hashLength));
+ return self::$hashLength;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Utils\Numbers;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+
+/**
+ * A number utility class
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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/>.
+ */
+final class NumberUtils extends BaseFrameworkSystem {
+ /**
+ * Private constructor, no instance needed. If PHP would have a static initializer ...
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+ }
+
+ /**
+ * Filter a given number into a localized number
+ *
+ * @param $value The raw float value from e.g. database
+ * @return $localized Localized value
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ */
+ public static function doFilterFormatNumber (float $value) {
+ // Check value
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NUMBER-UTILS: value=%s - CALLED!', $value));
+ if ($value < 0) {
+ // Not valid value
+ throw new InvalidArgumentException(sprintf('value=%s cannot be below zero', $value));
+ }
+
+ // Generate it from config and localize dependencies
+ switch (FrameworkBootstrap::getLanguageInstance()->getLanguageCode()) {
+ case 'de': // German format is a bit different to default
+ $localized = number_format($value, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('decimals'), ',', '.');
+ break;
+
+ default: // US, etc.
+ $localized = number_format($value, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('decimals'), '.', ',');
+ break;
+ }
+
+ // Return it
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NUMBER-UTILS: localized=%s - CALLED!', $localized));
+ return $localized;
+ }
+
+ /**
+ * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
+ * beatiful for web-based front-ends. If null is given a message id
+ * null_timestamp will be resolved and returned.
+ *
+ * @param $timestamp Timestamp to prepare (filter) for display
+ * @return $readable A readable timestamp
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ */
+ public static function doFilterFormatTimestamp (string $timestamp = NULL) {
+ // Check parameter
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NUMBER-UTILS: timestamp[%s]=%s - CALLED!', gettype($timestamp), $timestamp));
+ if (empty($timestamp)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "timestamp" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Default value to return
+ $readable = '???';
+
+ // Is the timestamp null?
+ if (is_null($timestamp)) {
+ // Get a message string
+ $readable = FrameworkBootstrap::getLanguageInstance()->getMessage('null_timestamp');
+ } else {
+ switch (FrameworkBootstrap::getLanguageInstance()->getLanguageCode()) {
+ case 'de': // German format is a bit different to default
+ // Split the GMT stamp up
+ $dateTime = explode(' ', $timestamp );
+ $dateArray = explode('-', $dateTime[0]);
+ $timeArray = explode(':', $dateTime[1]);
+
+ // Construct the timestamp
+ $readable = sprintf(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('german_date_time'),
+ $dateArray[0],
+ $dateArray[1],
+ $dateArray[2],
+ $timeArray[0],
+ $timeArray[1],
+ $timeArray[2]
+ );
+ break;
+
+ default: // Default is pass-through
+ $readable = $timestamp;
+ break;
+ }
+ }
+
+ // Return the stamp
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NUMBER-UTILS: readable=%s - EXIT!', $readable));
+ return $readable;
+ }
+
+ /**
+ * Checks whether the given number is really a number (only chars 0-9).
+ *
+ * @param $num A string consisting only chars between 0 and 9
+ * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
+ * @param $assertMismatch Whether to assert mismatches
+ * @return $formatted The (hopefully) secured numbered value
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ */
+ public static function bigintval (string $num, bool $castValue = true, bool $assertMismatch = false) {
+ // Check parameter
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NUMBER-UTILS: num=%s,castValue=%d,assertMismatch=%d - CALLED!', $num, intval($castValue), intval($assertMismatch)));
+ if ($num === '') {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "num" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Filter all numbers out
+ $formatted = preg_replace('/[^0123456789]/', '', $num);
+
+ // Shall we cast?
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('NUMBER-UTILS: formatted=%s', $formatted));
+ if ($castValue === true) {
+ // Cast to biggest numeric type, int is not enough for this cast
+ $formatted = (double) $formatted;
+ }
+
+ // Assert only if requested
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('NUMBER-UTILS: formatted[%s]=%s', gettype($formatted), $formatted));
+ if ($assertMismatch === true) {
+ // Has the whole value changed?
+ assert(('' . $formatted . '' != '' . $num . '') && (!is_null($num)));
+ }
+
+ // Return result
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NUMBER-UTILS: formatted[%s]=%s - EXIT!', gettype($formatted), $formatted));
+ return $formatted;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Utils\Strings;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Configuration\FrameworkConfiguration;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Generic\NullPointerException;
+use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+
+/**
+ * A string utility class
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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/>.
+ */
+final class StringUtils extends BaseFrameworkSystem {
+ /**
+ * Thousands separator
+ */
+ private static $thousands = ''; // German
+
+ /**
+ * Decimal separator
+ */
+ private static $decimals = ''; // German
+
+ /**
+ * In-method cache array
+ */
+ private static $cache = [];
+
+ /**
+ * Array with bitmasks and such for pack/unpack methods to support both
+ * 32-bit and 64-bit systems
+ */
+ private static $packingData = [
+ 32 => [
+ 'step' => 3,
+ 'left' => 0xffff0000,
+ 'right' => 0x0000ffff,
+ 'factor' => 16,
+ 'format' => 'II',
+ ],
+ 64 => [
+ 'step' => 7,
+ 'left' => 0xffffffff00000000,
+ 'right' => 0x00000000ffffffff,
+ 'factor' => 32,
+ 'format' => 'NN'
+ ]
+ ];
+
+ /**
+ * Hexadecimal->Decimal translation array
+ */
+ private static $hexdec = [
+ '0' => 0,
+ '1' => 1,
+ '2' => 2,
+ '3' => 3,
+ '4' => 4,
+ '5' => 5,
+ '6' => 6,
+ '7' => 7,
+ '8' => 8,
+ '9' => 9,
+ 'a' => 10,
+ 'b' => 11,
+ 'c' => 12,
+ 'd' => 13,
+ 'e' => 14,
+ 'f' => 15
+ ];
+
+ /**
+ * Decimal->hexadecimal translation array
+ */
+ private static $dechex = [
+ 0 => '0',
+ 1 => '1',
+ 2 => '2',
+ 3 => '3',
+ 4 => '4',
+ 5 => '5',
+ 6 => '6',
+ 7 => '7',
+ 8 => '8',
+ 9 => '9',
+ 10 => 'a',
+ 11 => 'b',
+ 12 => 'c',
+ 13 => 'd',
+ 14 => 'e',
+ 15 => 'f'
+ ];
+
+ /**
+ * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
+ *
+ * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
+ */
+ private static $archArrayElement = 0;
+
+ /**
+ * Private constructor, no instance needed. If PHP would have a static initializer ...
+ *
+ * @return void
+ */
+ private function __construct () {
+ // Call parent constructor
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STRING-UTILS: CONSTRUCTED!');
+ parent::__construct(__CLASS__);
+
+ // Is one not set?
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STRING-UTILS: self::archArrayElement=%d', self::$archArrayElement));
+ if (empty(self::$archArrayElement)) {
+ // Set array element
+ self::$archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
+
+ // Init from configuration
+ self::$thousands = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('thousands_separator');
+ self::$decimals = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('decimals_separator');
+ }
+
+ // Trace message
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STRING-UTILS: EXIT!');
+ }
+
+ /**
+ * Converts dashes to underscores, e.g. useable for configuration entries
+ *
+ * @param $str The string with maybe dashes inside
+ * @return $str The converted string with no dashed, but underscores
+ * @throws NullPointerException If $str is null
+ * @throws InvalidArgumentException If $str is empty
+ */
+ public static function convertDashesToUnderscores (string $str) {
+ // Validate parameter
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: str=%s - CALLED!', $str));
+ if (empty($str)) {
+ // Entry is empty
+ throw new InvalidArgumentException('Parameter "str" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Convert them all
+ $str = str_replace('-', '_', $str);
+
+ // Return converted string
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: str=%s - EXIT!', $str));
+ return $str;
+ }
+
+ /**
+ * Encodes raw data (almost any type) by "serializing" it and then pack it
+ * into a "binary format".
+ *
+ * @param $rawData Raw data (almost any type)
+ * @return $encoded Encoded data
+ * @throws InvalidArgumentException If $rawData has a non-serializable data type
+ */
+ public static function encodeData ($rawData) {
+ // Make sure no objects or resources pass through
+ //* N NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: rawData[]=%s - CALLED!', gettype($rawData)));
+ if (is_object($rawData) || is_resource($rawData)) {
+ // Not all variable types should be serialized here
+ throw new InvalidArgumentException(sprintf('rawData[]=%s cannot be serialized.', gettype($rawData)));
+ }
+
+ // Init instance
+ $dummyInstance = new StringUtils();
+
+ // First "serialize" it (json_encode() is faster than serialize())
+ $encoded = self::packString(json_encode($rawData));
+
+ // And return it
+ //* N NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: encoded()=%d - EXIT!', strlen($encoded)));
+ return $encoded;
+ }
+
+ /**
+ * Converts e.g. a command from URL to a valid class by keeping out bad characters
+ *
+ * @param $str The string, what ever it is needs to be converted
+ * @return $className Generated class name
+ * @throws InvalidArgumentException If a paramter is invalid
+ */
+ public static final function convertToClassName (string $str) {
+ // Is the parameter valid?
+ //* N NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: str=%s - CALLED!', $str));
+ if (empty($str)) {
+ // No empty strings, please
+ throw new InvalidArgumentException('Parameter "str" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (!isset(self::$cache[$str])) {
+ // Init class name
+ $className = '';
+
+ // Convert all dashes in underscores
+ $str = self::convertDashesToUnderscores($str);
+
+ // Now use that underscores to get classname parts for hungarian style
+ //* N NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STRING-UTILS: str=%s - AFTER!', $str));
+ foreach (explode('_', $str) as $strPart) {
+ // Make the class name part lower case and first upper case
+ $className .= ucfirst(strtolower($strPart));
+ }
+
+ // Set cache
+ //* N NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STRING-UTILS: self[%s]=%s - SET!', $str, $className));
+ self::$cache[$str] = $className;
+ }
+
+ // Return class name
+ //* N NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: self[%s]=%s - EXIT!', $str, $className));
+ return self::$cache[$str];
+ }
+
+ /**
+ * Formats computer generated price values into human-understandable formats
+ * with thousand and decimal separators.
+ *
+ * @param $value The in computer format value for a price
+ * @param $currency The currency symbol (use HTML-valid characters!)
+ * @param $decNum Number of decimals after commata
+ * @return $price The for the current language formated price string
+ * @throws MissingDecimalsThousandsSeparatorException If decimals or thousands separator is missing
+ */
+ public static function formatCurrency (float $value, string $currency = '€', int $decNum = 2) {
+ // Init instance
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: value=%s,currency=%s,decNum=%d - CALLED!', $value, $currency, $decNum));
+ $dummyInstance = new StringUtils();
+
+ // Reformat the US number
+ $price = number_format($value, $decNum, self::$decimals, self::$thousands) . $currency;
+
+ // Return as string...
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: price=%s - EXIT!', $price));
+ return $price;
+ }
+
+ /**
+ * Converts a hexadecimal string, even with negative sign as first string to
+ * a decimal number using BC functions.
+ *
+ * This work is based on comment #86673 on php.net documentation page at:
+ * <http://de.php.net/manual/en/function.dechex.php#86673>
+ *
+ * @param $hex Hexadecimal string
+ * @return $dec Decimal number
+ * @throws InvalidArgumentException If a paramter is invalid
+ */
+ public static function hex2dec (string $hex) {
+ // Check parameter
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: hex=%s - CALLED!', $hex));
+ if (empty($hex)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "hex" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Convert to all lower-case
+ $hex = strtolower($hex);
+
+ // Detect sign (negative/positive numbers)
+ $sign = '';
+ if (substr($hex, 0, 1) == '-') {
+ $sign = '-';
+ $hex = substr($hex, 1);
+ }
+
+ // Decode the hexadecimal string into a decimal number
+ $dec = 0;
+ for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
+ $factor = self::$hexdec[substr($hex, $i, 1)];
+ $dec = bcadd($dec, bcmul($factor, $e));
+ }
+
+ // Return the decimal number
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: sign=%s,dec=%s - EXIT!', $sign, $dec));
+ return $sign . $dec;
+ }
+
+ /**
+ * Converts even very large decimal numbers, also signed, to a hexadecimal
+ * string.
+ *
+ * This work is based on comment #97756 on php.net documentation page at:
+ * <http://de.php.net/manual/en/function.hexdec.php#97756>
+ *
+ * @param $dec Decimal number, even with negative sign
+ * @param $maxLength Optional maximum length of the string
+ * @return $hex Hexadecimal string
+ * @throws InvalidArgumentException If a paramter is invalid
+ */
+ public static function dec2hex (int $dec, int $maxLength = 0) {
+ // Check parameter
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: dec=%d,maxLength=%d - CALLED!', $dec, $maxLength));
+ if ($dec < 0) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('dec=%d is below zero', $dec));
+ } elseif ($maxLength != 0 && ($maxLength % 2) != 0) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('maxLength=%d is not dividable by 2 or zero', $maxLength));
+ }
+
+ // Detect sign (negative/positive numbers)
+ $sign = '';
+ if ($dec < 0) {
+ $sign = '-';
+ $dec = abs($dec);
+ }
+
+ // Encode the decimal number into a hexadecimal string
+ $hex = '';
+ do {
+ $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
+ $dec /= (2 ^ 4);
+ } while ($dec >= 1);
+
+ /*
+ * Leading zeros are required for hex-decimal "numbers". In some
+ * situations more leading zeros are wanted, so check for both
+ * conditions.
+ */
+ if ($maxLength > 0) {
+ // Prepend more zeros
+ $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
+ } elseif ((strlen($hex) % 2) != 0) {
+ // Only make string's length dividable by 2
+ $hex = '0' . $hex;
+ }
+
+ // Return the hexadecimal string
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: sign=%s,hex=%s - EXIT!', $sign, $hex));
+ return $sign . $hex;
+ }
+
+ /**
+ * Converts a ASCII string (0 to 255) into a decimal number.
+ *
+ * @param $asc The ASCII string to be converted
+ * @return $dec Decimal number
+ * @throws InvalidArgumentException If a paramter is invalid
+ */
+ public static function asc2dec (string $asc) {
+ // Check parameter
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: asc=%s - CALLED!', $asc));
+ if (empty($asc)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "asc" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Convert it into a hexadecimal number
+ $hex = bin2hex($asc);
+
+ // And back into a decimal number
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STRING-UTILS: hex=%s', $hex));
+ $dec = self::hex2dec($hex);
+
+ // Return it
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: dec=%d - EXIT!', $dec));
+ return $dec;
+ }
+
+ /**
+ * Converts a decimal number into an ASCII string.
+ *
+ * @param $dec Decimal number
+ * @return $asc An ASCII string
+ * @throws InvalidArgumentException If a paramter is invalid
+ */
+ public static function dec2asc (int $dec) {
+ // Check parameter
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: dec=%d - CALLED!', $dec));
+ if ($dec < 0) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('dec=%d is below zero', $dec));
+ }
+
+ // First convert the number into a hexadecimal string
+ $hex = self::dec2hex($dec);
+
+ // Then convert it into the ASCII string
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STRING-UTILS: hex=%s', $hex));
+ $asc = self::hex2asc($hex);
+
+ // Return it
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: asc=%s - EXIT!', $asc));
+ return $asc;
+ }
+
+ /**
+ * Converts a hexadecimal number into an ASCII string. Negative numbers
+ * are not allowed.
+ *
+ * @param $hex Hexadecimal string
+ * @return $asc An ASCII string
+ * @throws InvalidArgumentException If a paramter is invalid
+ */
+ public static function hex2asc (string $hex) {
+ // Check for length, it must be devideable by 2
+ /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: hex=%s - CALLED!', $hex));
+ if (empty($hex)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "hex" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ((strlen($hex) % 2) != 0) {
+ // Throw it again
+ throw new InvalidArgumentException(sprintf('hex=%s length not dividable by 2', $hex));
+ }
+
+ // Walk the string
+ $asc = '';
+ for ($idx = 0; $idx < strlen($hex); $idx+=2) {
+ // Get the decimal number of the chunk
+ $part = hexdec(substr($hex, $idx, 2));
+
+ // Add it to the final string
+ $asc .= chr($part);
+ }
+
+ // Return the final string
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: asc=%s - EXIT!', $asc));
+ return $asc;
+ }
+
+ /**
+ * Pack a string into a "binary format". Please execuse me that this is
+ * widely undocumented. :-(
+ *
+ * @param $str Unpacked string
+ * @return $packed Packed string
+ * @throws InvalidArgumentException If a paramter is invalid
+ * @todo Improve documentation
+ */
+ private static function packString (string $str) {
+ // Check parameter
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: str=%s - CALLED!', $str));
+ if (empty($str)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "str" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // First compress the string (gzcompress is okay)
+ $str = gzcompress($str);
+
+ // Init variable
+ $packed = '';
+
+ // And start the "encoding" loop
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STRING-UTILS: Looping through str()=%d ...', strlen($str)));
+ for ($idx = 0; $idx < strlen($str); $idx += self::$packingData[self::$archArrayElement]['step']) {
+ $big = 0;
+ for ($i = 0; $i < self::$packingData[self::$archArrayElement]['step']; $i++) {
+ $factor = (self::$packingData[self::$archArrayElement]['step'] - 1 - $i);
+
+ if (($idx + $i) <= strlen($str)) {
+ $ord = ord(substr($str, ($idx + $i), 1));
+
+ $add = $ord * pow(256, $factor);
+
+ $big += $add;
+
+ //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
+ }
+ }
+
+ // Left/right parts (low/high?)
+ $l = ($big & self::$packingData[self::$archArrayElement]['left']) >>self::$packingData[self::$archArrayElement]['factor'];
+ $r = $big & self::$packingData[self::$archArrayElement]['right'];
+
+ // Create chunk
+ $chunk = str_pad(pack(self::$packingData[self::$archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
+ //* N NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STRING-UTILS: big=%d,chunk(%d)=%s', $big, strlen($chunk), md5($chunk)));
+
+ $packed .= $chunk;
+ }
+
+ // Return it
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: packed=%s - EXIT!', $packed));
+ return $packed;
+ }
+
+ /**
+ * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
+ *
+ * @param $num A string consisting only chars between 0 and 9
+ * @param $assertMismatch Whether to assert mismatches
+ * @return $ret The (hopefully) secured hext-numbered value
+ * @throws InvalidArgumentException If a paramter is invalid
+ */
+ public static function hexval (string $num, bool $assertMismatch = false) {
+ // Check parameter
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: num=%s,assertMismatch=%d - CALLED!', $num, intval($assertMismatch)));
+ if (empty($num)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "num" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // Filter all numbers out
+ $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
+
+ // Assert only if requested
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STRING-UTILS: ret=%s', $ret));
+ if ($assertMismatch === true) {
+ // Has the whole value changed?
+ assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
+ }
+
+ // Return result
+ //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: ret=%s - EXIT!', $ret));
+ return $ret;
+ }
+
+}
<?php
// Own namespace
-namespace CoreFramework\Visitor\;
+namespace Org\Mxchange\CoreFramework\Visitor\;
// Import framework stuff
use Org\Mxchange\CoreFramework\Visitor\BaseVisitor;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
* @param $visitorMode New visitor mode to set
* @return void
*/
- protected final function setVisitorMode ($visitorMode) {
- $this->visitorMode = (string) $visitorMode;
+ protected final function setVisitorMode (string $visitorMode) {
+ $this->visitorMode = $visitorMode;
}
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* The super constructor for all exceptions
*
- * @param $msgArray An array with message parts
+ * @param $messageArray An array with message parts
* @param $code An optional code for better debugging
* @return void
*/
- public function __construct (array $msgArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Prepare the message
$message = sprintf('[%s:%d] Cannot resolve action <span class="exception_reason">%s (%s)</span>.',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1],
- $msgArray[0]->getClassName()
+ $messageArray[1],
+ $messageArray[0]->getClassName()
);
// Call parent contructor with message
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (Filterable $filterInstance, $code) {
+ public function __construct (Filterable $filterInstance, int $code) {
// Construct the message
$message = sprintf('[%s:%d] Authorization has failed. Error code %s',
$filterInstance->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
* @param $code Error code
* @return void
*/
- public function __construct (array $messageArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Construct message
$message = sprintf('[%s:%d] Raw data %s contains invalid characters for BASE64-encoding.',
$messageArray[0]->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
* @param $code Error code
* @return void
*/
- public function __construct (array $messageArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Construct message
$message = sprintf('[%s:%d] Data length %s modulo 4 is not zero: data=%s',
$messageArray[0]->__toString(),
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* @param $code Error code
* @return void
*/
- public function __construct ($message, $code) {
+ public function __construct (string $message, int $code) {
// Call parent exception constructor
parent::__construct($message, $code);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* Array for the backtrace
*/
- private $backTrace = array();
+ private $backTrace = [];
/**
* Extra data
* @param $code An optional code for better debugging
* @return void
*/
- public function __construct ($message, $code = 0) {
+ public function __construct (string $message, int $code = 0) {
// Make sure everything is assigned properly
parent::__construct($message, $code);
// Extract backtrace
$this->saveBackTrace();
- // Cast all data
- $message = (string) $message;
- $code = (int) $code;
-
// In emergency exit?
if (defined('EMERGENCY_EXIT_CALLED')) {
// Output message
// End here
exit();
- } // END - if
+ }
// Should we log exceptions? (bad implementation)
if (defined('LOG_EXCEPTIONS')) {
$message,
$this->getHexCode()
));
- } // END - if
+ }
}
/**
// Add only non-array elements
if (!is_array($debug)) {
$info .= $debug . ', ';
- } // END - if
- } // END - foreach
+ }
+ }
// Remove last chars (commata, space)
$info = substr($info, 0, -2);
- } // END - if
+ }
// Prepare argument infos
$info = '<em id="debug_args_' . $dbgIndex . '">' . $info . '</em>';
$file = 'Unknown file';
if (isset($dbgInfo['file'])) {
$file = basename($dbgInfo['file']);
- } // END - if
+ }
// Line detection
$line = 'Unknown line';
if (isset($dbgInfo['line'])) {
$line = 'line ' . $dbgInfo['line'];
- } // END - if
+ }
// The message
$dbgMsg .= "\t at <em id=\"debug_id_".$dbgIndex."\">".$dbgIndex."</em> <em id=\"debug_file_".$dbgIndex."\">".$file."</em> (<em id=\"debug_line_".$dbgIndex."\">".$line."</em>) -> ".$dbgInfo['function'].'('.$info.")<br />\n";
- } // END - if
+ }
// Add end-message
$dbgMsg .= "Debug backtrace end<br />\n";
* @param $code Integer code to encode in hex
* @return $hexCode The exception code in hex-decimal format
*/
- public final function getHexCode ($code = NULL) {
- // Get the decimal code
- if (is_null($code)) $code = $this->getCode();
+ public final function getHexCode (int $code = NULL) {
+ // Is NULL?
+ if (is_null($code)) {
+ // Get default error code
+ $code = $this->getCode();
+ }
// Format it to hex-decimal, 0x as prefix and 3 chars
$hexCode = sprintf("0x%03s", dechex($code));
* @param $extraData Extra data to store
* @return void
*/
- protected final function setExtraData ($extraData) {
+ protected final function setExtraData (string $extraData) {
$this->extraData = $extraData;
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @todo Rename to CompressorMismatchException
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $array, $code) {
+ public function __construct (array $array, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Der Kompressor %s zu den geladenen Daten aus %s und der aktuell verwendete Kompressor %s stimmen nicht überein!',
$array[0]->__toString(),
<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Configuration;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Generic\FrameworkException;
-
-/**
- * Thrown when the value variable type is NULL, an array, an object or a
- * resource as these values shall not be set as configuration values. Please use
- * FrameworkArrayObject instead!
- *
- * @author Roland Haeder <webmaster@ship-simu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.ship-simu.org
- * @todo These are invalid argument exceptions
- *
- * 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 ConfigValueTypeUnsupportedException extends FrameworkException {
- /**
- * The super constructor for all exceptions
- *
- * @param $message Message data array
- * @param $code Error code
- * @return void
- */
- public function __construct (array $messageArray, $code) {
- // Construct message
- $message = sprintf('[%s:%d] Configuration key %s has unspported value type %s.',
- $messageArray[0]->__toString(),
- $this->getLine(),
- $messageArray[1],
- gettype($messageArray[2])
- );
-
- // Call parent exception constructor
- parent::__construct($message, $code);
- }
-
-}
+// @DEPRECATED
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @todo Rename this class to NoFoundEntryException
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $classArray, $code) {
+ public function __construct (array $classArray, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Configuration entry %s not found.',
$classArray[0],
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (array $messageData, $code) {
+ public function __construct (array $messageData, int $code) {
// Construct the message
$message = sprintf('[%s:] Connection with socket %s is already registered.',
$messageData[0]->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code An optional code for better debugging
* @return void
*/
- public function __construct (ControllerResolver $resolverInstance, $code) {
+ public function __construct (ControllerResolver $resolverInstance, int $code) {
// Prepare the message
$message = sprintf('[%s:%d] Cannot resolve default controller <span class="exception_reason">(%s)</span>. Maybe missing?',
$resolverInstance->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* The super constructor for all exceptions
*
- * @param $msgArray An array with message parts
+ * @param $messageArray An array with message parts
* @param $code An optional code for better debugging
* @return void
*/
- public function __construct (array $msgArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Prepare the message
$message = sprintf('[%s:%d] Cannot resolve controller <span class="exception_reason">%s (class name: %s)</span>.',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1],
- $msgArray[0]->getClassName()
+ $messageArray[1],
+ $messageArray[0]->getClassName()
);
// Set extra data
- $this->setExtraData($msgArray[0]->getClassName() . ':' . $this->getLine());
+ $this->setExtraData($messageArray[0]->getClassName() . ':' . $this->getLine());
// Call parent contructor with message
parent::__construct($message, $code);
namespace Org\Mxchange\CoreFramework\Deprecated;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Filter\Filterable;
use Org\Mxchange\CoreFramework\Generic\FrameworkException;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
* @param $code Error code
* @return void
*/
- public function __construct (Filterable $filterInstance, $code) {
+ public function __construct (Filterable $filterInstance, int $code) {
// Get length
- $length = $filterInstance->getConfigInstance()->getConfigEntry('captcha_string_length');
+ $length = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('captcha_string_length');
// Construct message
$message = sprintf('[%s:%d] Encrypt string has an invalid length. Valid: %d',
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
* @param $code Error code
* @return void
*/
- public function __construct (Filterable $filterInstance, $code) {
+ public function __construct (Filterable $filterInstance, int $code) {
// Construct message
$message = sprintf('[%s:%d] Encrypt string is missing.',
$filterInstance->__toString(),
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct ($message, $code) {
+ public function __construct (string $message, int $code) {
// Just call the parent constructor
parent::__construct($message, $code);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* The constructor
*
- * @param $msgArray Message array
+ * @param $messageArray Message array
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $msgArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Construct the message
$message = sprintf('[%s:%d] SQL error detected. Message from database: %s, code: %s.',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1],
- $this->getHexCode($msgArray[2])
+ $messageArray[1],
+ $this->getHexCode($messageArray[2])
);
// Call parent constructor
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this
* @param $code Code number for the exception
* @return void
*/
- public function __construct ($path, $code) {
+ public function __construct (string $path, int $code) {
// Add a message around the missing class
$message = sprintf('Save path %s is no directory.', $path);
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Please don't use this
* @param $code Code number for the exception
* @return void
*/
- public function __construct ($path, $code) {
+ public function __construct (string $path, int $code) {
// Add a message around the missing class
$message = sprintf('Path %s is not readable. Please fix your file access rights.', $path);
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Please don't use this
* @param $code Code number for the exception
* @return void
*/
- public function __construct ($path, $code) {
+ public function __construct (string $path, int $code) {
// Add a message around the missing class
$message = sprintf('Save path %s is write-protected. Please fix your file permissions.', $path);
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* The constructor
*
- * @param $msgArray Message array holding all needed data
+ * @param $messageArray Message array holding all needed data
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $msgArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Add a message around the host name
$message = sprintf('[%s:%d] Host name "%s" cannot be resolved (NXDOMAIN).',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1]
+ $messageArray[1]
);
// Call parent constructor
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* @param $code Error code
* @return void
*/
- public function __construct (array $messageArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Construct message
$message = sprintf('[%s:%d] Method %s cannot be called.',
$messageArray[0],
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct ($path, $code) {
+ public function __construct (string $path, int $code) {
// Add a message around the missing class
$message = sprintf('No pointer could be initialized for path "%s".', $path);
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct (SplFileInfo $infoInstance, $code) {
+ public function __construct (SplFileInfo $infoInstance, int $code) {
// Add a message around the missing class
$message = sprintf('A problem has been detected reading or writing to/from %s.', $infoInstance->getPathname());
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct (SplFileInfo $infoInstance, $code) {
+ public function __construct (SplFileInfo $infoInstance, int $code) {
// Add a message around the missing class
$message = sprintf('File "%s" not found.', $infoInstance->getPathname());
<?php
// Own namespace
-namespace Org\Mxchange\CoreFramework\FileSystem;
+namespace Org\Mxchange\CoreFramework\Filesystem;
// Import framework stuff
use Org\Mxchange\CoreFramework\Generic\FrameworkException;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct (SplFileInfo $infoInstance, $code) {
+ public function __construct (SplFileInfo $infoInstance, int $code) {
// Add a message around the missing class
$message = sprintf('File %s is read-protected. Please set read access rights (CHMOD).', $infoInstance->getPathname());
<?php
// Own namespace
-namespace Org\Mxchange\CoreFramework\FileSystem;
+namespace Org\Mxchange\CoreFramework\Filesystem;
// Import framework stuff
use Org\Mxchange\CoreFramework\Generic\FrameworkException;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct (SplFileInfo $infoInstance, $code) {
+ public function __construct (SplFileInfo $infoInstance, int $code) {
// Add a message around the missing class
$message = sprintf('File %s cannot be written. Please check file and/or directory permissions.', $infoInstance->getPathname());
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
/**
* The constructor
*
- * @param $msgArray Message from the exception
+ * @param $messageArray Message from the exception
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $msgArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Unexpected data length of %s bytes has been detected, %s bytes were expected.',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1],
- $msgArray[2]
+ $messageArray[1],
+ $messageArray[2]
);
// Call parent constructor
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
/**
* The constructor
*
- * @param $msgArray Message from the exception
+ * @param $messageArray Message from the exception
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $msgArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] MD5 hashes %s and %s doesnt match.',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1],
- $msgArray[2]
+ $messageArray[1],
+ $messageArray[2]
);
// Call parent constructor
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct (FrameworkInterface $class, $code) {
+ public function __construct (FrameworkInterface $class, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Has an invalid resource.',
$class->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
* @param $code Code number for the exception
* @return void
*/
- public function __construct ($path, $code) {
+ public function __construct (string $path, int $code) {
// Add a message around the missing class
$message = sprintf('Der angegebene Pfad %s ist ungütig (kein Pfad).', $path);
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
* @param $code Code number for the exception
* @return void
*/
- public function __construct ($path, $code) {
+ public function __construct (string $path, int $code) {
// Add a message around the missing class
$message = sprintf('The path %s appears to be read-protected. Please fix your CHMOD rights.', $path);
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct (SplFileInfo $infoInstance, $code) {
+ public function __construct (SplFileInfo $infoInstance, int $code) {
// Add a message around the missing class
$message = sprintf('Path "%s" cannot be written to. Please check permissions.', $infoInstance->getPath());
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Exception code for better debugging
* @return void
*/
- public function __construct (Filterable $filterInstance, $code) {
+ public function __construct (Filterable $filterInstance, int $code) {
// Construct the message
$message = sprintf('[%s:%d] Filter chain interruppted by fatal error in filter.',
$filterInstance->__toString(),
<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Chain\Filter;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Generic\FrameworkException;
-
-/**
- * An exception thrown in a filter chain to stop processing further filters
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.shipsimu.org
- * @deprecated Don't use this anymore
- *
- * 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 InvalidFilterChainException extends FrameworkException {
- /**
- * The super constructor for all exceptions
- *
- * @param $filterInstance Instance of a filter class
- * @param $code Exception code for better debugging
- * @return void
- */
- public function __construct (array $filterArray, $code) {
- // Construct the message
- $message = sprintf('[%s:%d] Filter chain %s is not initialized.',
- $filterArray[0]->__toString(),
- $this->getLine(),
- $filterArray[1]
- );
-
- // Call the parent exception
- parent::__construct($message, $code);
- }
-
-}
+// @DEPRECATED
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $classArray, $code) {
+ public function __construct (array $classArray, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Could not add form element %s because form is closed.',
$classArray[0]->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $classArray, $code) {
+ public function __construct (array $classArray, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Could not add sub group %s because no form group has been opened before.',
$classArray[0]->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
* @param $code Code number for the exception
* @return void
*/
- public function __construct (BaseHelper $helperInstance, $code) {
+ public function __construct (BaseHelper $helperInstance, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Form is not yet closed. Close it with method <u>%s::addFormTag()</u> and add no parameters.',
$helperInstance->__toString(),
<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Deprecated;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Generic\FrameworkException;
-
-/**
- * An exception thrown when a group was added twice
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.shipsimu.org
- * @deprecated Don't use this anymore
- *
- * 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 HelperGroupAlreadyCreatedException extends FrameworkException {
- /**
- * The constructor
- *
- * @param $msgArray Array containing exception data
- * @param $code Code number for the exception
- * @return void
- */
- public function __construct (array $msgArray, $code) {
- // Add a message around the missing class
- $message = sprintf('[%s:%d] Group %s already opened before.',
- $msgArray[0]->__toString(),
- $this->getLine(),
- $msgArray[1]
- );
-
- // Call parent constructor
- parent::__construct($message, $code);
- }
-
-}
+// @DEPRECATED
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
/**
* The constructor
*
- * @param $msgArray Array containing exception data
+ * @param $messageArray Array containing exception data
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $msgArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Sub group not opened before. Raw text follows: %s',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1]
+ $messageArray[1]
);
// Call parent constructor
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
/**
* The constructor
*
- * @param $msgArray Array containing exception data
+ * @param $messageArray Array containing exception data
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $msgArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Sub group %s already opened before.',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1]
+ $messageArray[1]
);
// Call parent constructor
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
* @param $code Code number for the exception
* @return void
*/
- public function __construct (BaseHelper $helperInstance, $code) {
+ public function __construct (BaseHelper $helperInstance, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Form name not set.',
$helperInstance->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
/**
* The constructor
*
- * @param $msgArray Array containing exception data
+ * @param $messageArray Array containing exception data
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $msgArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Group not opened before. Raw text follows: %s',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1]
+ $messageArray[1]
);
// Call parent constructor
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $classArray, $code) {
+ public function __construct (array $classArray, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Registry key %s does not include a class with implemented interface <u>Manageable(User|Guest)</u>.',
$classArray[0]->__toString(),
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Deprecated;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Generic\FrameworkException;
-
-/**
- * An exception thrown when the language path string is invalid
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.shipsimu.org
- * @deprecated Don't use this anymore
- *
- * 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 InvalidLanguagePathStringException extends FrameworkException {
- /**
- * The constructor
- *
- * @param $classArray Array holding exception data
- * @param $code Code number for the exception
- * @return void
- */
- public function __construct (array $classArray, $code) {
- // Add a message around the missing class
- $message = sprintf('[%s:%d] %s is not a string with path.',
- $classArray[0]->__toString(),
- $this->getLine(),
- $classArray[1]
- );
-
- // Call parent constructor
- parent::__construct($message, $code);
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Deprecated;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Generic\FrameworkException;
-
-/**
- * An exception thrown when the language path is no directory
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.shipsimu.org
- * @todo Don't use this anymore
- *
- * 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 LanguagePathIsNoDirectoryException extends FrameworkException {
- /**
- * The constructor
- *
- * @param $classArray Array holding exception data
- * @param $code Code number for the exception
- * @return void
- */
- public function __construct (array $classArray, $code) {
- // Add a message around the missing class
- $message = sprintf('[%s:%d] Language base path %s does not exist or is not a directory.',
- $classArray[0]->__toString(),
- $this->getLine(),
- $classArray[1]
- );
-
- // Call parent constructor
- parent::__construct($message, $code);
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Deprecated;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Generic\FrameworkException;
-
-/**
- * An exception thrown when the language path is read-protected
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.shipsimu.org
- * @deprecated Don't use this anymore
- *
- * 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 LanguagePathReadProtectedException extends FrameworkException {
- /**
- * The constructor
- *
- * @param $class Array holding exception data
- * @param $code Code number for the exception
- * @return void
- */
- public function __construct (array $classArray, $code) {
- // Add a message around the missing class
- $message = sprintf('[%s:%d] Base language path %s is read-protected. Please change access rights (CHMOD).',
- $classArray[0]->__toString(),
- $this->getLine(),
- $classArray[1]
- );
-
- // Call parent constructor
- parent::__construct($message, $code);
- }
-
-}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct ($message, $code) {
+ public function __construct (string $message, int $code) {
// Call parent constructor
parent::__construct($message, $code);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $classArray, $code) {
+ public function __construct (array $classArray, int $code) {
// Add a message around the missing class
$message = sprintf('The class %s does not match class %s.',
$classArray[0],
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Please don't use this anymore
* @param $code Code number for the exception
* @return void
*/
- public function __construct (FrameworkInterface $class, $code) {
+ public function __construct (FrameworkInterface $class, int $code) {
if (is_object($class)) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Dimensions not found in array, array is invalid!',
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct ($message, $code) {
+ public function __construct (string $message, int $code) {
// Call parent constructor
parent::__construct($message, $code);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct ($message, $code) {
+ public function __construct (string $message, int $code) {
// Add a message around the missing class
$message = sprintf('%s is out of bounds.',
$message
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $array, $code) {
+ public function __construct (array $array, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] %s has %d elements, expected arre %d.',
$array[0]->__toString(),
+++ /dev/null
-<?php
-// [EOF]
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $msgArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Invalid command <span class="exception_reason">%s (class %s)</span> detected.',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1],
- $msgArray[0]->getClassName()
+ $messageArray[1],
+ $messageArray[0]->getClassName()
);
// Set extra data
- $this->setExtraData($msgArray[0]->getClassName() . ':' . $this->getLine());
+ $this->setExtraData($messageArray[0]->getClassName() . ':' . $this->getLine());
// Call parent constructor
parent::__construct($message, $code);
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Object;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Generic\FrameworkException;
-
-/**
- * An exception thrown when an class instance does not implement a given interface
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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 InvalidInterfaceException extends FrameworkException {
- /**
- * The constructor
- *
- * @param $classArray Array with exception data
- * @param $code Code number for the exception
- * @return void
- */
- public function __construct (array $classArray, $code) {
- // Add a message around the missing class
- $message = sprintf('[%s:%d] Object does not implement expected interface %s.',
- $classArray[0]->__toString(),
- $this->getLine(),
- $classArray[1]
- );
-
- // Call parent constructor
- parent::__construct($message, $code);
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Deprecated;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Generic\FrameworkException;
-use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
-
-/**
- * An exception thrown when an instance variable instances a non-object
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.shipsimu.org
- * @deprecated Don't use this anymore
- *
- * 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 InvalidObjectException extends FrameworkException {
- /**
- * The constructor
- *
- * @param $class Class throwing the exception
- * @param $code Code number for the exception
- * @return void
- */
- public function __construct (FrameworkInterface $class, $code) {
- // Add a message around the missing class
- $message = sprintf('[%s:%d] Object is not allowed here.',
- $class->__toString(),
- $this->getLine()
- );
-
- // Call parent constructor
- parent::__construct($message, $code);
- }
-
-}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $classArray, $code) {
+ public function __construct (array $classArray, int $code) {
// Extract all elements
$elements = '';
if ((isset($classArray[2])) && (is_array($classArray[2]))) {
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Deprecated;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Generic\FrameworkException;
-
-/**
- * An exception thrown when the decimal and thousands separators are missing
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.shipsimu.org
- * @deprecated Don't use this anymore
- *
- * 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 MissingDecimalsThousandsSeparatorException extends FrameworkException {
- /**
- * The constructor
- *
- * @param $message Message from the exception
- * @param $code Code number for the exception
- * @return void
- */
- public function __construct ($instance, $code) {
- // Add a message around the missing class
- $message = sprintf('[%s:%d] Decimal and thousand seperators are missing.',
- $instance->__toString(),
- $this->getLine()
- );
-
- // Call parent constructor
- parent::__construct($message, $code);
- }
-
-}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* The constructor
*
- * @param $msgArray Message from the exception
+ * @param $messageArray Message from the exception
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $msgArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Class %s not found.',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1]
+ $messageArray[1]
);
// Set extra data
- $this->setExtraData($msgArray[1]);
+ $this->setExtraData($messageArray[1]);
// Call parent constructor
parent::__construct($message, $code);
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct (FrameworkInterface $class = NULL, $code) {
+ public function __construct (FrameworkInterface $class = NULL, int $code) {
// Is the instance set?
if (is_null($class)) {
// Add a message around the missing class
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct (FrameworkInterface $class, $code) {
+ public function __construct (FrameworkInterface $class, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Headers are already sent.',
$class->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $classArray, $code) {
+ public function __construct (array $classArray, int $code) {
// Init extra class name
$extraClassName = '';
if ((isset($classArray[2])) && ($classArray[2] instanceof FrameworkInterface)) {
// Get the class name
$extraClassName = $classArray[2]->__toString();
- } // END - if
+ }
// Add a message around the missing class
$message = sprintf('[%s:%d] Method <u>%s()</u> is unsupported or should not be called. extraInstance=%s',
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $array, $code) {
+ public function __construct (array $array, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] While the application %s was initialized, a variable %s was not created.',
$array[0]->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* The super constructor for all exceptions
*
- * @param $msgArray Error message array
+ * @param $messageArray Error message array
* @param $code Error code
* @return void
*/
- public function __construct (array $msgArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Construct the message
$message = sprintf('[%s:%d] Database instance %s contains invalid entries.',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1]->__toString()
+ $messageArray[1]->__toString()
);
// Call parent exception constructor
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (UpdateableResult $resultInstance, $code) {
+ public function __construct (UpdateableResult $resultInstance, int $code) {
// Construct the message
$message = sprintf('[%s:%d] Update of result instance has nothing changed.',
$resultInstance->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (array $messageData, $code) {
+ public function __construct (array $messageData, int $code) {
// Construct the message
$message = sprintf('[%s:] Socket resource %s is not a server socket.',
$messageData[0]->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (array $messageData, $code) {
- // Is it a resource?
- if (is_resource($messageData[1])) {
- // Get last error
- $lastError = socket_last_error($messageData[1]);
-
- // Construct the message
- $message = sprintf('[%s:] Invalid socket, type=%s, errno=%s, errstr=%s',
- $messageData[0]->__toString(),
- gettype($messageData[1]),
- $lastError,
- socket_strerror($lastError)
- );
- } else {
- // Construct the message
- $message = sprintf('[%s:] Invalid socket, type=%s(%s), errno=%s, errstr=%s',
- $messageData[0]->__toString(),
- $messageData[1],
- gettype($messageData[1]),
- $messageData[2],
- $messageData[3]
- );
- }
+ public function __construct (array $messageData, int $code) {
+ // Construct the message
+ $message = sprintf('[%s:] Invalid socketResource[%s]=%s, errno=%s, errstr=%s',
+ $messageData[0]->__toString(),
+ gettype($messageData[0]->getSocketResource()),
+ $messageData[0]->getSocketResource(),
+ $messageData[1],
+ $messageData[2]
+ );
// Call parent exception constructor
parent::__construct($message, $code);
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @todo Those are logic exceptions and should be rewritten
* @param $code Error code
* @return void
*/
- public function __construct (array $messageData, $code) {
+ public function __construct (array $messageData, int $code) {
// Construct the message
$message = sprintf('[%s:] Socket %s has no error reported.',
$messageData[0]->__toString(),
- $messageData[1]
+ $messageData[0]->getSocketResource()
);
// Call parent exception constructor
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (array $messageData, $code) {
+ public function __construct (array $messageData, int $code) {
// Construct the message
$message = sprintf('[%s:] Socket %s is already registered.',
$messageData[0]->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (array $messageData, $code) {
+ public function __construct (array $messageData, int $code) {
// Construct the message
$message = sprintf('[%s:] Could not bind to socket %s: Type=%s, errno=%s, errstr=%s',
$messageData[0]->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (array $messageData, $code) {
+ public function __construct (array $messageData, int $code) {
// Construct the message
- $message = sprintf('[%s:] Could not make a connection, type=%s, errno=%s, errstr=%s',
+ $message = sprintf('[%s:] Could not make a connection: socketType=%s,errno=%s,errstr=%s',
$messageData[0]->__toString(),
- gettype($messageData[1]),
- $messageData[2],
- $messageData[3]
+ $messageData[0]->getSocketType(),
+ $messageData[1],
+ $messageData[2]
);
// Call parent exception constructor
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (array $messageData, $code) {
+ public function __construct (array $messageData, int $code) {
// Construct the message
$message = sprintf('[%s:] Cannot create socket, type=%s, errno=%s, errstr=%s',
$messageData[0]->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (array $messageData, $code) {
+ public function __construct (array $messageData, int $code) {
// Construct the message
$message = sprintf('[%s:] Socket operation failed, type=%s, errno=%s, errstr=%s',
$messageData[0]->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (array $messageData, $code) {
+ public function __construct (array $messageData, int $code) {
// Construct the message
$message = sprintf('[%s:] Changing option on socket failed, type=%s, errno=%s, errstr=%s',
$messageData[0]->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (array $messageData, $code) {
+ public function __construct (array $messageData, int $code) {
// Construct the message
$message = sprintf('[%s:] Socket error handler %s is not yet implemented, errorCode=%s, message=%s',
$messageData[0]->__toString(),
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Deprecated;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Generic\FrameworkException;
-
-/**
- * Thrown if a stacker is already initialized
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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 AlreadyInitializedStackerException extends FrameworkException {
- /**
- * The super constructor for all exceptions
- *
- * @param $messageArray Error message array
- * @param $code Error code
- * @return void
- */
- public function __construct (array $messageArray, $code) {
- // Construct message
- $message = sprintf('[%s:%d] Stacker %s already initialized, forceReInit=%d.',
- $messageArray[0]->__toString(),
- $this->getLine(),
- $messageArray[1],
- intval($messageArray[2])
- );
-
- // Call parent exception constructor
- parent::__construct($message, $code);
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Deprecated;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Generic\FrameworkException;
-
-/**
- * Thrown if a stacker is empty
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.shipsimu.org
- * @deprecated Don't use this anymore
- *
- * 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 EmptyStackerException extends FrameworkException {
- /**
- * The super constructor for all exceptions
- *
- * @param $messageArray Error message array
- * @param $code Error code
- * @return void
- */
- public function __construct (array $messageArray, $code) {
- // Construct message
- $message = sprintf('[%s:%d] Stacker %s is empty.',
- $messageArray[0]->__toString(),
- $this->getLine(),
- $messageArray[1]
- );
-
- // Call parent exception constructor
- parent::__construct($message, $code);
- }
-
-}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (array $messageArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Construct message
$message = sprintf('[%s:%d] Stacker %s is full.',
$messageArray[0]->__toString(),
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Stack\File;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Generic\FrameworkException;
+use Org\Mxchange\CoreFramework\Stack\File\StackableFile;
+
+/**
+ * Invalid/bad magic found
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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 InvalidMagicException extends FrameworkException {
+ /**
+ * Constructor with data string
+ *
+ * @param $data Raw data
+ * @param $code Error code
+ * @return void
+ */
+ public function __construct (string $data, int $code) {
+ // Construct message
+ $message = sprintf('data(%d)=%s has a bad magic, expected: %s',
+ strlen($data),
+ $data,
+ StackableFile::STACK_MAGIC
+ );
+
+ // Call parent exception constructor
+ parent::__construct($message, $code);
+ }
+
+}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Deprecated;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Generic\FrameworkException;
-
-/**
- * Thrown if a stacker is empty
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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 NoStackerException extends FrameworkException {
- /**
- * The super constructor for all exceptions
- *
- * @param $messageArray Error message array
- * @param $code Error code
- * @return void
- */
- public function __construct (array $messageArray, $code) {
- // Construct message
- $message = sprintf('[%s:%d] Stacker %s is not initialized.',
- $messageArray[0]->__toString(),
- $this->getLine(),
- $messageArray[1]
- );
-
- // Call parent exception constructor
- parent::__construct($message, $code);
- }
-
-}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $msgArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Invalid state %s of type %s detected.',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1],
+ $messageArray[1],
gettype($mgArray[2])
);
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (Stateable $stateInstance, $code) {
+ public function __construct (Stateable $stateInstance, int $code) {
// Construct the message
$message = sprintf('[%s:%d] Unexpected state detected.',
$stateInstance->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* The super constructor for all exceptions
*
- * @param $msgArray An array with message parts
+ * @param $messageArray An array with message parts
* @param $code An optional code for better debugging
* @return void
*/
- public function __construct (array $msgArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Prepare the message
$message = sprintf('[%s:%d] Cannot resolve state <span class="exception_reason">%s (class name: %s)</span>.',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1],
- $msgArray[0]->getClassName()
+ $messageArray[1],
+ $messageArray[0]->getClassName()
);
// Set extra data
- $this->setExtraData($msgArray[0]->getClassName() . ':' . $this->getLine());
+ $this->setExtraData($messageArray[0]->getClassName() . ':' . $this->getLine());
// Call parent contructor with message
parent::__construct($message, $code);
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $classArray, $code) {
+ public function __construct (array $classArray, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Der Template-Basispfad %s ist lesegeschützt! Bitte Zugriffsrechte (CHMOD) ändern.',
$classArray[0]->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $classArray, $code) {
+ public function __construct (array $classArray, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Path "%s" is no directory.',
$classArray[0]->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $messageArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Variable %s is not set, cannot modify(?) its value to %s.',
$messageArray[0]->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated Don't use this anymore
/**
* The constructor
*
- * @param $msgArray An array holding our informations
+ * @param $messageArray An array holding our informations
* @param $code Code number for the exception
* @return void
*/
- public function __construct (array $msgArray, $code) {
+ public function __construct (array $messageArray, int $code) {
// Add a message around the missing class
$message = sprintf('[%s:%d] Der Template-Typ %s entspricht nicht dem erwartetem Template-Typ %s.',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1],
- $msgArray[2]
+ $messageArray[1],
+ $messageArray[2]
);
// Call parent constructor
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Code number for the exception
* @return void
*/
- public function __construct (FrameworkInterface $class, $code) {
+ public function __construct (FrameworkInterface $class, int $code) {
// Add a message around the missing class
$message = sprintf('Template-Engine %s not (yet) supported.',
$class->__toString()
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code An optional code for better debugging
* @return void
*/
- public function __construct (Filterable $filterInstance, $code) {
+ public function __construct (Filterable $filterInstance, int $code) {
// Create the message
$message = sprintf('[%s:%d] Supplied account password did not match with stored.',
$filterInstance->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* The super constructor for all exceptions
*
- * @param $msgArray The non-optional message for the exception
+ * @param $messageArray The non-optional message for the exception
* @param $code An optional code for better debugging
* @return void
*/
- public function __construct (array $msgArray, $code = 0) {
+ public function __construct (array $messageArray, $code = 0) {
// Create the message
$message = sprintf('[%s:%d] User %s is a guest account.',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1]
+ $messageArray[1]
);
// Make sure everything is assigned properly
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* The super constructor for all exceptions
*
- * @param $msgArray The non-optional message for the exception
+ * @param $messageArray The non-optional message for the exception
* @param $code An optional code for better debugging
* @return void
*/
- public function __construct (array $msgArray, $code = 0) {
+ public function __construct (array $messageArray, $code = 0) {
// Create the message
$message = sprintf('[%s:%d] User email %s was not found.',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1]
+ $messageArray[1]
);
// Make sure everything is assigned properly
namespace Org\Mxchange\CoreFramework\Deprecated;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseWrapper;
+use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseFrontend;
use Org\Mxchange\CoreFramework\Generic\FrameworkException;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @todo Better rename this
/**
* The super constructor for all exceptions
*
- * @param $msgArray The non-optional message for the exception
+ * @param $messageArray The non-optional message for the exception
* @param $code An optional code for better debugging
* @return void
*/
- public function __construct (array $msgArray, $code = 0) {
+ public function __construct (array $messageArray, $code = 0) {
// Create the message
$message = sprintf('[%s:%d] User %s is not a guest account: %s',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1],
- $msgArray[0]->getField(UserDatabaseWrapper::DB_COLUMN_USER_STATUS)
+ $messageArray[1],
+ $messageArray[0]->getField(UserDatabaseFrontend::DB_COLUMN_USER_STATUS)
);
// Make sure everything is assigned properly
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* The super constructor for all exceptions
*
- * @param $msgArray The non-optional message for the exception
+ * @param $messageArray The non-optional message for the exception
* @param $code An optional code for better debugging
* @return void
*/
- public function __construct (array $msgArray, $code = 0) {
+ public function __construct (array $messageArray, $code = 0) {
// Create the message
$message = sprintf('[%s:%d] Supplied password for user %s did not match with stored password.',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1]->getUserName()
+ $messageArray[1]->getUserName()
);
// Make sure everything is assigned properly
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* The super constructor for all exceptions
*
- * @param $msgArray The non-optional message for the exception
+ * @param $messageArray The non-optional message for the exception
* @param $code An optional code for better debugging
* @return void
*/
- public function __construct (array $msgArray, $code = 0) {
+ public function __construct (array $messageArray, $code = 0) {
// Create the message
$message = sprintf('[%s:%d] Username %s was not found.',
- $msgArray[0]->__toString(),
+ $messageArray[0]->__toString(),
$this->getLine(),
- $msgArray[1]
+ $messageArray[1]
);
// Make sure everything is assigned properly
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (array $classArray, $code) {
+ public function __construct (array $classArray, int $code) {
// Extract attributes
$attributes = '<em>None</em>';
if ((is_array($classArray[2])) && (count($classArray[2]) > 0)) {
$attributes = implode(', ', $classArray[2]);
- } // END - if
+ }
// Construct our message
$message = sprintf('[%s:%d] Invalid XML node found: %s, attributes: %s.',
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (array $classArray, $code) {
+ public function __construct (array $classArray, int $code) {
// Construct our message
$message = sprintf('[%s:%d] XML nodes mismatch. Given: %s, Expected: %s',
$classArray[0]->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $code Error code
* @return void
*/
- public function __construct (array $classArray, $code) {
+ public function __construct (array $classArray, int $code) {
// Construct our message
$message = sprintf('[%s:%d] XML Error: %s at line %d.',
$classArray[0]->__toString(),
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*/
function addExtraFilters (Controller $controllerInstance, Requestable $requestInstance);
+ /**
+ * Initializes the template engine
+ *
+ * @param $templateType Type of template, e.g. 'html', 'image', 'console' ...
+ * @return void
+ */
+ function initTemplateEngine (string $templateType);
+
}
* An interface for managing applications. This can be a lot. E.g.:
*
* - Un-/locking applications
- * - Creating selectors for the selector-mode
* - Usage statistics
* - And many more...
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
interface ManageableApplication extends FrameworkInterface {
+ /**
+ * Getter for the version number
+ *
+ * @return $appVersion The application's version number
+ */
+ function getAppVersion ();
+
+ /**
+ * Setter for the version number
+ *
+ * @param $appVersion The application's version number
+ * @return void
+ */
+ function setAppVersion (string $appVersion);
+
+ /**
+ * Getter for human-readable name
+ *
+ * @return $appName The application's human-readable name
+ */
+ function getAppName ();
+
+ /**
+ * Setter for human-readable name
+ *
+ * @param $appName The application's human-readable name
+ * @return void
+ */
+ function setAppName (string $appName);
+
+ /**
+ * Getter for short uni*-like name
+ *
+ * @return $shortName The application's short uni*-like name
+ */
+ function getAppShortName ();
+
+ /**
+ * Setter for short uni*-like name
+ *
+ * @param $shortName The application's short uni*-like name
+ * @return void
+ */
+ function setAppShortName (string $shortName);
+
/**
* 1) Setups application data
*
*
* @return $masterTemplateName Name of the master template
*/
- function buildMasterTemplateName();
+ function buildMasterTemplateName ();
/**
* Assigns extra application-depending data
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
>>>>>>> Some updates::inc/main/interfaces/auth/class_Authorizeable.php
* @license GNU GPL 3.0 or any newer version
* @link http://www.shipsimu.org
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
interface Block extends FrameworkInterface {
- /**
- * Reads the file header
- *
- * @return void
- */
- function readFileHeader ();
-
- /**
- * Flushes the file header
- *
- * @return void
- */
- function flushFileHeader ();
-
- /**
- * Determines whether the EOF has been reached
- *
- * @return $isEndOfFileReached Whether the EOF has been reached
- */
- function isEndOfFileReached ();
-
- /**
- * Initializes counter for valid entries, arrays for damaged entries and
- * an array for gap seek positions. If you call this method on your own,
- * please re-analyze the file structure. So you are better to call
- * analyzeFile() instead of this method.
- *
- * @return void
- */
- function initCountersGapsArray ();
-
- /**
- * Getter for header size
- *
- * @return $totalEntries Size of file header
- */
- function getHeaderSize ();
-
- /**
- * Setter for header size
- *
- * @param $headerSize Size of file header
- * @return void
- */
- function setHeaderSize ($headerSize);
-
- /**
- * Getter for header array
- *
- * @return $totalEntries Size of file header
- */
- function getHeader ();
-
- /**
- * Setter for header
- *
- * @param $header Array for a file header
- * @return void
- */
- function setHeader (array $header);
-
- /**
- * Updates seekPosition attribute from file to avoid to much access on file.
- *
- * @return void
- */
- function updateSeekPosition ();
-
- /**
- * Getter for total entries
- *
- * @return $totalEntries Total entries in this file
- */
- function getCounter ();
-
- /**
- * "Getter" for file size
- *
- * @return $fileSize Size of currently loaded file
- */
- function getFileSize ();
-
- /**
- * Writes given value to the file and returns a hash and gap position for it
- *
- * @param $groupId Group identifier
- * @param $value Value to be added to the stack
- * @return $data Hash and gap position
- */
- function writeValueToFile ($groupId, $rawData);
-
- /**
- * Writes given raw data to the file and returns a gap position and length
- *
- * @param $groupId Group identifier
- * @param $hash Hash from encoded value
- * @param $encoded Encoded value to be written to the file
- * @return $data Gap position and length of the raw data
- */
- function writeDataToFreeGap ($groupId, $hash, $encoded);
-
- /**
- * Writes data at given position
- *
- * @param $seekPosition Seek position
- * @param $data Data to be written
- * @param $flushHeader Whether to flush the header (default: flush)
- * @return void
- */
- function writeData ($seekPosition, $data, $flushHeader = true);
-
- /**
- * Searches for next suitable gap the given length of data can fit in
- * including padding bytes.
- *
- * @param $length Length of raw data
- * @return $seekPosition Found next gap's seek position
- */
- function searchNextGap ($length);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
<?php
// Own namespace
-namespace CoreFramework\!!!;
+namespace Org\Mxchange\CoreFramework\!!!;
// Import framework stuff
use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @todo Find a better name for this interface
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
interface FrameworkInterface {
+ // Exception constants
+ const EXCEPTION_INVALID_ARGUMENT = 0x200;
+ const EXCEPTION_LOGIC_EXCEPTION = 0x201;
+ const EXCEPTION_UNSPPORTED_OPERATION = 0x202;
+ const EXCEPTION_UNEXPECTED_VALUE = 0x203;
+ const EXCEPTION_CLASS_NOT_FOUND = 0x204;
+ const EXCEPTION_BAD_METHOD_CALL = 0x205;
+ const EXCEPTION_OUT_OF_BOUNDS = 0x206;
+ const EXCEPTION_IS_NULL_POINTER = 0x207;
+
/**
* Getter for field name
*
* @return $fieldValue Field value from the user
* @throws NullPointerException If the result instance is null
*/
- function getField ($fieldName);
+ function getField (string $fieldName);
/**
* Checks if given field is set
* @return $isSet Whether the given field name is set
* @throws NullPointerException If the result instance is null
*/
- function isFieldSet ($fieldName);
+ function isFieldSet (string $fieldName);
/**
* Setter for call-back instance
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @param $streamData Mixed non-object stream data
* @return $streamData The compressed stream data
- * @throws InvalidObjectException If the stream is an object
+ * @throws InvalidArgumentException If the stream is not compressable or decompressable
*/
- function compressStream ($streamData);
+ function compressStream (string $streamData);
/**
* A decompression stream
*
* @param $streamData Mixed non-object stream data
* @return $streamData The decompressed stream data
- * @throws InvalidObjectException If the stream is an object
+ * @throws InvalidArgumentException If the stream is not compressable or decompressable
*/
- function decompressStream ($streamData);
+ function decompressStream (string $streamData);
/**
* Getter for the file extension of this compressor
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Criteria\Add;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+
+/**
+ * An interface for classes which are allowed to add criteria
+ *
+ * @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/>.
+ */
+interface AddableCriteria extends FrameworkInterface {
+ /**
+ * Adds registration elements to a given dataset instance
+ *
+ * @param $criteriaInstance An instance of a StoreableCriteria class
+ * @return void
+ */
+ function addElementsToDataSet (StoreableCriteria $criteriaInstance);
+
+}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
interface Criteria extends FrameworkInterface {
+ // Criteria types
+ const CRITERIA_TYPE_DEFAULT = 'default';
+ const CRITERIA_TYPE_CHOICE = 'choice';
+ const CRITERIA_TYPE_EXCLUDE = 'exclude';
+
/**
- * Setter for wrapper class name
+ * Setter for frontend class name
*
- * @param $wrapperConfigEntry Configuration entry which hold the wrapper class' name
+ * @param $frontendConfigEntry Configuration entry which hold the frontend class' name
* @return void
*/
- function setWrapperConfigEntry ($wrapperConfigEntry);
+ function setFrontendConfigEntry (string $frontendConfigEntry);
/**
- * Getter for wrapper class name
+ * Getter for Frontend class name
*
- * @return $wrapperConfigEntry Configuration entry which hold the wrapper class' name
+ * @return $frontendConfigEntry Configuration entry which hold the Frontend class' name
*/
- function getWrapperConfigEntry ();
+ function getFrontendConfigEntry ();
/**
* Checks whether given key is set
* @param $criteriaKey Criteria key
* @return $isSet Whether key is set
*/
- function isKeySet ($criteriaType, $criteriaKey);
+ function isKeySet (string $criteriaType, string $criteriaKey);
/**
* Checks whether given key is set for 'choice' type
* @param $criteriaKey Criteria key
* @return $isSet Whether key is set
*/
- function isChoiceKeySet ($criteriaKey);
+ function isChoiceKeySet (string $criteriaKey);
/**
* Checks whether given key is set for 'exclude' type
* @param $criteriaKey Criteria key
* @return $isSet Whether key is set
*/
- function isExcludeKeySet ($criteriaKey);
+ function isExcludeKeySet (string $criteriaKey);
/**
* Getter for criteria array
* @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
* @return $criteria
*/
- function getCriteriaArray ($criteriaType = 'default');
+ function getCriteriaArray (string $criteriaType = 'default');
/**
* Getter for criteria array 'choice' type
* @param $criteriaKey Criteria key to unset
* @return void
*/
- function unsetCriteria ($criteriaKey);
+ function unsetCriteria (string $criteriaKey);
/**
* Add criteria, this method converts dashes to underscores because dashes
* @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
* @return void
*/
- function addCriteria ($criteriaKey, $criteriaValue, $criteriaType = 'default');
+ function addCriteria (string $criteriaKey, $criteriaValue, string $criteriaType = 'default');
/**
* Sets criteria, this method converts dashes to underscores because dashes
* @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
* @return void
*/
- function setCriteria ($criteriaKey, $criteriaValue, $criteriaType = 'default');
+ function setCriteria (string $criteriaKey, $criteriaValue, string $criteriaType = 'default');
/**
* Add "choice" criteria, this method converts dashes to underscores because
* @param $criteriaValue Criteria value
* @return void
*/
- function addChoiceCriteria ($criteriaKey, $criteriaValue);
+ function addChoiceCriteria (string $criteriaKey, $criteriaValue);
/**
* Add "exclude" criteria, this method converts dashes to underscores because
* @param $criteriaValue Criteria value
* @return void
*/
- function addExcludeCriteria ($criteriaKey, $criteriaValue);
+ function addExcludeCriteria (string $criteriaKey, $criteriaValue);
/**
* Add configured criteria
* @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
* @return void
*/
- function addConfiguredCriteria ($criteriaKey, $configEntry, $criteriaType = 'default');
+ function addConfiguredCriteria (string $criteriaKey, string $configEntry, string $criteriaType = 'default');
/**
* Get criteria element or false if not found
* @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
* @return $value Whether the value of the critera or false
*/
- function getCriteriaElemnent ($criteriaKey, $criteriaType = 'default');
+ function getCriteriaElemnent (string $criteriaKey, string $criteriaType = 'default');
/**
* Get criteria element or false if not found for 'choice' type
* @param $criteriaKey The requested criteria key
* @return $value Whether the value of the critera or false
*/
- function getCriteriaChoiceElemnent ($criteriaKey);
+ function getCriteriaChoiceElemnent (string $criteriaKey);
/**
* Get criteria element or false if not found for 'exclude' type
* @param $criteriaKey The requested criteria key
* @return $value Whether the value of the critera or false
*/
- function getCriteriaExcludeElemnent ($criteriaKey);
+ function getCriteriaExcludeElemnent (string $criteriaKey);
/**
* Checks whether given array entry matches
* @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
* @return $matches Whether the entry matches or not
*/
- function ifEntryMatches (array $entryArray, $criteriaType = 'default');
+ function ifEntryMatches (array $entryArray, string $criteriaType = 'default');
/**
* Checks whether given array 'choice' entry matches
* @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
* @return $cacheKey The key suitable for the cache system
*/
- function getCacheKey ($onlyKeys = array(), $criteriaType = 'default');
+ function getCacheKey (array $onlyKeys = [], string $criteriaType = 'default');
/**
* "Getter" for a cache key ('choice' type)
* @param $onlyKeys Only use these keys for a cache key
* @return $cacheKey The key suitable for the cache system
*/
- function getCacheKeyChoice ($onlyKeys = array());
+ function getCacheKeyChoice (array $onlyKeys = []);
/**
* "Getter" for a cache key ('exclude' type)
* @param $onlyKeys Only use these keys for a cache key
* @return $cacheKey The key suitable for the cache system
*/
- function getCacheKeyExclude ($onlyKeys = array());
-
- /**
- * Count the criteria, e.g. useful to find out if a database query has no
- * limitation (search criteria).
- *
- * @param $criteriaType Type of this criteria, can be one of 'default' (default), 'choice' or 'exclude'
- * @return $count Count of all criteria entries
- */
- function count ($criteriaType = 'default');
+ function getCacheKeyExclude (array $onlyKeys = []);
/**
* Count 'choice' criteria, e.g. useful to find out if a database query
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Criteria\Add;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
-use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
-
-/**
- * An interface for classes which are allowed to add criteria
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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/>.
- */
-interface AddableCriteria extends FrameworkInterface {
- /**
- * Adds registration elements to a given dataset instance
- *
- * @param $criteriaInstance An instance of a StoreableCriteria class
- * @return void
- */
- function addElementsToDataSet (StoreableCriteria $criteriaInstance);
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Criteria\Local;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Criteria\Criteria;
-
-/**
- * An interface for local criterias
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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/>.
- */
-interface LocalSearchCriteria extends Criteria {
- /**
- * Setter for limit
- *
- * @param $limit Search limit
- * @return void
- * @todo Find a nice casting here. (int) allows until and including 32766.
- */
- function setLimit ($limit);
-
- /**
- * "Setter" for limit from a configuration entry
- *
- * @param $configEntry The configuration entry which hold a number as limit
- * @return void
- */
- function setConfiguredLimit ($configEntry);
-
- /**
- * Getter for limit
- *
- * @return $limit Search limit
- */
- function getLimit ();
-
- /**
- * Setter for skip
- *
- * @param $skip Search skip
- * @return void
- * @todo Find a nice casting here. (int) allows until and including 32766.
- */
- function setSkip ($skip);
-
- /**
- * Getter for skip
- *
- * @return $skip Search skip
- */
- function getSkip ();
-
- /**
- * Checks whether the given key/value pair is matching with 'default' and one of 'choice' and
- * never with in 'exclude'.
- *
- * @param $key Key element to check
- * @param $value Value to check
- * @param $separator Separator for "exploding" $value (default: ',')
- * @return $isMatching Whether the key/value is matching or excluded
- */
- function isCriteriaMatching ($key, $value, $separator = ',');
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Criteria\Local;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Criteria\Criteria;
-
-/**
- * An interface for local criterias
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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/>.
- */
-interface LocalUpdateCriteria extends Criteria {
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Criteria\Storing;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Criteria\Criteria;
-
-/**
- * An interface for storeable data sets
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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/>.
- */
-interface StoreableCriteria extends Criteria {
- /**
- * Setter for table name
- *
- * @param $tableName Name of the table to set
- * @return void
- */
- function setTableName ($tableName);
-
- /**
- * Getter for table name
- *
- * @return $tableName Name of the table to set
- */
- function getTableName ();
-
- /**
- * Setter for unique key
- *
- * @param $uniqueKey Column to use as unique key
- * @return void
- */
- function setUniqueKey ($uniqueKey);
-
- /**
- * Getter for unique key
- *
- * @return $uniqueKey Column to use as unique key
- */
- function getUniqueKey ();
-
- /**
- * Getter for unique key value
- *
- * @return $uniqueValue Value of the unique key
- */
- function getUniqueValue ();
-
- /**
- * Getter for primary key or unique key if not set
- *
- * @return $primaryKey Primary key or unique key if not set
- */
- function getPrimaryKey ();
-
- /**
- * Setter for primary key
- *
- * @param $primaryKey Primary key to set
- * @return void
- */
- function setPrimaryKey ($primaryKey);
-
- /**
- * Setter for primary key array
- *
- * @param $primaryKeys Primary key array to set
- * @return void
- */
- function setPrimaryKeyCombined (array $primaryKeys);
-
- /**
- * Getter for primary keys
- *
- * @return $primaryKeys Primary key array
- */
- function getPrimaryKeys ();
-
-}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Criteria\Local;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Criteria\Criteria;
+
+/**
+ * An interface for local criterias
+ *
+ * @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/>.
+ */
+interface LocalSearchCriteria extends Criteria {
+ /**
+ * Setter for limit
+ *
+ * @param $limit Search limit
+ * @return void
+ * @todo Find a nice casting here. (int) allows until and including 32766.
+ */
+ function setLimit (int $limit);
+
+ /**
+ * "Setter" for limit from a configuration entry
+ *
+ * @param $configEntry The configuration entry which hold a number as limit
+ * @return void
+ */
+ function setConfiguredLimit (string $configEntry);
+
+ /**
+ * Getter for limit
+ *
+ * @return $limit Search limit
+ */
+ function getLimit ();
+
+ /**
+ * Setter for skip
+ *
+ * @param $skip Search skip
+ * @return void
+ * @todo Find a nice casting here. (int) allows until and including 32766.
+ */
+ function setSkip (int $skip);
+
+ /**
+ * Getter for skip
+ *
+ * @return $skip Search skip
+ */
+ function getSkip ();
+
+ /**
+ * Checks whether the given key/value pair is matching with 'default' and one of 'choice' and
+ * never with in 'exclude'.
+ *
+ * @param $key Key element to check
+ * @param $value Value to check
+ * @param $separator Separator for "exploding" $value (default: ',')
+ * @return $isMatching Whether the key/value is matching or excluded
+ * @throws InvalidArgumentException If parameter is invalid
+ */
+ function isCriteriaMatching (string $key, $value, string $separator = ',');
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Criteria\Storing;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Criteria\Criteria;
+use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
+
+/**
+ * An interface for storeable data sets
+ *
+ * @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/>.
+ */
+interface StoreableCriteria extends Criteria {
+ /**
+ * Setter for table name
+ *
+ * @param $tableName Name of the table to set
+ * @return void
+ */
+ function setTableName (string $tableName);
+
+ /**
+ * Getter for table name
+ *
+ * @return $tableName Name of the table to set
+ */
+ function getTableName ();
+
+ /**
+ * Setter for unique key
+ *
+ * @param $uniqueKey Column to use as unique key
+ * @return void
+ */
+ function setUniqueKey (string $uniqueKey);
+
+ /**
+ * Getter for unique key
+ *
+ * @return $uniqueKey Column to use as unique key
+ */
+ function getUniqueKey ();
+
+ /**
+ * Setter for primary key
+ *
+ * @param $primaryKey Primary key to set
+ * @return void
+ */
+ function setPrimaryKey (string $primaryKey);
+
+ /**
+ * Setter for primary key array
+ *
+ * @param $primaryKeys Primary key array to set
+ * @return void
+ */
+ public function setPrimaryKeyCombined (array $primaryKeys);
+
+ /**
+ * Getter for primary keys
+ *
+ * @return $primaryKeys Primary key array
+ */
+ function getPrimaryKeys ();
+
+ /**
+ * Setter for search instance
+ *
+ * @param $searchInstance Searchable criteria instance
+ * @return void
+ */
+ function setSearchInstance (LocalSearchCriteria $searchInstance);
+
+ /**
+ * Getter for search instance
+ *
+ * @return $searchInstance Searchable criteria instance
+ */
+ function getSearchInstance ();
+
+ /**
+ * Getter for unique key value
+ *
+ * @return $uniqueValue Value of the unique key
+ */
+ function getUniqueValue ();
+
+ /**
+ * Getter for primary key or unique key if not set
+ *
+ * @return $primaryKey Primary key or unique key if not set
+ */
+ function getPrimaryKey ();
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Criteria\Local;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Criteria\Criteria;
+use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
+
+/**
+ * An interface for local criterias
+ *
+ * @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/>.
+ */
+interface LocalUpdateCriteria extends Criteria {
+ /**
+ * Getter for update criteria array
+ *
+ * @return $updateCriteria Array holding the update criteria
+ */
+ function getUpdateCriteria ();
+
+ /**
+ * Setter for search instance
+ *
+ * @param $searchInstance Searchable criteria instance
+ * @return void
+ */
+ function setSearchInstance (LocalSearchCriteria $searchInstance);
+
+ /**
+ * Getter for search instance
+ *
+ * @return $searchInstance Searchable criteria instance
+ */
+ function getSearchInstance ();
+
+}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $withFixed Whether to include a fixed salt (not recommended in p2p applications)
* @return $hashed The hashed and salted string
*/
- function hashString ($str, $oldHash = '', $withFixed = true);
+ function hashString (string $str, string $oldHash = '', bool $withFixed = true);
/**
* Encrypt the string with fixed salt
* @param $key Optional key, if none provided, a random key will be generated
* @return $encrypted Encrypted string
*/
- function encryptString ($str, $key = NULL);
+ function encryptString (string $str, string $key = NULL);
/**
* Decrypt the string with fixed salt
* @param $encrypted Encrypted string
* @return $str The unencrypted string
*/
- function decryptString ($encrypted);
+ function decryptString (string $encrypted);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @throws UnsupportedCriteriaException If the criteria is unsupported
* @throws SqlException If an 'SQL error' occurs
*/
- function querySelect ($tableName, LocalSearchCriteria $searchInstance);
+ function querySelect (string $tableName, LocalSearchCriteria $searchInstance);
/**
* "Inserts" a data set instance into a local file database folder
* @param $tableName Name of the table we need the primary key from
* @return $primaryKey Primary key column of the given table
*/
- function getPrimaryKeyOfTable ($tableName);
+ function getPrimaryKeyOfTable (string $tableName);
/**
* Removes non-data from given array.
* @param $tableName Table name
* @return $count Total rows of given table
*/
- function countTotalRows($tableName);
+ function countTotalRows(string $tableName);
}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Database\Frontend;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Criteria\Criteria;
-use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
-
-/**
- * The general interface for all other database wrappers
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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/>.
- */
-interface DatabaseWrapper extends FrameworkInterface {
- /**
- * Getter for index key
- *
- * @return $indexKey Index key
- */
- function getIndexKey();
-
- /**
- * Getter for last exception
- *
- * @return $lastException Last exception or NULL if none occured
- */
- function getLastException();
-
- /**
- * Do a "select" query on the current table with the given search criteria and
- * store it in cache for later usage
- *
- * @param $criteriaInstance An instance of a Criteria class
- * @param $onlyKeys Only use these keys for a cache key
- * @return $resultInstance An instance of a database result class
- */
- function doSelectByCriteria(Criteria $criteriaInstance, array $onlyKeys = array());
-
- /**
- * Count the numbers of rows we shall receive
- *
- * @param $criteriaInstance An instance of a Criteria class
- * @param $onlyKeys Only use these keys for a cache key
- * @return $numRows Numbers of rows of database entries
- */
- function doSelectCountByCriteria(Criteria $criteriaInstance, $onlyKeys = array());
-
- /**
- * Getter for primary key used in wrapped table
- *
- * @return $primaryKey Primary key used in wrapped table
- */
- function getPrimaryKeyValue();
-
- /**
- * Counts total rows of this table
- *
- * @return $count Total rows of this table
- */
- function countTotalRows();
-
-}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $fieldValue New value to store
* @return void
*/
- function updateDatabaseField ($fieldName, $fieldValue);
+ function updateDatabaseField (string $fieldName, $fieldValue);
}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Frontend\Account;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseFrontend;
+use Org\Mxchange\CoreFramework\Registration\User\UserRegister;
+use Org\Mxchange\CoreFramework\Result\Update\UpdateableResult;
+
+/**
+ * An interface for frontend handling manageable accounts
+ *
+ * @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/>.
+ */
+interface ManageableAccountFrontend extends DatabaseFrontend {
+ /**
+ * Handles inserting the registration data from a registration instance into the database
+ *
+ * @param $registrationInstance An instance of a registration class
+ * @return void
+ */
+ function insertRegistrationObject (UserRegister $registrationInstance);
+
+ /**
+ * Updates an user database entry with given result
+ *
+ * @param $resultInstance An instance of a UpdateableResult class
+ * @return void
+ */
+ function doUpdateByResult (UpdateableResult $resultInstance);
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Database\Frontend;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Criteria\Criteria;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+
+/**
+ * The general interface for all other database frontends
+ *
+ * @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/>.
+ */
+interface DatabaseFrontend extends FrameworkInterface {
+ /**
+ * Getter for index key
+ *
+ * @return $indexKey Index key
+ */
+ function getIndexKey ();
+
+ /**
+ * Getter for last exception
+ *
+ * @return $lastException Last exception or NULL if none occured
+ */
+ function getLastException ();
+
+ /**
+ * Do a "select" query on the current table with the given search criteria and
+ * store it in cache for later usage
+ *
+ * @param $criteriaInstance An instance of a Criteria class
+ * @param $onlyKeys Only use these keys for a cache key
+ * @return $resultInstance An instance of a database result class
+ */
+ function doSelectByCriteria (Criteria $criteriaInstance, array $onlyKeys = []);
+
+ /**
+ * Count the numbers of rows we shall receive
+ *
+ * @param $criteriaInstance An instance of a Criteria class
+ * @param $onlyKeys Only use these keys for a cache key
+ * @return $numRows Numbers of rows of database entries
+ */
+ function doSelectCountByCriteria (Criteria $criteriaInstance, array $onlyKeys = []);
+
+ /**
+ * Generates primary key for this database frontend
+ *
+ * @return $primaryKey Primary key used in wrapped table
+ */
+ function generatePrimaryKey ();
+
+ /**
+ * Counts total rows of this table
+ *
+ * @return $count Total rows of this table
+ */
+ function countTotalRows ();
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Database\Frontend\Points;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseFrontend;
+use Org\Mxchange\CoreFramework\Result\Update\UpdateableResult;
+
+/**
+ * An interface for frontend dealing with bookable points
+ *
+ * @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/>.
+ */
+interface BookablePointsFrontend extends DatabaseFrontend {
+ /**
+ * Inserts the given points for the given user in the database
+ *
+ * @param $pointsInstance An instance of a user class
+ * @return void
+ */
+ function insertUserPoints (BookablePoints $pointsInstance);
+
+ /**
+ * Updates an user database entry with given result
+ *
+ * @param $resultInstance An instance of a UpdateableResult class
+ * @return void
+ */
+ function doUpdateByResult (UpdateableResult $resultInstance);
+
+}
// Import framework stuff
use Org\Mxchange\CoreFramework\Criteria\Criteria;
use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
-use Org\Mxchange\CoreFramework\Database\Backend\DatabaseBackend;
use Org\Mxchange\CoreFramework\Database\FrameworkDatabase;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $host Hostname to use
* @return void
*/
- function setConnectionData ($login, $pass, $dbase, $host='localhost');
+ function setConnectionData (string $login, string $pass, string $dbase, string $host = 'localhost');
/**
* Getter for connection data
*/
function getConnectionData ();
- /**
- * Setter for the real database layer
- * @param $dbLayer An instance of the real database layer
- * @return void
- */
- function setDatabaseLayer (DatabaseBackend $dbLayer);
-
/**
* Getter for index key
*
* @param $criteriaInstance An instance of a Criteria class
* @return $result The result as an array
*/
- function doSelectByTableCriteria ($tableName, Criteria $criteriaInstance);
+ function doSelectByTableCriteria (string $tableName, Criteria $criteriaInstance);
/**
* Getter for last exception
* @param $tableName Name of table we need the primary key column from
* @return $primaryKey Primary key column of requested table
*/
- function getPrimaryKeyOfTable ($tableName);
+ function getPrimaryKeyOfTable (string $tableName);
/**
* Removes non-public data from given array.
* @param $tableName Table name
* @return $count Total rows of given table
*/
- function countTotalRows($tableName);
+ function countTotalRows (string $tableName);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
+ * @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
*
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Database\Frontend\Points;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseWrapper;
-use Org\Mxchange\CoreFramework\Result\Update\UpdateableResult;
-
-/**
- * An interface for wrapper dealing with bookable points
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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/>.
- */
-interface BookablePointsWrapper extends DatabaseWrapper {
- /**
- * Inserts the given points for the given user in the database
- *
- * @param $pointsInstance An instance of a user class
- * @return void
- */
- function insertUserPoints (BookablePoints $pointsInstance);
-
- /**
- * Updates an user database entry with given result
- *
- * @param $resultInstance An instance of a Updateable database result
- * @return void
- */
- function doUpdateByResult (UpdateableResult $resultInstance);
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Wrapper\Account;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseWrapper;
-use Org\Mxchange\CoreFramework\Registration\User\UserRegister;
-use Org\Mxchange\CoreFramework\Result\Update\UpdateableResult;
-
-/**
- * An interface for wrapper handling manageable accounts
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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/>.
- */
-interface ManageableAccountWrapper extends DatabaseWrapper {
- /**
- * Handles inserting the registration data from a registration instance into the database
- *
- * @param $registrationInstance An instance of a registration class
- * @return void
- */
- function insertRegistrationObject (UserRegister $registrationInstance);
-
- /**
- * Updates an user database entry with given result
- *
- * @param $resultInstance An instance of a Updateable database result
- * @return void
- */
- function doUpdateByResult (UpdateableResult $resultInstance);
-
-}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $stripTags Whether HTML tags shall be stripped out
* @return void
*/
- function outputStream ($output, $stripTags = false);
+ function outputStream (string $output, bool $stripTags = false);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Hub Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Filesystem\File;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Filesystem\Filesystem;
+
+/**
+ * A virtual file system interface
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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/>.
+ */
+interface BinaryFile extends Filesystem {
+ /**
+ * Separator for header data
+ */
+ const SEPARATOR_HEADER_DATA = 0x01;
+
+ /**
+ * Separator header->entries
+ */
+ const SEPARATOR_HEADER_ENTRIES = 0x02;
+
+ /**
+ * Separator group->hash
+ */
+ const SEPARATOR_GROUP_HASH = 0x03;
+
+ /**
+ * Separator hash->value
+ */
+ const SEPARATOR_HASH_VALUE = 0x04;
+
+ /**
+ * Separator entry->entry
+ */
+ const SEPARATOR_ENTRIES = 0x05;
+
+ /**
+ * Separator type->position
+ */
+ const SEPARATOR_TYPE_POSITION = 0x06;
+
+ /**
+ * Length of count
+ */
+ const LENGTH_COUNT = 20;
+
+ /**
+ * Length of position
+ */
+ const LENGTH_POSITION = 20;
+
+ /**
+ * Length of group
+ */
+ const LENGTH_GROUP = 10;
+
+ /**
+ * Maximum length of entry type
+ */
+ const LENGTH_TYPE = 20;
+
+ //***** Array elements for 'gaps' array *****
+
+ /**
+ * Start of gap
+ */
+ const GAPS_INDEX_START = 'start';
+
+ /**
+ * End of gap
+ */
+ const GAPS_INDEX_END = 'end';
+
+ // Header names
+ const HEADER_NAME_MAGIC = 'magic';
+ const HEADER_NAME_TOTAL_ENTRIES = 'total';
+ const HEADER_NAME_SEEK_POSITION = 'seek';
+
+ // Header element counts
+ const HEADER_INDEX_ELEMENT_COUNT = 2;
+ const HEADER_STACK_ELEMENT_COUNT = 3;
+
+ /**
+ * Reads the file header
+ *
+ * @return void
+ */
+ function readFileHeader ();
+
+ /**
+ * Flushes the file header
+ *
+ * @return void
+ */
+ function flushFileHeader ();
+
+ /**
+ * Determines whether the EOF has been reached
+ *
+ * @return $isEndOfFileReached Whether the EOF has been reached
+ */
+ function isEndOfFileReached ();
+
+ /**
+ * Getter for header size
+ *
+ * @return $totalEntries Size of file header
+ */
+ function getHeaderSize ();
+
+ /**
+ * Setter for header size
+ *
+ * @param $headerSize Size of file header
+ * @return void
+ */
+ function setHeaderSize (int $headerSize);
+
+ /**
+ * Getter for header array
+ *
+ * @return $totalEntries Size of file header
+ */
+ function getHeader ();
+
+ /**
+ * Setter for header
+ *
+ * @param $header Array for a file header
+ * @return void
+ */
+ function setHeader (array $header);
+
+ /**
+ * Initializes counter for valid entries, arrays for damaged entries and
+ * an array for gap seek positions. If you call this method on your own,
+ * please re-analyze the file structure. So you are better to call
+ * analyzeFileStructure() instead of this method.
+ *
+ * @return void
+ */
+ function initCountersGapsArray ();
+
+ /**
+ * Updates seekPosition attribute from file to avoid to much access on file.
+ *
+ * @return void
+ */
+ function updateSeekPosition ();
+
+ /**
+ * Getter for total entries
+ *
+ * @return $totalEntries Total entries in this file
+ */
+ function getCounter ();
+
+ /**
+ * "Getter" for file size
+ *
+ * @return $fileSize Size of currently loaded file
+ */
+ function getFileSize ();
+
+ /**
+ * Checks whether the abstracted file only contains gaps by counting all
+ * gaps' bytes together and compare it to total length.
+ *
+ * @return $isGapsOnly Whether the abstracted file only contains gaps
+ */
+ function isFileGapsOnly();
+
+ /**
+ * Searches for next suitable gap the given length of data can fit in
+ * including padding bytes.
+ *
+ * @param $length Length of raw data
+ * @return $seekPosition Found next gap's seek position
+ */
+ function searchNextGap (int $length);
+
+ /**
+ * Writes given value to the file and returns a hash and gap position for it
+ *
+ * @param $groupId Group identifier
+ * @param $value Value to be added to the stack
+ * @return $data Hash and gap position
+ */
+ function writeValueToFile (string $groupId, string $rawData);
+
+ /**
+ * Writes given raw data to the file and returns a gap position and length
+ *
+ * @param $groupId Group identifier
+ * @param $hash Hash from encoded value
+ * @param $encoded Encoded value to be written to the file
+ * @return $data Gap position and length of the raw data
+ */
+ function writeDataToFreeGap (string $groupId, string $hash, string $encoded);
+
+ /**
+ * Writes data at given position
+ *
+ * @param $seekPosition Seek position
+ * @param $data Data to be written
+ * @param $flushHeader Whether to flush the header (default: flush)
+ * @return void
+ */
+ function writeData (int $seekPosition, string $data, bool $flushHeader = true);
+
+ /**
+ * Writes at given position by seeking to it.
+ *
+ * @param $seekPosition Seek position in file
+ * @param $dataStream Data to be written
+ * @return mixed Number of writes bytes or false on error
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ function writeAtPosition (int $seekPosition, string $dataStream);
+
+}
<?php
// Own namespace
-namespace Org\Mxchange\CoreFramework\FileSystem;
+namespace Org\Mxchange\CoreFramework\Filesystem;
// Import framework stuff
use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Filesystem\Index;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Filesystem\File\BinaryFile;
+
+/**
+ * An interface for Indexable file classes
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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/>.
+ */
+interface IndexableFile extends BinaryFile {
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Filesystem\Stack;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Filesystem\File\BinaryFile;
+
+/**
+ * An interface for files of file-based stacks
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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/>.
+ */
+interface FileStacker extends BinaryFile {
+
+}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @todo HandleableDataSet looks strange here
* Registers a task with a task handler.
*
* @param $taskName A task name to register the task on
- * @param $taskInstance The instance we should register as a task
+ * @param $taskInstance An instance of a Taskable class
* @return void
*/
- function registerTask ($taskName, Visitable $taskInstance);
+ function registerTask (string $taskName, Taskable $taskInstance);
/**
* Checks whether tasks are left including idle task
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
<?php
// Own namespace
-namespace CoreFramework\Index\!!!;
+namespace Org\Mxchange\CoreFramework\Index\!!!;
// Import framework stuff
use Org\Mxchange\CoreFramework\Index\Indexable;
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
interface Indexable extends FrameworkInterface {
+ /**
+ * Magic for this index
+ */
+ const INDEX_MAGIC = 'INDEXv0.1';
+
+ /**
+ * Separator group->hash
+ */
+ const SEPARATOR_GROUP_HASH = 0x01;
+
+ /**
+ * Separator hash->gap position
+ */
+ const SEPARATOR_HASH_GAP_POSITION = 0x02;
+
+ /**
+ * Separator gap position->length
+ */
+ const SEPARATOR_GAP_LENGTH = 0x03;
+
+ /**
+ * Checks whether the index has been fully loaded (and parsed)
+ *
+ * @return $isLoaded Whether the index has been loaded
+ */
+ function isIndexLoaded ();
}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Index\File;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Index\Indexable;
+
+/**
+ * An interface for indexable file classes
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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/>.
+ */
+interface FileIndexer extends Indexable {
+ /**
+ * Adds given data's hash to the index file
+ *
+ * @param $stackName Name of stack to add hash
+ * @param $data Hash and gap position to be added to the index
+ * @return void
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ function addHashedDataToIndex (string $stackName, array $data);
+
+ /**
+ * Searches for next suitable gap the given length of data can fit in
+ * including padding bytes.
+ *
+ * @param $length Length of raw data
+ * @return $seekPosition Found next gap's seek position
+ * @throws InvalidArgumentException If the parameter is not valid
+ */
+ function searchNextGap (int $length);
+
+ /**
+ * Writes at given position by seeking to it.
+ *
+ * @param $seekPosition Seek position in file
+ * @param $dataStream Data to be written
+ * @return mixed Number of writes bytes or false on error
+ * @throws InvalidArgumentException If a parameter is not valid
+ */
+ function writeAtPosition (int $seekPosition, string $dataStream);
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Index\File\Stack;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Filesystem\Block\CalculatableBlock;
+use Org\Mxchange\CoreFramework\Index\File\FileIndexer;
+
+/**
+ * An interface for Indexable stack classes
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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/>.
+ */
+interface IndexableStack extends FileIndexer {
+
+}
+++ /dev/null
-
- /**
- * Adds given hash to an index file
- *
- * @param $stackName Name of stack to add hash
- * @param $data Hash and gap position to be added to the index
- * @return void
- */
- function addHashToIndex ($stackName, array $data);
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Stacker\Index;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Filesystem\Block\CalculatableBlock;
-use Org\Mxchange\CoreFramework\Index\Indexable;
-
-/**
- * An interface for Indexable stack classes
- *
- * @author Roland Haeder <webmaster@ship-simu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.ship-simu.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/>.
- */
-interface IndexableStack extends Indexable, CalculatableBlock {
- /**
- * Adds given hash to an index file
- *
- * @param $stackName Name of stack to add hash
- * @param $data Hash and gap position to be added to the index
- * @return void
- */
- function addHashToIndex ($stackName, array $data);
-
-}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
interface Streamable extends FrameworkInterface {
- /**
- * Determines seek position
- *
- * @return $seekPosition Current seek position
- */
- function determineSeekPosition ();
-
- /**
- * Seek to given offset (default) or other possibilities as fseek() gives.
- *
- * @param $offset Offset to seek to (or used as "base" for other seeks)
- * @param $whence Added to offset (default: only use offset to seek to)
- * @return $status Status of file seek: 0 = success, -1 = failed
- */
- function seek ($offset, $whence = SEEK_SET);
-
- /**
- * Size of file stack
- *
- * @return $size Size (in bytes) of file
- */
- function size ();
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
interface StreamableInput extends Streamable {
+ /**
+ * Determines seek position
+ *
+ * @return $seekPosition Current seek position
+ */
+ function determineSeekPosition ();
+
+ /**
+ * Seek to given offset (default) or other possibilities as fseek() gives.
+ *
+ * @param $offset Offset to seek to (or used as "base" for other seeks)
+ * @param $whence Added to offset (default: only use offset to seek to)
+ * @return void
+ * @throws OutOfBoundsException If the position is not seekable
+ */
+ function seek (int $offset, int $whence = SEEK_SET);
+
+ /**
+ * Size of file stack
+ *
+ * @return $size Size (in bytes) of file
+ */
+ function size ();
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $except Some parts of a directory we want to ignore. Valid: directory and file names, other values will be silently ignored
* @return SplFileInfo An instance of a SplFileInfo class
*/
- function readDirectoryExcept (array $except = array());
+ function readDirectoryExcept (array $except = []);
/**
* Close a directory source and set it's instance to null and the path name
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* Reads a line from CSV file and returns it as an indexed array
*
* @param $columnSeparator Character to use separting columns
+ * @param $expectedMatches Expected matches, 0 is default and means flexible
* @return $lineArray An index array with the read line
+ * @throws InvalidArgumentException If a parameter is invalid
*/
- function readCsvFileLine ($columnSeparator);
+ function readCsvFileLine (string $columnSeparator, int $expectedMatches = 0);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* Setter for the *real* file input instance
*
- * @param $inputStream The *real* file-input class
+ * @param $inputStreamerInstance The *real* file-input class
* @return void
*/
- function setInputStream (FileInputStreamer $inputStream);
+ function setInputStreamerInstance (FileInputStreamer $inputStreamerInstance);
/**
* Getter for the *real* file input instance
*
* @return $inputStream The *real* file-input class
*/
- function getInputStream ();
+ function getInputStreamerInstance ();
/**
* Setter for the *real* file output instance
*
- * @param $outputStream The *real* file-output class
+ * @param $outputStreamerInstance The *real* file-output class
* @return void
*/
- function setOutputStream (FileOutputStreamer $outputStream);
+ function setOutputStreamerInstance (FileOutputStreamer $outputStreamerInstance);
/**
* Getter for the *real* file output instance
*
* @return $outputStream The *real* file-output class
*/
- function getOutputStream ();
+ function getOutputStreamerInstance ();
/**
* Saves a file with data by using the current output stream
* @param $objectInstance An instance of a FrameworkInterface class (default: NULL)
* @return void
*/
- function saveStreamToFile (SplFileInfo $infoInstance, $dataStream, FrameworkInterface $objectInstance = NULL);
+ function saveStreamToFile (SplFileInfo $infoInstance, string $dataStream, FrameworkInterface $objectInstance = NULL);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $stripTags Whether HTML tags shall be stripped out
* @return void
*/
- function output ($outStream = false, $stripTags = false);
+ function output (string $outStream = '', bool $stripTags = false);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* is not set by setFileObject()
* @throws InvalidResourceException If there is being set
*/
- function read ($bytes = NULL);
+ function read (int $bytes = 0);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @throws InvalidResourceException If there is being set
* an invalid file resource
*/
- function writeToFile ($dataStream);
+ function writeToFile (string $dataStream);
/**
* Writes at given position by seeking to it.
* @param $data Data to be written
* @return mixed Number of writes bytes or false on error
*/
- function writeAtPosition ($seedPosition, $data);
+ function writeAtPosition (int $seedPosition, string $data);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Iterator\Filesystem;
-
-// Import SPL stuff
-use \SeekableIterator;
-
-/**
- * An interface for seekable iterators which also allow to write to the file
- * in different ways.
- *
- * @author Roland Haeder <webmaster@ship-simu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.ship-simu.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/>.
- */
-interface SeekableWritableFileIterator extends SeekableIterator {
- /**
- * Seeks to given position
- *
- * @param $seekPosition Seek position in file
- * @return $status Status of this operation
- */
- function seek ($seekPosition);
-
- /**
- * Size of file stack
- *
- * @return $size Size (in bytes) of file
- */
- function size ();
-
- /**
- * Reads given amount of bytes from file.
- *
- * @param $bytes Amount of bytes to read
- * @return $data Data read from file
- */
- function read ($bytes);
-
- /**
- * Analyzes entries in index file. This will count all found (and valid)
- * entries, mark invalid as damaged and count gaps ("fragmentation"). If
- * only gaps are found, the file is considered as "virgin" (no entries).
- *
- * @return void
- */
- function analyzeFile ();
-
- /**
- * Checks whether the file header is initialized
- *
- * @return $isInitialized Whether the file header is initialized
- */
- function isFileHeaderInitialized ();
-
- /**
- * Creates the assigned file
- *
- * @return void
- */
- function createFileHeader ();
-
- /**
- * Pre-allocates file (if enabled) with some space for later faster write access.
- *
- * @param $type Type of the file
- * @return void
- */
- function preAllocateFile ($type);
-
- /**
- * Initializes counter for valid entries, arrays for damaged entries and
- * an array for gap seek positions. If you call this method on your own,
- * please re-analyze the file structure. So you are better to call
- * analyzeFile() instead of this method.
- *
- * @return void
- */
- function initCountersGapsArray ();
-
- /**
- * Getter for header size
- *
- * @return $totalEntries Size of file header
- */
- function getHeaderSize ();
-
- /**
- * Setter for header size
- *
- * @param $headerSize Size of file header
- * @return void
- */
- function setHeaderSize ($headerSize);
-
- /**
- * Getter for header array
- *
- * @return $totalEntries Size of file header
- */
- function getHeader ();
-
- /**
- * Setter for header
- *
- * @param $header Array for a file header
- * @return void
- */
- function setHeader (array $header);
-
- /**
- * Updates seekPosition attribute from file to avoid to much access on file.
- *
- * @return void
- */
- function updateSeekPosition ();
-
- /**
- * Getter for total entries
- *
- * @return $totalEntries Total entries in this file
- */
- function getCounter ();
-
- /**
- * "Getter" for file size
- *
- * @return $fileSize Size of currently loaded file
- */
- function getFileSize ();
-
- /**
- * Writes data at given position
- *
- * @param $seekPosition Seek position
- * @param $data Data to be written
- * @param $flushHeader Whether to flush the header (default: flush)
- * @return void
- */
- function writeData ($seekPosition, $data, $flushHeader = true);
-
- /**
- * Getter for seek position
- *
- * @return $seekPosition Current seek position (stored here in object)
- */
- function getSeekPosition ();
-
- /**
- * Writes given value to the file and returns a hash and gap position for it
- *
- * @param $groupId Group identifier
- * @param $value Value to be added to the stack
- * @return $data Hash and gap position
- */
- function writeValueToFile ($groupId, $value);
-
- /**
- * Writes given raw data to the file and returns a gap position and length
- *
- * @param $groupId Group identifier
- * @param $hash Hash from encoded value
- * @param $encoded Encoded value to be written to the file
- * @return $data Gap position and length of the raw data
- */
- function writeDataToFreeGap ($groupId, $hash, $encoded);
-
- /**
- * Searches for next suitable gap the given length of data can fit in
- * including padding bytes.
- *
- * @param $length Length of raw data
- * @return $seekPosition Found next gap's seek position
- */
- function searchNextGap ($length);
-
-}
*
* @author Roland Haeder <webmaster@ship-simu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.ship-simu.org
*
/**
* Initializes this iterator by scanning over the registry for all keys.
*
+ * @param $onlyRegistries Only iterate on these sub-registry keys, default is all
* @return void
* @throws LogicException If a registry entry does not implement Registerable
* @throws NullPointerException If criteriaKey or criteriaMethod is not set but a call-back instance is set
*/
- function initIterator (FrameworkInterface $callbackInstance = NULL, $criteriaKey = NULL, $criteriaMethod = NULL);
+ function initIterator (array $onlyRegistries = []);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $groupName Group to check if found in list
* @return $isset Whether the group is valid
*/
- function isGroupSet ($groupName);
+ function isGroupSet (string $groupName);
/**
- * Adds the given group or if already added issues a ListGroupAlreadyAddedException
+ * Adds the given group or if already added issues a BadMethodCallException
*
* @param $groupName Group to add
* @return void
- * @throws ListGroupAlreadyAddedException If the given group is already added
+ * @throws BadMethodCallException If the given group is already added
*/
- function addGroup ($groupName);
+ function addGroup (string $groupName);
/**
* Adds the given instance to list group and sub group
* @param $subGroup Sub group to add instance to
* @param $visitableInstance An instance of Visitable
* @return void
- * @throws NoListGroupException If the given group is not found
+ * @throws BadMethodCallException If the given group is not found
*/
- function addInstance ($groupName, $subGroup, Visitable $visitableInstance);
+ function addInstance (string $groupName, string $subGroup, Visitable $visitableInstance);
/**
* Adds the given entry to list group
* @param $groupName Group to add instance to
* @param $entry An entry of any type
* @return void
- * @throws NoListGroupException If the given group is not found
+ * @throws BadMethodCallException If the given group is not found
*/
- function addEntry ($groupName, $entry);
+ function addEntry (string $groupName, $entry);
/**
* Updates the given entry by hash with given array
* @return void
* @throws InvalidListHashException If the solved hash index is invalid
*/
- function updateCurrentEntryByHash ($hash, array $entryArray);
+ function updateCurrentEntryByHash (string $hash, array $entryArray);
/**
* "Getter" for an iterator instance of this list
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Logging;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+
+/**
+ * A Logger interface
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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/>.
+ */
+interface Logger extends FrameworkInterface {
+
+ // Logger levels
+ const LOGGER_LEVEL_DEBUG = 'DEBUG';
+ const LOGGER_LEVEL_DEPRECATED = 'DEPRECATED';
+ const LOGGER_LEVEL_INFO = 'INFO';
+ const LOGGER_LEVEL_TRACE = 'TRACE';
+ const LOGGER_LEVEL_WARNING = 'WARNING';
+
+ /**
+ * Outputs a trace message whether to debug instance (should be set!) or
+ * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
+ * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
+ *
+ * @param $message Message we shall send out...
+ * @param $doPrint Whether print or die here (default: print)
+ * @paran $stripTags Whether to strip tags (default: false)
+ * @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ * @throws NullPointerException If this->outputInstance is NULL
+ * @todo Remove $doPrint parameter
+ */
+ public function traceMessage (string $message, bool $doPrint = true, bool $stripTags = false);
+
+ /**
+ * Outputs a debug message whether to debug instance (should be set!) or
+ * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
+ * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
+ *
+ * @param $message Message we shall send out...
+ * @param $doPrint Whether print or die here (default: print)
+ * @paran $stripTags Whether to strip tags (default: false)
+ * @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ * @throws NullPointerException If this->outputInstance is NULL
+ * @todo Remove $doPrint parameter
+ */
+ public function debugMessage (string $message, bool $doPrint = true, bool $stripTags = false);
+
+ /**
+ * Outputs an informational message whether to debug instance (should be set!) or
+ * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
+ * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
+ *
+ * @param $message Message we shall send out...
+ * @param $doPrint Whether print or die here (default: print)
+ * @paran $stripTags Whether to strip tags (default: false)
+ * @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ * @throws NullPointerException If this->outputInstance is NULL
+ * @todo Remove $doPrint parameter
+ */
+ public function infoMessage (string $message, bool $doPrint = true, bool $stripTags = false);
+
+ /**
+ * Outputs a warning message whether to debug instance (should be set!) or
+ * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
+ * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
+ *
+ * @param $message Message we shall send out...
+ * @param $doPrint Whether print or die here (default: print)
+ * @paran $stripTags Whether to strip tags (default: false)
+ * @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ * @throws NullPointerException If this->outputInstance is NULL
+ * @todo Remove $doPrint parameter
+ */
+ public function warningMessage (string $message, bool $doPrint = true, bool $stripTags = false);
+
+ /**
+ * Output a partial stub message for the caller method
+ *
+ * @param $message An optional message to display
+ * @return void
+ */
+ public function partialStub (string $message = '');
+
+ /**
+ * Outputs a deprecated message whether to debug instance (should be set!) or
+ * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
+ * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
+ *
+ * @param $message Message we shall send out...
+ * @param $doPrint Whether print or die here (default: print)
+ * @paran $stripTags Whether to strip tags (default: false)
+ * @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ * @throws NullPointerException If this->outputInstance is NULL
+ * @todo Remove $doPrint parameter
+ * @todo When all old method invocations are fixed, renamed this do deprecatedMessage
+ */
+ public function debugOutput (string $message, bool $doPrint = true, bool $stripTags = false);
+
+}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
interface Parseable extends FrameworkInterface {
+ // Exception constants
+ const EXCEPTION_XML_PARSER_ERROR = 0x1e0;
+ const EXCEPTION_XML_NODE_UNKNOWN = 0x1e1;
+ const EXCEPTION_XML_NODE_MISMATCH = 0x1e2;
+
/**
* Parses the given XML content
*
* @return void
* @throws XmlParserException If an XML error was found
*/
- function parseXmlContent ($content);
+ function parseXmlContent (string $content);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $action The action or configuration entry plus prefix the user wants to perform
* @return $hasRequired Whether the user has the required points
*/
- function ifUserHasRequiredPoints ($action);
+ function ifUserHasRequiredPoints (string $action);
/**
* "Books" the given points amount on the current user's account
* @param $amount Amount of points we shall book
* @return void
*/
- function bookPointsDirectly ($amount);
+ function bookPointsDirectly (float $amount);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $requestKey Key in request class
* @return void
*/
- function encryptPassword ($requestKey);
+ function encryptPassword (string $requestKey);
/**
* Perform things like informing assigned affilates about new registration
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
interface Register extends FrameworkInterface {
- /**
- * Checks whether an instance key was found
- *
- * @param $instanceKey The key holding an instance in registry
- * @return $exists Whether the key exists in registry
- */
- function instanceExists ($instanceKey);
-
- /**
- * Adds/overwrites a new instance to the registry at the given key
- *
- * @param $instanceKey The key to identify the instance
- * @param $objectInstance An instance we shall store
- * @return void
- */
- function addInstance ($instanceKey, Registerable $objectInstance);
/**
* Getter for whole generic registry
*/
function getGenericRegistry ();
- /**
- * Getter for whole instance registry
- *
- * @return $instanceRegistry The whole instance registry array
- */
- function getInstanceRegistry ();
-
/**
* Adds a new entry to the given list name. If you want to add objects
* please use addInstance() and getInstance() instead.
* @param $value The value to be stored
* @return void
*/
- function addEntry ($key, $value);
+ function addEntry (string $key, $value);
/**
* Getter for entries or "sub entries"
*
* @return $entries An array with entries from this registry
*/
- function getEntries ($key = NULL);
+ function getEntries (string $key = NULL);
/**
* "Getter" for an array of all entries for given key
* @param $lookFor The key to look for
* @return $entry An array with all keys
*/
- function getArrayFromKey ($arrayKey, $lookFor);
-
- /**
- * Gets a registered instance or null if not found
- *
- * @param $instanceKey The key to identify the instance
- * @return $objectInstance An instance we shall store
- * @throws NullPointerException If the requested key is not found
- */
- function getInstance ($instanceKey);
+ function getArrayFromKey (string $arrayKey, string $lookFor);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
+ * @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
*
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Registry\Object;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Registry\Register;
+use Org\Mxchange\CoreFramework\Registry\Registerable;
+
+/**
+ * An interface for 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/>.
+ */
+interface ObjectRegister extends Register {
+ /**
+ * Checks whether an instance key was found
+ *
+ * @param $instanceKey The key holding an instance in registry
+ * @return $exists Whether the key exists in registry
+ */
+ function instanceExists (string $instanceKey);
+
+ /**
+ * Adds/overwrites a new instance to the registry at the given key
+ *
+ * @param $instanceKey The key to identify the instance
+ * @param $objectInstance An instance we shall store
+ * @return void
+ */
+ function addInstance (string $instanceKey, Registerable $objectInstance);
+
+ /**
+ * Getter for whole instance registry
+ *
+ * @return $instanceRegistry The whole instance registry array
+ */
+ function getInstanceRegistry ();
+
+ /**
+ * Gets a registered instance or null if not found
+ *
+ * @param $instanceKey The key to identify the instance
+ * @return $objectInstance An instance we shall store
+ * @throws NullPointerException If the requested key is not found
+ */
+ function getInstance (string $instanceKey);
+
+}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $element Name of the request element we want to check
* @return $isSet Whether the request element is set
*/
- function isRequestElementSet ($element);
+ function isRequestElementSet (string $element);
/**
* Getter for request element or 'null' if element was not found
* @return $value Value of the found request element or 'null' if the
* element was not found
*/
- function getRequestElement ($element);
+ function getRequestElement (string $element);
/**
* Setter for request elements
* @param $value Value to set
* @return void
*/
- function setRequestElement ($element, $value);
+ function setRequestElement (string $element, $value);
/**
* Setter for request data array
function getParameterNames ();
/**
- * Sets whether the request was valid (default: true)
+ * Sets whether the request was valid
*
* @param $isValid Whether the request is valid
* @return void
*/
- function requestIsValid ($isValid = true);
+ function setIsRequestValid (bool $isValid);
/**
* Returns whether this request is valid
*
- * @return $requestIsValid Whether this request is valid
+ * @return $isRequestValid Whether this request is valid
*/
function isRequestValid ();
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @return $isValid Whether the given action is valid
* @throws InvalidArgumentException Thrown if namespace or action is not set
*/
- function isActionValid ($namespace, $actionName);
+ function isActionValid (string $namespace, string $actionName);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*/
interface CommandResolver extends Resolver {
/**
- * Returns an command instance for a given request class
+ * Getter for command name
+ *
+ * @return $commandName Last validated command name
+ */
+ function getCommandName ();
+
+ /**
+ * Returns an command instance for a given request class or null if
+ * it was not found
*
* @param $requestInstance An instance of a Requestable class
* @return $commandInstance An instance of the resolved command
+ * @throws InvalidCommandException Thrown if $commandName is invalid
+ * @throws UnexpectedValueException Thrown if $commandInstance is an invalid instance
*/
function resolveCommandByRequest (Requestable $requestInstance);
+ /**
+ * Resolves the command by its direct name and returns an instance of its class
+ *
+ * @param $namespace Namespace to look in
+ * @param $commandName The direct command name we shall resolve
+ * @return $commandInstance An instance of the command class
+ * @throws InvalidCommandException Thrown if $commandName is invalid
+ */
+ function resolveCommand (string $namespace, string $commandName);
+
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $status New response status
* @return void
*/
- function setResponseStatus ($status);
+ function setResponseStatus (string $status);
/**
* Adds a header to the response. This method "wraps" the direct header()
* @param $value Value of header element
* @return void
*/
- function addHeader ($name, $value);
+ function addHeader (string $name, $value);
/**
* "Writes" data to the response body
* @param $output Output we shall sent in the HTTP response
* @return void
*/
- function writeToBody ($output);
+ function writeToBody (string $output);
/**
* Flushs the cached HTTP response to the outer world
* @throws ResponseHeadersAlreadySentException Thrown if headers are
* already sent
*/
- function flushBuffer ($force = false);
+ function flushBuffer (bool $force = false);
/**
* Adds a fatal message id to the response. The added messages can then be
* @param $messageId The message id we shall add
* @return void
*/
- function addFatalMessage ($messageId);
+ function addFatalMessage (string $messageId);
/**
* Adds a cookie to the response
* @param $cookieName Cookie's name
* @param $cookieValue Value to store in the cookie
* @param $encrypted Do some extra encryption on the value
+ * @param $expires Timestamp of expiration (default: configured)
* @return void
* @throws ResponseHeadersAlreadySentException If headers are already sent
*/
- function addCookie ($cookieName, $cookieValue, $encrypted = false);
+ function addCookie (string $cookieName, $cookieValue, bool $encrypted = FALSE, int $expires = NULL);
/**
* Redirect to a configured URL. The URL can be absolute or relative. In
* @return void
* @throws ResponseHeadersAlreadySentException If headers are already sent
*/
- function redirectToConfiguredUrl ($configEntry);
+ function redirectToConfiguredUrl (string $configEntry);
/**
* Expires the given cookie if it is set
* @param $cookieName Cookie to expire
* @return void
*/
- function expireCookie ($cookieName);
+ function expireCookie (string $cookieName);
/**
* Refreshs a given cookie. This will make the cookie live longer
* @param $cookieName Cookie to refresh
* @return void
*/
- function refreshCookie ($cookieName);
+ function refreshCookie (string $cookieName);
}
// Import framework stuff
use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
-use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseWrapper;
+use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseFrontend;
use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @para $callBack Call-back object for setting the index
* @return void
*/
- function solveResultIndex ($databaseColumn, DatabaseWrapper $wrapperInstance, array $callBack);
+ function solveResultIndex (string $databaseColumn, DatabaseFrontend $frontendInstance, array $callBack);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
<?php
// Own namespace
-namespace Org\Mxchange\CoreFramework\Stacker;
+namespace Org\Mxchange\CoreFramework\Stack;
// Import framework stuff
use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $stackerName Name of the stacker
* @param $value Value to push on it
* @return void
- * @throws StackerFullException If the stacker is full
+ * @throws BadMethodCallException If the stacker is full
*/
- function pushNamed ($stackerName, $value);
+ function pushNamed (string $stackerName, $value);
/**
* 'Pops' a value from a named stacker and returns it's value
*
* @param $stackerName Name of the stacker
* @return $value Value of the current stack entry
- * @throws NoStackerException If the named stacker was not found
- * @throws EmptyStackerException If the named stacker is empty
+ * @throws BadMethodCallException If the named stacker was not found
+ * @throws BadMethodCallException If the named stacker is empty
*/
- function popNamed ($stackerName);
+ function popNamed (string $stackerName);
/**
* Get value from named stacker but don't "pop" it
*
* @param $stackerName Name of the stacker
* @return $value Value of last added value
- * @throws NoStackerException If the named stacker was not found
- * @throws EmptyStackerException If the named stacker is empty
+ * @throws BadMethodCallException If the named stacker was not found
+ * @throws BadMethodCallException If the named stacker is empty
*/
- function getNamed ($stackerName);
+ function getNamed (string $stackerName);
/**
* Checks whether the given stack is initialized (set in array $stackers)
* @param $stackerName Name of the stack
* @return $isInitialized Whether the stack is initialized
*/
- function isStackInitialized ($stackerName);
+ function isStackInitialized (string $stackerName);
/**
* Checks whether the given stack is empty
*
* @param $stackerName Name of the stack
* @return $isEmpty Whether the stack is empty
- * @throws NoStackerException If given stack is missing
+ * @throws BadMethodCallException If given stack is missing
*/
- function isStackEmpty ($stackerName);
+ function isStackEmpty (string $stackerName);
+
+ /**
+ * Initializes given stacker
+ *
+ * @param $stackerName Name of the stack
+ * @param $forceReInit Force re-initialization
+ * @return void
+ * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
+ */
+ function initStack (string $stackerName, bool $forceReInit = false);
+
+ /**
+ * Initializes all stacks
+ *
+ * @return void
+ * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
+ */
+ function initStacks (array $stacks, bool $forceReInit = false);
+
+ /**
+ * Getter for size of given stack (array count)
+ *
+ * @param $stackerName Name of the stack
+ * @return $count Size of stack (array count)
+ */
+ function getStackCount (string $stackerName);
}
<?php
// Own namespace
-namespace Org\Mxchange\CoreFramework\Filesystem\Stack;
+namespace Org\Mxchange\CoreFramework\Stack\File;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Stacker\Stackable;
+use Org\Mxchange\CoreFramework\Stack\Stackable;
/**
* A Stackable file interface
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
interface StackableFile extends Stackable {
+ /**
+ * Magic for this stack
+ */
+ const STACK_MAGIC = 'STACKv0.1';
+
+ /**
+ * Name of array index for gap position
+ */
+ const ARRAY_NAME_GAP_POSITION = 'gap';
+
+ /**
+ * Name of array index for hash
+ */
+ const ARRAY_NAME_HASH = 'hash';
+
+ /**
+ * Name of array index for length of raw data
+ */
+ const ARRAY_NAME_DATA_LENGTH = 'length';
+
/**
* Seeks to given position
*
* @param $seekPosition Seek position in file
* @return $status Status of this operation
*/
- function seek ($seekPosition);
+ function seek (int $seekPosition);
/**
* Size of file stack
*/
function size ();
+ /**
+ * Reads the stack's file header
+ *
+ * @return void
+ * @todo To hard assertions here, better rewrite them to exceptions
+ * @throws UnexpectedValueException If header is not proper length
+ * @throws InvalidMagicException If a bad magic was found
+ */
+ function readStackHeader ();
+
+ /**
+ * Flushes the file header
+ *
+ * @return void
+ */
+ function flushFileHeader ();
+
+ /**
+ * Determines whether the EOF has been reached
+ *
+ * @return $isEndOfFileReached Whether the EOF has been reached
+ * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
+ */
+ function isEndOfFileReached ();
+
+ /**
+ * Calculates minimum length for one entry/block
+ *
+ * @return $length Minimum length for one entry/block
+ */
+ function calculateMinimumBlockLength ();
+
+ /**
+ * Initializes counter for valid entries, arrays for damaged entries and
+ * an array for gap seek positions. If you call this method on your own,
+ * please re-analyze the file structure. So you are better to call
+ * analyzeFileStructure() instead of this method.
+ *
+ * @return void
+ * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
+ */
+ function initCountersGapsArray ();
+
+ /**
+ * Getter for header size
+ *
+ * @return $totalEntries Size of file header
+ * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
+ */
+ function getHeaderSize ();
+
+ /**
+ * Setter for header size
+ *
+ * @param $headerSize Size of file header
+ * @return void
+ * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
+ */
+ function setHeaderSize (int $headerSize);
+
+ /**
+ * Getter for header array
+ *
+ * @return $totalEntries Size of file header
+ * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
+ */
+ function getHeader ();
+
+ /**
+ * Setter for header
+ *
+ * @param $header Array for a file header
+ * @return void
+ * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
+ */
+ function setHeader (array $header);
+
+ /**
+ * Updates seekPosition attribute from file to avoid to much access on file.
+ *
+ * @return void
+ * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
+ */
+ function updateSeekPosition ();
+
+ /**
+ * Getter for total entries
+ *
+ * @return $totalEntries Total entries in this file
+ * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
+ */
+ function getCounter ();
+
+ /**
+ * Writes data at given position
+ *
+ * @param $seekPosition Seek position
+ * @param $data Data to be written
+ * @param $flushHeader Whether to flush the header (default: flush)
+ * @return void
+ * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
+ */
+ function writeData (int $seekPosition, string $data, bool $flushHeader = true);
+
+ /**
+ * Writes at given position by seeking to it.
+ *
+ * @param $seekPosition Seek position in file
+ * @param $dataStream Data to be written
+ * @return mixed Number of writes bytes or false on error
+ * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
+ */
+ function writeAtPosition (int $seekPosition, string $dataStream);
+
+ /**
+ * Writes given value to the file and returns a hash and gap position for it
+ *
+ * @param $groupId Group identifier
+ * @param $value Value to be added to the stack
+ * @return $data Hash and gap position
+ * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
+ */
+ function writeValueToFile (string $groupId, $value);
+
+ /**
+ * Searches for next suitable gap the given length of data can fit in
+ * including padding bytes.
+ *
+ * @param $length Length of raw data
+ * @return $seekPosition Found next gap's seek position
+ * @throws UnsupportedOperationException This method is not (and maybe never will be) supported
+ */
+ function searchNextGap (int $length);
+
+ /**
+ * "Getter" for file size
+ *
+ * @return $fileSize Size of currently loaded file
+ */
+ function getFileSize ();
+
+ /**
+ * Writes given raw data to the file and returns a gap position and length
+ *
+ * @param $groupId Group identifier
+ * @param $hash Hash from encoded value
+ * @param $encoded Encoded value to be written to the file
+ * @return $data Gap position and length of the raw data
+ */
+ function writeDataToFreeGap (string $groupId, string $hash, string $encoded);
+
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $data The data (string mostly) to "stream"
* @return $data The data (string mostly) to "stream"
*/
- function streamData ($data);
+ function streamData (string $data);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $key Optional key, if none provided, a random key will be generated
* @return $encrypted Encrypted string
*/
- function encryptStream ($str, $key = NULL);
+ function encryptStream (string $str, string $key = NULL);
/**
* Decrypt the string with fixed salt
*
* @param $encrypted Encrypted string
+ * @param $key Optional key, if none provided, a random key will be generated
* @return $str The unencrypted string
*/
- function decryptStream ($encrypted);
+ function decryptStream (string $encrypted, string $key = NULL);
}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* @param $value The value we want to store in the variable
* @return void
*/
- function assignVariable ($variableName, $value);
+ function assignVariable (string $variableName, $value);
/**
* Load a specified HTML template into the engine
* "html" by default
* @return void
*/
- function loadHtmlTemplate ($template);
+ function loadHtmlTemplate (string $template);
/**
* Load a specified code template into the engine for later compilation
* located in "html" by default
* @return void
*/
- function loadCodeTemplate ($template);
+ function loadCodeTemplate (string $template);
/**
* Load a specified email template into the engine for later compilation
* located in "html" by default
* @return void
*/
- function loadEmailTemplate ($template);
+ function loadEmailTemplate (string $template);
/**
* Compile all variables by inserting their respective values
* @param $value Value to store in variable
* @return void
*/
- function addGroupVariable ($variableName, $value);
+ function addGroupVariable (string $variableName, $value);
/**
* Removes a given variable
* @param $variableGroup Name of variable group (default: 'general')
* @return void
*/
- function removeVariable ($variableName, $variableGroup = 'general');
+ function removeVariable (string $variableName, string $variableGroup = 'general');
/**
* Assign a given congfiguration variable with a value
* @param $variableName The configuration variable we want to assign
* @return void
*/
- function assignConfigVariable ($variableName);
+ function assignConfigVariable (string $variableName);
/**
* Compiles configuration place-holders in all variables. This 'walks'
* @param $variableName Name of the variable we want to assign
* @return void
*/
- function assignTemplateWithVariable ($templateName, $variableName);
+ function assignTemplateWithVariable (string $templateName, string $variableName);
/**
* Transfers the content of this template engine to a given response instance
* @param $setMatchAsCode Sets $match if readVariable() returns empty result (default: false)
* @return $rawCode Compile code with inserted variable value
*/
- function compileRawCode ($rawCode, $setMatchAsCode = false);
+ function compileRawCode (string $rawCode, bool $setMatchAsCode = false);
/**
* Renames a variable in code and in stack
* @param $newName New name of variable
* @return void
*/
- function renameVariable ($oldName, $newName);
-
- /**
- * Renders the given XML content
- *
- * @param $content Valid XML content or if not set the current loaded raw content
- * @return void
- * @throws XmlParserException If an XML error was found
- */
- function renderXmlContent ($content = NULL);
+ function renameVariable (string $oldName, string $newName);
/**
* Enables or disables language support
* @param $languageSupport New language support setting
* @return void
*/
- function enableLanguageSupport ($languageSupport = true);
+ function enableLanguageSupport (bool $languageSupport = true);
/**
* Checks whether language support is enabled
*/
function isLanguageSupportEnabled ();
- /**
- * Enables or disables XML compacting
- *
- * @param $xmlCompacting New XML compacting setting
- * @return void
- */
- function enableXmlCompacting ($xmlCompacting = true);
-
- /**
- * Checks whether XML compacting is enabled
- *
- * @return $xmlCompacting Whether XML compacting is enabled or disabled
- */
- function isXmlCompactingEnabled ();
-
- /**
- * Removes all comments, tabs and new-line charcters to compact the content
- *
- * @param $uncompactedContent The uncompacted content
- * @return $compactedContent The compacted content
- */
- function compactContent ($uncompactedContent);
-
/**
* Getter for given variable group
*
* @param $variableGroup Variable group to check
* @return $varStack Found variable group
*/
- function getVarStack ($variableGroup);
+ function getVarStack (string $variableGroup);
/**
* Settter for variable group
* @param $add Whether add this group
* @return void
*/
- function setVariableGroup ($groupName, $add = true);
+ function setVariableGroup (string $groupName, bool $add = true);
/**
* Getter for template type
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Template\Xml;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
+
+/**
+ * An interface for template engines
+ *
+ * @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/>.
+ */
+interface CompileableXmlTemplate extends CompileableTemplate {
+
+ /**
+ * Renders the given XML content
+ *
+ * @param $content Valid XML content or if not set the current loaded raw content
+ * @return void
+ * @throws XmlParserException If an XML error was found
+ */
+ function renderXmlContent (string $content = NULL);
+
+ /**
+ * Enables or disables XML compacting
+ *
+ * @param $xmlCompacting New XML compacting setting
+ * @return void
+ */
+ function enableXmlCompacting (bool $xmlCompacting = true);
+
+ /**
+ * Checks whether XML compacting is enabled
+ *
+ * @return $xmlCompacting Whether XML compacting is enabled or disabled
+ */
+ function isXmlCompactingEnabled ();
+
+ /**
+ * Removes all comments, tabs and new-line charcters to compact the content
+ *
+ * @param $uncompactedContent The uncompacted content
+ * @return $compactedContent The compacted content
+ */
+ function compactContent (string $uncompactedContent);
+
+}
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
// Import framework stuff
use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+use Org\Mxchange\CoreFramework\Traits\Streamer\Output\OutputStreamerTrait;
/**
* An abstract middleware class for all other middlware classes
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseMiddleware extends BaseFrameworkSystem {
+ // Load traits
+ use OutputStreamerTrait;
+
/**
* Protected constructor
*
* @param $className Name of the class
* @return void
*/
- protected function __construct ($className) {
+ protected function __construct (string $className) {
// Call parent constructor
parent::__construct($className);
}
namespace Org\Mxchange\CoreFramework\Middleware\Compressor;
// Import framework stuff
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Compressor\Compressor;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Middleware\BaseMiddleware;
use Org\Mxchange\CoreFramework\Registry\Registerable;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor!
parent::__construct(__CLASS__);
}
) {
// Init base directory
$baseDir =
- $compressorInstance->getConfigInstance()->getConfigEntry('framework_base_path') .
- $compressorInstance->getConfigInstance()->getConfigEntry('compressor_base_path');
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('framework_base_path') .
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('compressor_base_path');
// Get a directory pointer
$directoryInstance = ObjectFactory::createObjectByConfiguredName('directory_class', array($baseDir));
// Read all directories but no sub directories, .htaccess files and NullCompressor class
- while ($directoryEntry = $directoryInstance->readDirectoryExcept(array('.htaccess', 'class_NullCompressor.php'))) {
- // Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('COMPRESSOR[' . __METHOD__ . ':' . __LINE__ . ']: directoryEntry=' . $directoryEntry);
-
+ while ($directoryEntry = $directoryInstance->readDirectoryExcept(array('class_NullCompressor.php'))) {
// Is this a class file?
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('COMPRESSOR: directoryEntry=' . $directoryEntry);
if ((substr($directoryEntry, 0, 6) == 'class_') && (substr($directoryEntry, -4, 4) == '.php')) {
/* Get the compressor's name. That's why you must name
* your files like your classes and also that's why you
if (is_null($tempInstance)) {
// Then skip to the next one
continue;
- } // END - if
+ }
// Set the compressor
$compressorInstance->setCompressor($tempInstance);
// No more searches required because we have found a valid compressor stream
break;
- } // END - if
- } // END - while
+ }
+ }
// Close the directory
$directoryInstance->closeDirectory();
- } // END - if
+ }
// Check again if there is a compressor
if (
// Set the null compressor handler. This should not be configureable!
// @TODO Is there a configurable fall-back compressor needed, or is NullCompressor okay?
$compressorInstance->setCompressor(ObjectFactory::createObjectByName('Org\Mxchange\CoreFramework\Compressor\Null\NullCompressor'));
- } // END - if
+ }
// Return the compressor instance
return $compressorInstance;
use Org\Mxchange\CoreFramework\Criteria\Criteria;
use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
use Org\Mxchange\CoreFramework\Database\Backend\DatabaseBackend;
-use Org\Mxchange\CoreFramework\Registry\Registerable;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Middleware\BaseMiddleware;
-use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+use Org\Mxchange\CoreFramework\Registry\Registerable;
+use Org\Mxchange\CoreFramework\Result\Database\BaseDatabaseResult;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+use \OutOfBoundsException;
+use \UnexpectedValueException;
/**
- * Database selector class
+ * Database connectivity class
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
/**
* Array for connection data
*/
- private $connectData = array(
+ private $connectData = [
'login' => '',
'pass' => '',
'dbase' => '',
- 'host' => ''
- );
+ 'host' => '',
+ ];
/**
* The real database layer
*/
- private $dbLayer = NULL;
+ private $backendInstance = NULL;
/**
* An instance of this class
/**
* Protected constructor
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
}
/**
* Creates a new database connection layer
*
- * @param $debugInstance An instance of a DebugMiddleware class
- * @param $dbLayer An instance of a DatabaseBackend class
+ * @param $backendInstance An instance of a DatabaseBackend class
* @todo $debugInstance is currently not used
*/
- public static final function createDatabaseConnection (DebugMiddleware $debugInstance, DatabaseBackend $dbLayer) {
+ public static final function createDatabaseConnection (DatabaseBackend $backendInstance) {
// Get instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: backendInstance=%s - CALLED!', $backendInstance->__toString()));
$databaseInstance = new DatabaseConnection();
// Set database layer
- $databaseInstance->setDatabaseLayer($dbLayer);
+ $databaseInstance->setBackendInstance($backendInstance);
// Set db instance
self::$selfInstance = $databaseInstance;
// Return instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: databaseInstance=%s - EXIT!', $databaseInstance->__toString()));
return $databaseInstance;
}
return self::$selfInstance;
}
+ /**
+ * Setter for the real database layer
+ * @param $backendInstance An instance of a DatabaseBackend class
+ * @return void
+ */
+ private final function setBackendInstance (DatabaseBackend $backendInstance) {
+ $this->backendInstance = $backendInstance;
+ }
+
/**
* Setter for all database connection data. All these parameters may be
* supported by the underlaying backend.
* @param $dbase Name of used database
* @param $host Host to connect to (default: 127.0.0.1)
* @return void
+ * @throws InvalidArgumentException If a parameter is empty
*/
- public final function setConnectionData ($login, $pass, $dbase, $host = '127.0.0.1') {
+ public final function setConnectionData (string $login, string $pass, string $dbase, string $host = 'localhost') {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: login=%s,pass=%s,dbase=%s,host=%s CALLED!', $login, $pass, $dbase, $host));
+ if (empty($login)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "login" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($dbase)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "dbase" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($host)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "host" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Transfer connection data
- $this->connectData['login'] = (string) $login;
- $this->connectData['pass'] = (string) $pass;
- $this->connectData['dbase'] = (string) $dbase;
- $this->connectData['host'] = (string) $host;
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('DATABASE-CONNECTION: Setting data ...');
+ $this->connectData['login'] = $login;
+ $this->connectData['pass'] = $pass;
+ $this->connectData['dbase'] = $dbase;
+ $this->connectData['host'] = $host;
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('DATABASE-CONNECTION: EXIT!');
}
/**
return $this->connectData;
}
- /**
- * Setter for the real database layer
- * @param $dbLayer An instance of the real database layer
- * @return void
- */
- public final function setDatabaseLayer (DatabaseBackend $dbLayer) {
- $this->dbLayer = $dbLayer;
- }
-
/**
* Getter for index key
*
* @return $indexKey Index key
*/
public final function getIndexKey () {
- return $this->dbLayer->getIndexKey();
+ return $this->backendInstance->getIndexKey();
}
/**
* @param $tableName Name of the 'table' we shall query
* @param $criteriaInstance An instance of a Criteria class
* @return $result The result as an array
+ * @throws InvalidArgumentException If a parameter is empty
+ * @throws OutOfBoundsException If important array elements are not present
+ * @throws UnexpectedValueException If $result['status'] is not 'ok'
*/
- public function doSelectByTableCriteria ($tableName, Criteria $criteriaInstance) {
+ public function doSelectByTableCriteria (string $tableName, Criteria $criteriaInstance) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: tableName=%s,criteriaInstance=%s - CALLED!', $tableName, $criteriaInstance->__toString()));
+ if (empty($tableName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "tableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Connect to the database
- $this->dbLayer->connectToDatabase();
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('DATABASE-CONNECTION: Invoking this->backendInstance->connectToDatabase() ...');
+ $this->backendInstance->connectToDatabase();
// Get result from query
- $result = $this->dbLayer->querySelect($tableName, $criteriaInstance);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: Invoking this->backendInstance->querySelect(%s,%s) ...', $tableName, $criteriaInstance->__toString()));
+ $result = $this->backendInstance->querySelect($tableName, $criteriaInstance);
+
+ // Is a valid array returned?
+ if (!isset($result[BaseDatabaseResult::RESULT_NAME_STATUS])) {
+ // Missing element
+ throw new OutOfBoundsException(sprintf('result()=%d does not have element "%s"', count($result), BaseDatabaseResult::RESULT_NAME_STATUS), FrameworkInterface::EXCEPTION_OUT_OF_BOUNDS);
+ } elseif ($result[BaseDatabaseResult::RESULT_NAME_STATUS] != 'ok') {
+ // Is exception given?
+ if (isset($result[BaseDatabaseResult::RESULT_NAME_EXCEPTION])) {
+ // Attach it
+ throw new UnexpectedValueException(sprintf('result[%s]=%s is not "ok" with cause', BaseDatabaseResult::RESULT_NAME_STATUS), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT, BaseDatabaseResult::RESULT_NAME_EXCEPTION);
+ } else {
+ // No exception attached
+ throw new UnexpectedValueException(sprintf('result[%s]=%s is not "ok"', BaseDatabaseResult::RESULT_NAME_STATUS, $result[BaseDatabaseResult::RESULT_NAME_STATUS]), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+ }
// Return the result
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: result[]=%s - EXIT!', gettype($result)));
return $result;
}
* @return $exceptionInstance Last thrown exception
*/
public final function getLastException () {
- $exceptionInstance = $this->dbLayer->getLastException();
+ // Get instance
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('DATABASE-CONNECTION: CALLED!');
+ $exceptionInstance = $this->backendInstance->getLastException();
+
+ // Return it
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: exceptionInstance=%s - EXIT!', $exceptionInstance->__toString()));
return $exceptionInstance;
}
*/
public function queryInsertDataSet (StoreableCriteria $dataSetInstance) {
// Connect to the database
- $this->dbLayer->connectToDatabase();
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
+ $this->backendInstance->connectToDatabase();
// Ask the database layer
- $this->dbLayer->queryInsertDataSet($dataSetInstance);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: Invoking this->backendInstance->queryInsertDataSet(%s) ...', $dataSetInstance->__toString()));
+ $this->backendInstance->queryInsertDataSet($dataSetInstance);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('DATABASE-CONNECTION: EXIT!');
}
/**
*/
public function queryUpdateDataSet (StoreableCriteria $dataSetInstance) {
// Connect to the database
- $this->dbLayer->connectToDatabase();
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: dataSetInstance=%s - CALLED!', $dataSetInstance->__toString()));
+ $this->backendInstance->connectToDatabase();
// Ask the database layer
- $this->dbLayer->queryUpdateDataSet($dataSetInstance);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: Invoking this->backendInstance->queryUpdateDataSet(%s) ...', $dataSetInstance->__toString()));
+ $this->backendInstance->queryUpdateDataSet($dataSetInstance);
+
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('DATABASE-CONNECTION: EXIT!');
}
/**
*
* @param $tableName Name of table we need the primary key column from
* @return $primaryKey Primary key column of requested table
+ * @throws InvalidArgumentException If a parameter is empty
*/
- public function getPrimaryKeyOfTable ($tableName) {
+ public function getPrimaryKeyOfTable (string $tableName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: tableName=%s - CALLED!', $tableName));
+ if (empty($tableName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "tableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Connect to the database
- $this->dbLayer->connectToDatabase();
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('DATABASE-CONNECTION: Invoking this->backendInstance->connectToDatabase() ...');
+ $this->backendInstance->connectToDatabase();
// Ask the database layer
- $primaryKey = $this->dbLayer->getPrimaryKeyOfTable($tableName);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: Invoking this->backendInstance->getPrimaryKeyOfTable(%s) ...', $tableName));
+ $primaryKey = $this->backendInstance->getPrimaryKeyOfTable($tableName);
// Return the value
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: primaryKey=%s - CALLED!', $primaryKey));
return $primaryKey;
}
*
* @param $data An array with possible non-public data that needs to be removed.
* @return $data A cleaned up array with only public data.
+ * @throws InvalidArgumentException If a parameter has an invalid value
*/
public function removeNonPublicDataFromArray (array $data) {
+ // Check parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: data()=%d - CALLED!', count($data)));
+ if (count($data) == 0) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "data" is an empty array', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Connect to the database
- $this->dbLayer->connectToDatabase();
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('DATABASE-CONNECTION: Invoking this->backendInstance->connectToDatabase() ...');
+ $this->backendInstance->connectToDatabase();
// Call database backend
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DB-CONNECTION[' . $this->__toString() . ']: Calling this->dbLayer->removeNonPublicDataFromArray(data) ...');
- $data = $this->dbLayer->removeNonPublicDataFromArray($data);
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: Invoking this->backendInstance->removeNonPublicDataFromArray(data()=%d) ...', count($data)));
+ $data = $this->backendInstance->removeNonPublicDataFromArray($data);
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('DB-CONNECTION[' . $this->__toString() . ']: data[]=' . gettype($data));
+ // Trace message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: data()=%d - EXIT!', count($data)));
return $data;
}
*
* @param $tableName Table name
* @return $count Total row count
+ * @throws InvalidArgumentException If a parameter is empty
*/
- public function countTotalRows ($tableName) {
+ public function countTotalRows (string $tableName) {
+ // Validate parameter
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: tableName=%s - CALLED!', $tableName));
+ if (empty($tableName)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "tableName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Connect to the database
- $this->dbLayer->connectToDatabase();
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('DATABASE-CONNECTION: Invoking this->backendInstance->connectToDatabase() ...');
+ $this->backendInstance->connectToDatabase();
// Ask the database layer
- $count = $this->dbLayer->countTotalRows($tableName);
+ $count = $this->backendInstance->countTotalRows($tableName);
// Return the value
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('DATABASE-CONNECTION: count=%d - CALLED!', $count));
return $count;
}
namespace Org\Mxchange\CoreFramework\Middleware\Debug;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
+use Org\Mxchange\CoreFramework\Logging\Logger;
use Org\Mxchange\CoreFramework\Middleware\BaseMiddleware;
use Org\Mxchange\CoreFramework\Registry\Registerable;
use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
+// Import SPL stuff
+use \InvalidArgumentException;
+
/**
* The middlware debug output system. A *real* or concrete output class shall
* become registered with this middleware because the back-fall class will
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
* @deprecated See LoggerFactory for a more flexible approach
* 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 DebugMiddleware extends BaseMiddleware implements Registerable {
+class DebugMiddleware extends BaseMiddleware implements Registerable, Logger {
/**
* An instance of this class
*/
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CONSTRUCTED!' . PHP_EOL, __METHOD__, __LINE__);
parent::__construct(__CLASS__);
- // Set own instance
- self::$selfInstance = $this;
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
/**
* @param $className Class where a output should be created and
* configured for
* @return $debugInstance An instance of this middleware class
+ * @throws InvalidArgumentException If a parameter has an invalid value
*/
- public static final function createDebugMiddleware ($outputClass, $className) {
- //* DEBUG-DIE: */ die(__METHOD__.': outputClass=' . $outputClass . ',className=' . $className);
-
- // Create an instance if this middleware
- $debugInstance = new DebugMiddleware();
+ public static final function createDebugMiddleware (string $outputClass, string $className) {
+ // Check parameter
+ //* NOISY-DEBUG: */ printf('[%s:%d]: outputClass=%s,className=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $outputClass, $className);
+ if (empty($outputClass)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "outputClass" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (empty($className)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "className" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
- // Default is that $outputClass may be invalid
- $isInitialized = false;
+ // Is a static instance there?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::selfInstance[]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype(self::$selfInstance));
+ if (is_null(self::$selfInstance)) {
+ // Create an instance if this middleware
+ self::$selfInstance = new DebugMiddleware();
+ }
// Is there a valid output instance provided?
- if ((!is_null($outputClass)) && (is_object($outputClass)) && ($outputClass instanceof OutputStreamer)) {
- // Use the given output instance
- $debugInstance->setOutputInstance($outputClass);
-
- // All fine
- $isInitialized = true;
- } elseif ((!is_null($outputClass)) && (is_string($outputClass)) && (class_exists($outputClass))) {
+ //* NOISY-DEBUG: */ printf('[%s:%d]: outputClass=%s' . PHP_EOL, __METHOD__, __LINE__, $outputClass);
+ if (class_exists($outputClass) && is_null(self::$selfInstance->getOutputInstance())) {
// A name for a debug output class has been provided so we try to get it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Initializing outputClass=%s ...' . PHP_EOL, __METHOD__, __LINE__, $outputClass);
$outputInstance = ObjectFactory::createObjectByName($outputClass);
// Set this as output class
- $debugInstance->setOutputInstance($outputInstance);
-
- // All fine
- $isInitialized = true;
+ //* NOISY-DEBUG: */ printf('[%s:%d]: outputInstance=%s' . PHP_EOL, __METHOD__, __LINE__, $outputInstance->__toString());
+ self::$selfInstance->setOutputInstance($outputInstance);
}
- // Is the output class initialized?
- if ($isInitialized === true) {
+ // Is the output class loadable and an output instance is set?
+ if (class_exists($outputClass) && !is_null(self::$selfInstance->getOutputInstance())) {
// Then set class name
- $debugInstance->getOutputInstance()->setLoggerClassName($className);
- } // END - if
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Setting className=%s as logger class ...' . PHP_EOL, __METHOD__, __LINE__, $className);
+ self::$selfInstance->getOutputInstance()->setLoggerClassName($className);
+ }
// Return instance
- return $debugInstance;
+ //* NOISY-DEBUG: */ printf('[%s:%d]: debugInstance=%s - EXIT!' . PHP_EOL, __METHOD__, __LINE__, self::$selfInstance->__toString());
+ return self::$selfInstance;
+ }
+
+ /**
+ * This method shall send debug output which can be HTML code for the
+ * browser or debug lines for a log file, etc. to the registered debug
+ * output instance.
+ *
+ * @param $message Data we shall 'stream' out to the world
+ * @param $stripTags Whether HTML tags shall be stripped out
+ * @return void
+ * @throws NullPointerException If this->outputInstance is NULL
+ */
+ private function outputMessage (string $logLevel, string $message, bool $stripTags = false) {
+ // Get backtrace
+ //* NOISY-DEBUG: */ printf('[%s:%d]: logLevel=%s,message=%s,stripTags=%d - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $logLevel, $message, intval($stripTags));
+ $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
+
+ // Is the deprecated debugOutput() or partialStub() invoked before?
+ if (isset($backtrace[4]) && $backtrace[3]['function'] == 'partialStub') {
+ // Prepend class::function:line from 2nd element
+ //* NOISY-DEBUG: */ printf('[%s:%d]: partialStub() was invoked ...' . PHP_EOL, __METHOD__, __LINE__);
+ $message = sprintf('[%s] [%s::%s:%d]: %s',
+ $logLevel,
+ $backtrace[4]['class'],
+ $backtrace[4]['function'],
+ (isset($backtrace[4]['line']) ? $backtrace[4]['line'] : '0'),
+ $message
+ );
+ } elseif (isset($backtrace[3]) && $backtrace[2]['function'] == 'debugOutput') {
+ // Prepend class::function:line from 2nd element
+ //* NOISY-DEBUG: */ printf('[%s:%d]: debugOutput() was invoked ...' . PHP_EOL, __METHOD__, __LINE__);
+ $message = sprintf('[%s] [%s::%s:%d]: %s',
+ $logLevel,
+ $backtrace[3]['class'],
+ $backtrace[3]['function'],
+ (isset($backtrace[3]['line']) ? $backtrace[3]['line'] : '0'),
+ $message
+ );
+ } else {
+ // Prepend class::function:line from 2nd element
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Ordinary invocation ...' . PHP_EOL, __METHOD__, __LINE__);
+ $message = sprintf('[%s] [%s::%s:%d]: %s',
+ $logLevel,
+ $backtrace[2]['class'],
+ $backtrace[2]['function'],
+ (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
+ $message
+ );
+ }
+
+ // Use the output instance
+ $this->getOutputInstance()->outputStream($message, $stripTags);
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
/**
}
/**
- * This method shall send debug output which can be HTML code for the
- * browser or debug lines for a log file, etc. to the registered debug
- * output instance.
+ * Outputs a trace message whether to debug instance (should be set!) or
+ * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
+ * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
*
- * @param $outStream Data we shall 'stream' out to the world
- * @param $stripTags Whether HTML tags shall be stripped out
+ * @param $message Message we shall send out...
+ * @param $doPrint Whether print or die here (default: print)
+ * @paran $stripTags Whether to strip tags (default: false)
* @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ * @throws NullPointerException If this->outputInstance is NULL
+ * @todo Remove $doPrint parameter
*/
- public final function output ($outStream, $stripTags = false) {
- // Is the output stream set
- if (empty($outStream)) {
- // @TODO Initialization phase
- return;
+ public function traceMessage (string $message, bool $doPrint = true, bool $stripTags = false) {
+ // Check parameter
+ //* NOISY-DEBUG: */ printf('[%s:%d]: message=%s,doPrint=%d,stripTags=%d - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $message, intval($doPrint), intval($stripTags));
+ if (empty($message)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "message" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
} elseif (is_null($this->getOutputInstance())) {
// Should not be NULL
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
}
- // Use the output instance
- $this->getOutputInstance()->outputStream($outStream, $stripTags);
+ // Use debug output handler
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Invoking this->outputMessage(%s,%s,%d) ...' . PHP_EOL, __METHOD__, __LINE__, Logger::LOGGER_LEVEL_TRACE, $message, intval($stripTags));
+ $this->outputMessage(Logger::LOGGER_LEVEL_TRACE, $message, $stripTags);
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
+ }
+
+ /**
+ * Outputs a debug message whether to debug instance (should be set!) or
+ * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
+ * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
+ *
+ * @param $message Message we shall send out...
+ * @param $doPrint Whether print or die here (default: print)
+ * @paran $stripTags Whether to strip tags (default: false)
+ * @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ * @throws NullPointerException If this->outputInstance is NULL
+ * @todo Remove $doPrint parameter
+ */
+ public function debugMessage (string $message, bool $doPrint = true, bool $stripTags = false) {
+ // Check parameter
+ //* NOISY-DEBUG: */ printf('[%s:%d]: message=%s,doPrint=%d,stripTags=%d - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $message, intval($doPrint), intval($stripTags));
+ if (empty($message)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "message" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (is_null($this->getOutputInstance())) {
+ // Should not be NULL
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
+ }
+
+ // Use debug output handler
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Invoking this->outputMessage(%s,%s,%d) ...' . PHP_EOL, __METHOD__, __LINE__, $message, intval($stripTags));
+ $this->outputMessage(Logger::LOGGER_LEVEL_DEBUG, $message, $stripTags);
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
+ }
+
+ /**
+ * Outputs an informational message whether to debug instance (should be set!) or
+ * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
+ * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
+ *
+ * @param $message Message we shall send out...
+ * @param $doPrint Whether print or die here (default: print)
+ * @paran $stripTags Whether to strip tags (default: false)
+ * @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ * @throws NullPointerException If this->outputInstance is NULL
+ * @todo Remove $doPrint parameter
+ */
+ public function infoMessage (string $message, bool $doPrint = true, bool $stripTags = false) {
+ // Check parameter
+ //* NOISY-DEBUG: */ printf('[%s:%d]: message=%s,doPrint=%d,stripTags=%d - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $message, intval($doPrint), intval($stripTags));
+ if (empty($message)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "message" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (is_null($this->getOutputInstance())) {
+ // Should not be NULL
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
+ }
+
+ // Use debug output handler
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Invoking this->outputMessage(%s,%s,%d) ...' . PHP_EOL, __METHOD__, __LINE__, Logger::LOGGER_LEVEL_INFO, $message, intval($stripTags));
+ $this->outputMessage(Logger::LOGGER_LEVEL_INFO, $message, $stripTags);
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
+ }
+
+ /**
+ * Outputs a warning message whether to debug instance (should be set!) or
+ * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
+ * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
+ *
+ * @param $message Message we shall send out...
+ * @param $doPrint Whether print or die here (default: print)
+ * @paran $stripTags Whether to strip tags (default: false)
+ * @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ * @throws NullPointerException If this->outputInstance is NULL
+ * @todo Remove $doPrint parameter
+ */
+ public function warningMessage (string $message, bool $doPrint = true, bool $stripTags = false) {
+ // Check parameter
+ //* NOISY-DEBUG: */ printf('[%s:%d]: message=%s,doPrint=%d,stripTags=%d - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $message, intval($doPrint), intval($stripTags));
+ if (empty($message)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "message" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (is_null($this->getOutputInstance())) {
+ // Should not be NULL
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
+ }
+
+ // Use debug output handler
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Invoking this->outputMessage(%s,%s,%d) ...' . PHP_EOL, __METHOD__, __LINE__, Logger::LOGGER_LEVEL_WARNING, $message, intval($stripTags));
+ $this->outputMessage(Logger::LOGGER_LEVEL_WARNING, $message, $stripTags);
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
+ }
+
+ /**
+ * Output a partial stub message for the caller method
+ *
+ * @param $message An optional message to display
+ * @return void
+ */
+ public function partialStub (string $message = '') {
+ // Init variable
+ //* NOISY-DEBUG: */ printf('[%s:%d]: message=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $message);
+ $stubMessage = 'Partial stub!';
+
+ // Is an extra message given?
+ if (!empty($message)) {
+ // Then add it as well
+ $stubMessage .= ' Message: ' . $message;
+ }
+
+ // Output stub message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Invoking this->outputMessage(%s,%s) ...' . PHP_EOL, __METHOD__, __LINE__, Logger::LOGGER_LEVEL_WARNING, $subMessage);
+ $this->outputMessage(Logger::LOGGER_LEVEL_WARNING, $stubMessage);
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
+ }
+
+ /**
+ * Outputs a deprecated message whether to debug instance (should be set!) or
+ * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
+ * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
+ *
+ * @param $message Message we shall send out...
+ * @param $doPrint Whether print or die here (default: print)
+ * @paran $stripTags Whether to strip tags (default: false)
+ * @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
+ * @throws NullPointerException If this->outputInstance is NULL
+ * @todo Remove $doPrint parameter
+ * @todo When all old method invocations are fixed, renamed this do deprecatedMessage
+ */
+ public function debugOutput (string $message, bool $doPrint = true, bool $stripTags = false) {
+ // Check parameter
+ //* NOISY-DEBUG: */ printf('[%s:%d]: message=%s,doPrint=%d,stripTags=%d - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $message, intval($doPrint), intval($stripTags));
+ if (empty($message)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "message" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (is_null($this->getOutputInstance())) {
+ // Should not be NULL
+ throw new NullPointerException($this, FrameworkInterface::EXCEPTION_IS_NULL_POINTER);
+ }
+
+ // Invoke Inner method
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Invoking this->outputMessage(%s,%s) ...' . PHP_EOL, __METHOD__, __LINE__, Logger::LOGGER_LEVEL_DEPRECATED, $subMessage);
+ $this->outputMessage(Logger::LOGGER_LEVEL_DEPRECATED, $message, $doPrint, $stripTags);
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
}
namespace Org\Mxchange\CoreFramework\Handler\Filesystem;
// Import framework stuff
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
use Org\Mxchange\CoreFramework\Handler\Stream\IoHandler;
use Org\Mxchange\CoreFramework\Middleware\BaseMiddleware;
-use Org\Mxchange\CoreFramework\Stream\Filesystem\FileInputStreamer;
-use Org\Mxchange\CoreFramework\Stream\Filesystem\FileOutputStreamer;
+use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
+use Org\Mxchange\CoreFramework\Traits\Streamer\File\Input\FileInputStreamerTrait;
+use Org\Mxchange\CoreFramework\Traits\Streamer\File\Output\FileOutputStreamerTrait;
// Import SPL stuff
+use \InvalidArgumentException;
use \SplFileInfo;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @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
*
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class FileIoHandler extends BaseMiddleware implements IoHandler {
- /**
- * The *real* file input class we shall use for reading data
- */
- private $inputStream = NULL;
-
- /**
- * The *real* file output class we shall use for reading data
- */
- private $outputStream = NULL;
+ // Load traits
+ use FileInputStreamerTrait;
+ use FileOutputStreamerTrait;
/**
* An instance of this class
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-IO-HANDLER: CONSTRUCTED!');
parent::__construct(__CLASS__);
// Set own instance
self::$selfInstance = $this;
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-IO-HANDLER: EXIT!');
}
/**
* Creates an instance of this class and prepares the IO system. This is
* being done by setting the default file IO class
*
- * @return $ioInstance A prepared instance of FilIOHandler
+ * @return $ioHandlerInstance A prepared instance of FilIoHandler
*/
public static final function createFileIoHandler () {
// Get instance
- $ioHandler = new FileIoHandler();
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-IO-HANDLER: CALLED!');
+ $ioHandlerInstance = new FileIoHandler();
// Set the *real* file IO instances (both the same)
- $ioHandler->setInputStream(ObjectFactory::createObjectByConfiguredName('file_input_class'));
- $ioHandler->setOutputStream(ObjectFactory::createObjectByConfiguredName('file_output_class'));
+ $ioHandlerInstance->setInputStreamerInstance(ObjectFactory::createObjectByConfiguredName('file_input_class'));
+ $ioHandlerInstance->setOutputStreamerInstance(ObjectFactory::createObjectByConfiguredName('file_output_class'));
// Return instance
- return $ioHandler;
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-IO-HANDLER: ioHandlerInstance=%s - EXIT!', $ioHandlerInstance->__toString()));
+ return $ioHandlerInstance;
}
/**
* @return $selfInstance An instance of this class
*/
public static final function getSelfInstance () {
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-IO-HANDLER: Returning self::selfInstance[]=%s - EXIT!', gettype(self::$selfInstance)));
return self::$selfInstance;
}
- /**
- * Setter for the *real* file input instance
- *
- * @param $inputStream The *real* file-input class
- * @return void
- */
- public final function setInputStream (FileInputStreamer $inputStream) {
- $this->inputStream = $inputStream;
- }
-
- /**
- * Getter for the *real* file input instance
- *
- * @return $inputStream The *real* file-input class
- */
- public final function getInputStream () {
- return $this->inputStream;
- }
-
- /**
- * Setter for the *real* file output instance
- *
- * @param $outputStream The *real* file-output class
- * @return void
- */
- public final function setOutputStream (FileOutputStreamer $outputStream) {
- $this->outputStream = $outputStream;
- }
-
- /**
- * Getter for the *real* file output instance
- *
- * @return $outputStream The *real* file-output class
- */
- public final function getOutputStream () {
- return $this->outputStream;
- }
/**
* Saves streamed (that are mostly serialized objects) data to files or
* external servers.
* @throws UnsupportedOperationException If this method is called
*/
public function saveFile (SplFileInfo $infoInstance, array $dataArray) {
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('infoInstance.pathname=' . $infoInstance->getPathname() . ',dataArray()=' . count($dataArray));
- throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+ // Trace message for logging parameters
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-IO-HANDLER: infoInstance.pathname=%s,dataArray()=%d - CALLED!', $infoInstance->getPathname(), count($dataArray)));
+ throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
}
/**
* @param $dataStream File data stream
* @param $objectInstance An instance of a FrameworkInterface class (default: NULL)
* @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
*/
- public function saveStreamToFile (SplFileInfo $infoInstance, $dataStream, FrameworkInterface $objectInstance = NULL) {
+ public function saveStreamToFile (SplFileInfo $infoInstance, string $dataStream, FrameworkInterface $objectInstance = NULL) {
+ // Check parameters
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-IO-HANDLER: infoInstance=%s,dataStream()=%d,objectInstance[]=%s - CALLED!', $infoInstance->__toString(), strlen($dataStream), gettype($objectInstance)));
+ if (empty($dataStream)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "dataStream" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Default is this array
$className = $this->__toString();
// Is the object instance set?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-HANDLER: className=%s - BEFORE!', $className));
if ($objectInstance instanceof FrameworkInterface) {
// Then use this
$className = $objectInstance->__toString();
- } // END - if
+ }
- // Prepare output array
- $dataArray = array(
+ // Send the infoInstance and data array to the output handler
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-IO-HANDLER: className=%s - AFTER!', $className));
+ $this->getOutputStreamerInstance()->saveFile($infoInstance, [
0 => $className,
1 => $dataStream
- );
+ ]);
- // Send the infoInstance and dataArray to the output handler
- $this->getOutputStream()->saveFile($infoInstance, $dataArray);
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-IO-HANDLER: EXIT!');
}
/** Loads data from a file over the input handler
*/
public function loadFileContents (SplFileInfo $infoInstance) {
// Read from the input handler
- return $this->getInputStream()->loadFileContents($infoInstance);
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-IO-HANDLER: infoInstance=%s - CALLED!', $infoInstance->__toString()));
+ return $this->getInputStreamerInstance()->loadFileContents($infoInstance);
}
/**
* @todo 0% done
*/
public function determineSeekPosition () {
- $this->partialStub();
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-IO-HANDLER: CALLED!');
+ DebugMiddleware::getSelfInstance()->partialStub();
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-IO-HANDLER: EXIT!');
}
/**
*
* @param $offset Offset to seek to (or used as "base" for other seeks)
* @param $whence Added to offset (default: only use offset to seek to)
- * @return $status Status of file seek: 0 = success, -1 = failed
+ * @return void
+ * @throws InvalidArgumentException If a parameter has an invalid value
*/
- public function seek ($offset, $whence = SEEK_SET) {
- $this->partialStub('offset=' . $offset . ',whence=' . $whence);
+ public function seek (int $offset, int $whence = SEEK_SET) {
+ // Check parameter
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-IO-HANDLER: offset=%d,whence=%d - CALLED!', $offset, $whence));
+ if ($offset < 0) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "offset" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
+ // @TODO Unfinished work
+ DebugMiddleware::getSelfInstance()->partialStub('offset=' . $offset . ',whence=' . $whence);
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-IO-HANDLER: EXIT!');
}
/**
* Size of file stack
*
* @return $size Size (in bytes) of file
+ * @todo 0% done
*/
public function size () {
- $this->partialStub();
+ // @TODO: Unfinished method:
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-IO-HANDLER: CALLED!');
+ DebugMiddleware::getSelfInstance()->partialStub();
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-IO-HANDLER: EXIT!');
}
/**
* @todo 0% done
*/
public function getPosition () {
- $this->partialStub();
+ // @TODO: Unfinished method:
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-IO-HANDLER: CALLED!');
+ DebugMiddleware::getSelfInstance()->partialStub();
+
+ // Trace message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-IO-HANDLER: EXIT!');
}
}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Tests\Command;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Command\BaseCommand;
-use Org\Mxchange\CoreFramework\Command\Commandable;
-use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
-use Org\Mxchange\CoreFramework\Request\Requestable;
-use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
-use Org\Mxchange\CoreFramework\Response\Responseable;
-
-/**
- * A command for the 'main' routine
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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 TestsConsoleMainCommand extends BaseCommand implements Commandable {
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of this class
- *
- * @param $resolverInstance An instance of a command resolver class
- * @return $commandInstance An instance a prepared command class
- */
- public static final function createTestsConsoleMainCommand (CommandResolver $resolverInstance) {
- // Get new instance
- $commandInstance = new TestsConsoleMainCommand();
-
- // Set the application instance
- $commandInstance->setResolverInstance($resolverInstance);
-
- // Return the prepared instance
- return $commandInstance;
- }
-
- /**
- * Executes the given command with given request and response objects
- *
- * @param $requestInstance An instance of a class with an Requestable interface
- * @param $responseInstance An instance of a class with an Responseable interface
- * @return void
- */
- public function execute (Requestable $requestInstance, Responseable $responseInstance) {
- // Debug message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('MAIN: --- Starting tests ... ---');
-
- // Get controller
- $controllerInstance = GenericRegistry::getRegistry()->getInstance('controller');
-
- // Run all tests
- $controllerInstance->executeTestsFilters($requestInstance, $responseInstance);
-
- // Debug message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('MAIN: --- Leaving main ... ---');
- }
-
- /**
- * Adds extra filters to the given controller instance
- *
- * @param $controllerInstance A controller instance
- * @param $requestInstance An instance of a class with an Requestable interface
- * @return void
- */
- public function addExtraFilters (Controller $controllerInstance, Requestable $requestInstance) {
- // Add pre filters (e.g. for requirements checks)
- $controllerInstance->addPreFilter(ObjectFactory::createObjectByConfiguredName('tests_php_requirements_filter_class'));
-
- // Add 'tests' filters which will run the actual tests
- $controllerInstance->addTestsFilter(ObjectFactory::createObjectByConfiguredName('tests_configuration_classes_loadable_test_filter_class'));
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Tests\Controller;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Controller\BaseController;
-use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
-use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Request\Requestable;
-use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
-use Org\Mxchange\CoreFramework\Response\Responseable;
-
-/**
- * The default controller with news for e.g. home or news page
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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 TestsConsoleDefaultNewsController extends BaseController implements Controller {
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
-
- // Init additional filter chains
- foreach (array('bootstrap', 'tests', 'shutdown') as $filterChain) {
- $this->initFilterChain($filterChain);
- } // END - foreach
- }
-
- /**
- * Creates an instance of this class
- *
- * @param $resolverInstance An instance of a command resolver class
- * @return $controllerInstance A prepared instance of this class
- */
- public static final function createTestsConsoleDefaultNewsController (CommandResolver $resolverInstance) {
- // Create the instance
- $controllerInstance = new TestsConsoleDefaultNewsController();
-
- // Set the command resolver
- $controllerInstance->setResolverInstance($resolverInstance);
-
- // Add news filters to this controller
- $controllerInstance->addPreFilter(ObjectFactory::createObjectByConfiguredName('news_download_filter_class'));
- $controllerInstance->addPreFilter(ObjectFactory::createObjectByConfiguredName('news_process_filter_class'));
-
- // Return the prepared instance
- return $controllerInstance;
- }
-
- /**
- * Handles the given request and response
- *
- * @param $requestInstance An instance of a request class
- * @param $responseInstance An instance of a response class
- * @return void
- */
- public function handleRequest (Requestable $requestInstance, Responseable $responseInstance) {
- // Get the command instance from the resolver by sending a request instance to the resolver
- $commandInstance = $this->getResolverInstance()->resolveCommandByRequest($requestInstance);
-
- // Add more filters by the command
- $commandInstance->addExtraFilters($this, $requestInstance);
-
- // Run the pre filters
- $this->executePreFilters($requestInstance, $responseInstance);
-
- // This request was valid! :-D
- $requestInstance->requestIsValid();
-
- // Execute the command
- $commandInstance->execute($requestInstance, $responseInstance);
-
- // Run the post filters
- $this->executePostFilters($requestInstance, $responseInstance);
-
- // Flush the response out
- $responseInstance->flushBuffer();
- }
-
- /**
- * Add a bootstrap filter
- *
- * @param $filterInstance A Filterable class
- * @return void
- */
- public function addBootstrapFilter (Filterable $filterInstance) {
- $this->addFilter('bootstrap', $filterInstance);
- }
-
- /**
- * Add a tests filter
- *
- * @param $filterInstance A Filterable class
- * @return void
- */
- public function addTestsFilter (Filterable $filterInstance) {
- $this->addFilter('tests', $filterInstance);
- }
-
- /**
- * Executes all bootstrap filters
- *
- * @param $requestInstance A Requestable class
- * @param $responseInstance A Responseable class
- * @return void
- */
- public function executeBootstrapFilters (Requestable $requestInstance, Responseable $responseInstance) {
- $this->executeFilters('bootstrap', $requestInstance, $responseInstance);
- }
-
- /**
- * Executes all tests filters
- *
- * @param $requestInstance A Requestable class
- * @param $responseInstance A Responseable class
- * @return void
- */
- public function executeTestsFilters (Requestable $requestInstance, Responseable $responseInstance) {
- $this->executeFilters('tests', $requestInstance, $responseInstance);
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Tests\Filter;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Filter\BaseFilter;
-
-/**
- * A generic filter for tests
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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/>.
- */
-abstract class BaseTestsFilter extends BaseFilter {
- /**
- * Protected constructor
- *
- * @param $className Real name of class
- * @return void
- */
- protected function __construct ($className) {
- // Call parent constructor
- parent::__construct($className);
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace CoreFramework\Tests\Filter\!!!;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Request\Requestable;
-use Org\Mxchange\CoreFramework\Response\Responseable;
-use Org\Mxchange\CoreFramework\Tests\Filter\BaseTestsFilter;
-
-/**
- * A ??? filter for tests
- *
- * @author Roland Haeder <webmaster@ship-simu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.ship-simu.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 Tests???Filter extends BaseTestsFilter implements Filterable {
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of this filter class
- *
- * @return $filterInstance An instance of this filter class
- */
- public final static function createTests???Filter () {
- // Get a new instance
- $filterInstance = new Tests???Filter();
-
- // Return the instance
- return $filterInstance;
- }
-
- /**
- * Executes the filter with given request and response objects
- *
- * @param $requestInstance An instance of a class with an Requestable interface
- * @param $responseInstance An instance of a class with an Responseable interface
- * @return void
- * @todo 0% done
- */
- public function execute (Requestable $requestInstance, Responseable $responseInstance) {
- // Implement this!
- $this->partialStub('Please implement this method.');
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace CoreFramework\Tests\Filter\Configuration\!!!;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Request\Requestable;
-use Org\Mxchange\CoreFramework\Response\Responseable;
-use Org\Mxchange\CoreFramework\Tests\Filter\BaseTestsFilter;
-
-/**
- * A ??? filter for tests
- *
- * @author Roland Haeder <webmaster@ship-simu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.ship-simu.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 TestConfiguration???Filter extends BaseTestsFilter implements Filterable {
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of this filter class
- *
- * @return $filterInstance An instance of this filter class
- */
- public final static function createTestConfiguration???Filter () {
- // Get a new instance
- $filterInstance = new TestConfiguration???Filter();
-
- // Return the instance
- return $filterInstance;
- }
-
- /**
- * Executes the filter with given request and response objects
- *
- * @param $requestInstance An instance of a class with an Requestable interface
- * @param $responseInstance An instance of a class with an Responseable interface
- * @return void
- * @todo 0% done
- */
- public function execute (Requestable $requestInstance, Responseable $responseInstance) {
- // Implement this!
- $this->partialStub('Please implement this method.');
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Tests\Filter\Configuration\Classes;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Request\Requestable;
-use Org\Mxchange\CoreFramework\Response\Responseable;
-use Org\Mxchange\CoreFramework\Tests\Filter\BaseTestsFilter;
-
-// Import SPL stuff
-use \InvalidArgumentException;
-
-/**
- * A LoadableClasses filter for tests
- *
- * @author Roland Haeder <webmaster@ship-simu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.ship-simu.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 TestConfigurationLoadableClassesFilter extends BaseTestsFilter implements Filterable {
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of this filter class
- *
- * @return $filterInstance An instance of this filter class
- */
- public final static function createTestConfigurationLoadableClassesFilter () {
- // Get a new instance
- $filterInstance = new TestConfigurationLoadableClassesFilter();
-
- // Return the instance
- return $filterInstance;
- }
-
- /**
- * Executes the filter with given request and response objects
- *
- * @param $requestInstance An instance of a class with an Requestable interface
- * @param $responseInstance An instance of a class with an Responseable interface
- * @return void
- * @todo 0% done
- */
- public function execute (Requestable $requestInstance, Responseable $responseInstance) {
- // Init counter
- $passed = 0;
- $failed = 0;
-
- // Loop through all configuration keys
- foreach ($this->getConfigInstance()->getConfigurationArray() as $configKey => $configValue) {
- // Key must end with _class
- if (substr($configKey, -6, 6) != '_class') {
- // Skip this
- continue;
- } // END - if
-
- // Output message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Testing configKey=%s,configValue[%s]=%s', $configKey, gettype($configValue), $configValue));
-
- // This may throw exceptions
- try {
- // Is the class there?
- if (!class_exists($configValue)) {
- // Class not found
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Class "%s" not found. FAILED', $configValue));
-
- // Skip further tests
- $failed++;
- continue;
- } // END - if
- } catch (InvalidArgumentException $e) {
- // Maybe not conform?
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Class "%s" failed to load. Message: "%s"', $configValue, $e->getMessage()));
-
- // Skip further tests
- $failed++;
- continue;
- }
-
- // class_exists() didn't fail
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Class "%s" loaded successfully. OKAY', $configValue));
- $passed++;
- } // END - foreach
-
- // Output result
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('Test result: %d okay, %d failed (%0.02f%% passed)', $passed, $failed, ($passed / ($passed + $failed) * 100)));
-
- // Implement this!
- $this->partialStub('Please implement this method.');
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Tests\Filter\Requirements;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Filter\Filterable;
-use Org\Mxchange\CoreFramework\Request\Requestable;
-use Org\Mxchange\CoreFramework\Response\Responseable;
-use Org\Mxchange\CoreFramework\Tests\Filter\BaseTestsFilter;
-
-/**
- * A PhpRequirements filter for tests
- *
- * @author Roland Haeder <webmaster@ship-simu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.ship-simu.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 TestsPhpRequirementsFilter extends BaseTestsFilter implements Filterable {
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of this filter class
- *
- * @return $filterInstance An instance of this filter class
- */
- public final static function createTestsPhpRequirementsFilter () {
- // Get a new instance
- $filterInstance = new TestsPhpRequirementsFilter();
-
- // Return the instance
- return $filterInstance;
- }
-
- /**
- * Executes the filter with given request and response objects
- *
- * @param $requestInstance An instance of a class with an Requestable interface
- * @param $responseInstance An instance of a class with an Responseable interface
- * @return void
- * @todo 0% done
- */
- public function execute (Requestable $requestInstance, Responseable $responseInstance) {
- // Implement this!
- $this->partialStub('Please implement this method.');
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Tests\Resolver\Command;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Command\InvalidCommandException;
-use Org\Mxchange\CoreFramework\Resolver\Command\BaseCommandResolver;
-use Org\Mxchange\CoreFramework\Resolver\Command\CommandResolver;
-
-// Import SPL stuff
-use \InvalidArgumentException;
-
-/**
- * A command resolver for console commands
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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 TestsConsoleCommandResolver extends BaseCommandResolver implements CommandResolver {
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
-
- // Set prefix to "TestsConsole"
- $this->setClassPrefix('tests_console');
- }
-
- /**
- * Creates an instance of a TestsConsole command resolver with a given default command
- *
- * @param $commandName The default command we shall execute
- * @return $resolverInstance The prepared command resolver instance
- * @throws InvalidArgumentException Thrown if default command is not set
- * @throws InvalidCommandException Thrown if default command is invalid
- */
- public static final function createTestsConsoleCommandResolver ($commandName) {
- // Create the new instance
- $resolverInstance = new TestsConsoleCommandResolver();
-
- // Is the variable $commandName set and the command is valid?
- if (empty($commandName)) {
- // Then thrown an exception here
- throw new InvalidArgumentException('Parameter "commandName" is empty');
- } elseif ($resolverInstance->isCommandValid('Org\Mxchange\CoreFramework\Tests\Command', $commandName) === false) {
- // Invalid command found
- throw new InvalidCommandException(array($resolverInstance, $commandName), self::EXCEPTION_INVALID_COMMAND);
- }
-
- // Set namespace for command
- $resolverInstance->setNamespace('Org\Mxchange\CoreFramework\Tests\Command');
- $resolverInstance->setCommandName($commandName);
-
- // Return the prepared instance
- return $resolverInstance;
- }
-
-}
+++ /dev/null
-<?php
-// Own namespace
-namespace Org\Mxchange\CoreFramework\Tests\Resolver\Controller;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Controller\BaseController;
-use Org\Mxchange\CoreFramework\Controller\Controller;
-use Org\Mxchange\CoreFramework\Controller\InvalidControllerException;
-use Org\Mxchange\CoreFramework\Resolver\Controller\BaseControllerResolver;
-use Org\Mxchange\CoreFramework\Resolver\Controller\ControllerResolver;
-
-// Import SPL stuff
-use \InvalidArgumentException;
-
-/**
- * A resolver for resolving controllers locally
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 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 TestsConsoleControllerResolver extends BaseControllerResolver implements ControllerResolver {
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
-
- // Set prefix to "TestsConsole"
- $this->setClassPrefix('tests_console');
- }
-
- /**
- * Creates an instance of a resolver class with a given command
- *
- * @param $controllerName The controller we shall resolve
- * @return $resolverInstance The prepared controller resolver instance
- * @throws InvalidArgumentException Thrown if default command is not set
- * @throws InvalidControllerException Thrown if default controller is invalid
- */
- public static final function createTestsConsoleControllerResolver ($controllerName) {
- // Create the new instance
- $resolverInstance = new TestsConsoleControllerResolver();
-
- // Is the variable $controllerName set and the command is valid?
- if (empty($controllerName)) {
- // Then thrown an exception here
- throw new InvalidArgumentException('Parameter "controllerName" is empty');
- } elseif ($resolverInstance->isControllerValid('Org\Mxchange\CoreFramework\Tests\Controller', $controllerName) === false) {
- // Invalid command found
- throw new InvalidControllerException(array($resolverInstance, $controllerName), self::EXCEPTION_INVALID_CONTROLLER);
- }
-
- // Set namespace and controller name
- $resolverInstance->setNamespace('Org\Mxchange\CoreFramework\Tests\Controller');
- $resolverInstance->setControllerName($controllerName);
-
- // Return the prepared instance
- return $resolverInstance;
- }
-
- /**
- * Resolves the default controller of the given command
- *
- * @return $controllerInstance A controller instance for the default
- * command
- * @throws InvalidControllerInstanceException Thrown if $controllerInstance
- * is invalid
- */
- public function resolveController () {
- // Init variables
- $controllerName = '';
- $controllerInstance = NULL;
-
- // Get namespace and command name
- $controllerName = $this->getControllerName();
-
- // Get the command
- $controllerInstance = $this->loadController($controllerName);
-
- // And validate it
- if ((!is_object($controllerInstance)) || (!$controllerInstance instanceof Controller)) {
- // This command has an invalid instance!
- throw new InvalidControllerInstanceException(array($this, $controllerName), self::EXCEPTION_INVALID_CONTROLLER);
- } // END - if
-
- // Set last controller
- $this->setResolvedInstance($controllerInstance);
-
- // Return the maybe resolved instance
- return $controllerInstance;
- }
-
-}
+++ /dev/null
-<?php
-/**
- * 01.07.2008 22:32:28est
- *
- * Akismet PHP4 class
- *
- * <b>Usage</b>
- * <code>
- * $comment = array(
- * 'author' => 'viagra-test-123',
- * 'email' => 'test@example.com',
- * 'website' => 'http://www.example.com/',
- * 'body' => 'This is a test comment',
- * 'permalink' => 'http://yourdomain.com/yourblogpost.url',
- * );
- *
- * $akismet = new Akismet('http://www.yourdomain.com/', 'YOUR_WORDPRESS_API_KEY', $comment);
- *
- * if($akismet->errorsExist()) {
- * echo"Couldn't connected to Akismet server!";
- * } else {
- * if($akismet->isSpam()) {
- * echo"Spam detected";
- * } else {
- * echo"yay, no spam!";
- * }
- * }
- * </code>
- *
- * @author Bret Kuhns {@link www.miphp.net}
- * @link http://www.miphp.net/blog/view/new_akismet_class/
- * @version 0.3.4
- * @license http://www.opensource.org/licenses/mit-license.php MIT License
- */
-
-
-
-// Error constants
-define("AKISMET_SERVER_NOT_FOUND", 0);
-define("AKISMET_RESPONSE_FAILED", 1);
-define("AKISMET_INVALID_KEY", 2);
-
-
-
-// Base class to assist in error handling between Akismet classes
-class AkismetObject {
- var $errors = array();
-
-
- /**
- * Add a new error to the errors array in the object
- *
- * @param String $name A name (array key) for the error
- * @param String $string The error message
- * @return void
- */
- // Set an error in the object
- function setError($name, $message) {
- $this->errors[$name] = $message;
- }
-
-
- /**
- * Return a specific error message from the errors array
- *
- * @param String $name The name of the error you want
- * @return mixed Returns a String if the error exists, a false boolean if it does not exist
- */
- function getError($name) {
- if($this->isError($name)) {
- return $this->errors[$name];
- } else {
- return false;
- }
- }
-
-
- /**
- * Return all errors in the object
- *
- * @return String[]
- */
- function getErrors() {
- return (array)$this->errors;
- }
-
-
- /**
- * Check if a certain error exists
- *
- * @param String $name The name of the error you want
- * @return boolean
- */
- function isError($name) {
- return isset($this->errors[$name]);
- }
-
-
- /**
- * Check if any errors exist
- *
- * @return boolean
- */
- function errorsExist() {
- return (count($this->errors) > 0);
- }
-
-
-}
-
-
-
-
-
-// Used by the Akismet class to communicate with the Akismet service
-class AkismetHttpClient extends AkismetObject {
- var $akismetVersion = '1.1';
- var $con;
- var $host;
- var $port;
- var $apiKey;
- var $blogUrl;
- var $errors = array();
-
-
- // Constructor
- function AkismetHttpClient($host, $blogUrl, $apiKey, $port = 80) {
- $this->host = $host;
- $this->port = $port;
- $this->blogUrl = $blogUrl;
- $this->apiKey = $apiKey;
- }
-
-
- // Use the connection active in $con to get a response from the server and return that response
- function getResponse($request, $path, $type = "post", $responseLength = 1160) {
- $this->_connect();
-
- if($this->con && !$this->isError(AKISMET_SERVER_NOT_FOUND)) {
- $request =
- strToUpper($type)." /{$this->akismetVersion}/$path HTTP/1.1\r\n" .
- "Host: ".((!empty($this->apiKey)) ? $this->apiKey."." : null)."{$this->host}\r\n" .
- "Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n" .
- "Content-Length: ".strlen($request)."\r\n" .
- "User-Agent: Akismet PHP4 Class\r\n" .
- "\r\n" .
- $request
- ;
- $response = "";
-
- @fwrite($this->con, $request);
-
- while(!feof($this->con)) {
- $response .= @fgets($this->con, $responseLength);
- }
-
- $response = explode("\r\n\r\n", $response, 2);
- return $response[1];
- } else {
- $this->setError(AKISMET_RESPONSE_FAILED, "The response could not be retrieved.");
- }
-
- $this->_disconnect();
- }
-
-
- // Connect to the Akismet server and store that connection in the instance variable $con
- function _connect() {
- if(!($this->con = @fsockopen($this->host, $this->port))) {
- $this->setError(AKISMET_SERVER_NOT_FOUND, "Could not connect to akismet server.");
- }
- }
-
-
- // Close the connection to the Akismet server
- function _disconnect() {
- @fclose($this->con);
- }
-
-
-}
-
-
-
-
-
-// The controlling class. This is the ONLY class the user should instantiate in
-// order to use the Akismet service!
-class Akismet extends AkismetObject {
- var $apiPort = 80;
- var $akismetServer = 'rest.akismet.com';
- var $akismetVersion = '1.1';
- var $http;
-
- var $ignore = array(
- 'HTTP_COOKIE',
- 'HTTP_X_FORWARDED_FOR',
- 'HTTP_X_FORWARDED_HOST',
- 'HTTP_MAX_FORWARDS',
- 'HTTP_X_FORWARDED_SERVER',
- 'REDIRECT_STATUS',
- 'SERVER_PORT',
- 'PATH',
- 'DOCUMENT_ROOT',
- 'SERVER_ADMIN',
- 'QUERY_STRING',
- 'PHP_SELF',
- 'argv'
- );
-
- var $blogUrl = "";
- var $apiKey = "";
- var $comment = array();
-
-
- /**
- * Constructor
- *
- * Set instance variables, connect to Akismet, and check API key
- *
- * @param String $blogUrl The URL to your own blog
- * @param String $apiKey Your wordpress API key
- * @param String[] $comment A formatted comment array to be examined by the Akismet service
- * @return Akismet
- */
- function Akismet($blogUrl, $apiKey, $comment = array()) {
- $this->blogUrl = $blogUrl;
- $this->apiKey = $apiKey;
- $this->setComment($comment);
-
- // Connect to the Akismet server and populate errors if they exist
- $this->http = new AkismetHttpClient($this->akismetServer, $blogUrl, $apiKey);
- if($this->http->errorsExist()) {
- $this->errors = array_merge($this->errors, $this->http->getErrors());
- }
-
- // Check if the API key is valid
- if(!$this->_isValidApiKey($apiKey)) {
- $this->setError(AKISMET_INVALID_KEY, "Your Akismet API key is not valid.");
- }
- }
-
-
- /**
- * Query the Akismet and determine if the comment is spam or not
- *
- * @return boolean
- */
- function isSpam() {
- $response = $this->http->getResponse($this->_getQueryString(), 'comment-check');
-
- return ($response == "true");
- }
-
-
- /**
- * Submit this comment as an unchecked spam to the Akismet server
- *
- * @return void
- */
- function submitSpam() {
- $this->http->getResponse($this->_getQueryString(), 'submit-spam');
- }
-
-
- /**
- * Submit a false-positive comment as "ham" to the Akismet server
- *
- * @return void
- */
- function submitHam() {
- $this->http->getResponse($this->_getQueryString(), 'submit-ham');
- }
-
-
- /**
- * Manually set the comment value of the instantiated object.
- *
- * @param Array $comment
- * @return void
- */
- function setComment($comment) {
- $this->comment = $comment;
- if(!empty($comment)) {
- $this->_formatCommentArray();
- $this->_fillCommentValues();
- }
- }
-
-
- /**
- * Returns the current value of the object's comment array.
- *
- * @return Array
- */
- function getComment() {
- return $this->comment;
- }
-
-
- /**
- * Check with the Akismet server to determine if the API key is valid
- *
- * @access Protected
- * @param String $key The Wordpress API key passed from the constructor argument
- * @return boolean
- */
- function _isValidApiKey($key) {
- $keyCheck = $this->http->getResponse("key=".$this->apiKey."&blog=".$this->blogUrl, 'verify-key');
-
- return ($keyCheck == "valid");
- }
-
-
- /**
- * Format the comment array in accordance to the Akismet API
- *
- * @access Protected
- * @return void
- */
- function _formatCommentArray() {
- $format = array(
- 'type' => 'comment_type',
- 'author' => 'comment_author',
- 'email' => 'comment_author_email',
- 'website' => 'comment_author_url',
- 'body' => 'comment_content'
- );
-
- foreach($format as $short => $long) {
- if(isset($this->comment[$short])) {
- $this->comment[$long] = $this->comment[$short];
- unset($this->comment[$short]);
- }
- }
- }
-
-
- /**
- * Fill any values not provided by the developer with available values.
- *
- * @return void
- */
- function _fillCommentValues() {
- if(!isset($this->comment['user_ip'])) {
- $this->comment['user_ip'] = ($_SERVER['REMOTE_ADDR'] != getenv('SERVER_ADDR')) ? $_SERVER['REMOTE_ADDR'] : getenv('HTTP_X_FORWARDED_FOR');
- }
- if(!isset($this->comment['user_agent'])) {
- $this->comment['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
- }
- if(!isset($this->comment['referrer'])) {
- $this->comment['referrer'] = $_SERVER['HTTP_REFERER'];
- }
- if(!isset($this->comment['blog'])) {
- $this->comment['blog'] = $this->blogUrl;
- }
- }
-
-
- /**
- * Build a query string for use with HTTP requests
- *
- * @access Protected
- * @return String
- */
- function _getQueryString() {
- foreach($_SERVER as $key => $value) {
- if(!in_array($key, $this->ignore)) {
- if($key == 'REMOTE_ADDR') {
- $this->comment[$key] = $this->comment['user_ip'];
- } else {
- $this->comment[$key] = $value;
- }
- }
- }
-
- $query_string = '';
-
- foreach($this->comment as $key => $data) {
- $query_string .= $key . '=' . urlencode(stripslashes($data)) . '&';
- }
-
- return $query_string;
- }
-
-
-}
-?>
\ No newline at end of file
+++ /dev/null
-<?php
-// Own namespace
-namespace Wds66\Api;
-
-// Import framework stuff
-use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
-
-/**
- * Class for connecting to the Wernis-Portal at http://www.wds66.com
- *
- * @author Roland Haeder <webmaster@shipsimu.org>
- * @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
- * @license GNU GPL 3.0 or any newer version
- * @link http://www.shipsimu.org
- * @todo Out-dated since 0.6-BETA
- *
- * 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 WernisApi extends BaseFrameworkSystem {
- /**
- * Static base API URL
- */
- private static $apiUrl = 'https://www.wds66.com/api/';
-
- /**
- * API Wernis amount
- */
- private $wernis_amount = 0;
-
- /**
- * API username
- */
- private $w_id = 0;
-
- /**
- * API Wernis password (not account password!)
- */
- private $w_md5 = '';
-
- /**
- * Nickname of the user
- */
- private $w_nick = '';
-
- /**
- * Wernis amount of the user
- */
- private $w_amount = 0;
-
- /**
- * Array with status informations
- */
- private $statusArray = array();
-
- /**
- * Status for 'okay'
- */
- private $statusOkay = 'OK';
-
- /**
- * Protected constructor
- *
- * @return void
- */
- protected function __construct () {
- // Call parent constructor
- parent::__construct(__CLASS__);
- }
-
- /**
- * Creates an instance of this API class
- *
- * @param $cfg Configuration array
- * @return $apiInstance An instance of this API class
- */
- public static final function createWernisApi (array $cfg) {
- // Create a new instance
- $apiInstance = new WernisApi();
-
- // Fix missing
- if (!isset($cfg['api_url'])) $cfg['api_url'] = self::$apiUrl;
-
- // Konfiguration uebertragen
- $apiInstance->setCoonfigArray($cfg);
-
- // Return the instance
- return $apiInstance;
- }
-
- /**
- * Setter for gamer data
- *
- * @param $w_id Username (id) of the gamer
- * @param $w_pwd Clear password of the gamer
- * @return void
- */
- public function setUser ($w_id, $w_pwd) {
- // Set username (id)
- $this->w_id = $w_id;
-
- // Hash clear password and set it
- $this->w_md5 = md5($w_pwd);
- }
-
- /************************************************
- * The following methods are not yet rewritten! *
- ************************************************/
-
- public function einziehen ($amount) {
- // amount auf Gueltigkeit pruefen
- $amount = isset($amount) ? $amount+0 : 0;
-
- if ($amount < $this->config['mineinsatz']) {
- $this->setStatusMessage('low_stakes', sprintf('Dein Einsatz muss mindestens %d Wernis betragen.', $this->config['mineinsatz']));
- return false;
- }
-
- // Abfrage senden
- return $this->executeWithdraw($amount);
- }
-
- public function verschicken ($amount) {
- // amount auf Gueltigkeit pruefen
- $amount = isset($amount) ? $amount+0 : 0;
-
- if ($amount < $this->config['mineinsatz']) {
- $this->setStatusMessage('low_stakes', sprintf('Dein Einsatz muss mindestens %d Wernis betragen.', $this->config['mineinsatz']));
- return false;
- }
-
- // Abfrage senden
- return $this->executePayout($amount);
- }
-
- // Script abbrechen mit Zurueck-Buttom
- public function ende () {
- global $_CONFIG;
- include 'templates/zurueck.html';
- include 'templates/fuss.html';
- exit();
- }
-
- // Fehlermeldung ausgeben und beenden
- public function error () {
- print "<div class=\"fehler\">Fehler im Spiel: ".$this->getErrorMessage()."<div><br />\n";
- $this->ende();
- }
-
- // Sets a status message and code
- public function setStatusMessage ($msg, $status) {
- $this->statusArray['message'] = $msg;
- $this->statusArray['status'] = $status;
- }
-
- // Get the status message
- public function getErrorMessage () {
- if (isset($this->statusArray['message'])) {
- // Use raw message
- return $this->statusArray['message'];
- } else {
- // Fall-back to status
- return sprintf('Fehler-Code <u>%s</u> ist keiner Nachricht zugewiesen.', $this->getErrorCode());
- }
- }
-
- // Get the status code
- public function getErrorCode () {
- if (isset($this->statusArray['status'])) {
- // Use raw message
- return $this->statusArray['status'];
- } else {
- // Something bad happend
- return 'unknown';
- }
- }
-
- // Sends out a request to the API and returns it's result
- private function sendRequest ($scriptName, array $requestData = array()) {
- // Is the requestData an array?
- if (!is_array($requestData)) {
- // Then abort here!
- return array(
- 'status' => 'failed_general',
- 'message' => 'API-Daten in <strong>config</strong> sind ungültig!'
- );
- }
-
- // Is the API id and MD5 hash there?
- if ((empty($this->config['wernis_api_id'])) || (empty($this->config['wernis_api_key']))) {
- // Abort here...
- return array(
- 'status' => 'failed_general',
- 'message' => 'API-Daten in config.php sind leer!'
- );
- }
-
- // Construct the request string
- $requestString = $this->config['api_url'] . $scriptName . '?api_id=' . $this->config['wernis_api_id'] . '&api_key='.$this->config['wernis_api_key'];
- foreach ($requestData as $key => $value) {
- $requestString .= '&' . $key . '=' . $value;
- }
-
- // Get the raw response from the lower function
- $response = $this->sendRawRequest($requestString);
-
- // Check the response header if all is fine
- if (strpos($response[0], '200') === false) {
- // Something bad happend... :(
- return array(
- 'status' => 'request_error',
- 'message' => sprintf('Servermeldung <u>%s</u> von WDS66-API erhalten.', $response[0])
- );
- }
-
- // All (maybe) fine so remove the response header from server
- for ($idx = (count($response) - 1); $idx > 1; $idx--) {
- $line = trim($response[$idx]);
- if (!empty($line)) {
- $response = $line;
- break;
- }
- }
-
- // Prepare the returning result for higher functions
- if (substr($response, 0, 1) == '&') {
- // Remove the leading & (which can be used in Flash)
- $response = substr($response, 1);
- }
-
- // Bring back the response
- $data = explode('=', $response);
-
- // Default return array (should not stay empty)
- $return = array();
-
- // We use only the first two entries (which shall be fine)
- if ($data[0] === 'error') {
- // The request has failed... :(
- switch ($data[1]) {
- case '404': // Invalid API ID
- case 'AUTH': // Authorization has failed
- $return = array(
- 'status' => 'auth_failed',
- 'message' => 'API-Daten scheinen nicht zu stimmen! (Access Denied)'
- );
- break;
-
- case 'LOCKED': // User account is locked!
- case 'PASS': // Bad passphrase entered
- case 'USER': // Missing account or invalid password
- $return = array(
- 'status' => 'user_failed',
- 'message' => 'Dein eingegebener WDS66-Username stimmt nicht, ist gesperrt oder du hast ein falsches Passwort eingegeben.'
- );
- break;
-
- case 'OWN': // Transfer to own account
- $return = array(
- 'status' => 'own_failed',
- 'message' => 'Du darfst dein eigenes Spiel leider nicht spielen.'
- );
- break;
-
- case 'AMOUNT': // Amount is depleted
- $return = array(
- 'status' => 'amount_failed',
- 'message' => 'Dein Guthaben reicht nicht aus, um das Spiel zu spielen.'
- );
- break;
-
- case 'AMOUNT-SEND': // API amount is depleted
- $return = array(
- 'status' => 'api_amount_failed',
- 'message' => 'Nicht genügend Guthaben auf dem API-Account.'
- );
- break;
-
- default: // Unknown error (maybe new?)
- $return = array(
- 'status' => 'request_failed',
- 'message' => sprintf('Unbekannter Fehler <u>%s</u> von API erhalten.', $data[1])
- );
- break;
- }
- } else {
- // All fine here
- $return = array(
- 'status' => $this->statusOkay,
- 'response' => $response
- );
- }
-
- // Return the result
- return $return;
- }
-
- // Widthdraw this amount
- private function executeWithdraw ($amount) {
- // First all fails...
- $result = false;
-
- // Prepare the purpose
- $purpose = "\"Bube oder Dame\"-Einsatz gesetzt.";
-
- // Prepare the request data
- $requestData = array(
- 'sub_request' => 'receive',
- 't_uid' => $this->w_id,
- 't_md5' => $this->w_md5,
- 'r_uid' => (int) $this->config['wernis_refid'],
- 'amount' => (int) $amount,
- 'purpose' => urlencode(base64_encode($purpose))
- );
-
- // Return the result from the lower functions
- $return = $this->sendRequest('book.php', $requestData);
-
- if ($return['status'] == $this->statusOkay) {
- // All fine!
- $result = true;
- } else {
- // Status failture text
- $this->setStatusMessage($return['message'], $return['status']);
- }
-
- // Return result
- return $result;
- }
-
- // Payout this amount
- private function executePayout ($amount) {
- // First all fails...
- $result = false;
-
- // Prepare the purpose
- $purpose = "\"Bube oder Dame\"-Gewinn erhalten.";
-
- // Prepare the request data
- $requestData = array(
- 'sub_request' => 'send',
- 't_uid' => $this->w_id,
- 't_md5' => $this->w_md5,
- 'r_uid' => (int) $this->config['wernis_refid'],
- 'amount' => (int) $amount,
- 'purpose' => urlencode(base64_encode($purpose))
- );
-
- // Return the result from the lower functions
- $return = $this->sendRequest("book.php", $requestData);
-
- if ($return['status'] == $this->statusOkay) {
- // All fine!
- $result = true;
- } else {
- // Status failture text
- $this->setStatusMessage($return['message'], $return['status']);
- }
-
- // Return result
- return $result;
- }
-
- // Send raw GET request
- private function sendRawRequest ($script) {
- // Use the hostname from script URL as new hostname
- $url = substr($script, 7);
- $extract = explode('/', $url);
-
- // Done extracting the URL :)
- $url = $extract[0];
-
- // Extract host name
- $host = str_replace('http://', '', $url);
- if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
-
- // Generate relative URL
- $script = substr($script, (strlen($url) + 7));
- if (substr($script, 0, 1) == '/') $script = substr($script, 1);
-
- // Open connection
- $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
- if (!$fp) {
- // Failed!
- return array('', '', '');
- }
-
- // Generate request header
- $request = "GET /" . trim($script) . " HTTP/1.0\r\n";
- $request .= "Host: " . $host . "\r\n";
- $request .= sprintf("User-Agent: WernisApi/1.0 by Quix0r [Spieler: %d]\r\n\r\n", $this->w_id);
-
- // Initialize array
- $response = array();
-
- // Write request
- fputs($fp, $request);
-
- // Read response
- while(!feof($fp)) {
- array_push($response, trim(fgets($fp, 1024)));
- } // END - while
-
- // Close socket
- fclose($fp);
-
- // Was the request successfull?
- if ((!ereg('200 OK', $response[0])) && (empty($response[0]))) {
- // Not found / access forbidden
- $response = array('', '', '');
- } // END - if
-
- // Return response
- return $response;
- }
-
-}
+++ /dev/null
-scrypt
-Dominic Black
\ No newline at end of file
+++ /dev/null
-Original Scrypt Implementation;
- Copyright (c) 2009 Colin Percival
-
-PHP Module;
- Copyright (c) 2012, Dominic Black
-
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
-1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-
-2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+++ /dev/null
-PHP scrypt module
-=================
-
-[![Build Status](https://travis-ci.org/DomBlack/php-scrypt.svg?branch=master)](https://travis-ci.org/DomBlack/php-scrypt)
-
-This is a PHP library providing a wrapper to [Colin Percival's scrypt implementation](http://www.tarsnap.com/scrypt.html). Scrypt is a key derivation function designed to be far more secure against hardware brute-force attacks than alternative functions such as PBKDF2 or bcrypt.
-
-Details of the scrypt key derivation function are given in a paper by Colin Percival, Stronger Key Derivation via Sequential Memory-Hard Functions: [PDF](http://www.tarsnap.com/scrypt/scrypt-slides.pdf).
-
-An example class using this module can be found in; scrypt.php
-
-Join in!
---------
-
-We are happy to receive bug reports, fixes, documentation enhancements, and other improvements.
-
-Please report bugs via the [github issue tracker](http://github.com/DomBlack/php-scrypt/issues).
-
-Master [git repository](https://github.com/DomBlack/php-scrypt):
-
- git clone git://github.com/DomBlack/php-scrypt.git
-
-Authors
--------
-
-This library is written and maintained by Dominic Black, <thephenix@gmail.com>.
-
-----
-
-PECL Install
-============
-
-This extension is now avaible through PECL.
-
-```
-pecl install scrypt
-```
-
-Build From Source
-=================
-
-Unix/OSX
---------
-
-1. `phpize`
-2. If on OSX; `export CFLAGS='-arch i386 -arch x86_64'`
-3. `./configure --enable-scrypt`
-4. `make`
-5. `make install`
-6. Add the extension to your php.ini
-
-````
- ; Enable scrypt extension module
- extension=scrypt.so
-````
-
-Windows
--------
-
-Using Visual Studio 2008 (or Visual C++ Express 2008) open up the attached project
-inside the VS2008 folder. This project assumes you have the PHP thread safe source at;
-`C:\phpsrcts\`, a PHP install at `C:\php\` and this source code extracted to
-`C:\php-scrypt\`.
-
-1. Build the project.
-2. Copy the resultant `scrypt.dll` to your ext directory in PHP.
-3. Add the extension to your php.ini
-
-````
- ; Enable scrypt extension module
- extension=scrypt.dll
-````
-
-Legal Stuff
-===========
-This works is licensed under the BSD 2-Clause license.
-
-Original Scrypt Implementation;
- Copyright (c) 2009 Colin Percival
-
-PHP Module;
- Copyright (c) 2012, Dominic Black
-
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
-Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Cache;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Cache\Cacheable;
+
+/**
+ * A trait for cache
+ *
+ * @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/>.
+ */
+trait CacheableTrait {
+ /**
+ * Cache instance
+ */
+ private $cacheInstance = NULL;
+
+ /**
+ * Setter for table name
+ *
+ * @param $cacheInstance Name of table name to set
+ * @return void
+ */
+ protected final function setCacheInstance (Cacheable $cacheInstance) {
+ $this->cacheInstance = $cacheInstance;
+ }
+
+ /**
+ * Getter for table name
+ *
+ * @return $cacheInstance Name of table name to set
+ */
+ protected final function getCacheInstance () {
+ return $this->cacheInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Compressor\Channel;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Middleware\Compressor\CompressorChannel;
+
+/**
+ * A trait for compressor channels
+ *
+ * @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/>.
+ */
+trait CompressorChannelTrait {
+ /**
+ * A Compressor instance
+ */
+ private $compressorChannelInstance = NULL;
+
+ /**
+ * Setter for compressor channel
+ *
+ * @param $compressorChannelInstance An instance of a CompressorChannel class
+ * @return void
+ */
+ protected final function setCompressorChannelInstance (CompressorChannel $compressorChannelInstance) {
+ $this->compressorChannelInstance = $compressorChannelInstance;
+ }
+
+ /**
+ * Getter for compressor channel
+ *
+ * @return $compressorChannelInstance An instance of a CompressorChannel class
+ */
+ protected final function getCompressorChannelInstance () {
+ return $this->compressorChannelInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Crypto;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Crypto\Cryptable;
+
+/**
+ * A trait for crypto classes
+ *
+ * @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/>.
+ */
+trait CryptoTrait {
+ /**
+ * Instance of a crypto helper
+ */
+ private $cryptoInstance = NULL;
+
+ /**
+ * Setter for Cryptable instance
+ *
+ * @param $cryptoInstance An instance of a Cryptable class
+ * @return void
+ */
+ protected final function setCryptoInstance (Cryptable $cryptoInstance) {
+ $this->cryptoInstance = $cryptoInstance;
+ }
+
+ /**
+ * Getter for Cryptable instance
+ *
+ * @return $cryptoInstance An instance of a Cryptable class
+ */
+ public final function getCryptoInstance () {
+ return $this->cryptoInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Database\Frontend;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseFrontend;
+
+/**
+ * A trait for database frontend
+ *
+ * @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/>.
+ */
+trait DatabaseFrontendTrait {
+ /**
+ * An instance of a DatabaseFrontend class
+ */
+ private $frontendInstance = NULL;
+
+ /**
+ * Setter for DatabaseFrontend instance
+ *
+ * @param $frontendInstance An instance of a DatabaseFrontend class
+ * @return void
+ */
+ public final function setFrontendInstance (DatabaseFrontend $frontendInstance) {
+ $this->frontendInstance = $frontendInstance;
+ }
+
+ /**
+ * Getter for DatabaseFrontend instance
+ *
+ * @return $frontendInstance An instance of a DatabaseFrontend class
+ */
+ public final function getFrontendInstance () {
+ return $this->frontendInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\File;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Filesystem\File\BinaryFile;
+
+/**
+ * A trait for binary files
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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/>.
+ */
+trait BinaryFileTrait {
+ /**
+ * An instance of an BinaryFile class
+ */
+ private $binaryFileInstance = NULL;
+
+ /**
+ * Setter for BinaryFile instance
+ *
+ * @param $binaryFileInstance An instance of an BinaryFile class
+ * @return void
+ */
+ protected final function setBinaryFileInstance (BinaryFile $binaryFileInstance) {
+ $this->binaryFileInstance = $binaryFileInstance;
+ }
+
+ /**
+ * Getter for BinaryFile instance
+ *
+ * @return $binaryFileInstance An instance of an BinaryFile class
+ */
+ public final function getBinaryFileInstance () {
+ return $this->binaryFileInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Handler;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Handler\Handleable;
+
+/**
+ * A trait for handlers
+ *
+ * @author Roland Haeder <webmaster@shipsimu.org>
+ * @version 0.0.0
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2018 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/>.
+ */
+trait HandleableTrait {
+ /**
+ * Handler instance
+ */
+ private $handlerInstance = NULL;
+
+ /**
+ * Setter for handler instance
+ *
+ * @param $handlerInstance An instance of a Handleable class
+ * @return void
+ */
+ protected final function setHandlerInstance (Handleable $handlerInstance) {
+ $this->handlerInstance = $handlerInstance;
+ }
+
+ /**
+ * Getter for handler instance
+ *
+ * @return $handlerInstance A Handleable instance
+ */
+ public final function getHandlerInstance () {
+ return $this->handlerInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Handler\Io;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Handler\Stream\IoHandler;
+
+/**
+ * A trait for file I/O handler
+ *
+ * @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/>.
+ */
+trait IoHandlerTrait {
+ /**
+ * The file I/O instance for the template loader
+ */
+ private $fileIoInstance = NULL;
+
+ /**
+ * Private getter for file IO instance
+ *
+ * @return $fileIoInstance An instance to the file I/O sub-system
+ */
+ protected final function getFileIoInstance () {
+ return $this->fileIoInstance;
+ }
+
+ /**
+ * Setter for file I/O instance
+ *
+ * @param $fileIoInstance An instance to the file I/O sub-system
+ * @return void
+ */
+ public final function setFileIoInstance (IoHandler $fileIoInstance) {
+ $this->fileIoInstance = $fileIoInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Helper;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Helper\Helper;
+
+/**
+ * A trait for helper
+ *
+ * @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/>.
+ */
+trait HelperTrait {
+ /**
+ * A helper instance for the form
+ */
+ private $helperInstance = NULL;
+
+ /**
+ * Setter for helper instance
+ *
+ * @param $helperInstance An instance of a helper class
+ * @return void
+ */
+ protected final function setHelperInstance (Helper $helperInstance) {
+ $this->helperInstance = $helperInstance;
+ }
+
+ /**
+ * Getter for helper instance
+ *
+ * @return $helperInstance An instance of a helper class
+ */
+ public final function getHelperInstance () {
+ return $this->helperInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Index;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Index\Indexable;
+
+/**
+ * A trait for indexes
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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/>.
+ */
+trait IndexableTrait {
+ /**
+ * An instance of an Indexable class
+ */
+ private $indexInstance = NULL;
+
+ /**
+ * Setter for Indexable instance
+ *
+ * @param $indexInstance An instance of an Indexable class
+ * @return void
+ */
+ protected final function setIndexInstance (Indexable $indexInstance) {
+ $this->indexInstance = $indexInstance;
+ }
+
+ /**
+ * Getter for Indexable instance
+ *
+ * @return $indexInstance An instance of an Indexable class
+ */
+ public final function getIndexInstance () {
+ return $this->indexInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Iterator;
+
+// Import SPL stuff
+use \Iterator;
+
+/**
+ * A trait for iterators
+ *
+ * @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/>.
+ */
+trait IteratorTrait {
+ /**
+ * Instance of an Iterator class
+ */
+ private $iteratorInstance = NULL;
+
+ /**
+ * Setter for Iterator instance
+ *
+ * @param $iteratorInstance An instance of an Iterator
+ * @return void
+ */
+ protected final function setIteratorInstance (Iterator $iteratorInstance) {
+ $this->iteratorInstance = $iteratorInstance;
+ }
+
+ /**
+ * Getter for Iterator instance
+ *
+ * @return $iteratorInstance An instance of an Iterator
+ */
+ public final function getIteratorInstance () {
+ return $this->iteratorInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Lists;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Lists\Listable;
+
+/**
+ * A trait for lists
+ *
+ * @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/>.
+ */
+trait ListableTrait {
+ /**
+ * Instance of the list
+ */
+ private $listInstance = NULL;
+
+ /**
+ * Setter for the list instance
+ *
+ * @param $listInstance A list of Listable
+ * @return void
+ */
+ protected final function setListInstance (Listable $listInstance) {
+ $this->listInstance = $listInstance;
+ }
+
+ /**
+ * Getter for the list instance
+ *
+ * @return $listInstance A list of Listable
+ */
+ protected final function getListInstance () {
+ return $this->listInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Manager\Account;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\User\ManageableAccount;
+
+/**
+ * A trait for manageable user/guest accounts
+ *
+ * @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/>.
+ */
+trait ManageableAccountTrait {
+ /**
+ * Instance for user class
+ * @todo Rename to $accountInstance ?
+ */
+ private $userInstance = NULL;
+
+ /**
+ * Protected setter for user instance
+ *
+ * @param $userInstance An instance of a user class
+ * @return void
+ */
+ protected final function setUserInstance (ManageableAccount $userInstance) {
+ $this->userInstance = $userInstance;
+ }
+
+ /**
+ * Getter for user instance
+ *
+ * @return $userInstance An instance of a user class
+ */
+ public final function getUserInstance () {
+ return $this->userInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Registry;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Registry\Register;
+
+/**
+ * A trait for registries
+ *
+ * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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/>.
+ */
+trait RegisterTrait {
+ /**
+ * Registry instance (implementing Register)
+ */
+ private $registryInstance = NULL;
+
+ /**
+ * Setter for registry instance
+ *
+ * @param $registryInstance An instance of a Register class
+ * @return void
+ */
+ protected final function setRegistryInstance (Register $registryInstance) {
+ $this->registryInstance = $registryInstance;
+ }
+
+ /**
+ * Getter for registry instance
+ *
+ * @return $registryInstance The debug registry instance
+ */
+ protected final function getRegistryInstance () {
+ return $this->registryInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Resolver;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Resolver\Resolver;
+
+/**
+ * A trait for resolver
+ *
+ * @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/>.
+ */
+trait ResolverTrait {
+ /**
+ * Resolver instance
+ */
+ private $resolverInstance = NULL;
+
+ /**
+ * Setter for resolver instance
+ *
+ * @param $resolverInstance Instance of a command resolver class
+ * @return void
+ */
+ protected final function setResolverInstance (Resolver $resolverInstance) {
+ $this->resolverInstance = $resolverInstance;
+ }
+
+ /**
+ * Getter for resolver instance
+ *
+ * @return $resolverInstance Instance of a command resolver class
+ */
+ protected final function getResolverInstance () {
+ return $this->resolverInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Result\Search;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
+
+/**
+ * A trait for searchable results
+ *
+ * @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/>.
+ */
+trait SearchableResultTrait {
+ /**
+ * Database result instance
+ */
+ private $resultInstance = NULL;
+
+ /**
+ * Setter for database result instance
+ *
+ * @param $resultInstance An instance of a database result class
+ * @return void
+ * @todo SearchableResult and UpdateableResult shall have a super interface to use here
+ */
+ protected final function setResultInstance (SearchableResult $resultInstance) {
+ $this->resultInstance = $resultInstance;
+ }
+
+ /**
+ * Getter for database result instance
+ *
+ * @return $resultInstance An instance of a database result class
+ */
+ public final function getResultInstance () {
+ return $this->resultInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Stack;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Stack\Stackable;
+
+/**
+ * A trait for stacker
+ *
+ * @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/>.
+ */
+trait StackableTrait {
+ /**
+ * Instance of the stacker
+ */
+ private $stackInstance = NULL;
+
+ /**
+ * Setter for stacker instance
+ *
+ * @param $stackInstance An instance of an stacker
+ * @return void
+ */
+ protected final function setStackInstance (Stackable $stackInstance) {
+ $this->stackInstance = $stackInstance;
+ }
+
+ /**
+ * Getter for stacker instance
+ *
+ * @return $stackInstance An instance of an stacker
+ */
+ public final function getStackInstance () {
+ return $this->stackInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\State;
+
+// Load framework stuff
+use Org\Mxchange\CoreFramework\State\Stateable;
+
+/**
+ * A trait for states
+ *
+ * @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/>.
+ */
+trait StateableTrait {
+ /**
+ * State instance
+ */
+ private $stateInstance = NULL;
+
+ /**
+ * Setter for state instance
+ *
+ * @param $stateInstance A Stateable instance
+ * @return void
+ */
+ public final function setStateInstance (Stateable $stateInstance) {
+ $this->stateInstance = $stateInstance;
+ }
+
+ /**
+ * Getter for state instance
+ *
+ * @return $stateInstance A Stateable instance
+ */
+ public final function getStateInstance () {
+ return $this->stateInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Stream\Input;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Stream\Input\InputStream;
+
+/**
+ * A trait for input stream classes
+ *
+ * @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/>.
+ */
+trait InputStreamTrait {
+ /**
+ * An instance of a InputStream class
+ */
+ private $inputStreamInstance = NULL;
+
+ /**
+ * Getter for a InputStream instance
+ *
+ * @param $inputStreamInstance An instance of an InputStream class
+ */
+ protected final function getInputStreamInstance () {
+ return $this->inputStreamInstance;
+ }
+
+ /**
+ * Setter for a InputStream instance
+ *
+ * @param $inputStreamInstance An instance of an InputStream class
+ * @return void
+ */
+ protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
+ $this->inputStreamInstance = $inputStreamInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Stream\Output;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Stream\Output\OutputStream;
+
+/**
+ * A trait for output stream classes
+ *
+ * @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/>.
+ */
+trait OutputStreamTrait {
+ /**
+ * An instance of a OutputStream class
+ */
+ private $outputStreamInstance = NULL;
+
+ /**
+ * Getter for a OutputStream instance
+ *
+ * @param $outputStreamInstance An instance of an OutputStream class
+ */
+ protected final function getOutputStreamInstance () {
+ return $this->outputStreamInstance;
+ }
+
+ /**
+ * Setter for a OutputStream instance
+ *
+ * @param $outputStreamInstance An instance of an OutputStream class
+ * @return void
+ */
+ protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
+ $this->outputStreamInstance = $outputStreamInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Streamer\File\Input;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Stream\Filesystem\FileInputStreamer;
+
+/**
+ * Trait for file input streamer
+ *
+ * @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/>.
+ */
+trait FileInputStreamerTrait {
+ /**
+ * The *real* file input class we shall use for reading data
+ */
+ private $inputStreamerInstance = NULL;
+
+ /**
+ * Setter for the *real* file input instance
+ *
+ * @param $inputStreamerInstance The *real* file-input class
+ * @return void
+ */
+ public final function setInputStreamerInstance (FileInputStreamer $inputStreamerInstance) {
+ $this->inputStreamerInstance = $inputStreamerInstance;
+ }
+
+ /**
+ * Getter for the *real* file input instance
+ *
+ * @return $inputStreamerInstance The *real* file-input class
+ */
+ public final function getInputStreamerInstance () {
+ return $this->inputStreamerInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Streamer\File\Output;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Stream\Filesystem\FileOutputStreamer;
+
+/**
+ * A trait for file output streamer
+ *
+ * @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/>.
+ */
+trait FileOutputStreamerTrait {
+ /**
+ * The *real* file output class we shall use for reading data
+ */
+ private $outputStreamerInstance = NULL;
+
+ /**
+ * Setter for the *real* file output instance
+ *
+ * @param $outputStreamerInstance The *real* file-output class
+ * @return void
+ */
+ public final function setOutputStreamerInstance (FileOutputStreamer $outputStreamerInstance) {
+ $this->outputStreamerInstance = $outputStreamerInstance;
+ }
+
+ /**
+ * Getter for the *real* file output instance
+ *
+ * @return $outputStreamerInstance The *real* file-output class
+ */
+ public final function getOutputStreamerInstance () {
+ return $this->outputStreamerInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Streamer\Output;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
+
+/**
+ * A trait for output streamer instance
+ *
+ * @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/>.
+ */
+trait OutputStreamerTrait {
+ /**
+ * The concrete output instance
+ */
+ private $outputInstance = NULL;
+
+ /**
+ * Setter for output instance
+ *
+ * @param $outputInstance The debug output instance
+ * @return void
+ */
+ protected final function setOutputInstance (OutputStreamer $outputInstance) {
+ $this->outputInstance = $outputInstance;
+ }
+
+ /**
+ * Getter for output instance
+ *
+ * @return $outputInstance The debug output instance
+ */
+ protected final function getOutputInstance () {
+ return $this->outputInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Template;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
+
+/**
+ * A trait for compileable templates
+ *
+ * @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/>.
+ */
+trait CompileableTemplateTrait {
+ /**
+ * Template engine instance
+ */
+ private $templateInstance = NULL;
+
+ /**
+ * Setter for template engine instances
+ *
+ * @param $templateInstance An instance of a CompileableTemplate class
+ * @return void
+ */
+ public final function setTemplateInstance (CompileableTemplate $templateInstance) {
+ $this->templateInstance = $templateInstance;
+ }
+
+ /**
+ * Getter for template engine instances
+ *
+ * @return $templateInstance An instance of a CompileableTemplate class
+ */
+ public final function getTemplateInstance () {
+ return $this->templateInstance;
+ }
+
+}
--- /dev/null
+<?php
+// Own namespace
+namespace Org\Mxchange\CoreFramework\Traits\Visitor;
+
+// Import framework stuff
+use Org\Mxchange\CoreFramework\Visitor\Visitor;
+
+/**
+ * A trait for visitors
+ *
+ * @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/>.
+ */
+trait VisitorTrait {
+ /**
+ * Visitor handler instance
+ */
+ private $visitorInstance = NULL;
+
+ /**
+ * Setter for visitor instance
+ *
+ * @param $visitorInstance An instance of a Visitor class
+ * @return void
+ */
+ protected final function setVisitorInstance (Visitor $visitorInstance) {
+ $this->visitorInstance = $visitorInstance;
+ }
+
+ /**
+ * Getter for visitor instance
+ *
+ * @return $visitorInstance An instance of a Visitor class
+ */
+ protected final function getVisitorInstance () {
+ return $this->visitorInstance;
+ }
+
+}
// Import framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
-use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
use Org\Mxchange\CoreFramework\Localization\LanguageSystem;
+use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
use Org\Mxchange\CoreFramework\Loader\ClassLoader;
use Org\Mxchange\CoreFramework\Generic\FrameworkException;
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2021 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.shipsimu.org
*
* @return void
* @todo This method is old code and needs heavy rewrite and should be moved to ApplicationHelper
*/
- public static final function exitApplication ($message = '', $code = false, $extraData = '', $silentMode = false) {
+ public static final function exitApplication (string $message = '', int $code = -1, string $extraData = '', bool $silentMode = false) {
// Is this method already called?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: message=%s,code=%d,extraData=%s,silentMode=%d - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $message, $code, $extraData, intval($silentMode));
if (isset($GLOBALS['app_die_called'])) {
// Then output the text directly
- exit($message);
- } // END - if
+ print $message . PHP_EOL;
+ exit(255);
+ }
// This method shall not be called twice
$GLOBALS['app_die_called'] = true;
if (empty($message)) {
// No message provided
$message = 'No message provided.';
- } // END - if
+ }
// Get config instance
$configInstance = FrameworkBootstrap::getConfigurationInstance();
// Do we have debug installation?
if (($configInstance->getConfigEntry('product_install_mode') == 'productive') || ($silentMode === true)) {
// Abort here
- exit();
- } // END - if
+ //* NOISY-DEBUG: */ printf('[%s:%d]: product_install_mode=%d,silentMode=%d - EXIT!' . PHP_EOL, __METHOD__, __LINE__, $configInstance->getConfigEntry('product_install_mode'), intval($silentMode));
+ exit(255);
+ }
// Get some instances
- $tpl = $configInstance->getConfigEntry('html_template_class');
+ $templateClassName = $configInstance->getConfigEntry('html_template_class');
$languageInstance = LanguageSystem::getSelfInstance();
// Initialize template instance here to avoid warnings in IDE
$responseInstance = FrameworkBootstrap::getResponseInstance();
// Is the template engine loaded?
- if ((class_exists($tpl)) && (is_object($languageInstance))) {
+ if ((class_exists($templateClassName)) && ($languageInstance instanceof ManageableLanguage)) {
// Use the template engine for putting out (nicer look) the message
try {
// Get the template instance from our object factory
- $templateInstance = ObjectFactory::createObjectByName($tpl);
+ $templateInstance = ObjectFactory::createObjectByName($templateClassName);
} catch (FrameworkException $e) {
exit(sprintf('[Main:] Could not initialize template engine for reason: <span class="exception_reason">%s</span>',
$e->getMessage()
}
// Get and prepare backtrace for output
- $backtraceArray = debug_backtrace();
$backtrace = '';
- foreach ($backtraceArray as $key => $trace) {
+ foreach (debug_backtrace() as $key => $trace) {
// Set missing array elements
if (!isset($trace['file'])) {
$trace['file'] = __FILE__;
- } // END - if
+ }
if (!isset($trace['line'])) {
$trace['line'] = __LINE__;
- } // END - if
+ }
if (!isset($trace['args'])) {
$trace['args'] = array();
- } // END - if
+ }
// Add the traceback path to the final output
$backtrace .= sprintf('<span class="backtrace_file">%s</span>:%d, <span class="backtrace_function">%s(%d)</span><br />' . PHP_EOL,
$trace['function'],
count($trace['args'])
);
- } // END - foreach
+ }
// Init application instance
$applicationInstance = NULL;
- // Is the class there?
+ /*
+ * The following class may NOT be loaded at all times. For example,
+ * it might be the (rare) case that an error has happened BEFORE
+ * that class had been loaded and cannot be loaded or else an
+ * infinte loop in invoking this method will take place resulting in
+ * a stack-overflow error.
+ */
if (class_exists('Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper')) {
// Get application instance
$applicationInstance = ApplicationHelper::getSelfInstance();
// Assign application data
$templateInstance->assignApplicationData();
- } // END - if
+ }
// We only try this
try {
// Assign variables
- $templateInstance->assignVariable('message', $message);
- $templateInstance->assignVariable('code', $code);
- $templateInstance->assignVariable('extra', $extraData);
- $templateInstance->assignVariable('backtrace', $backtrace);
+ $templateInstance->assignVariable('message' , $message);
+ $templateInstance->assignVariable('code' , $code);
+ $templateInstance->assignVariable('extra' , $extraData);
+ $templateInstance->assignVariable('backtrace' , $backtrace);
$templateInstance->assignVariable('total_includes', ClassLoader::getSelfInstance()->getTotal());
- $templateInstance->assignVariable('total_objects', ObjectFactory::getTotal());
- $templateInstance->assignVariable('title', $languageInstance->getMessage('emergency_exit_title'));
+ $templateInstance->assignVariable('total_objects' , ObjectFactory::getTotal());
+ $templateInstance->assignVariable('title' , $languageInstance->getMessage('emergency_exit_title'));
// Load the template
$templateInstance->loadCodeTemplate('emergency_exit');
$responseInstance->flushBuffer();
} catch (FileNotFoundException $e) {
// Even the template 'emergency_exit' wasn't found so output both message
- exit($message . ', exception: ' . $e->getMessage());
+ print ($message . ', exception: ' . $e->getMessage() . PHP_EOL);
+ exit($e->getCode());
}
// Good bye...
- exit();
+ exit(255);
} else {
// Output message and die
- exit(sprintf('[Main:] Emergency exit reached: <span class="emergency_span">%s</span>',
- $message
- ));
+ printf('[Main:] Emergency exit reached: <span class="emergency_span">%s</span>', $message);
+ exit(255);
}
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
/**
*/
public static final function detectFrameworkPath () {
// Is it not set?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::frameworkPath=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, self::$frameworkPath);
if (empty(self::$frameworkPath)) {
// Auto-detect core path (first application-common)
- foreach (array('core', __DIR__, '/usr/local/share/php/core', '/usr/share/php/core') as $possiblePath) {
+ foreach (['core', self::getRootPath(), '/usr/local/share/php/core', '/usr/share/php/core'] as $possiblePath) {
// Create full path for testing
+ //* NOISY-DEBUG: */ printf('[%s:%d]: possiblePath=%s' . PHP_EOL, __METHOD__, __LINE__, $possiblePath);
$realPath = realpath($possiblePath);
- // Debug message
- //* NOISY-DEBUG: */ printf('[%s:%d]: realPath[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($realPath), $realPath);
-
// Is it false?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: realPath[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($realPath), $realPath);
if ($realPath === false) {
// Then, not found.
+ //* NOISY-DEBUG: */ printf('[%s:%d]: possiblePath=%s was not found. - SKIPPED!' . PHP_EOL, __METHOD__, __LINE__, $possiblePath);
continue;
- } // END - if
+ }
// Append framework path
$frameworkPath = sprintf('%s%sframework%s', $realPath, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR);
// First create full-qualified file name (FQFN) to framework/config-global.php
+ //* NOISY-DEBUG: */ printf('[%s:%d]: frameworkPath=%s' . PHP_EOL, __METHOD__, __LINE__, $frameworkPath);
$configFile = $frameworkPath . 'config-global.php';
- // Debug message
- //* NOISY-DEBUG: */ printf('[%s:%d]: configFile=%s' . PHP_EOL, __METHOD__, __LINE__, $configFile);
-
// Is it readable?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: configFile=%s' . PHP_EOL, __METHOD__, __LINE__, $configFile);
if (is_readable($configFile)) {
// Found one
self::$frameworkPath = $frameworkPath;
// Abort here
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Setting self::frameworkPath=%s - BREAK!' . PHP_EOL, __METHOD__, __LINE__, $frameworkPath);
break;
- } // END - if
- } // END - foreach
+ }
+ }
// Able to find?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::frameworkPath=%s - Checking ...' . PHP_EOL, __METHOD__, __LINE__, self::$frameworkPath);
if (!is_dir(self::$frameworkPath)) {
// Is no directory
throw new Exception('Cannot find framework.');
- } // END - if
- } // END - if
+ }
+ }
// Return it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::frameworkPath=%s - EXIT!' . PHP_EOL, __METHOD__, __LINE__, self::$frameworkPath);
return self::$frameworkPath;
}
*/
public static final function main () {
// Load bootstrap file
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
require sprintf('%sbootstrap%sbootstrap.inc.php', self::detectFrameworkPath(), DIRECTORY_SEPARATOR);
/*
* register the application instance in registry.
*/
FrameworkBootstrap::startApplication();
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
}
-// Developer mode active? Comment out if no dev!
-define('DEVELOPER', true);
-
// Log all exceptions (only debug! This option can create large error logs)
//define('LOG_EXCEPTIONS', true);
-//xdebug_start_trace();
-
// Call above main() method
ApplicationEntryPoint::main();
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
/*
- * Copyright (C) 2017 Roland Haeder<roland@mxchange.org>
+ * Copyright (C) 2017 - 2023 Core Developer Team
*
* 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
if (extension_loaded('xdebug')) {
// Quiet it a bit as this interfers with the nice testing output
ini_set('xdebug.show_exception_trace', FALSE);
-} // END - if
+}
// Autoload more stuff
require dirname(__DIR__) . '/vendor/autoload.php';
// Quiet DNS resolver as this is not wanted here
-FrameworkBootstrap::getConfigurationInstance()->setConfigEntry('quiet_dns_resolver', TRUE);
+FrameworkBootstrap::getConfigurationInstance()->setConfigEntry('is_quiet_dns_resolver_enabled', TRUE);
<?php
-
// Same namespace as target class
namespace Org\Mxchange\CoreFramework\Bootstrap;
// Inport framework stuff
use Org\Mxchange\CoreFramework\Console\Tools\ConsoleTools;
-use Org\Mxchange\CoreFramework\Loader\ClassLoader;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
+use Org\Mxchange\CoreFramework\Loader\ClassLoader;
// Import PHPUnit stuff
use PHPUnit\Framework\Error\Notice;
// Import SPL stuff
use \InvalidArgumentException;
+use \SplFileInfo;
/*
- * Copyright (C) 2017 Roland Haeder<roland@mxchange.org>
+ * Copyright (C) 2017 - 2023 Core Developer Team
*
* 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
/**
* Own IP address
*/
- private static $ipAddress = FALSE;
+ private static $ipAddress = '0.0.0.0';
+
+ /**
+ * Own host name
+ */
+ private static $hostname = 'host.invalid';
/**
* Setup test case
// Trace message
//* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
-
}
/**
* Setup test case
*/
public static function setUpBeforeClass() {
- // Trace message
- //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
-
// Call parent method
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
parent::setUpBeforeClass();
- /*
- * Disable strict naming-convention check in own class loader, because
- * PHP_Invoker doesn't have namespaces.
- */
- ClassLoader::enableStrictNamingConventionCheck(FALSE);
+ // Lookup own hostname
+ self::$hostname = ConsoleTools::acquireHostname();
// Lookup own IP address
self::$ipAddress = ConsoleTools::acquireSelfIpAddress();
// Trace message
- //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
- }
-
- /**
- * Tests setting a NULL default timezone
- */
- public function testSettingNullDefaultTimezone () {
- // Will throw this exception
- $this->expectException(NullPointerException::class);
-
- // Test it
- FrameworkBootstrap::setDefaultTimezone(NULL);
- }
-
- /**
- * Tests setting a boolean default timezone
- */
- public function testSettingBooleanDefaultTimezone () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- FrameworkBootstrap::setDefaultTimezone(FALSE);
- }
-
- /**
- * Tests setting a decimal default timezone
- */
- public function testSettingDecimalDefaultTimezone () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- FrameworkBootstrap::setDefaultTimezone(12345);
- }
-
- /**
- * Tests setting a float default timezone
- */
- public function testSettingFloatDefaultTimezone () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- FrameworkBootstrap::setDefaultTimezone(123.45);
- }
-
- /**
- * Tests setting an array default timezone
- */
- public function testSettingArrayDefaultTimezone () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- FrameworkBootstrap::setDefaultTimezone(array());
- }
-
- /**
- * Tests setting an object default timezone
- */
- public function testSettingObjectDefaultTimezone () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- FrameworkBootstrap::setDefaultTimezone($this);
- }
-
- /**
- * Tests setting a resource default timezone
- */
- public function testSettingResourceDefaultTimezone () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Init some resource
- $resource = fopen(__FILE__, 'r');
-
- // Test it
- FrameworkBootstrap::setDefaultTimezone($resource);
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::ipAddress[%s]=%s,self::hostname=%s - EXIT!' . PHP_EOL, __METHOD__, __LINE__, gettype(self::$ipAddress), self::$ipAddress, self::$hostname);
}
/**
* Tests if detectServerAddress() is returning what it should for tests.
* This will always be 127.0.0.1.
*/
- public function testConfigDetectServerAddress () {
+ public function testBootstrapDetectServerAddress () {
// Call it
$serverAddress = FrameworkBootstrap::detectServerAddress();
/**
* Re-tests if detectServerAddress() is returning what it should for tests.
- * This will always be 127.0.0.1. This call should not invoke
+ * This will always be 127.0.0.1. This method should not invoke
* ConsoleTools's method as the configuration entry is already cached.
*/
- public function testConfigDetectServerAddressCached () {
+ public function testBootstrapDetectServerAddressCached () {
// Call it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
$serverAddress = FrameworkBootstrap::detectServerAddress();
// Should be the same
+ //* NOISY-DEBUG: */ printf('[%s:%d]: self::ipAddress=%s,serverAddress=%s' . PHP_EOL, __METHOD__, __LINE__, self::$ipAddress, $serverAddress);
$this->assertEquals(self::$ipAddress, $serverAddress);
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
+ }
+
+ /**
+ * Tests method BootstrapFramework::isReachableFilePath() with a
+ * non-existing path. $isReachable should always return TRUE as nothing is
+ * restricting PHP.
+ */
+ public function testBootstrapIsReachableFilePathUnrestrictedNotExisting () {
+ // Init SPL file info instance
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
+ $infoInstance = new SplFileInfo('/does/not/exist/');
+
+ // Invoke method
+ //* NOISY-DEBUG: */ printf('[%s:%d]: infoInstance=%s' . PHP_EOL, __METHOD__, __LINE__, get_class($infoInstance));
+ $isReachable = FrameworkBootstrap::isReachableFilePath($infoInstance);
+
+ // Test if it is not reachable
+ //* NOISY-DEBUG: */ printf('[%s:%d]: isReachable=%d' . PHP_EOL, __METHOD__, __LINE__, intval($isReachable));
+ $this->assertTrue($isReachable, 'Returned true on a non-existing path');
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
+ }
+
+ /**
+ * Tests method BootstrapFramework::isReachableFilePath() with a
+ * non-existing path. $isReachable should be FALSE here as it is always
+ * outside the scope of open_basedir.
+ */
+ public function testBootstrapIsReachableFilePathRestrictedNotExisting () {
+ // Init SPL file info instance
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
+ $infoInstance = new SplFileInfo('/does/not/exist/');
+
+ // "Detect" root path
+ //* NOISY-DEBUG: */ printf('[%s:%d]: infoInstance=%s' . PHP_EOL, __METHOD__, __LINE__, get_class($infoInstance));
+ $rootScriptPath = realpath(dirname(dirname(FrameworkBootstrap::detectScriptPath())));
+
+ // Set it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: open_basedir=%s,rootScriptPath[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, ini_get('open_basedir'), gettype($rootScriptPath), $rootScriptPath);
+ $result = ini_set('open_basedir', $rootScriptPath . ':/etc/');
+
+ // Was it set?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: result[]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($result));
+ if ($result === FALSE) {
+ // Didn't work
+ $this->failed(sprintf('Cannot set open_basepath=%s', $rootScriptPath));
+ }
+
+ // Invoke method
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Testing method FrameworkBootstrap::isReachableFilePath(%s) ...' . PHP_EOL, __METHOD__, __LINE__, get_class($infoInstance));
+ $isReachable = FrameworkBootstrap::isReachableFilePath($infoInstance);
+
+ // Test if
+ //* NOISY-DEBUG: */ printf('[%s:%d]: isReachable=%d - Testing method ...' . PHP_EOL, __METHOD__, __LINE__, intval($isReachable));
+ $this->assertTrue(!$isReachable, 'Returned true on a non-existing path');
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
+ }
+
+ /**
+ * Tests method BootstrapFramework::isReachableFilePath() with an
+ * existing path. $isReachable should be TRUE here as it is within the scope
+ * of open_basedir.
+ */
+ public function testBootstrapIsReachableFilePathRestrictedExisting () {
+ // Init SPL file info instance
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
+ $infoInstance = new SplFileInfo(__DIR__);
+
+ // "Detect" root path
+ //* NOISY-DEBUG: */ printf('[%s:%d]: infoInstance=%s' . PHP_EOL, __METHOD__, __LINE__, get_class($infoInstance));
+ $rootScriptPath = realpath(dirname(dirname(FrameworkBootstrap::detectScriptPath())));
+
+ // Set it
+ //* NOISY-DEBUG: */ printf('[%s:%d]: rootScriptPath[%s]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($rootScriptPath), $rootScriptPath);
+ $result = ini_set('open_basedir', $rootScriptPath . ':/etc/');
+
+ // Was it set?
+ //* NOISY-DEBUG: */ printf('[%s:%d]: result[]=%s' . PHP_EOL, __METHOD__, __LINE__, gettype($result));
+ if ($result === FALSE) {
+ // Didn't work
+ $this->failed(sprintf('Cannot set open_basepath=%s', $rootScriptPath));
+ }
+
+ // Invoke method
+ //* NOISY-DEBUG: */ printf('[%s:%d]: Testing method FrameworkBootstrap::isReachableFilePath(%s) ...' . PHP_EOL, __METHOD__, __LINE__, get_class($infoInstance));
+ $isReachable = FrameworkBootstrap::isReachableFilePath($infoInstance);
+
+ // Test if
+ //* NOISY-DEBUG: */ printf('[%s:%d]: isReachable=%d - Testing method ...' . PHP_EOL, __METHOD__, __LINE__, intval($isReachable));
+ $this->assertTrue($isReachable, 'Returned true on a non-existing path');
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
}
// Inport framework stuff
use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
use Org\Mxchange\CoreFramework\Configuration\FrameworkConfiguration;
-use Org\Mxchange\CoreFramework\Loader\ClassLoader;
+use Org\Mxchange\CoreFramework\Configuration\NoConfigEntryException;
use Org\Mxchange\CoreFramework\Generic\NullPointerException;
use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
// Import PHPUnit stuff
-use PHPUnit\Framework\Error\Notice;
use PHPUnit\Framework\TestCase;
// Import SPL stuff
use \InvalidArgumentException;
+use \UnexpectedValueException;
/*
- * Copyright (C) 2017 Roland Haeder<roland@mxchange.org>
+ * Copyright (C) 2017 - 2020 - Core Developer Team
*
* 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
// Init instance
self::$configInstance = FrameworkBootstrap::getConfigurationInstance();
- /*
- * Disable strict naming-convention check in own class loader, because
- * PHP_Invoker doesn't have namespaces.
- */
- ClassLoader::enableStrictNamingConventionCheck(FALSE);
-
// Trace message
//* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
}
$this->assertEquals($config1, $config2);
}
- /**
- * Tests if a proper exception is thrown when check for a NULL key
- */
- public function testCheckingNullConfigKey () {
- // Will throw this exception
- $this->expectException(NullPointerException::class);
-
- // Test it
- $dummy = self::$configInstance->isConfigurationEntrySet(NULL);
- }
-
- /**
- * Tests if a proper exception is thrown when checking a boolean key
- */
- public function testCheckingBooleanConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- $dummy = self::$configInstance->isConfigurationEntrySet(FALSE);
- }
-
/**
* Tests if a proper exception is thrown when checking an empty key
*/
$dummy = self::$configInstance->isConfigurationEntrySet('');
}
- /**
- * Tests if a proper exception is thrown when checking an array key
- */
- public function testCheckingArrayConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- $dummy = self::$configInstance->isConfigurationEntrySet(array());
- }
-
- /**
- * Tests if a proper exception is thrown when checking a decimal key
- */
- public function testCheckingDecimalConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- $dummy = self::$configInstance->isConfigurationEntrySet(12345);
- }
-
- /**
- * Tests if a proper exception is thrown when checking a float key
- */
- public function testCheckingFloatConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- $dummy = self::$configInstance->isConfigurationEntrySet(123.45);
- }
-
- /**
- * Tests if a proper exception is thrown when checking an object key
- */
- public function testCheckingObjectConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- $dummy = self::$configInstance->isConfigurationEntrySet($this);
- }
-
- /**
- * Tests if a proper exception is thrown when checking a resource key
- */
- public function testCheckingResourceConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Init some resource
- $resource = fopen(__FILE__, 'r');
-
- // Test it
- $dummy = self::$configInstance->isConfigurationEntrySet($resource);
- }
-
/**
* Tests if checking an existing (well-known) key can be found and returns
* TRUE.
$this->assertFalse(self::$configInstance->isConfigurationEntrySet('__non_existing_key__'));
}
- /**
- * Tests if a proper exception is thrown when getting a NULL key
- */
- public function testGettingNullConfigKey () {
- // Will throw this exception
- $this->expectException(NullPointerException::class);
-
- // Test it
- $dummy = self::$configInstance->getConfigEntry(NULL);
- }
-
- /**
- * Tests if a proper exception is thrown when getting a boolean key
- */
- public function testGettingBooleanConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- $dummy = self::$configInstance->getConfigEntry(FALSE);
- }
-
/**
* Tests if a proper exception is thrown when getting an empty key
*/
$dummy = self::$configInstance->getConfigEntry('');
}
- /**
- * Tests if a proper exception is thrown when getting a decimal key
- */
- public function testGettingDecimalConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- $dummy = self::$configInstance->getConfigEntry(12345);
- }
-
- /**
- * Tests if a proper exception is thrown when getting a float key
- */
- public function testGettingFloatConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- $dummy = self::$configInstance->getConfigEntry(123.45);
- }
-
- /**
- * Tests if a proper exception is thrown when getting an array key
- */
- public function testGettingArrayConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- $dummy = self::$configInstance->getConfigEntry(array());
- }
-
- /**
- * Tests if a proper exception is thrown when getting an object key
- */
- public function testGettingObjectConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- $dummy = self::$configInstance->getConfigEntry($this);
- }
-
- /**
- * Tests if a proper exception is thrown when getting a resource key
- */
- public function testGettingResourceConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Init some resource
- $resource = fopen(__FILE__, 'r');
-
- // Test it
- $dummy = self::$configInstance->getConfigEntry($resource);
- }
-
/**
* Tests if getting a non-existing key will cause a proper exception been
* thrown.
$this->assertDirectoryIsReadable($value);
}
- /**
- * Tests setting a NULL key (value doesn't matter)
- */
- public function testSettingNullConfigKey () {
- // Will throw this exception
- $this->expectException(NullPointerException::class);
-
- // Test it
- self::$configInstance->setConfigEntry(NULL, 'foo');
- }
-
- /**
- * Tests setting a boolean key (value doesn't matter)
- */
- public function testSettingBooleanConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- self::$configInstance->setConfigEntry(FALSE, 'foo');
- }
-
/**
* Tests setting an empty key (value doesn't matter)
*/
self::$configInstance->setConfigEntry('', 'foo');
}
- /**
- * Tests setting a decimal key (value doesn't matter)
- */
- public function testSettingDecimalConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- self::$configInstance->setConfigEntry(12345, 'foo');
- }
-
- /**
- * Tests setting a float key (value doesn't matter)
- */
- public function testSettingFloatConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- self::$configInstance->setConfigEntry(123.45, 'foo');
- }
-
- /**
- * Tests setting an array key (value doesn't matter)
- */
- public function testSettingArrayConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- self::$configInstance->setConfigEntry(array(), 'foo');
- }
-
- /**
- * Tests setting an object key (value doesn't matter)
- */
- public function testSettingObjectConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- self::$configInstance->setConfigEntry($this, 'foo');
- }
-
- /**
- * Tests setting a resource key (value doesn't matter)
- */
- public function testSettingResourceConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Init some resource
- $resource = fopen(__FILE__, 'r');
-
- // Test it
- self::$configInstance->setConfigEntry($resource, 'foo');
- }
-
/**
* Tests setting a valid key but array for value
*/
self::$configInstance->setConfigEntry('foo', $resource);
}
- /**
- * Tests unsetting NULL key
- */
- public function testUnsettingNullConfigKey () {
- // Will throw this exception
- $this->expectException(NullPointerException::class);
-
- // Test it
- self::$configInstance->unsetConfigEntry(NULL);
- }
-
- /**
- * Tests unsetting boolean key
- */
- public function testUnsettingBooleanConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- self::$configInstance->unsetConfigEntry(FALSE);
- }
-
- /**
- * Tests unsetting decimal key
- */
- public function testUnsettingDecimalConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- self::$configInstance->unsetConfigEntry(12345);
- }
-
- /**
- * Tests unsetting float key
- */
- public function testUnsettingFloatConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- self::$configInstance->unsetConfigEntry(123.45);
- }
-
- /**
- * Tests unsetting array key
- */
- public function testUnsettingArrayConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- self::$configInstance->unsetConfigEntry(array());
- }
-
- /**
- * Tests unsetting object key
- */
- public function testUnsettingObjectConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Test it
- self::$configInstance->unsetConfigEntry($this);
- }
-
- /**
- * Tests unsetting resource key
- */
- public function testUnsettingResourceConfigKey () {
- // Will throw this exception
- $this->expectException(InvalidArgumentException::class);
-
- // Init some resource
- $resource = fopen(__FILE__, 'r');
-
- // Test it
- self::$configInstance->unsetConfigEntry($resource);
- }
-
/**
* Tests unsetting an empty key
*/
$dummy = self::$configInstance->isFieldSet('foo');
}
+ /**
+ * Tests isEnabled() method being called with empty parameter
+ */
+ public function testConfigIsEnabledEmptyString () {
+ // Expect IAE
+ $this->expectException(InvalidArgumentException::class);
+
+ // Just invoke it
+ $dummy = self::$configInstance->isEnabled('');
+ }
+
+ /**
+ * Tests isEnabled() method being called with missing configuration key
+ */
+ public function testConfigIsEnabledMissingConfigKey () {
+ // Expect NoConfig
+ $this->expectException(NoConfigEntryException::class);
+
+ // Just invoke it
+ $dummy = self::$configInstance->isEnabled('does_not_exist');
+ }
+
+ /**
+ * Tests isEnabled() method being called with non-boolean configuration key
+ */
+ public function testConfigIsEnabledNonBooleanConfigKey () {
+ // Expect UVE
+ $this->expectException(UnexpectedValueException::class);
+
+ // Set it temporary
+ self::$configInstance->setConfigEntry('is_non_boolean_enabled', 'Y');
+
+ // Just invoke it
+ $dummy = self::$configInstance->isEnabled('non_boolean');
+ }
+
+ /**
+ * Tests isEnabled() method being called with 'single_server'
+ */
+ public function testConfigIsEnabledSingleServerConfigKey () {
+ // Check it on known boolean value
+ $this->assertTrue(is_bool(self::$configInstance->isEnabled('single_server')));
+ }
+
+ /**
+ * Tests if sorting the configuration array is always returning the same
+ * array (but sorted) back.
+ */
+ public function testConfigSortConfigurationArray () {
+ // First get configuration array
+ //* NOISY-DEBUG: */ printf('[%s:%d]: CALLED!' . PHP_EOL, __METHOD__, __LINE__);
+ $config = self::$configInstance->getConfigurationArray();
+
+ // Run sort method
+ //* NOISY-DEBUG: */ printf('[%s:%d]: config()=%d' . PHP_EOL, __METHOD__, __LINE__, count($config));
+ self::$configInstance->sortConfigurationArray();
+
+ // This should be an empty array
+ $diff = array_diff($config, self::$configInstance->getConfigurationArray());
+
+ // Check condition
+ //* NOISY-DEBUG: */ printf('[%s:%d]: diff()=%d' . PHP_EOL, __METHOD__, __LINE__, count($diff));
+ $this->assertTrue(count($diff) === 0);
+
+ // Trace message
+ //* NOISY-DEBUG: */ printf('[%s:%d]: EXIT!' . PHP_EOL, __METHOD__, __LINE__);
+ }
+
}