current state as framework

This commit is contained in:
coderkun 2013-08-09 02:41:06 +02:00
commit 8cd746750a
56 changed files with 5981 additions and 0 deletions

30
.htaccess Normal file
View file

@ -0,0 +1,30 @@
Allow From All
Options -Indexes -MultiViews
ErrorDocument 403 /www/error403.html
ErrorDocument 404 /www/error404.html
ErrorDocument 500 /www/error500.html
<Files ~ "\.inc$">
Order Deny,Allow
Deny From All
</Files>
<Files ~ "\.tpl$">
Order Deny,Allow
Deny From All
</Files>
<Files ~ "\.log$">
Order Deny,Allow
Deny From All
</Files>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^(.*)$ www/$1 [L]
</IfModule>

View file

@ -0,0 +1,53 @@
<?php
/**
* NRE
*
* @author coderkun <olli@coderkun.de>
* @copyright 2013 coderkun (http://www.coderkun.de)
* @license http://www.gnu.org/licenses/gpl.html
* @link http://www.coderkun.de/projects/nre
*/
namespace nre\agents;
/**
* The BottomlevelAgent is the standard Agent and can have indefinite
* SubAgents.
*
* @author coderkun <olli@coderkun.de>
*/
abstract class BottomlevelAgent extends \nre\core\Agent
{
/**
* Load a BottomlevelAgent.
*
* @throws AgentNotFoundException
* @throws AgentNotValidException
* @param string $agentName BottomlevelAgent name
*/
public static function load($agentName)
{
// Load class
parent::load_agent($agentName, Autoloader::getClassName(get_class()));
// Determine full classname
$className = Autoloader::concatClassNames($agentName, Autoloader::getClassType(get_class()));
// Validate class
try {
ClassLoader::check($className, get_class());
}
catch(ClassNotValidException $e) {
throw new AgentNotValidException($e->getClassName());
}
}
}
?>

View file

@ -0,0 +1,48 @@
<?php
/**
* NRE
*
* @author coderkun <olli@coderkun.de>
* @copyright 2013 coderkun (http://www.coderkun.de)
* @license http://www.gnu.org/licenses/gpl.html
* @link http://www.coderkun.de/projects/nre
*/
namespace nre\agents;
/**
* The IntermediateAgent assumes the task of a module. There is only one
* IntermediateAgent per request.
*
* @author coderkun <olli@coderkun.de>
*/
abstract class IntermediateAgent extends \nre\core\Agent
{
/**
* Get the layout if it was explicitly defined.
*
* @return string Layout of the IntermediateAgent
*/
public static function getLayout($agentName)
{
// Determine classname
$className = Autoloader::concatClassNames($agentName, 'Agent');
// Check property
if(isset($className::$layout)) {
return $className::$layout;
}
return null;
}
}
?>

379
agents/ToplevelAgent.inc Normal file
View file

