summaryrefslogtreecommitdiff
path: root/app/Core/Router.php
diff options
context:
space:
mode:
Diffstat (limited to 'app/Core/Router.php')
-rw-r--r--app/Core/Router.php111
1 files changed, 111 insertions, 0 deletions
diff --git a/app/Core/Router.php b/app/Core/Router.php
new file mode 100644
index 00000000..3a5df715
--- /dev/null
+++ b/app/Core/Router.php
@@ -0,0 +1,111 @@
+<?php
+
+namespace Core;
+
+/**
+ * Router class
+ *
+ * @package core
+ * @author Frederic Guillot
+ */
+class Router
+{
+ /**
+ * Controller name
+ *
+ * @access private
+ * @var string
+ */
+ private $controller = '';
+
+ /**
+ * Action name
+ *
+ * @access private
+ * @var string
+ */
+ private $action = '';
+
+ /**
+ * Registry instance
+ *
+ * @access private
+ * @var Core\Registry
+ */
+ private $registry;
+
+ /**
+ * Constructor
+ *
+ * @access public
+ * @param Core\Registry $registry Registry instance
+ * @param string $controller Controller name
+ * @param string $action Action name
+ */
+ public function __construct(Registry $registry, $controller = '', $action = '')
+ {
+ $this->registry = $registry;
+ $this->controller = empty($_GET['controller']) ? $controller : $_GET['controller'];
+ $this->action = empty($_GET['action']) ? $controller : $_GET['action'];
+ }
+
+ /**
+ * Check controller and action parameter
+ *
+ * @access public
+ * @param string $value Controller or action name
+ * @param string $default_value Default value if validation fail
+ */
+ public function sanitize($value, $default_value)
+ {
+ return ! ctype_alpha($value) || empty($value) ? $default_value : strtolower($value);
+ }
+
+ /**
+ * Load a controller and execute the action
+ *
+ * @access public
+ * @param string $filename Controller filename
+ * @param string $class Class name
+ * @param string $method Method name
+ */
+ public function load($filename, $class, $method)
+ {
+ if (file_exists($filename)) {
+
+ require $filename;
+
+ if (! method_exists($class, $method)) {
+ return false;
+ }
+
+ $instance = new $class($this->registry);
+ $instance->request = new Request;
+ $instance->response = new Response;
+ $instance->session = new Session;
+ $instance->template = new Template;
+ $instance->beforeAction($this->controller, $this->action);
+ $instance->$method();
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Find a route
+ *
+ * @access public
+ */
+ public function execute()
+ {
+ $this->controller = $this->sanitize($this->controller, 'app');
+ $this->action = $this->sanitize($this->action, 'index');
+ $filename = __DIR__.'/../Controller/'.ucfirst($this->controller).'.php';
+
+ if (! $this->load($filename, '\Controller\\'.$this->controller, $this->action)) {
+ die('Page not found!');
+ }
+ }
+}