Continued:
[core.git] / inc / main / classes / class_BaseFrameworkSystem.php
index a1f970d9aed4a64c9eca2986803e7b256ee60c10..7cd7419b9338f19c33b7df389de080070a4f0a0c 100644 (file)
@@ -1,11 +1,33 @@
 <?php
+// Own namespace
+namespace CoreFramework\Object;
+
+// Import framework stuff
+use CoreFramework\Configuration\FrameworkConfiguration;
+use CoreFramework\Factory\ObjectFactory;
+use CoreFramework\Generic\FrameworkInterface;
+use CoreFramework\Generic\NullPointerException;
+use CoreFramework\Handler\Stream\IoHandler;
+use CoreFramework\Loader\ClassLoader;
+use CoreFramework\Manager\ManageableApplication;
+use CoreFramework\Middleware\Debug\DebugMiddleware;
+use CoreFramework\Registry\Register;
+use CoreFramework\Registry\Generic\Registry;
+use CoreFramework\Request\Requestable;
+use CoreFramework\Response\Responseable;
+use CoreFramework\Stream\Output\OutputStreamer;
+use CoreFramework\Template\CompileableTemplate;
+
+// Import SPL stuff
+use \stdClass;
+
 /**
  * The simulator system class is the super class of all other classes. This
  * class handles saving of games etc.
  *
  * @author             Roland Haeder <webmaster@shipsimu.org>
  * @version            0.0.0
- * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Core Developer Team
+ * @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
  *
@@ -34,12 +56,12 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
        private $realClass = 'BaseFrameworkSystem';
 
        /**
-        * Instance of a request class
+        * Instance of a Requestable class
         */
        private $requestInstance = NULL;
 
        /**
-        * Instance of a response class
+        * Instance of a Responseable class
         */
        private $responseInstance = NULL;
 
@@ -458,7 +480,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                        $this->setRealClass('DestructedObject');
                } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
                        // Already destructed object
-                       self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
+                       self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
                                __CLASS__,
                                $this->__toString()
                        ));
@@ -488,6 +510,9 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         * @return      void
         */
        public static final function __callStatic ($methodName, $args) {
+               // Trace message
+               //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
+
                // Init argument string
                $argsString = '';
 
@@ -548,7 +573,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
 
                // Output stub message
                // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
-               self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
+               self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
                        $methodName,
                        $argsString
                ));
@@ -1182,7 +1207,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         * @return      void
         */
        public final function setSocketResource ($socketResource) {
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
                $this->socketResource = $socketResource;
        }
 
@@ -1192,7 +1217,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         * @return      $socketResource         A valid socket resource
         */
        public final function getSocketResource () {
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
                return $this->socketResource;
        }
 
@@ -1203,7 +1228,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         * @return      void
         */
        public final function setRegularExpression ($regularExpression) {
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
                $this->regularExpression = $regularExpression;
        }
 
@@ -1213,7 +1238,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         * @return      $regularExpression      A valid regular expression
         */
        public final function getRegularExpression () {
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
                return $this->regularExpression;
        }
 
@@ -1842,7 +1867,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                // Debug instance is there?
                if (!is_null($this->getDebugInstance())) {
                        // Output stub message
-                       self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
+                       self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
                } else {
                        // Trigger an error
                        trigger_error($stubMessage);
@@ -1878,10 +1903,11 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         * Creates an instance of a debugger instance
         *
         * @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
         * @deprecated  Not fully, as the new Logger facilities are not finished yet.
         */
-       public final static function createDebugInstance ($className) {
+       public final static function createDebugInstance ($className, $lineNumber = NULL) {
                // Is the instance set?
                if (!Registry::getRegistry()->instanceExists('debug')) {
                        // Init debug instance
@@ -1893,7 +1919,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                                $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
                        } catch (NullPointerException $e) {
                                // Didn't work, no instance there
-                               exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
+                               exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
                        }
 
                        // Empty string should be ignored and used for testing the middleware
@@ -2166,7 +2192,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
 
                // Get current array
                $fieldArray = $resultInstance->current();
-               //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
+               //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
 
                // Convert dashes to underscore
                $fieldName2 = self::convertDashesToUnderscores($fieldName);
@@ -2177,10 +2203,10 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                        $fieldValue = $fieldArray[$fieldName2];
                } elseif (defined('DEVELOPER')) {
                        // Missing field entry, may require debugging
-                       self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
+                       self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
                } else {
                        // Missing field entry, may require debugging
-                       self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
+                       self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
                }
 
                // Return it
@@ -2206,7 +2232,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
 
                // Get current array
                $fieldArray = $resultInstance->current();
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
 
                // Convert dashes to underscore
                $fieldName = self::convertDashesToUnderscores($fieldName);
@@ -2253,7 +2279,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                        // Debug instance is there?
                        if (!is_null($this->getDebugInstance())) {
                                // Output stub message
-                               self::createDebugInstance(__CLASS__)->debugOutput($message);
+                               self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
                        } else {
                                // Trigger an error
                                trigger_error($message . "<br />\n");
@@ -2441,7 +2467,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         */
        protected function hex2asc ($hex) {
                // Check for length, it must be devideable by 2
-               //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
+               //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
                assert((strlen($hex) % 2) == 0);
 
                // Walk the string
@@ -2509,7 +2535,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                );
 
                // And return it
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
                return $cacheKey;
        }
 
@@ -3292,7 +3318,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         */
        protected function packString ($str) {
                // Debug message
-               //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
+               //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
 
                // First compress the string (gzcompress is okay)
                $str = gzcompress($str);
@@ -3327,7 +3353,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                } // END - for
 
                // Return it
-               //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');
+               //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
                return $packed;
        }
 
@@ -3450,6 +3476,7 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
         * @return      void
         * @throws      InvalidSocketException  If $socketResource is no socket resource
         * @throws      NoSocketErrorDetectedException  If socket_last_error() gives zero back
+        * @todo        Move all this socket-related stuff into own class, most of it resides in BaseListener
         */
        protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
                // This method handles only socket resources
@@ -3482,174 +3509,4 @@ class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
                socket_clear_error($socketResource);
        }
 