@ -0,0 +1,379 @@
<?php
/**
* NRE
*
* @author coderkun <olli@coderkun.de>
* @copyright 2013 coderkun (http://www.coderkun.de)
* @license http://www.gnu.org/licenses/gpl.html
* @link http://www.coderkun.de/projects/nre
*/
namespace nre\agents;
/**
* The ToplevelAgent assumes the task of a FrontController. There is
* only one per request.
*
* @author coderkun <olli@coderkun.de>
*/
class ToplevelAgent extends \nre\core\Agent
{
/**
* Stage: Load
*
* @var string
*/
const STAGE_LOAD = 'load';
/**
* Stage: Run
*
* @var string
*/
const STAGE_RUN = 'run';
/**
* Current request
*
* @var Request
*/
private $request;
/**
* Current response
*
* @var Response
*/
private $response;
/**
* Layout instace
*
* @var Layout
*/
private $layout = null;
/**
* IntermediateAgent instance
*
* @var IntermediateAgent
*/
private $intermediateAgent = null;
/**
* Construct a ToplevelAgent.
*
* @throws ServiceUnavailableException
* @throws DatamodelException
* @throws DriverNotValidException
* @throws DriverNotFoundException
* @throws ViewNotFoundException
* @throws ModelNotValidException
* @throws ModelNotFoundException
* @throws ControllerNotValidException
* @throws ControllerNotFoundException
* @param Request $request Current request
* @param Response $respone Current response
* @param Logger $log Log-system
*/
protected function __construct(\nre\core\Request $request, \nre\core\Response $response, \nre\core\Logger $log=null)
{
// Store values
$this->request = $request;
$this->response = $response;
// Create response
$response = clone $response;
$response->clearParams(1);
$response->addParams(
null,
\nre\configs\CoreConfig::$defaults['action']
);
// Call parent constructor
parent::__construct($request, $response, $log, true);
// Load IntermediateAgent
$this->loadIntermediateAgent();
}
/**
* Run the Controller of this Agent and its SubAgents.
*
* @throws ServiceUnavailableException
* @param Request $request Current request
* @param Response $response Current response
* @return Exception Last occurred exception of SubAgents
*/
public function run(\nre\core\Request $request, \nre\core\Response $response)
{
try {
return $this->_run($request, $response);
}
catch(ParamsNotValidException $e) {
$this->error($e, WebUtils::HTTP_NOT_FOUND, self::STAGE_RUN);
}
catch(IdNotFoundException $e) {
$this->error($e, WebUtils::HTTP_NOT_FOUND, self::STAGE_RUN);
}
catch(DatamodelException $e) {
$this->error($e, WebUtils::HTTP_SERVICE_UNAVAILABLE, self::STAGE_RUN);
}
catch(ActionNotFoundException $e) {
$this->error($e, WebUtils::HTTP_NOT_FOUND, self::STAGE_RUN);
}
}
/**
* Generate output of the Controller of this Agent and its
* SubAgents.
*
* @param array $data View data
* @return string Generated output
*/
public function render($data=array())
{
// Render IntermediateAgent
$data = array();
$data['intermediate'] = $this->intermediateAgent->render();
// Render ToplevelAgent
return parent::render($data);
}
/**
* Load a SubAgent and add it.
*
* @throws ServiceUnavailableException
* @throws FatalDatamodelException
* @throws AgentNotFoundException
* @throws AgentNotValidException
* @param string $agentName Name of the Agent to load
* @param mixed … Additional parameters for the agent
*/
protected function addSubAgent($agentName)
{
try {
call_user_func_array(
array(
$this,
'_addSubAgent'
),
func_get_args()
);
}
catch(DatamodelException $e) {
throw new FatalDatamodelException($e->getDatamodelMessage(), $e->getDatamodelErrorNumber());
}
}
/**
* Load IntermediateAgent defined by the current request.
*
* @throws ServiceUnavailableException
*/
private function loadIntermediateAgent()
{
try {
$this->_loadIntermediateAgent();
}
catch(\nre\exceptions\ViewNotFoundException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_NOT_FOUND);
}
catch(\nre\exceptions\DatamodelException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_SERVICE_UNAVAILABLE);
}
catch(\nre\exceptions\DriverNotValidException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_SERVICE_UNAVAILABLE);
}
catch(\nre\exceptions\DriverNotFoundException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_SERVICE_UNAVAILABLE);
}
catch(\nre\exceptions\ModelNotValidException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_SERVICE_UNAVAILABLE);
}
catch(\nre\exceptions\ModelNotFoundException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_SERVICE_UNAVAILABLE);
}
catch(\nre\exceptions\ControllerNotValidException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_SERVICE_UNAVAILABLE);
}
catch(\nre\exceptions\ControllerNotFoundException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_NOT_FOUND);
}
catch(\nre\exceptions\AgentNotValidException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_SERVICE_UNAVAILABLE);
}
catch(\nre\exceptions\AgentNotFoundException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_NOT_FOUND);
}
}
/**
* Load IntermediateAgent defined by the current request.
*
* @throws ServiceUnavailableException
*/
private function _loadIntermediateAgent()
{
// Determine IntermediateAgent
$agentName = $this->response->getParam(1);
if(is_null($agentName)) {
$agentName = $this->request->getParam(1, 'intermediate');
$this->response->addParam($agentName);
}
// Load IntermediateAgent
IntermediateAgent::load($agentName);
// Determine Action
$action = $this->response->getParam(2);
if(is_null($action)) {
$action = $this->request->getParam(2, 'action');
$this->response->addParam($action);
}
// Construct IntermediateAgent
$this->intermediateAgent = \nre\agents\IntermediateAgent::factory(
$agentName,
$this->request,
$this->response,
$this->log
);
}
/**
* Run the Controller of this Agent and its SubAgents.
*
* @throws IdNotFoundException
* @throws ServiceUnavailableException
* @throws DatamodelException
* @param Request $request Current request
* @param Response $response Current response
* @return Exception Last occurred exception of SubAgents
*/
private function _run(\nre\core\Request $request, \nre\core\Response $response)
{
// Run IntermediateAgent
$this->runIntermediateAgent();
// TODO Request instead of response?
$response = clone $response;
$response->clearParams(2);
$response->addParam(\nre\configs\CoreConfig::$defaults['action']);
// Run ToplevelAgent
return parent::run($request, $response);
}
/**
* Run IntermediateAgent.
*
* @throws ParamsNotValidException
* @throws IdNotFoundException
* @throws ServiceUnavailableException
* @throws DatamodelException
*/
private function runIntermediateAgent()
{
$this->intermediateAgent->run(
$this->request,
$this->response
);
}
/**
* Handle an error that occurred during
* loading/cnostructing/running of the IntermediateAgent.
*
* @throws ServiceUnavailableException
* @param Exception $exception Occurred exception
* @param int $httpStatusCode HTTP-statuscode
* @param string $stage Stage of execution
*/
private function error($exception, $httpStatusCode, $stage=self::STAGE_LOAD)
{
// Log error
$this->log($exception, \nre\core\Logger::LOGMODE_AUTO);
try {
// Define ErrorAgent
$this->response->clearParams(1);
$this->response->addParams(
\nre\configs\AppConfig::$defaults['intermediate-error'],
\nre\configs\CoreConfig::$defaults['action'],
$httpStatusCode
);
// Load ErrorAgent
$this->_loadIntermediateAgent();
// Run ErrorAgent
if($stage == self::STAGE_RUN) {
$this->_run($this->request, $this->response);
}
}
catch(\nre\exceptions\ActionNotFoundException $e) {
throw new \nre\exceptions\ServiceUnavailableException($e);
}
catch(\nre\exceptions\DatamodelException $e) {
throw new \nre\exceptions\ServiceUnavailableException($e);
}
catch(\nre\exceptions\DriverNotValidException $e) {
throw new \nre\exceptions\ServiceUnavailableException($e);
}
catch(\nre\exceptions\DriverNotFoundException $e) {
throw new \nre\exceptions\ServiceUnavailableException($e);
}
catch(\nre\exceptions\ModelNotValidException $e) {
throw new \nre\exceptions\ServiceUnavailableException($e);
}
catch(\nre\exceptions\ModelNotFoundException $e) {
throw new \nre\exceptions\ServiceUnavailableException($e);
}
catch(\nre\exceptions\ViewNotFoundException $e) {
throw new \nre\exceptions\ServiceUnavailableException($e);
}
catch(\nre\exceptions\ControllerNotValidException $e) {
throw new \nre\exceptions\ServiceUnavailableException($e);
}
catch(\nre\exceptions\ControllerNotFoundException $e) {
throw new \nre\exceptions\ServiceUnavailableException($e);
}
catch(\nre\exceptions\AgentNotValidException $e) {
throw new \nre\exceptions\ServiceUnavailableException($e);
}
catch(\nre\exceptions\AgentNotFoundException $e) {
throw new \nre\exceptions\ServiceUnavailableException($e);
}
catch(Exception $e) {
throw new \nre\exceptions\ServiceUnavailableException($e);
}
}
}
?>

0
agents/bottomlevel/empty Normal file
View file

View file

0
agents/toplevel/empty Normal file
View file

245
apis/WebApi.inc Normal file
View file

