public function __construct() { $this->app = \Framework\App::getInstance(); $this->view = \Framework\View::getInstance(); $this->config = $this->app->getConfig(); $this->input = \Framework\InputData::getInstance(); }
public function __construct() { $this->app = App::getInstance(); $this->view = View::getInstance(); $this->config = $this->app->getConfig(); $this->input = InputData::getInstance(); $this->session = $this->app->getSession(); $this->db = new SimpleDB(); }
public function __construct() { $this->app = App::getInstance(); $this->view = View::getInstance(); $this->config = $this->app->getConfig(); $this->input = InputData::getInstance(); if (is_null($this->session)) { $this->session = new NativeSession('session'); } }
public function __construct() { $this->app = App::getInstance(); $this->view = View::getInstance(); $this->config = $this->app->getConfig(); $this->input = InputData::getInstance(); $this->db = new SimpleDatabase(); $this->session = $this->app->getSession(); $this->path = isset($this->config->app['default_path']) ? $this->config->app['default_path'] : null; }
private function __construct() { $this->___viewPath = \Framework\App::getInstance()->getConfig()->app['viewDirectory']; if ($this->___viewPath == null) { $this->___viewPath = realpath('../views/'); } }
public function __construct($connection = null) { if ($connection instanceof \PDO) { $this->_database = $connection; } else { if ($connection != null) { $this->_database = App::getInstance()->getDatabaseConnection($connection); $this->connectionAlias = $connection; } else { $this->_database = App::getInstance()->getDatabaseConnection($this->connectionAlias); } } }
public function __construct($connection = null) { if ($connection instanceof \PDO) { $this->db = $connection; } else { if ($connection != null) { $this->db = App::getInstance()->getDbConnection($connection); $this->connection = $connection; } else { $this->db = App::getInstance()->getDbConnection($this->connection); } } }
public function getUri() { if (!is_array($this->map) || count($this->map) == 0) { $ar = \Framework\App::getInstance()->getConfig()->rpcRoutes; if (is_array($ar) && count($ar) > 0) { $this->map = $ar; } else { throw new \Exception("Router require method map", 500); } } $request = json_decode(file_get_contents('php://input', true)); if (!is_array($request) || !isset($request['method'])) { throw new \Exception("Require json request", 400); } else { if ($this->map[$request['method']]) { $this->requestId = $request['id']; $this->post = $request['params']; return $this->map[$request[$method]]; } throw new \Exception("Require json request", 501); } }
public function getUri() { if (!is_array($this->_map) || count($this->_map) == 0) { $ar = App::getInstance()->getConfig()->rpcRoutes; if (is_array($ar) && count($ar) > 0) { $this->_map = $ar; } else { throw new \Exception('Router requires method map', 400); } } $request = json_decode(file_get_contents('php://input'), true); if (!is_array($request) || !isset($request['method'])) { throw new \Exception('Required json request', 400); } else { if ($this->_map[$request['method']]) { $this->_requestId = $request['id']; $this->_post = $request['params']; return $this->_map[$request['method']]; } else { throw new \Exception('Method not found', 501); } } }
public function getURI() { if (!is_array($this->_routeMappings) || count($this->_routeMappings) == 0) { $rpcRoutes = App::getInstance()->getConfig()->rpcRoutes; if (is_array($rpcRoutes) && count($rpcRoutes) > 0) { $this->_routeMappings = $rpcRoutes; } else { throw new \Exception('Invalid route configurations', 500); } } $requestContent = json_decode(file_get_contents('php://input') . true); if (is_array($requestContent) || !isset($requestContent['method'])) { throw new \Exception('Invalid or no JSON request body', 400); } else { if ($this->_routeMappings[$requestContent['method']]) { $this->_requestId = $requestContent['id']; $this->_post = $requestContent['params']; return $this->_routeMappings[$requestContent['method']]; } else { throw new \Exception('Request method not found', 501); } } }
/** * @Get * @Route("product/{id:int}/show") */ public function product() { $id = $this->input->get(1); $this->db->prepare("\n SELECT p.id, p.name, p.description, p.price, p.quantity, c.name as category\n FROM products p\n JOIN products_categories pc\n ON p.id = pc.productId\n JOIN categories c\n ON pc.categoryId = c.id\n WHERE p.id = ?", [$id]); $response = $this->db->execute()->fetchRowAssoc(); if (!$response) { throw new \Exception("No product with id '{$id}'!", 404); } $quantity = Common::normalize($response['quantity'], 'noescape|int'); if ($quantity <= 0) { if (!App::getInstance()->isAdmin() && !App::getInstance()->isEditor()) { throw new \Exception("No product with id '{$id}'!", 404); } } $this->db->prepare("\n SELECT u.username, u.isAdmin, u.isEditor, u.isModerator, r.message, r.id\n FROM reviews r\n JOIN products p\n ON r.productId = p.id\n JOIN users u\n ON r.userId = u.id\n WHERE p.id = ?", [$id]); $reviews = $this->db->execute()->fetchAllAssoc(); $givenReviews = []; foreach ($reviews as $review) { $givenReviews[] = new ProductMessage(Common::normalize($review['id'], 'noescape|int'), $review['username'], $review['message'], Common::normalize($review['isAdmin'], 'noescape|bool'), Common::normalize($review['isEditor'], 'noescape|bool'), Common::normalize($review['isModerator'], 'noescape|bool')); } $this->db->prepare("\n SELECT percentage\n FROM promotions\n WHERE productId = ? AND NOW() < endDate", [$id]); $promos = $this->db->execute()->fetchAllAssoc(); $bestPromo = 0; foreach ($promos as $promo) { $currentPromo = Common::normalize($promo['percentage'], 'noescape|double'); if ($currentPromo > $bestPromo) { $bestPromo = $currentPromo; } } $product = new ProductViewModel(Common::normalize($response['id'], 'noescape|int'), $response['name'], $response['description'], Common::normalize($response['price'], 'noescape|double'), $quantity, $response['category'], $bestPromo, $givenReviews); $this->view->appendToLayout('header', 'header'); $this->view->appendToLayout('meta', 'meta'); $this->view->appendToLayout('body', $product); $this->view->appendToLayout('footer', 'footer'); $this->view->displayLayout('Layouts.product'); }
if ($review->getIsEditor()) { ?> <span class="label label-info">Editor</span> <?php } ?> <?php if ($review->getIsModerator()) { ?> <span class="label label-success">Moderator</span> <?php } ?> </div> <?php if (\Framework\App::getInstance()->isAdmin() || \Framework\App::getInstance()->isModerator()) { ?> <div class="col-sm-2 text-right"> <button class="btn btn-sm btn-default" onclick="enableReviewForm('<?php echo $review->getId() . 'r'; ?> ')">Edit</button> <?php \Framework\FormViewHelper::init()->initForm($this->getPath() . 'review/' . $review->getId() . '/delete', ['style' => 'display: inline;'], 'delete')->initSubmit()->setAttribute('value', 'Delete')->setAttribute('class', 'btn btn-sm btn-default')->create()->render(true); ?> </div> <?php \Framework\FormViewHelper::init()->initForm($this->getPath() . 'review/' . $review->getId() . '/edit', ['class' => 'form-group', 'style' => 'display: none', 'id' => $review->getId() . 'r'], 'put')->initLabel()->setAttribute('for', 'message')->setValue('Edit Message')->create()->initTextArea($review->getMessage())->setAttribute('name', 'message')->setAttribute('class', 'form-control input-md')->setAttribute('id', 'message')->create()->initSubmit()->setAttribute('value', 'Edit')->setAttribute('class', 'btn btn-primary btn-sm col-sm-1 col-sm-offset-5')->create()->render(true); ?> <?php }
private function ValidateAuthorization($doc) { $doc = strtolower($doc); $notLoggedRegex = '/@notlogged/'; preg_match($notLoggedRegex, $doc, $matches); if ($matches) { if (App::getInstance()->getSession()->_login) { throw new \Exception("Already logged in!", 400); } } $authorizeRegex = '/@authorize(?:\\s+error:\\("(.+)"\\))?/'; preg_match($authorizeRegex, $doc, $matches); if ($matches) { $error = 'Unauthorized!'; if ($matches[1]) { $error = ucfirst($matches[1]); } if (!App::getInstance()->getSession()->_login) { throw new \Exception($error, 401); } } $adminRegex = '/@admin/'; preg_match($adminRegex, $doc, $matches); if ($matches) { if (!SimpleDB::isAdmin()) { throw new \Exception("Admin access only!", 401); } } $roleRegex = '/@role\\s*\\("(.+)"\\)/'; preg_match($roleRegex, $doc, $matches); if ($matches[1]) { $role = $matches[1]; if (!SimpleDB::hasRole($role) && !SimpleDB::isAdmin()) { $role = ucfirst($role); throw new \Exception("{$role} access only!", 401); } } }
private function BindModel($annotations) { $bindingNamespace = null; $appConfig = App::getInstance()->getConfig()->app; $namespaces = $appConfig['namespaces']; foreach ($namespaces as $key => $value) { if (strpos($key, "BindingModels")) { $bindingNamespace = $key; } } $bindingModelName = null; foreach ($annotations as $annotation) { $bindingAnnotation = explode(' ', $annotation); if ($bindingAnnotation[0] === 'BingingModel') { $bindingModelName = $bindingAnnotation[1]; } } $bindingModel = null; if ($bindingNamespace && $bindingModelName) { $bindingModelClass = $bindingNamespace . "\\" . $bindingModelName; $bindingModel = new $bindingModelClass(); $reflectionModel = new ReflectionClass($bindingModel); $properties = $reflectionModel->getProperties(); $post = $this->input->post(); foreach ($properties as $property) { $propertyName = $property->getName(); $propertyDoc = $property->getDocComment(); $annotations = array(); preg_match_all('#@(.*?)\\n#s', $propertyDoc, $annotations); $set = 'set' . $propertyName; if ($annotations[1][0] === "Required" && !$post[$propertyName]) { throw new \Exception("Field " . $propertyName . " is required"); } if (array_key_exists($propertyName, $post)) { $bindingModel->{$set}($post[$propertyName]); } else { throw new \Exception("Field " . $propertyName . " is not accepted"); } } } return $bindingModel; }
public static function hasRole($role) { $col = 'is' . ucfirst($role); try { $statement = self::$database->prepare("\n SELECT {$col}\n FROM users\n WHERE username = ? AND id = ?"); $username = App::getInstance()->getSession()->_username; $id = App::getInstance()->getSession()->_login; $statement->bindColumn(1, $col); $statement->bindParam(1, $username); $statement->bindParam(2, $id); $statement->execute(); $response = $statement->fetch(\PDO::FETCH_ASSOC); $response = $response['is' . ucfirst($role)]; } catch (\PDOException $ex) { throw new \Exception("Please, check your database! Missing role: '{$col}'"); } if ($response) { return Common::normalize($response, 'bool'); } return false; }
public function getDefaultMethod() { $method = \Framework\App::getInstance()->getConfig()->app['default_method']; if ($method) { return strtolower($method); } return 'index'; }
<?php \Framework\FormViewHelper::init()->initLink()->setAttribute('href', $this->getPath() . "users/all/0/10")->setValue('All users')->create()->render(); ?> </li> <?php if (\Framework\App::getInstance()->isAdmin()) { ?> <li><a href="<?php echo $this->getPath(); ?> admin">Admin</a></li> <?php } ?> <?php if (\Framework\App::getInstance()->isAdmin() || \Framework\App::getInstance()->isEditor()) { ?> <li><a href="<?php echo $this->getPath(); ?> editor">Editor</a></li> <?php } ?> <li role="separator" class="divider"></li> <li> <?php Framework\FormViewHelper::init()->initLink()->setAttribute('href', $this->getPath() . 'user/logout')->setValue('Logout')->create()->render(); ?> </li> </ul>
public static function isAdmin() : bool { $statement = self::$database->prepare("SELECT u.id\n FROM user_roles ur\n JOIN users u\n ON u.id = ur.user_id\n WHERE (u.username = ? AND u.id = ?) AND ur.role_id = 2"); $statement->bindParam(1, App::getInstance()->getSession()->_username); $statement->bindParam(2, App::getInstance()->getSession()->_login); $statement->execute(); $response = $statement->fetch(\PDO::FETCH_ASSOC); if ($response) { $id = Normalizer::normalize($response['isAdmin'], 'bool'); return true; } return false; }
?> <span class="label label-danger">Admin</span> <?php } ?> <?php if ($this->_viewBag['body']->getIsEditor()) { ?> <span class="label label-info">Editor</span> <?php } ?> <?php if ($this->_viewBag['body']->getIsModerator()) { ?> <span class="label label-success">Moderator</span> <?php } ?> </h2> <?php if (strtolower($this->_viewBag['body']->getUsername()) === strtolower(\Framework\App::getInstance()->getUsername())) { ?> <div class="panel panel-heading">Your balance: <?php echo $this->_viewBag['body']->getBalance(); ?> lv</div> <?php \Framework\FormViewHelper::init()->initForm($this->getPath() . 'user/changePass', ['class' => 'form-group'], 'put')->initLabel()->setValue("Old Password")->setAttribute('for', 'oldPassword')->create()->initPasswordBox()->setAttribute('id', 'oldPassword')->setName('oldPassword')->setAttribute('class', 'form-control input-md')->create()->initLabel()->setValue("New Password")->setAttribute('for', 'newPassword')->create()->initPasswordBox()->setAttribute('id', 'newPassword')->setName('newPassword')->setAttribute('class', 'form-control input-md')->create()->initLabel()->setValue("Confirm Password")->setAttribute('for', 'conPassword')->create()->initPasswordBox()->setAttribute('id', 'conPassword')->setName('confirm')->setAttribute('class', 'form-control input-md')->create()->initSubmit()->setAttribute('value', 'Change password')->setAttribute('class', 'btn btn-default')->create()->render(); }
?> <a href="<?php echo $this->getPath(); ?> product/<?php echo $product->getId(); ?> /edit" class="panel panel-primary btn btn-default">Edit</a> <?php \Framework\FormViewHelper::init()->initForm($this->getPath() . 'product/' . $product->getId() . '/delete', ['style' => 'display: inline;'], 'delete')->initSubmit()->setAttribute('value', 'Delete')->setAttribute('class', 'panel panel-primary btn btn-default')->create()->render(true); ?> <?php } ?> <?php if (\Framework\App::getInstance()->isLogged()) { \Framework\FormViewHelper::init()->initForm($this->getPath() . 'review/add/' . $product->getId(), ['class' => 'form-group', 'style' => 'display: none', 'id' => $product->getId()])->initLabel()->setAttribute('for', 'message')->setValue('Message')->create()->initTextArea()->setAttribute('name', 'message')->setAttribute('class', 'form-control input-md')->setAttribute('id', 'message')->create()->initSubmit()->setAttribute('value', 'Send')->setAttribute('class', 'btn btn-primary btn-sm col-sm-1 col-sm-offset-5')->create()->render(true); } ?> </div> </div> <?php } ?> <ul class="pager"> <li> <?php $start = $this->_viewBag['body']->getStart(); $start - 3 >= 0 ? $start -= 3 : 0; $end = $this->_viewBag['body']->getEnd(); $end = $end - 3 > 0 ? $end -= 3 : 3;
<?php error_reporting(E_ALL); ini_set('display_errors', 1); use Framework\App; require_once 'Framework/App.php'; require_once 'ShoppingCart/Routers/SimpleRouter.php'; $app = App::getInstance(); $app->run();
<?php error_reporting(E_ALL ^ E_NOTICE); include '../../Framework/App.php'; $app = \Framework\App::getInstance(); $app->run();
private function overrideRoutes() { $configRoute = $this->_config->getConfigFolder() . "routes.php"; $testFile = fopen($configRoute, "w") or die("Unable to open file!"); $startTag = "<?php\n"; fwrite($testFile, $startTag); $namespaces = $this->getConfig()->app['namespaces']; foreach ($namespaces as $namespace => $value) { if (strpos($namespace, 'Controllers') || $namespace == 'Controllers') { $files = scandir($value); foreach ($files as $file) { if (strpos($file, '.php')) { $controllerName = str_replace('.php', '', $file); $controller = $namespace . '\\' . $controllerName; $reflectionController = new ReflectionClass(new $controller()); $reflectionMethods = $reflectionController->getMethods(); foreach ($reflectionMethods as $reflectionMethod) { $doc = $reflectionMethod->getDocComment(); $annotations = array(); preg_match_all('#@(.*?)\\n#s', $doc, $annotations); foreach ($annotations[1] as $annotation) { if (substr($annotation, 0, 5) == 'Route') { $newRoute = array(); preg_match('/"(.*?)"/', $annotation, $newRoute); $params = explode("/", $newRoute[1]); $params = array_values(array_filter($params)); if (count($params) > 2) { $area = $params[0]; $oldControllerName = strtolower($controllerName); $newControllerName = $params[1]; if ($newControllerName !== $oldControllerName) { $replaceController = "\$cnf['" . $area . "']['controllers']['" . $newControllerName . "']['to'] = '" . $oldControllerName . "';\n"; fwrite($testFile, $replaceController); } $oldMethodName = $reflectionMethod->getName(); $newMethodName = $params[2]; $replaceMethod = "\$cnf['" . $area . "']['controllers']['" . $newControllerName . "']['methods']['" . $newMethodName . "'] = '" . $oldMethodName . "';\n"; fwrite($testFile, $replaceMethod); if ($oldMethodName !== $newMethodName) { $replaceMethod = "\$cnf['" . $area . "']['controllers']['" . $oldControllerName . "']['methods']['" . $oldMethodName . "'] = '" . "notFound" . "';\n"; fwrite($testFile, $replaceMethod); } } else { $oldControllerName = strtolower($controllerName); $newControllerName = $params[0]; if ($newControllerName !== $oldControllerName) { $replaceController = "\$cnf['*']['controllers']['" . $newControllerName . "']['to'] = '" . $oldControllerName . "';\n"; fwrite($testFile, $replaceController); } $oldMethodName = $reflectionMethod->getName(); $newMethodName = $params[1]; $replaceMethod = "\$cnf['*']['controllers']['" . $newControllerName . "']['methods']['" . $newMethodName . "'] = '" . $oldMethodName . "';\n"; fwrite($testFile, $replaceMethod); if ($oldMethodName !== $newMethodName) { $replaceMethod = "\$cnf['*']['controllers']['" . $oldControllerName . "']['methods']['" . $oldMethodName . "'] = '" . "notFound" . "';\n"; fwrite($testFile, $replaceMethod); } } } } } } } } } $namespacesConfig = App::getInstance()->getConfig()->namespaces; foreach ($namespacesConfig as $k => $v) { $customNamespace = "\$cnf['" . $k . "']['namespace'] = '" . $v['namespace'] . "';\n"; fwrite($testFile, $customNamespace); } $returnCnf = "return \$cnf;"; fwrite($testFile, $returnCnf); fclose($testFile); }
/** * @return array Found routes */ private function findAllRoutesInApp() { $foundRoutes = array(); // Config routes $configRoutes = App::getInstance()->getConfig()->routes; foreach ($configRoutes as $area => $namespace) { if (isset($namespace['controllers'])) { foreach ($namespace['controllers'] as $controller => $methods) { foreach ($methods['methods'] as $newFunctionRoute => $originalFunction) { $file = App::getInstance()->getConfig()->app['namespaces']['Controllers']; //$file = $file . ucfirst($methods['goesTo']) . 'Controller'; if ($area !== '*') { $file .= $area; $file = $file . '\\' . ucfirst($methods['goesTo']) . 'Controller'; } else { $file = $file . ucfirst($methods['goesTo']) . 'Controller'; } $file = str_replace('../', '', $file); $file = str_replace('/', '\\', $file); $file = substr($file, 13); $reflection = new \ReflectionMethod($file, $originalFunction); $doc = $reflection->getDocComment(); $params = $this->findBindingModels($doc); $requestMethod = null; if (isset($methods['requestMethod'][$newFunctionRoute])) { $requestMethod = $methods['requestMethod'][$newFunctionRoute]; } else { // Methods without config request - checking controller for annotation if ($methods['goesTo'] && $originalFunction) { preg_match('/@(post|get|put|delete)/', strtolower($doc), $requestMethods); $requestMethod = 'Get'; if (isset($requestMethods[1])) { $requestMethod = $requestMethods[1]; } } } if ($area === '*') { $route = '@' . strtoupper($requestMethod) . ' ' . strtolower($controller . '/' . $newFunctionRoute); } else { $route = '@' . strtoupper($requestMethod) . ' ' . strtolower($area . '/' . $controller . '/' . $newFunctionRoute); } $foundRoutes[$route] = $params; } } } } // Custom routes and not listed ones $controllersFolder = App::getInstance()->getConfig()->app['namespaces']['Controllers']; $allFiles = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($controllersFolder)); $phpFiles = new \RegexIterator($allFiles, '/\\.php$/'); foreach ($phpFiles as $file) { $controllerPath = str_replace('../', '', $file->getPathName()); $controllerPath = str_replace('.php', '', $controllerPath); $normalizedPath = str_replace('/', '\\', $controllerPath); $normalizedPath = substr($normalizedPath, 13); $reflectionController = new \ReflectionClass(new $normalizedPath()); $methods = $reflectionController->getMethods(); foreach ($methods as $method) { $doc = $method->getDocComment(); @($params = $this->findBindingModels($doc)); $doc = strtolower($doc); preg_match('/@route\\("(.*)"\\)/', $doc, $matches); preg_match('/@(post|get|put|delete)/', $doc, $requestMethods); $route = isset($matches[1]) ? $matches[1] : null; $requestMethod = 'Get'; if (isset($requestMethods[1])) { $requestMethod = $requestMethods[1]; } if ($route) { $fullRoute = '@' . strtoupper($requestMethod) . ' ' . strtolower($route); $foundRoutes[$fullRoute] = $params; } } } return $foundRoutes; }
<?php /** * Created by PhpStorm. * User: lxpfigo * Date: 2015/12/1 * Time: 15:06 * 入口文件 */ require_once './Framework/App.class.php'; \Framework\App::init();