File: D:/HostingSpaces/SBogers10/deensekroon.komma-mediadesign.nl/wwwroot/App/Routes/RouteResolver.php
<?php
namespace App\Routes;
include_once($_SERVER['DOCUMENT_ROOT'] . '/App/Routes/RouteRedirector.php');
use App\Brands\BrandController;
use App\Categories\CategoryController;
class RouteResolver
{
/**
* @var RoutesRepository
*/
private $repository;
private $redirector;
/**
* RouteResolver constructor.
*/
public function __construct()
{
$this->repository = new RoutesRepository();
$this->redirector = new RouteRedirector();
}
/**
* Resolve route
*/
public function resolve()
{
// Get path
$path = $this->path();
// Is this an api path
$this->handlePostRequests();
// Check if this is a fixed route
// Todo: add 'new' ?
// Find route in database
$route = $this->repository->find($path);
if($route == null) {
// Old route ?
if($type = $this->isOldRoute($path)) $this->redirector->redirectOldRoute($type,$path);
return false;
}
return $route;
}
/**
* Quick and dirty solution for calling the right method
* @param $route
* @return string
*/
public function dispatchType($route)
{
if( ! $route) return false;
// Dispatch the type
switch($route->routeable_type)
{
case 'category':
// Create new controller
$controller = new CategoryController();
// Show category
return $controller->show($route->routeable_id);
break;
case 'brand':
// Create new controller
$controller = new BrandController();
// Show brand
return $controller->show($route->routeable_id);
break;
case 'product':
// Require product file
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/page_product.php';
// Show product
return \showProduct($route->routeable_id);
break;
}
return '';
}
/**
* Get path without first slash
*
* return path
*/
public function path()
{
substr($_SERVER['REQUEST_URI'],1) ? $path = substr($_SERVER['REQUEST_URI'],1) : $path = '';
return $path;
}
/**
* Check if the route is an old route that needs to be redirected
*
* @param $path
* @return bool|string
*/
private function isOldRoute($path)
{
// Define old strings
$oldStrings = [
'product' => 'toont-het-artikel',
'brand' => 'toont-haar-collectie/van-het-merk',
'category' => 'toont-haar-collectie/uit-de-categorie'
];
// Loop through strings
foreach($oldStrings as $type => $string)
{
// Check if path starts with string
if(substr($path,0,strlen($string)) == $string) return $type;
}
return false;
}
/**
* Handle post request
*
* @return bool
*/
private function handlePostRequests()
{
// Do we have a post request
if( ! isset($_POST)) return false;
// Add to cart
if(isset($_POST['add-to-cart']))
{
include_once($_SERVER['DOCUMENT_ROOT'] . '/php/page_product.php');
\validateAddProducts();
}
// Search
if(isset($_POST['search'])){
$_SESSION['search'] = $_POST['search'];
header('location: /zoekresultaten/');
}
}
}