@ -0,0 +1,245 @@
<?php
/**
* NRE
*
* @author coderkun <olli@coderkun.de>
* @copyright 2013 coderkun (http://www.coderkun.de)
* @license http://www.gnu.org/licenses/gpl.html
* @link http://www.coderkun.de/projects/nre
*/
namespace nre\apis;
/**
* WebApi-implementation.
*
* This class runs and renders an web-applictaion.
*
* @author coderkun <olli@coderkun.de>
*/
class WebApi extends \nre\core\Api
{
/**
* Construct a new WebApi.
*/
public function __construct()
{
parent::__construct(
new \nre\requests\WebRequest(),
new \nre\responses\WebResponse()
);
// Add routes
$this->addRoutes();
}
/**
* Run application.
*
* This method runs the application and handles all errors.
*/
public function run()
{
try {
$exception = parent::run();
if(!is_null($exception)) {
$this->errorService($exception);
}
}
catch(\nre\exceptions\ServiceUnavailableException $e) {
$this->errorService($e);
}
catch(\nre\exceptions\ActionNotFoundException $e) {
$this->error($e, WebUtils::HTTP_NOT_FOUND);
}
catch(\nre\exceptions\FatalDatamodelException $e) {
$this->errorService($e);
}
catch(\nre\exceptions\DatamodelException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_SERVICE_UNAVAILABLE);
}
catch(\nre\exceptions\DriverNotValidException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_SERVICE_UNAVAILABLE);
}
catch(\nre\exceptions\DriverNotFoundException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_SERVICE_UNAVAILABLE);
}
catch(\nre\exceptions\ModelNotValidException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_SERVICE_UNAVAILABLE);
}
catch(\nre\exceptions\ModelNotFoundException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_SERVICE_UNAVAILABLE);
}
catch(\nre\exceptions\ViewNotFoundException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_NOT_FOUND);
}
catch(\nre\exceptions\ControllerNotValidException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_SERVICE_UNAVAILABLE);
}
catch(\nre\exceptions\ControllerNotFoundException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_NOT_FOUND);
}
catch(\nre\exceptions\AgentNoaatValidException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_SERVICE_UNAVAILABLE);
}
catch(\nre\exceptions\AgentNotFoundException $e) {
$this->error($e, \nre\core\WebUtils::HTTP_NOT_FOUND);
}
catch(\nre\exceptions\ClassNotValidException $e) {
$this->errorService($e);
}
catch(\nre\exceptions\ClassNotFoundException $e) {
$this->errorService($e);
}
}
/**
* Render output.
*/
public function render()
{
// Generate output
parent::render();
// Set HTTP-header
$this->response->header();
// Show output
echo $this->response->getOutput();
}
/**
* Add routes (normal and reverse) defined in the AppConfig.
*/
private function addRoutes()
{
// Normal routes
if(property_exists('\nre\configs\AppConfig', 'routes')) {
foreach(\nre\configs\AppConfig::$routes as &$route) {
$this->request->addRoute($route[0], $route[1], $route[2]);
}
}
// Reverse routes
if(property_exists('\nre\configs\AppConfig', 'reverseRoutes')) {
foreach(\nre\configs\AppConfig::$reverseRoutes as &$route) {
$this->request->addReverseRoute($route[0], $route[1], $route[2]);
}
}
// Revalidate request
$this->request->revalidate();
}
/**
* Handle an error that orrcurred during the
* loading/constructing/running of the ToplevelAgent.
*
* @param Exception $exception Occurred exception
* @param int $httpStatusCode HTTP-statuscode
*/
private function error(\nre\core\Exception $exception, $httpStatusCode)
{
// Log error message
$this->log($exception, \nre\core\Logger::LOGMODE_AUTO);
try {
// Set agent for handling errors
$this->response->clearParams();
$this->response->addParams(
\nre\configs\AppConfig::$defaults['toplevel-error'],
\nre\configs\AppConfig::$defaults['intermediate-error'],
\nre\configs\CoreConfig::$defaults['action'],
$httpStatusCode
);
// Run this agent
parent::run();
}
catch(\nre\exceptions\ServiceUnavailableException $e) {
$this->errorService($e);
}
catch(\nre\exceptions\ActionNotFoundException $e) {
$this->errorService($e);
}
catch(\nre\exceptions\DatamodelException $e) {
$this->errorService($e);
}
catch(\nre\exceptions\DriverNotValidException $e) {
$this->errorService($e);
}
catch(\nre\exceptions\DriverNotFoundException $e) {
$this->errorService($e);
}
catch(\nre\exceptions\ModelNotValidException $e) {
$this->errorService($e);
}
catch(\nre\exceptions\ModelNotFoundException $e) {
$this->errorService($e);
}
catch(\nre\exceptions\ViewNotFoundException $e) {
$this->errorService($e);
}
catch(\nre\exceptions\ControllerNotValidException $e) {
$this->errorService($e);
}
catch(\nre\exceptions\ControllerNotFoundException $e) {
$this->errorService($e);
}
catch(\nre\exceptions\AgentNotValidException $e) {
$this->errorService($e);
}
catch(\nre\exceptions\AgentNotFoundException $e) {
$this->errorService($e);
}
catch(Exception $e) {
$this->errorService($e);
}
}
/**
* Handle a error which cannot be handles by the system (and
* HTTP 503).
*
* $param Exception $exception Occurred exception
*/
private function errorService($exception)
{
// Log error message
$this->log($exception, \nre\core\Logger::LOGMODE_AUTO);
// Set HTTP-rtatuscode
$this->response->addHeader(\nre\core\WebUtils::getHttpHeader(503));
// Read and print static error file
$fileName = ROOT.DS.\nre\configs\CoreConfig::getClassDir('views').DS.\nre\configs\CoreConfig::$defaults['errorFile'].\nre\configs\CoreConfig::getFileExt('views');
ob_start();
include($fileName);
$this->response->setOutput(ob_get_clean());
// Prevent further execution
$this->response->setExit();
}
}
?>

0
app/empty Normal file
View file

33
bootstrap.inc Normal file
View file

@ -0,0 +1,33 @@
<?php
/**
* NRE
*
* @author coderkun <olli@coderkun.de>
* @copyright 2013 coderkun (http://www.coderkun.de)
* @license http://www.gnu.org/licenses/gpl.html
* @link http://www.coderkun.de/projects/nre
*/
// Include required classes
require_once(ROOT.DS.'configs'.DS.'CoreConfig.inc');
require_once(ROOT.DS.\nre\configs\CoreConfig::getClassDir('core').DS.'Autoloader.inc');
// Set PHP-logging
ini_set('error_log', ROOT.DS.\nre\configs\CoreConfig::getClassDir('logs').DS.'php'.\nre\configs\CoreConfig::getFileExt('logs'));
// Register autoloader
\nre\core\Autoloader::register();
// Initialize WebApi
$webApi = new \nre\apis\WebApi();
// Run WebApi
$webApi->run();
// Render output
$webApi->render();
?>

75
configs/AppConfig.inc Normal file
View file

@ -0,0 +1,75 @@
<?php
/**
* NRE
*
* @author coderkun <olli@coderkun.de>
* @copyright 2013 coderkun (http://www.coderkun.de)
* @license http://www.gnu.org/licenses/gpl.html
* @link http://www.coderkun.de/projects/nre
*/
namespace nre\configs;
/**
* Application configuration.
*
* This class contains static variables with configuration values for
* the specific application.
*
* @author coderkun <olli@coderkun.de>
*/
final class AppConfig
{
/**
* Application values
*
* @static
* @var array
*/
public static $app = array(
//'namespace' => '',
//'timeZone' => ''
);
/**
* Default values
*
* @static
* @var array
*/
public static $defaults = array(
//'toplevel' => '',
//'toplevel-error' => '',
//'intermediate' => '',
//'intermediate-error' => ''
);
/**
* Routes
*
* @static
* @var array
*/
public static $routes = array(
//array('<pattern>', '<replace>', '<is_last>')
);
/**
* Reverse routes
*
* @static
* @var array
*/
public static $reverseRoutes = array(
//array('<pattern>', '<replace>', '<is_last>')
);
}
?>