-       /**
-        * Constructs a callable method name from given socket error code. If the
-        * method is not found, a generic one is used.
-        *
-        * @param       $errorCode              Error code from socket_last_error()
-        * @return      $handlerName    Call-back method name for the error handler
-        * @throws      UnsupportedSocketErrorHandlerException If the error handler is not implemented
-        */
-       protected function getSocketErrorHandlerFromCode ($errorCode) {
-               // Create a name from translated error code
-               $handlerName = 'socketError' . self::convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
-
-               // Is the call-back method there?
-               if (!method_exists($this, $handlerName)) {
-                       // Please implement this
-                       throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), BaseConnectionHelper::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
-               } // END - if
-
-               // Return it
-               return $handlerName;
-       }
-
-       /**
-        * Translates socket error codes into our own internal names which can be
-        * used for call-backs.
-        *
-        * @param       $errorCode      The error code from socket_last_error() to be translated
-        * @return      $errorName      The translated name (all lower-case, with underlines)
-        */
-       public function translateSocketErrorCodeToName ($errorCode) {
-               // Nothing bad happened by default
-               $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
-
-               // Is the code a number, then we have to change it
-               switch ($errorCode) {
-                       case 0: // Silently ignored, the socket is connected
-                               break;
-
-                       case 11:  // "Resource temporary unavailable"
-                               $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
-                               break;
-
-                       case 13:  // "Permission denied"
-                               $errorName = BaseRawDataHandler::SOCKET_ERROR_PERMISSION_DENIED;
-                               break;
-
-                       case 32:  // "Broken pipe"
-                               $errorName = BaseRawDataHandler::SOCKET_ERROR_BROKEN_PIPE;
-                               break;
-
-                       case 104: // "Connection reset by peer"
-                               $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
-                               break;
-
-                       case 107: // "Transport end-point not connected"
-                       case 134: // On some (?) systems for 'transport end-point not connected'
-                               // @TODO On some systems it is 134, on some 107?
-                               $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
-                               break;
-
-                       case 110: // "Connection timed out"
-                               $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
-                               break;
-
-                       case 111: // "Connection refused"
-                               $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
-                               break;
-
-                       case 113: // "No route to host"
-                               $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
-                               break;
-
-                       case 114: // "Operation already in progress"
-                               $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
-                               break;
-
-                       case 115: // "Operation now in progress"
-                               $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
-                               break;
-
-                       default: // Everything else <> 0
-                               // Unhandled error code detected, so first debug it because we may want to handle it like the others
-                               self::createDebugInstance(__CLASS__)->debugOutput('BASE-HUB[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
-
-                               // Change it only in this class
-                               $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
-                               break;
-               }
-
-               // Return translated name
-               return $errorName;
-       }
-
-       /**
-        * Shuts down a given socket resource. This method does only ease calling
-        * the right visitor.
-        *
-        * @param       $socketResource         A valid socket resource
-        * @return      void
-        */
-       public function shutdownSocket ($socketResource) {
-               // Debug message
-               self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
-
-               // Set socket resource
-               $this->setSocketResource($socketResource);
-
-               // Get a visitor instance
-               $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
-
-               // Debug output
-               self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
-
-               // Call the visitor
-               $this->accept($visitorInstance);
-       }
-
-       /**
-        * Half-shuts down a given socket resource. This method does only ease calling
-        * an other visitor than shutdownSocket() does.
-        *
-        * @param       $socketResource         A valid socket resource
-        * @return      void
-        */
-       public function halfShutdownSocket ($socketResource) {
-               // Debug message
-               self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
-
-               // Set socket resource
-               $this->setSocketResource($socketResource);
-
-               // Get a visitor instance
-               $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
-
-               // Debug output
-               self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
-
-               // Call the visitor
-               $this->accept($visitorInstance);
-       }
-
-       // ************************************************************************
-       //                 Socket error handler call-back methods
-       // ************************************************************************
-
-       /**
-        * Handles socket error 'permission denied', but does not clear it for
-        * later debugging purposes.
-        *
-        * @param       $socketResource         A valid socket resource
-        * @param       $socketData                     A valid socket data array (0 = IP/file name, 1 = port)
-        * @return      void
-        * @throws      SocketBindingException  The socket could not be bind to
-        */
-       protected function socketErrorPermissionDeniedHandler ($socketResource, array $socketData) {
-               // Get socket error code for verification
-               $socketError = socket_last_error($socketResource);
-
-               // Get error message
-               $errorMessage = socket_strerror($socketError);
-
-               // Shutdown this socket
-               $this->shutdownSocket($socketResource);
-
-               // Throw it again
-               throw new SocketBindingException(array($this, $socketData, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
-       }
 }
-
-// [EOF]
-?>