167
configs/CoreConfig.inc Normal file
View file

@ -0,0 +1,167 @@
<?php
/**
* NRE
*
* @author coderkun <olli@coderkun.de>
* @copyright 2013 coderkun (http://www.coderkun.de)
* @license http://www.gnu.org/licenses/gpl.html
* @link http://www.coderkun.de/projects/nre
*/
namespace nre\configs;
/**
* Core configuration.
*
* This class contains static variables with configuration values.
*
* @author coderkun <olli@coderkun.de>
*/
final class CoreConfig
{
/**
* Core values
*
* @static
* @var array
*/
public static $core = array(
'namespace' => 'nre\\',
);
/**
* Directories
*
* @static
* @var array
*/
public static $dirs = array(
'core' => 'core',
'publicDir' => 'www'
);
/**
* File extensions
*
* @static
* @var array
*/
public static $fileExts = array(
'default' => 'inc',
'views' => 'tpl',
'logs' => 'log',
);
/**
* Default values
*
* @static
* @var array
*/
public static $defaults = array(
'action' => 'index',
'errorFile' => 'error',
'inlineErrorFile' => 'inlineerror'
);
/**
* Miscellaneous settings
*
* @static
* @var array
*/
public static $misc = array(
'fileExtDot' => '.'
);
/**
* Logging settings
*
* @static
* @var array
*/
public static $log = array(
'filename' => 'errors',
'format' => 'Fehler %d: %s in %s, Zeile %d'
);
/**
* Class-specific settings
*
* @static
* @var array
*/
public static $classes = array(
'linker' => array(
'url' => array(
'length' => 50,
'delimiter' => '-'
)
)
);
/**
* Determine the directory for a specific classtype.
*
* @param string $classType Classtype to get directory of
* @return string Directory of given classtype
*/
public static function getClassDir($classType)
{
// Default directory (for core classes)
$classDir = self::$dirs['core'];
// Configurable directory
if(array_key_exists($classType, self::$dirs)) {
$classDir = self::$dirs[$classType];
}
else
{
// Default directory for classtype
if(is_dir(ROOT.DS.$classType)) {
$classDir = $classType;
}
}
// Return directory
return $classDir;
}
/**
* Determine the file extension for a specific filetype.
*
* @param string $fileType Filetype to get file extension of
* @return string File extension of given filetype
*/
public static function getFileExt($fileType)
{
// Default file extension
$fileExt = self::$fileExts['default'];
// Configurable file extension
if(array_key_exists($fileType, self::$fileExts)) {
$fileExt = self::$fileExts[$fileType];
}
// Return file extension
return self::$misc['fileExtDot'].$fileExt;
}
}
?>

0
controllers/empty Normal file
View file

607
core/Agent.inc Normal file
View file

@ -0,0 +1,607 @@
<?php
/**
* NRE
*
* @author coderkun <olli@coderkun.de>
* @copyright 2013 coderkun (http://www.coderkun.de)
* @license http://www.gnu.org/licenses/gpl.html
* @link http://www.coderkun.de/projects/nre
*/
namespace nre\core;
/**
* Abstract class for the implementation af an Agent.
*
* @author coderkun <olli@coderkun.de>
*/
abstract class Agent
{
/**
* Name of BottomlevelAgent for showing inline errors
*
* @var string
*/
const INLINEERROR_AGENT = 'inlineerror';
/**
* Current request
*
* @var Request
*/
private $request;
/**
* Current response
*
* @var Response
*/
private $response;
/**
* Log-system
*
* @var Logger
*/
protected $log;
/**
* SubAgents
*
* @var array
*/
protected $subAgents = array();
/**
* Controller of this Agent
*
* @var Controller
*/
public $controller = null;
/**
* Load the class of an Agent.
*
* @static
* @throws AgentNotFoundException
* @throws AgentNotValidException
* @param string $agentName Name of the Agent to load
*/
public static function load($agentName)
{
// Determine full classname
$agentType = self::getAgentType();
$className = self::getClassName($agentName, $agentType);
try {
// Load class
ClassLoader::load($className);
// Validate class
$parentAgentClassName = ClassLoader::concatClassNames($agentType, 'agent');
$parentAgentClassName = "\\nre\\agents\\$parentAgentClassName";
ClassLoader::check($className, $parentAgentClassName);
}
catch(\nre\exceptions\ClassNotValidException $e) {
throw new \nre\exceptions\AgentNotValidException($e->getClassName());
}
catch(\nre\exceptions\ClassNotFoundException $e) {
throw new \nre\exceptions\AgentNotFoundException($e->getClassName());
}
}
/**
* Instantiate an Agent (Factory Pattern).
*
* @static
* @throws DatamodelException
* @throws DriverNotValidException
* @throws DriverNotFoundException
* @throws ViewNotFoundException
* @throws ModelNotValidException
* @throws ModelNotFoundException
* @throws ControllerNotValidException
* @throws ControllerNotFoundException
* @param string $agentName Name of the Agent to instantiate
* @param Request $request Current request
* @param Response $respone Current respone
* @param Logger $log Log-system
*/
public static function factory($agentName, Request $request, Response $response, Logger $log=null)
{
// Determine full classname
$agentType = self::getAgentType();
$className = self::getClassName($agentName, $agentType);
// Construct and return Agent
return new $className($request, $response, $log);
}
/**
* Determine the type of an Agent.
*
* @static
* @return string Agent type
*/
private static function getAgentType()
{
return strtolower(ClassLoader::getClassName(get_called_class()));
}
/**
* Determine the classname for the given Agent name.
*
* @static
* @param string $agentName Agent name to get classname of
* @param string $agentType Agent type of given Agent name
* @return string Classname for the Agent name
*/
private static function getClassName($agentName, $agentType)
{
$className = ClassLoader::concatClassNames($agentName, 'agent');
return \nre\configs\AppConfig::$app['namespace']."agents\\$agentType\\$className";
}
/**
* Construct a new Agent.
*
* @throws DatamodelException
* @throws DriverNotValidException
* @throws DriverNotFoundException
* @throws ViewNotFoundException
* @throws ModelNotValidException
* @throws ModelNotFoundException
* @throws ControllerNotValidException
* @throws ControllerNotFoundException
* @param Request $request Current request
* @param Response $respone Current response
* @param Logger $log Log-system
*/
protected function __construct(Request $request, Response $response, Logger $log=null)
{
// Store values
$this->request = $request;
$this->response = $response;
$this->log = $log;
// Construct SubAgent
$this->actionConstruct();
// Load corresponding Controller
$this->loadController();
}
/**
* Run the Controller of this Agent and its SubAgents.
*
* @throws ParamsNotValidException
* @throws IdNotFoundException
* @throws DatamodelException
* @throws ActionNotFoundException
* @param Request $request Current request
* @param Response $response Current response
* @return Exception Last occurred exception of SubAgents
*/
public function run(Request $request, Response $response)
{
// Check Controller
if(!is_null($this->controller))
{
// Call prefilter
$this->controller->preFilter($request, $response);
// Run controller
$this->controller->run($request, $response);
// Call postfilter
$this->controller->postFilter($request, $response);
}
// Run SubAgents
$exception = null;
foreach($this->subAgents as &$subAgent)
{
try {
$subAgent['object']->run(
$request,
$subAgent['response']
);
}
catch(ParamsNotValidException $e) {
$subAgent = $this->errorInline($subAgent, $request, $e);
}
catch(IdNotFoundException $e) {
$subAgent = $this->errorInline($subAgent, $request, $e);
}
catch(DatamodelException $e) {
$exception = $e;
$subAgent = $this->errorInline($subAgent, $request, $e);
}
catch(ActionNotFoundException $e) {
$subAgent = $this->errorInline($subAgent, $request, $e);
}
}
// Return last occurred exception
return $exception;
}
/**
* Generate output of the Controller of this Agent and its
* SubAgents.
*
* @param array $data View data
* @return string Generated output
*/
public function render($data=array())
{
// Check Controller
if(!is_null($this->controller))
{
// Render SubAgents
foreach($this->subAgents as $subAgent)
{
$label = array_key_exists('label', $subAgent) ? $subAgent['label'] : $subAgent['name'];
$data[$label] = $this->renderSubAgent($subAgent);
}
// Render the Controller of this agent
return $this->controller->render($data);
}
}
/**
* Construct SubAgents (per Action).
*/
protected function actionConstruct()
{
// Action ermitteln
$action = $this->response->getParam(2);
if(is_null($action)) {
$action = $this->request->getParam(2, 'action');
$this->response->addParam($action);
}
// Initialisierungsmethode für diese Action ausführen
if(method_exists($this, $action))
{
call_user_func_array(
array(
$this,
$action
),
array(
$this->request,
$this->response
)
);
}
}
/**
* Load the Controller of this Agent.
*
* @throws DatamodelException
* @throws DriverNotValidException
* @throws DriverNotFoundException
* @throws ViewNotFoundException
* @throws ModelNotValidException
* @throws ModelNotFoundException
* @throws ControllerNotValidException
* @throws ControllerNotFoundException
*/
protected function loadController()
{
// Determine Controller name
$controllerName = ClassLoader::getClassName(get_class($this));
// Determine ToplevelAgent
$toplevelAgentName = $this->response->getParam(0);
if(is_null($toplevelAgentName)) {
$toplevelAgentName = $this->request->getParam(0, 'toplevel');
$this->response->addParam($toplevelAgentName);
}
// Determine Action
$action = $this->response->getParam(2);
if(is_null($action)) {
$action = $this->request->getParam(2, 'action');
$this->response->addParam($action);
}
// Load Controller
Controller::load($controllerName);
// Construct Controller
$this->controller = Controller::factory($controllerName, $toplevelAgentName, $action, $this);
}
/**
* Log an error.
*
* @param Exception $exception Occurred exception
* @param int $logMode Log mode
*/
protected function log($exception, $logMode)
{
if(is_null($this->log)) {
return;
}
$this->log->log(
$exception->getMessage(),
$logMode
);
}
/**
* Load a SubAgent and add it.
*
* @throws ServiceUnavailableException
* @throws AgentNotFoundException
* @throws AgentNotValidException
* @param string $agentName Name of the Agent to load
* @param mixed … Additional parameters for the agent
*/
protected function addSubAgent($agentName)
{
try {
call_user_func_array(
array(
$this,
'_addSubAgent'
),
func_get_args()
);
}
catch(DatamodelException $e) {
$this->subAgents[] = $this->newInlineError($agentName, $e);
}
}
/**
* Load a SubAgent and add it.
*
* @throws ServiceUnavailableException
* @throws DatamodelException
* @throws AgentNotFoundException
* @throws AgentNotValidException
* @param string $agentName Name of the Agent to load
* @param mixed … Additional parameters for the agent
*/
protected function _addSubAgent($agentName)
{
try {
// Load Agent
BottomlevelAgent::load($agentName);
// Construct Agent
$this->subAgents[] = call_user_func_array(
array(
$this,
'newSubAgent'
),
func_get_args()
);
}
catch(ViewNotFoundException $e) {
$this->subAgents[] = $this->newInlineError($agentName, $e);
}
catch(DriverNotValidException $e) {
$this->subAgents[] = $this->newInlineError($agentName, $e);
}
catch(DriverNotFoundException $e) {
$this->subAgents[] = $this->newInlineError($agentName, $e);
}
catch(ModelNotValidException $e) {
$this->subAgents[] = $this->newInlineError($agentName, $e);
}
catch(ModelNotFoundException $e) {
$this->subAgents[] = $this->newInlineError($agentName, $e);
}
catch(ControllerNotValidException $e) {
$this->subAgents[] = $this->newInlineError($agentName, $e);
}
catch(ControllerNotFoundException $e) {
$this->subAgents[] = $this->newInlineError($agentName, $e);
}
catch(AgentNotValidException $e) {
$this->subAgents[] = $this->newInlineError($agentName, $e);
}
catch(AgentNotFoundException $e) {
$this->subAgents[] = $this->newInlineError($agentName, $e);
}
}
/**
* Create a new SubAgent.
*
* @throws DatamodelException
* @param string $agentName Agent name
* @return array SubAgent
*/
private function newSubAgent($agentName)
{
// Response
$response = clone $this->response;
$response->clearParams(1);
$params = func_get_args();
if(count($params) < 2 || empty($params[1])) {
$params[1] = \nre\configs\CoreConfig::$defaults['action'];
}
call_user_func_array(
array(
$response,
'addParams'
),
$params
);
return array(
'name' => strtolower($agentName),
'response' => $response,
'object' => BottomlevelAgent::factory(
$agentName,
$this->request,
$response,
$this->log
)
);
}
/**
* Render a SubAgent.
*
* @param array $subAgent SubAgent to render
* @return string Generated output
*/
private function renderSubAgent(&$subAgent)
{
// Check for InlineError
if(array_key_exists('inlineerror', $subAgent) && !empty($subAgent['inlineerror'])) {
return file_get_contents($subAgent['inlineerror']);
}
// Rendern SubAgent and return its output
return $subAgent['object']->render();
}
/**
* Handle the exception of a SubAgent.
*
* @param string $label Name of the original Agent
* @param Excepiton $exception Occurred exception
* @return array InlineError-SubAgent
*/
private function errorInline($subAgent, $request, $exception)
{
// Create the SubAgent for the exception
$subAgent = $this->newInlineError($subAgent['name'], $exception);
// Run the InlineError-SubAgent
try {
$subAgent['object']->run(
$request,
$subAgent['response']
);
}
catch(ActionNotFoundException $e) {
$this->log($e, Logger::LOGMODE_AUTO);
$subAgent['inlineerror'] = $this->newInlineErrorService();
}
// Return the InlineError-SubAgent
return $subAgent;
}
/**
* Create a new InlineError.
*
* @param string $label Name of the original Agent
* @param Exception $exception Occurred exception
*/
private function newInlineError($label, $exception)
{
// Log error
$this->log($exception, Logger::LOGMODE_AUTO);
// Determine Agent name
$agentName = self::INLINEERROR_AGENT;
// Create SugAgent
$subAgent = array();
try {
// Load Agenten
BottomlevelAgent::load($agentName);
// Construct Agent
$subAgent = $this->newSubAgent($agentName);
$subAgent['label'] = $label;
$subAgent['response']->addParam($exception);
}
catch(ViewNotFoundException $e) {
$subAgent['inlineerror'] = $this->newInlineErrorService();
}
catch(DatamodelException $e) {
$subAgent['inlineerror'] = $this->newInlineErrorService();
}
catch(DriverNotValidException $e) {
$subAgent['inlineerror'] = $this->newInlineErrorService();
}
catch(DriverNotFoundException $e) {
$subAgent['inlineerror'] = $this->newInlineErrorService();
}
catch(ModelNotValidException $e) {
$subAgent['inlineerror'] = $this->newInlineErrorService();
}
catch(ModelNotFoundException $e) {
$subAgent['inlineerror'] = $this->newInlineErrorService();
}
catch(ControllerNotValidException $e) {
$subAgent['inlineerror'] = $this->newInlineErrorService();
}
catch(ControllerNotFoundException $e) {
$subAgent['inlineerror'] = $this->newInlineErrorService();
}
catch(AgentNotValidException $e) {
$subAgent['inlineerror'] = $this->newInlineErrorService();
}
catch(AgentNotFoundException $e) {
$subAgent['inlineerror'] = $this->newInlineErrorService();
}
// Return SubAgent
return $subAgent;
}
/**
* Handle a hardcore error that could not be handled by the
* system.
*/
private function newInlineErrorService()
{
// Read and return static error file
return ROOT.DS.\nre\configs\CoreConfig::getClassDir('views').DS.\nre\configs\CoreConfig::$defaults['inlineErrorFile'].\nre\configs\Config::getFileExt('views');
}
}
?>

163
core/Api.inc Normal file
View file

@ -0,0 +1,163 @@
<?php
/**
* NRE
*
* @author coderkun <olli@coderkun.de>
* @copyright 2013 coderkun (http://www.coderkun.de)
* @license http://www.gnu.org/licenses/gpl.html
* @link http://www.coderkun.de/projects/nre
*/
namespace nre\core;
/**
* Abstract class to implement an API.
*
* The API is the center of each application and specifies how and what
* to run and render.
*
* @author coderkun <olli@coderkun.de>
*/
abstract class Api
{
/**
* Die aktuelle Anfrage
*
* @var Request
*/
protected $request;
/**
* Der Toplevelagent
*
* @var ToplevelAgent
*/
private $toplevelAgent = null;
/**
* Die aktuelle Antwort
*
* @var Response
*/
protected $response;
/**
* Log-System
*
* @var Logger
*/
private $log;
/**
* Construct a new API.
*
* @param Request $request Current request
* @param Response $respone Current response
*/
public function __construct(Request $request, Response $response)
{
// Store request
$this->request = $request;
// Store response
$this->response = $response;
// Init logging
$this->log = new \nre\core\Logger();
}
/**
* Run the application.
*
* @throws DatamodelException
* @throws DriverNotValidException
* @throws DriverNotFoundException
* @throws ViewNotFoundException
* @throws ModelNotValidException
* @throws ModelNotFoundException
* @throws ControllerNotValidException
* @throws ControllerNotFoundException
* @throws AgentNotValidException
* @throws AgentNotFoundException
* @return Exception Last occurred exception of an subagent
*/
public function run()
{
// Load ToplevelAgent
$this->loadToplevelAgent();
// Run ToplevelAgent
return $this->toplevelAgent->run($this->request, $this->response);
}
/**
* Render the output.
*/
public function render()
{
// Check exit-status
if($this->response->getExit()) {
return;
}
// Render ToplevelAgent
$this->response->setOutput($this->toplevelAgent->render());
}
/**
* Log an exception
*
* @param Exception $exception Occurred exception
* @param int $logMode Log-mode
*/
protected function log($exception, $logMode)
{
$this->log->log(
$exception->getMessage(),
$logMode
);
}
/**
* Load the ToplevelAgent specified by the request.
*
* @throws ServiceUnavailableException
* @throws AgentNotValidException
* @throws AgentNotFoundException
*/
private function loadToplevelAgent()
{
// Determine agent
$agentName = $this->response->getParam(0);
if(is_null($agentName)) {
$agentName = $this->request->getParam(0, 'toplevel');
$this->response->addParam($agentName);
}
// Load agent
\nre\agents\ToplevelAgent::load($agentName);
// Construct agent
$this->toplevelAgent = \nre\agents\ToplevelAgent::factory(
$agentName,
$this->request,
$this->response,
$this->log
);
}
}
?>

98
core/Autoloader.inc Normal file
View file

@ -0,0 +1,98 @@
<?php
/**
* NRE
*
* @author coderkun <olli@coderkun.de>
* @copyright 2013 coderkun (http://www.coderkun.de)
* @license http://www.gnu.org/licenses/gpl.html
* @link http://www.coderkun.de/projects/nre
*/
namespace nre\core;
/**
* Autoloader.
*
* This class tries to load not yet used classes.
*
* @author coderkun <olli@coderkun.de>
*/
class Autoloader
{
/**
* Private construct().
*/
private function __construct() {}
/**
* Private clone().
*/
private function __clone() {}
/**
* Register load-method.
*/
public static function register()
{
spl_autoload_register(
array(
get_class(),
'load'
)
);
}
/**
* Look for the given class and try to load it.
*
* @param string $fullClassName Die zu ladende Klasse
*/
public static function load($fullClassName)
{
$fullClassNameA = explode('\\', $fullClassName);
if(strpos($fullClassName, \nre\configs\CoreConfig::$core['namespace']) !== 0)
{
// App
$className = array_slice($fullClassNameA, substr_count(\nre\configs\AppConfig::$app['namespace'], '\\'));
array_unshift($className, \nre\configs\CoreConfig::getClassDir('app'));
$filename = ROOT.DS.implode(DS, $className).\nre\configs\CoreConfig::getFileExt('includes');
if(file_exists($filename)) {
require_once($filename);
}
}
else
{
// Core
$className = array_slice($fullClassNameA, substr_count(\nre\configs\CoreConfig::$core['namespace'], '\\'));
$filename = ROOT.DS.implode(DS, $className).\nre\configs\CoreConfig::getFileExt('includes');
if(file_exists($filename)) {
require_once($filename);
}
}
}
/**
* Determine classtype of a class.
*
* @param string $className Name of the class to determine the classtype of
* @return string Classtype of the given class
*/
public static function getClassType($className)
{
// CamelCase
return strtolower(preg_replace('/^.*([A-Z][^A-Z]+)$/', '$1', $className));
}
}
?>

129
core/ClassLoader.inc Normal file
View file

@ -0,0 +1,129 @@
<?php
/**
* NRE
*
* @author coderkun <olli@coderkun.de>
* @copyright 2013 coderkun (http://www.coderkun.de)
* @license http://www.gnu.org/licenses/gpl.html
* @link http://www.coderkun.de/projects/nre
*/
namespace nre\core;
/**
* Class for safely loading classes.
*
* @author coderkun <olli@coderkun.de>
*/
class ClassLoader
{
/**
* Load a class.
*
* @throws ClassNotFoundException
* @param string $className Name of the class to load
*/
public static function load($fullClassName)
{
// Determine folder to look in
$className = explode('\\', $fullClassName);
$className = array_slice($className, substr_count(\nre\configs\AppConfig::$app['namespace'], '\\'));
// Determine filename
$fileName = ROOT.DS.implode(DS, $className). \nre\configs\CoreConfig::getFileExt('includes');
// Check file
if(!file_exists($fileName))
{
throw new \nre\exceptions\ClassNotFoundException(
$fullClassName
);
}
// Include file
include_once($fileName);
}
/**
* Check inheritance of a class.
*
* @throws ClassNotValidException
* @param string $className Name of the class to check
* @param string $parentClassName Name of the parent class
*/
public static function check($className, $parentClassName)
{
// Check if class is subclass of parent class
if(!is_subclass_of($className, $parentClassName)) {
throw new \nre\exceptions\ClassNotValidException(
$className
);
}
}
/**
* Strip the namespace from a class name.
*
* @param string $class Name of a class including its namespace
* @return Name of the given class without its namespace
*/
public static function stripNamespace($class)
{
return array_slice(explode('\\', $class), -1)[0];
}
/**
* Strip the class type from a class name.
*
* @param string $className Name of a class
* @return Name of the given class without its class type
*/
public static function stripClassType($className)
{
return preg_replace('/^(.*)[A-Z][^A-Z]+$/', '$1', $className);
}
/**
* Strip the namespace and the class type of a full class name
* to get only its name.
*
* @param string $class Full name of a class
* @return Only the name of the given class
*/
public static function getClassName($class)
{
return self::stripClassType(self::stripNamespace($class));
}
/**
* Concatenate strings to a class name following the CamelCase
* pattern.
*
* @param string $className1 Arbitrary number of strings to concat
* @return string Class name as CamelCase
*/
public static function concatClassNames($className1)
{
return implode('', array_map(
function($arg) {
return ucfirst(strtolower($arg));
},
func_get_args()
));
}
}
?>

49
core/Config.inc Normal file
View file

@ -0,0 +1,49 @@
<?php
/**
* NRE
*
* @author coderkun <olli@coderkun.de>
* @copyright 2013 coderkun (http://www.coderkun.de)
* @license http://www.gnu.org/licenses/gpl.html
* @link http://www.coderkun.de/projects/nre
*/
namespace nre\core;
/**
* Configuration.
*
* This class does not hold any configuration value but helps to
* determine values that can be hold by AppConfig or CoreConfig.
*
* @author coderkun <olli@coderkun.de>
*/
final class Config
{
/**
* Get a default value.
*
* @param string $index Index of value to get
*/
public static function getDefault($index)
{
if(array_key_exists($index, \nre\configs\AppConfig::$defaults)) {
return \nre\configs\AppConfig::$defaults[$index];
}
if(array_key_exists($index, \nre\configs\CoreConfig::$defaults)) {
return \nre\configs\CoreConfig::$defaults[$index];
}
return null;
}
}
?>

381
core/Controller.inc Normal file
View file

@ -0,0 +1,381 @@
<?php
/**
* NRE
*
* @author coderkun <olli@coderkun.de>
* @copyright 2013 coderkun (http://www.coderkun.de)
* @license http://www.gnu.org/licenses/gpl.html
* @link http://www.coderkun.de/projects/nre
*/
namespace nre\core;
/**
* Abstract class for implementing a Controller.
*
* @author coderkun <olli@coderkun.de>
*/
abstract class Controller
{
/**
* Corresponding Agent
*
* @var Agent
*/
protected $agent;
/**
* View of the Controller
*
* @var View
*/
private $view = null;
/**
* Data to pass to the View
*
* @var array
*/
protected $viewData = array();
/**
* Current request
*
* @var Request
*/
protected $request = null;
/**
* Current response
*
* @var Response
*/
protected $response = null;
/**
* Load the class of a Controller.
*
* @throws ControllerNotFoundException
* @throws ControllerNotValidException
* @param string $controllerName Name of the Controller to load
*/
public static function load($controllerName)
{
// Determine full classname
$className = self::getClassName($controllerName);
try {
// Load class
ClassLoader::load($className);
// Validate class
ClassLoader::check($className, get_class());
}
catch(\nre\exceptions\ClassNotValidException $e) {
throw new \nre\exceptions\ControllerNotValidException($e->getClassName());
}
catch(\nre\exceptions\ClassNotFoundException $e) {
throw new \nre\exceptions\ControllerNotFoundException($e->getClassName());
}
}
/**
* Instantiate a Controller (Factory Pattern).
*
* @throws DatamodelException
* @throws DriverNotFoundException
* @throws DriverNotValidException
* @throws ModelNotValidException
* @throws ModelNotFoundException
* @throws ViewNotFoundException
* @param string $controllerName Name of the Controller to instantiate
* @param string $layoutName Name of the current Layout
* @param string $action Current Action
*/
public static function factory($controllerName, $layoutName, $action, $agent)
{
// Determine full classname
$className = self::getClassName($controllerName);
// Construct and return Controller
return new $className($layoutName, $action, $agent);
}
/**
* Determine the classname for the given Controller name.
*
* @param string $controllerName Controller name to get classname of
* @return string Classname for the Controller name
*/
private static function getClassName($controllerName)
{
$className = \nre\core\ClassLoader::concatClassNames($controllerName, \nre\core\ClassLoader::stripNamespace(get_class()));
return \nre\configs\AppConfig::$app['namespace']."controllers\\$className";
}
/**
* Construct a new Controller.
*
* @throws DriverNotFoundException
* @throws DriverNotValidException
* @throws ModelNotValidException
* @throws ModelNotFoundException
* @throws ViewNotFoundException
* @param string $layoutName Name of the current Layout
* @param string $action Current Action
* @param Agent $agent Corresponding Agent
*/
protected function __construct($layoutName, $action, $agent)
{
// Store values
$this->agent = $agent;
// Load Models
$this->loadModels();
// Load View
$this->loadView($layoutName, $action);
}
/**
* Prefilter that is executed before running the Controller.
*
* @param Request $request Current request
* @param Response $response Current response
*/
public function preFilter(Request $request, Response $response)
{
// Request speichern
$this->request = $request;
// Response speichern
$this->response = $response;
// Linker erstellen
$this->set('linker', new \nre\core\Linker($request));
}
/**
* Prefilter that is executed after running the Controller.
*
* @param Request $request Current request
* @param Response $response Current response
*/
public function postFilter(Request $request, Response $response)
{
}
/**
* Run the Controller.
*
* This method executes the Action of the Controller defined by
* the current Request.
*
* @throws ParamsNotValidException
* @throws IdNotFoundException
* @throws DatamodelException
* @throws ActionNotFoundException
* @param Request $request Current request
* @param Response $response Current response
*/
public function run(Request $request, Response $response)
{
// Determine Action
$action = $response->getParam(2, 'action');
if(!method_exists($this, $action)) {
throw new \nre\exceptions\ActionNotFoundException($action);
}
// Determine parameters
$params = $response->getParams(3);
if(empty($params)) {
$params = $request->getParams(3);
}
// Fill missing parameters
$rc = new \ReflectionClass($this);
$nullParamsCount = $rc->getMethod($action)->getNumberOfParameters() - count($params);
$nullParams = ($nullParamsCount > 0 ? array_fill(0, $nullParamsCount, NULL) : array());
// Call Action
call_user_func_array(
array(
$this,
$action
),
array_merge(
$params,
$nullParams
)
);
}
/**
* Generate the output.
*
* @param array $viewData Data to pass to the View
* @return string Generated output
*/
public function render($viewData=null)
{
// Combine given data and data of this Controller
$data = $this->viewData;
if(!is_null($viewData)) {
$data = array_merge($viewData, $data);
}
// Rendern and return output
return $this->view->render($data);
}
/**
* Set data for the View.
*
* @param string $name Key
* @param mixed $data Value
*/
protected function set($name, $data)
{
$this->viewData[$name] = $data;
}
/**
* Redirect to the given URL.
*
* @param string $url Relative URL
*/
protected function redirect($url)
{
$url = 'http://'.$_SERVER['HTTP_HOST'].$url;
header('Location: '.$url);
exit;
}
/**
* Check if Models of this Controller are loaded and available.
*
* @param string $modelName Arbitrary number of Models to check
* @return bool All given Models are loaded and available
*/
protected function checkModels($modelName)
{
foreach(func_get_args() as $modelName)
{
if(!isset($this->$modelName) || !is_subclass_of($this->$modelName, 'Model')) {
return false;
}
}
return true;
}
/**
* Get the View of the Controller
*
* @return View View of the Controller
*/
protected function getView()
{
return $this->view;
}
/**
* Load the Models of this Controller.
*
* @throws DatamodelException
* @throws DriverNotFoundException
* @throws DriverNotValidException
* @throws ModelNotValidException
* @throws ModelNotFoundException
*/
private function loadModels()
{
// Determine Models
$explicit = false;
$models = \nre\core\ClassLoader::stripClassType(\nre\core\ClassLoader::stripNamespace(get_class($this)));
if(property_exists($this, 'models'))
{
$models = $this->models;
$explicit = true;
}
if(!is_array($models)) {
$models = array($models);
}
// Load Models
foreach($models as &$model)
{
try {
// Load class
Model::load($model);
// Construct Model
$this->$model = Model::factory($model);
}
catch(\nre\exceptions\ModelNotValidException $e) {
if($explicit) {
throw $e;
}
}
catch(\nre\exceptions\ModelNotFoundException $e) {
if($explicit) {
throw $e;
}
}
}
}
/**
* Load the View of this Controller.
*
* @throws ViewNotFoundException
* @param string $layoutName Name of the current Layout
* @param string $action Current Action
*/
private function loadView($layoutName, $action)
{
// Check Layout name
if(is_null($layoutName)) {
return;
}
// Determine controller name
$controllerName = \nre\core\ClassLoader::getClassName(get_class($this));
// Load view
$isToplevel = is_subclass_of($this->agent, '\nre\agents\ToplevelAgent');
$this->view = View::loadAndFactory($layoutName, $controllerName, $action, $isToplevel);
}
}
?>

96
core/Driver.inc Normal file
View file

@ -0,0 +1,96 @@
<?php
/**
* NRE
*
* @author coderkun <olli@coderkun.de>
* @copyright 2013 coderkun (http://www.coderkun.de)
* @license http://www.gnu.org/licenses/gpl.html
* @link http://www.coderkun.de/projects/nre
*/
namespace nre\core;
/**
* Abstract class for implementing a Driver.
*
* @author coderkun <olli@coderkun.de>
*/
abstract class Driver
{
/**
* Load the class of a Driver.
*
* @throws DriverNotFoundException
* @throws DriverNotValidException
* @param string $driverName Name of the Driver to load
*/
public static function load($driverName)
{
// Determine full classname
$className = self::getClassName($driverName);
try {
// Load class
ClassLoader::load($className);
// Validate class
ClassLoader::check($className, get_class());
}
catch(ClassNotValidException $e) {
throw new DriverNotValidException($e->getClassName());
}
catch(ClassNotFoundException $e) {
throw new DriverNotFoundException($e->getClassName());
}
}
/**
* Instantiate a Driver (Factory Pattern).
*
* @param string $driverName Name of the Driver to instantiate
*/
public static function factory($driverName, $config)
{
// Determine full classname
$className = self::getClassName($driverName);
// Construct and return Driver
return new $className($config);
}
/**
* Determine the classname for the given Driver name.
*
* @param string $driverName Driver name to get classname of
* @return string Classname fore the Driver name
*/
private static function getClassName($driverName)
{
$className = \nre\core\ClassLoader::concatClassNames($driverName, \nre\core\ClassLoader::stripNamespace(get_class()));
return "\\nre\\drivers\\$className";
}
/**
* Construct a new Driver.
*/
protected function __construct()
{
}
}
?>

Some files were not shown because too many files have changed in this diff Show more