function __construct() { self::$instance = $this; define('ROOT', substr(dirname(__FILE__), 0, -4)); //тут описана работа с базой данных if (!defined('DB_TYPE')) { define('DB_TYPE', 'mysql'); } try { if (DB_TYPE == 'mysql') { define('DB_FIELD_DEL', '`'); $this->db = new PDO(DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD); $this->db->exec('SET CHARACTER SET utf8'); $this->db->exec('SET NAMES utf8'); } else { define('DB_FIELD_DEL', ''); $this->db = new PDO(DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD); } } catch (PDOException $e) { $this->db_error = $e; //Создание заголовки для подавления ошибок и доступа к скаффолдингу $this->db = new PDODummy(); } // Массив для шаблонизатора // <foreach users as user> $this->template_patterns[] = '/<foreach\\s+(.*?)\\s+as\\s+([a-zA-Z0-9_]+)>/'; $this->template_replacements[] = '<' . '?php $tmparr= $doit->$1; if(!isset($doit->datapool[\'this\'])){ $doit->datapool[\'this\']=array(); } array_push($doit->_this_cache,$doit->datapool[\'this\']); if(is_string($tmparr)) $tmparr=array($tmparr); foreach($tmparr as $key=>$subval) if(is_string($subval)) print $subval;else { $doit->key = $key; $doit->datapool["override"]=""; if(is_object($subval)){ $doit->datapool[\'$2\']=$subval; $doit->datapool[\'this\']=$subval; $doit->datapool[\'override\']=$subval->override; }else{ $doit->datapool[\'this\']=array(); foreach($subval as $subkey=>$subvalue) { $doit->datapool[\'$2\'][$subkey]=$subvalue; $doit->datapool[\'this\'][$subkey]=$subvalue; } } if ($doit->datapool["override"]!="") { print $doit->{$doit->datapool["override"]}(); } else { ?' . '>'; //TODO: приписать if (is_object($tmparr)) $Tmparr=array($tmparr) // TODO: foreach($subval as $subkey=>$subvalue) $doit->datapool[$subkey]=$subvalue; // возможно, убрать эту конструкцию // <foreach users> $this->template_patterns[] = '/<foreach\\s+(.*)>/'; $this->template_replacements[] = '<' . '?php $tmparr= $doit->$1; if(!isset($doit->datapool[\'this\'])){ $doit->datapool[\'this\']=array(); } array_push($doit->_this_cache,$doit->datapool[\'this\']); if(is_string($tmparr)) $tmparr=array($tmparr); foreach($tmparr as $key=>$subval) if(is_string($subval)) print $subval;else { $doit->key = $key; $doit->datapool["override"]=""; if(is_object($subval)){ $doit->datapool[\'this\']=$subval; $doit->datapool[\'override\']=$subval->override; }else{ $doit->datapool[\'this\']=array(); foreach($subval as $subkey=>$subvalue) { $doit->datapool[\'this\'][$subkey]=$subvalue; } } if ($doit->datapool["override"]!="") { print $doit->{$doit->datapool["override"]}(); } else { ?' . '>'; // {* comment *} $this->template_patterns[] = '#{\\*.*?\\*}#muis'; $this->template_replacements[] = ''; // @ print 2+2; $this->template_patterns[] = '#^\\s*@((?!import|page|namespace|charset|media|font-face|keyframes|-webkit|-moz-|-ms-|-o-|region|supports|document).+)$#mui'; $this->template_replacements[] = '<?php $1; ?>'; $this->template_patterns[] = '/<tree\\s+(.*)>/'; $this->template_replacements[] = '<?php $passed_tree_elements = array(); $child_branch_name = "$1"; $call_stack = array(); $last_next = true; d()->level = 0; while (true) { if(is_object(d()->this)){ $is_valid = d()->this->valid(); }else{ break; } if($is_valid){ if(isset($passed_tree_elements[d()->this["id"]])){ break; } $passed_tree_elements[d()->this["id"]]=true; ?>'; $this->template_patterns[] = '/<\\/tree>/'; $this->template_replacements[] = '<?php } if( isset( d()->this[$child_branch_name]) && count(d()->this[$child_branch_name])>0){ $call_stack[] = d()->this; d()->this = d()->this[$child_branch_name]; d()->level++; continue; }else{ if(is_object(d()->this)){ if(!d()->this->valid()){ if( count($call_stack)>0){ d()->this = array_pop($call_stack); d()->level--; d()->this->next(); continue; }else { break; } }else{ d()->this->next(); } continue 1; }else{ break; } } } ?>'; // {{{content}}} $this->template_patterns[] = '/\\{{{([#a-zA-Z0-9_]+)\\}}}/'; $this->template_replacements[] = '<' . '?php print $doit->render("$1"); ?' . '>'; // <type admin> //DEPRECATED // $this->template_patterns[]='/<type\s+([a-zA-Z0-9_-]+)>/'; // $this->template_replacements[]='<'.'?php if($doit->type=="$1"){ ?'.'>'; // <content for header> $this->template_patterns[] = '/<content\\s+for\\s+([a-zA-Z0-9_-]+)>/'; $this->template_replacements[] = '<' . '?php ob_start(); $doit->datapool["current_ob_content_for"] = "$1"; ?' . '>'; // </content> $this->template_patterns[] = '/<\\/content>/'; $this->template_replacements[] = '<' . '?php $doit->datapool[$doit->datapool["current_ob_content_for"]] = ob_get_contents(); ob_end_clean(); ?' . '>'; // </foreach> $this->template_patterns[] = '/<\\/foreach>/'; $this->template_replacements[] = '<' . '?php } } $doit->datapool[\'this\'] = array_pop($doit->_this_cache ); ?' . '>'; // </type> $this->template_patterns[] = '/<\\/type>/'; $this->template_replacements[] = '<' . '?php } ?' . '>'; /* // {{helper 'parame' 'param' 'param2'=>'any'}} $this->template_patterns[]='/\{{([#a-zA-Z0-9_]+)\s+([a-Z0-9\s\"\\\']+)\}}/'; $this->template_replacements[]='{{test}}>'; */ $this->template_patterns[] = '#\\{{([\\\\a-zA-Z0-9_/]+\\.html)}}#'; $this->template_replacements[] = '<' . '?php print $doit->view->partial("$1"); ?' . '>'; // {{content}} $this->template_patterns[] = '/\\{{([#a-zA-Z0-9_]+)\\}}/'; $this->template_replacements[] = '<' . '?php print $doit->call("$1"); ?' . '>'; // {{helper param}} $this->template_patterns[] = '/\\{{([#a-zA-Z0-9_]+)\\s+([a-zA-Z0-9_]+)\\}}/'; $this->template_replacements[] = '<' . '?php print $doit->call("$1", array(d()->$2)); ?' . '>'; // {{helper 'parame','param2'=>'any'}} ## $this->template_patterns[]='/\{{([#a-zA-Z0-9_]+)\s+(.*?)\}}/'; ## $this->template_replacements[]='<'.'?php print $doit->call("$1",array(array($2))); ?'.'>'; // <@helper 'parame' param2 = 'any'> $this->template_patterns[] = '/<@([#a-zA-Z0-9_]+)\\s+(.*?)>/'; $this->template_replacements[] = '<' . '?php print $doit->call("$1",array(d()->prepare_smart_array(\'$2\'))); ?' . '>'; // {{@helper 'parame' param2 = 'any'}} $this->template_patterns[] = '/\\{{\\@([#a-zA-Z0-9_]+)\\s+(.*?)\\}}/'; $this->template_replacements[] = '<' . '?php print $doit->call("$1",array(d()->prepare_smart_array(\'$2\'))); ?' . '>'; // {if url()==23?} $this->template_patterns[] = '/\\{if\\s(.*)\\?\\}/'; $this->template_replacements[] = '<' . '?php if ($doit->$1) { ?' . '>'; // {or url()==23?} $this->template_patterns[] = '/\\{(or|elseif)\\s(.*)\\?\\}/'; $this->template_replacements[] = '<' . '?php } elseif($doit->$1) { ?' . '>'; // {url()==23?} $this->template_patterns[] = '/\\{(.*)\\?\\}/'; $this->template_replacements[] = '<' . '?php if ($doit->$1) { ?' . '>'; // {else} $this->template_patterns[] = '/\\{else\\}/'; $this->template_replacements[] = '<' . '?php } else { ?' . '>'; // {(endif)} или {/} $this->template_patterns[] = '/\\{(endif|\\/)\\}/'; $this->template_replacements[] = '<' . '?php } ?' . '>'; // {title} ## $this->template_patterns[]='/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/'; ## $this->template_replacements[]='<'.'?php print $doit->$1; ?'.'>'; // {:title} $this->template_patterns[] = '/\\{:([a-zA-Z0-9\\._]+)\\}/'; $this->template_replacements[] = '<' . '?php } ?' . '>'; // {title:} $this->template_patterns[] = '/\\{([a-zA-Z0-9_]+):\\}/'; $this->template_replacements[] = '<' . '?php if($doit->$1) { ?' . '>'; // <if user> //DEPRECATED // $this->template_patterns[]='/\<if\s([a-zA-Z0-9_]+)\>/'; // $this->template_replacements[]='<'.'?php if($doit->$1) { ?'.'>'; // <if user.title> //DEPRECATED // $this->template_patterns[]='/\<if\s([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+)\>/'; // $this->template_replacements[]='<'.'?php if((is_array($doit->$1) && $doit->$1[\'$2\']) || $doit->$1->$2) { ?'.'>'; // {page.title} ## $this->template_patterns[]='/\{([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+)\}/'; ## $this->template_replacements[]='<'.'?php if(is_array($doit->$1)) { print $doit->$1[\'$2\']; }else{ print $doit->$1->$2; } ?'.'>'; //DEPRECATED // {page.title:} $this->template_patterns[] = '/\\{([a-zA-Z0-9_]+)\\.([a-zA-Z0-9_]+):\\}/'; $this->template_replacements[] = '<' . '?php if((is_array($doit->$1) && $doit->$1[\'$2\']) || $doit->$1->$2) { ?' . '>'; // {.title} $this->template_patterns[] = '/\\{\\.([a-zA-Z0-9_]+)\\}/'; $this->template_replacements[] = '<' . '?php if(is_array($doit->this)) { print $doit->this[\'$1\']; }else{ print $doit->this->$1; } ?' . '>'; // {.title|h} $this->template_patterns[] = '/\\{\\.([a-zA-Z0-9_]+)\\|([a-zA-Z0-9_]+)\\}/'; $this->template_replacements[] = '<' . '?php if(is_array($doit->this)) { print $2($doit->this[\'$1\']); }else{ print $2($doit->this->$1); } ?' . '>'; // </if> //DEPRECATED // $this->template_patterns[]='/\<\/if\>/'; // $this->template_replacements[]='<'.'?php } ?'.'>'; // {title|h} ## $this->template_patterns[]='/\{([a-zA-Z0-9_]+)\|([a-zA-Z0-9_]+)\}/'; ## $this->template_replacements[]='<'.'?php print $doit->$2($doit->$1); ?'.'>'; // {{.image|preview 'parame','param2'=>'any'}} ## $this->template_patterns[]='/\{\.([a-zA-Z0-9_]+)\|([#a-zA-Z0-9_]+)\s+(.*?)\}/'; ## $this->template_replacements[]='<'.'?php print $doit->call("$2",array(array($doit->this[\'$1\'], $3))); ?'.'>'; // {{image|preview 'parame','param2'=>'any'}} ## $this->template_patterns[]='/\{([a-zA-Z0-9_]+)\|([#a-zA-Z0-9_]+)\s+(.*?)\}/'; ## $this->template_replacements[]='<'.'?php print $doit->call("$2",array(array($doit->$1, $3))); ?'.'>'; // {{news.image|preview 'parame','param2'=>'any'}} ## $this->template_patterns[]='/\{([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+)\|([#a-zA-Z0-9_]+)\s+(.*?)\}/'; ## $this->template_replacements[]='<'.'?php print $doit->call("$3",array(array($doit->$1[\'$2\'], $4))); ?'.'>'; // {"userlist"|t} $this->template_patterns[] = '/\\{\\"(.+?)\\"\\|([a-zA-Z0-9_]+)\\}/'; $this->template_replacements[] = '<' . '?php print $doit->$2("$1"); ?' . '>'; // {page.title|h} $this->template_patterns[] = '/\\{([a-zA-Z0-9_]+)\\.([a-zA-Z0-9_]+)\\|([a-zA-Z0-9_]+)\\}/'; $this->template_replacements[] = '<' . '?php if(is_array($doit->$1)) { print $doit->$3($doit->$1[\'$2\']); }else{ print $doit->$3($doit->$1->$2); } ?' . '>'; // {page.user.title} ## $this->template_patterns[]='/\{([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+).([a-zA-Z0-9_]+)\}/'; ## $this->template_replacements[]='<'.'?php print $doit->$1->$2->$3; ?'.'>'; // {page.user.title|h} ## $this->template_patterns[]='/\{([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+).([a-zA-Z0-9_]+)\|([a-zA-Z0-9_]+)\}/'; ## $this->template_replacements[]='<'.'?php print $doit->$4( $doit->$1->$2->$3); ?'.'>'; // {page.parent.user.title} ## $this->template_patterns[]='/\{([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+).([a-zA-Z0-9_]+).([a-zA-Z0-9_]+)\}/'; ## $this->template_replacements[]='<'.'?php print $doit->$1->$2->$3->$4; ?'.'>'; // {page.parent.user.avatar.url} ## $this->template_patterns[]='/\{([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+).([a-zA-Z0-9_]+).([a-zA-Z0-9_]+).([a-zA-Z0-9_]+)\}/'; ## $this->template_replacements[]='<'.'?php print $doit->$1->$2->$3->$4->$5; ?'.'>'; // {{/form}} $this->template_patterns[] = '/\\{{\\/([a-zA-Z0-9_]+)\\}}/'; $this->template_replacements[] = '</$1>'; //Синтаксический сахар // {=url(0)} $this->template_patterns[] = '/\\{=(.+)\\}/'; $this->template_replacements[] = '<' . '?php print $1; ?' . '>'; //Обрезка GET-параметров $_tmpurl = urldecode($_SERVER['REQUEST_URI']); //Проверка на мультиязычность сайта if (substr($_tmpurl, 3, 1) == '/') { $probablyLang = substr($_tmpurl, 1, 2); //Язык /ml/ при отсуствующем файле запрещён if (file_exists('app/lang/' . $probablyLang . '.ini')) { $this->load_and_parse_ini_file('app/lang/' . $probablyLang . '.ini'); $this->lang = $probablyLang; $_tmpurl = substr($_tmpurl, 3); } else { if (file_exists('app/lang/' . $this->lang . '.ini')) { $this->load_and_parse_ini_file('app/lang/' . $this->lang . '.ini'); } } } else { if (file_exists('app/lang/' . $this->lang . '.ini')) { $this->load_and_parse_ini_file('app/lang/' . $this->lang . '.ini'); } } $this->langlink = ''; if ($this->lang != '' && $this->lang != 'ru') { $this->langlink = '/' . $this->lang; } $_where_question_sign = strpos($_tmpurl, '?'); if ($_where_question_sign !== false) { $_tmpurl = substr($_tmpurl, 0, $_where_question_sign); } $this->url_string_raw = $_tmpurl; //приписывание в конце слешей index if (substr($_tmpurl, -1) == '/') { $_tmpurl = $_tmpurl . "index"; } $this->url_string = $_tmpurl; //сохранение фрагментов url $this->url_parts = explode('/', substr($_tmpurl, 1)); $_files = array(); //сначала инициализируются файлы из ./cms, затем из ./app $_work_folders = array('cms', 'app'); $ignore_subfolders = array('.', '..', 'internal', 'external', 'fields', 'vendor'); define('SERVER_NAME', preg_replace('/^www./i', '', $_SERVER['SERVER_NAME'])); if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/sites/' . SERVER_NAME)) { $_work_folders[] = 'sites/' . SERVER_NAME; } else { preg_match('#(^.*?)\\.#', SERVER_NAME, $m); $subdomain = $m[1]; if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/sites/' . $subdomain)) { $_work_folders[] = 'sites/' . $subdomain; } } $disabled_modules = array(); if (defined('DISABLED_MODULES')) { $disabled_modules = explode(',', DISABLED_MODULES); } $simple_folders = array(); foreach ($_work_folders as $dirname) { $_files[$dirname]['/'] = array(); $_handle = opendir($_SERVER['DOCUMENT_ROOT'] . '/' . $dirname); while (false !== ($_file = readdir($_handle))) { if (substr($_file, 0, 4) == 'mod_') { if (!in_array(substr($_file, 4), $disabled_modules)) { $_subhandle = opendir($_SERVER['DOCUMENT_ROOT'] . '/' . $dirname . '/' . $_file); $_files[$dirname]['/' . $_file . '/'] = array(); while (false !== ($_subfile = readdir($_subhandle))) { $_files[$dirname]['/' . $_file . '/'][] = $_subfile; } closedir($_subhandle); } } elseif (is_dir($_SERVER['DOCUMENT_ROOT'] . '/' . $dirname . '/' . $_file) && !in_array($_file, $ignore_subfolders)) { //Модули 2.0, список директорий $simple_folders[] = $dirname . '/' . $_file; } else { $_files[$dirname]['/'][] = $_file; } } closedir($_handle); } $for_include = array(); $for_ini = array(); $ini_files_dirs = array(); $ini_files_local = array(); foreach ($_work_folders as $dirname) { foreach ($_files[$dirname] as $_dir => $_subfiles) { foreach ($_subfiles as $_file) { if (strrchr($_file, '.') == '.html') { $_fragmentname = str_replace('.', '_', substr($_file, 0, -5)); } else { $_fragmentname = str_replace('.', '_', substr($_file, 0, -4)); } if (substr($_fragmentname, 0, 1) == '_') { $_fragmentname = substr($_dir, 5, -1) . $_fragmentname; } if (strrchr($_file, '.') == '.html') { if (substr($_file, -9) != '.tpl.html') { $_fragmentname .= '_tpl'; } $this->fragmentslist[$_fragmentname] = $dirname . $_dir . $_file; continue; } //Контроллер - функции для работы с данными и бизнес-логика. Работа шаблонизатора подавлена. if (substr($_file, -9) == '.func.php') { $this->for_include[$_dir . $_file] = $dirname . $_dir . $_file; continue; } if (strrchr($_file, '.') == '.php') { $this->php_files_list[$_fragmentname] = $dirname . $_dir . $_file; continue; } //Обработка факта наличия .ini-файлов if (strrchr($_file, '.') == '.ini') { //Правила, срабатывающие в любом случае, инициализация опций системы и плагинов if (substr($_file, -8) == 'init.ini') { //Если имя файла оканчивается на .init.ini, инициализировать его сразу $this->for_ini[$_dir . $_file] = $dirname . $_dir . $_file; } else { //При первом запросе адрес сбрасывается в false для предотвращения последующего чтения //Хранит адрес ini-файла, запускаемого перед определённой функцией //DEPRECATED $_dir_file = $_dir . $_file; //Реалзация приоритетов: одноимённый файл из папки app переопределит тотже из папки cms if (isset($ini_files_dirs[$_dir_file])) { foreach ($this->ini_database as $_key => $_ininame) { foreach ($_ininame as $key => $value) { if ($value == $ini_files_dirs[$_dir_file]) { unset($this->ini_database[$_key][$key]); } } } } $ini_files_dirs[$_dir_file] = $dirname . $_dir . $_file; if (isset($this->ini_database[substr($_file, 0, -4)])) { $this->ini_database[substr($_file, 0, -4)][] = $dirname . $_dir . $_file; } else { $this->ini_database[substr($_file, 0, -4)] = array($dirname . $_dir . $_file); } } continue; } } } } $autoload_folders = array(); foreach ($simple_folders as $folder) { $_handle = opendir($_SERVER['DOCUMENT_ROOT'] . '/' . $folder); while (false !== ($_file = readdir($_handle))) { //ищем php файлы if (strrchr($_file, '.') == '.php' || is_dir($_SERVER['DOCUMENT_ROOT'] . '/' . $folder . '/' . $_file)) { $fistrsim = $_file[0]; if ($fistrsim >= 'A' && $fistrsim <= 'Z') { //это класс $autoload_folders[$folder] = true; } else { $this->for_include[$folder . '/' . $_file] = $folder . '/' . $_file; } } } //создаём план работы над директориями и их кодом //PHP файлы инклудим //HTML файлы запоминаем } foreach ($this->for_ini as $value) { $this->load_and_parse_ini_file($value); } doitClass::$autoload_folders = array_keys($autoload_folders); spl_autoload_register(function ($class_name) { $class_name = ltrim($class_name, '\\'); $fileName = ''; $namespace = ''; if ($lastNsPos = strripos($class_name, '\\')) { $namespace = substr($class_name, 0, $lastNsPos); $class_name = substr($class_name, $lastNsPos + 1); $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; } $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $class_name) . '.php'; //$fileName = 'vendors'.DIRECTORY_SEPARATOR.$fileName; $lover_class_name = strtolower($class_name); foreach (doitClass::$autoload_folders as $path) { if (is_file($_SERVER['DOCUMENT_ROOT'] . '/' . $path . '/' . $fileName)) { require $_SERVER['DOCUMENT_ROOT'] . '/' . $path . '/' . $fileName; return; } } }, true, true); if (PHP_VERSION_ID > 50408) { $this->http_request = Zend\Diactoros\ServerRequestFactory::fromGlobals($_SERVER, $_GET, $_POST, $_COOKIE, $_FILES); $this->http_response = new Zend\Diactoros\Response(); $this->middleware_pipe = new Zend\Stratigility\MiddlewarePipe(); } foreach ($this->for_include as $value) { $this->_current_include_directory = dirname($_SERVER['DOCUMENT_ROOT'] . '/' . $value); $this->_current_route_basename = false; if (is_file($_SERVER['DOCUMENT_ROOT'] . '/' . $value)) { include $_SERVER['DOCUMENT_ROOT'] . '/' . $value; } $this->_current_route_basename = false; } //Отрабатывает роутинг if ($this->is_using_route_all) { $url = $this->url_string; $uparts = array(); preg_match_all('#\\/([0-9a-zA-Z_]+)\\/.*#', $url, $uparts); $upart_found = false; if (isset($uparts[1][0]) && class_exists($uparts[1][0] . 'controller')) { //Мы находимся по адресу /users/ и у нас есть контроллер users. Строго гоовря, мы готовы. $sub_uparts = array(); foreach (doitClass::$instance->datapool['urls'] as $rule) { preg_match_all('#\\^?\\/([0-9a-zA-Z_]+)\\/.*#', $rule[0], $sub_uparts); if (isset($sub_uparts[1][0]) && $sub_uparts == $uparts[1][0]) { $upart_found = true; break; } } if (!$upart_found) { route($uparts[1][0]); } } } d()->bootstrap(); if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/app/static') && strpos($this->url_string, '..') === false && $this->url_string != '/' && file_exists($_SERVER['DOCUMENT_ROOT'] . '/app/static' . $this->url_string) && is_file($_SERVER['DOCUMENT_ROOT'] . '/app/static' . $this->url_string)) { $this->compiled_fragments['doit_open_static_file'] = $this->shablonize(file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/app/static' . $this->url_string)); $this->_prepared_content['main'] = $this->compile_and_run_template('doit_open_static_file'); } if (isset($_POST['_global']) && $_POST['_global'] == '1') { if (isset($_POST['_run_before']) && $_POST['_run_before'] != '') { $this->_run_before = $_POST['_run_before']; } else { $this->validate_global_handlers(); } } }
<?php declare (strict_types=1); /** @var Spot\Api\ApplicationInterface $app */ $app = (require __DIR__ . '/../app_init.php'); // Create request from globals $request = Zend\Diactoros\ServerRequestFactory::fromGlobals(); // Execute the application $response = $app->execute($request); // Output the response (new Zend\Diactoros\Response\SapiEmitter())->emit($response);
<?php require '../vendor/autoload.php'; // Get URI object. $uri = Zend\Diactoros\ServerRequestFactory::fromGlobals()->getUri(); // Setup DebugBar $debugbar = new DebugBar\StandardDebugBar(); $debugbar->getJavascriptRenderer()->setBaseUrl($uri->withPort('8000')->withPath('/')); // Setting up the stack off middlewares. $handler = GuzzleHttp\HandlerStack::create(); $middleware = new GuzzleHttp\Profiling\Middleware(new GuzzleHttp\Profiling\Debugbar\Profiler($debugbar->getCollector('time'))); $handler->unshift($middleware); $handler->unshift(Demo1\GithubAuth::create()); // Boot application. $controller = new Demo6\Controller(new GuzzleHttp\Client(compact('handler')), $debugbar->getJavascriptRenderer()); // Let application do the magic. $response = $controller->index(); // Output Response. (new Zend\Diactoros\Response\SapiEmitter())->emit($response);
<?php /** * Part of Windwalker project. * * @copyright Copyright (C) 2016 LYRASOFT. All rights reserved. * @license GNU General Public License version 2 or later. */ use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; include_once __DIR__ . '/../../../../vendor/autoload.php'; $request = Zend\Diactoros\ServerRequestFactory::fromGlobals($_SERVER, $_GET, $_POST, $_COOKIE, $_FILES); $server = \Zend\Diactoros\Server::createServerFromRequest(function (RequestInterface $request, ResponseInterface $response, $done) { $response->getBody()->write("Hello world!"); show($request->getUri()); }, $request); $server->listen();
public function register(Pimple\Container $c) { include __DIR__ . '/../local/config.php'; foreach ($env as $envk => $envval) { $c["config/{$envk}"] = $envval; } $c['routes'] = ['/' => 'route/index', '/test', '/index', '/form', '/exception']; $c['entityManager'] = function ($c) { $config = Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(array(__DIR__ . "/orm"), $c['config/devVersion']); $conn = $c['config/databases']['default']; return Doctrine\ORM\EntityManager::create($conn, $config); }; $c['dispatcher'] = function ($c) { $routes = $c['routes']; $dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) use($routes) { foreach ($routes as $k => $v) { if (is_int($k)) { $k = $v; $v = "route{$v}"; } $r->addRoute('*', $k, $v); } }); return $dispatcher; }; $c['request'] = function ($c) { $req = Zend\Diactoros\ServerRequestFactory::fromGlobals($_SERVER, $_GET, $_POST, $_COOKIE, $_FILES); $c['logger']->notice('Started ' . $req->getMethod() . ' ' . $req->getUri()->getPath()); return $req; }; $c['resource'] = function ($c) { $dispatcher = $c['dispatcher']; $request = $c['request']; $uri = $request->getUri(); $path = $uri->getPath(); if (preg_match("|^(.+)\\..+\$|", $path, $matches)) { //if path ends in .json, .html, etc, ignore it $path = $matches[1]; } $res = $dispatcher->dispatch('*', $path); if ($res[0] == FastRoute\Dispatcher::NOT_FOUND) { throw new WebAppRouteNotFoundException("Route '{$path}' not found on routing table"); } $reqParameters = $res[2]; $c['requestParameters'] = $reqParameters; $entry = $res[1]; if (!isset($c[$entry])) { throw new WebAppResourceNotFoundException("Resource '{$entry}' not found on DI container"); } $res = $c[$entry]; $c['logger']->notice("Resource Selected ({$entry}): " . get_class($res)); return $res; }; $c['response'] = function ($c) { try { $resource = $c['resource']; return $resource->exec(); } catch (Exception $e) { return $c['handleException']($e); } }; $c['templaterFactory'] = function ($c) { $temp = new ExampleApp\templater\SampleTemplaterFactory(); $temp->globalContext = ['url' => $c['config/publicUrl'], 'assetsUrl' => $c['config/assetsUrl']]; return $temp; }; $c['responseFactory'] = function ($c) { $respFactory = new Resourceful\ResponseFactory(); $respFactory->templaterFactory = $c['templaterFactory']; return $respFactory; }; $c['responseEmitter'] = function ($c) { return new Zend\Diactoros\Response\SapiEmitter(); }; $c['session'] = function ($c) { $sess = new Resourceful\SessionStorage("ExampleApp"); $sess->startSession(); return $sess; }; $c['logger'] = function ($c) { $handler = new Monolog\Handler\ErrorLogHandler(Monolog\Handler\ErrorLogHandler::SAPI, Monolog\Logger::NOTICE); $formatter = new Monolog\Formatter\LineFormatter(); $formatter->includeStacktraces(true); $handler->setFormatter($formatter); $log = new Monolog\Logger('webapp'); $log->pushHandler($handler); return $log; }; $c['handleException'] = $c->protect(function ($e) use($c) { $c['logger']->error($e); $exceptionBuilder = new \Resourceful\Exception\ExceptionResponseBuilder(); $exceptionBuilder->includeStackTrace = $c['config/devVersion']; $exceptionBuilder->responseFactory = $c['responseFactory']; $request = null; try { $request = $c['request']; } catch (Exception $e) { //ignore and just use a null request } $resp = $exceptionBuilder->buildResponse($e, $request); return $resp; }); $mkres = function ($cls) use($c) { return function ($c) use($cls) { $res = new $cls(); $res->request = $c['request']; $res->parameters = $c['requestParameters']; $res->responseFactory = $c['responseFactory']; $res->session = $c['session']; return $res; }; }; $c['route/index'] = $mkres('ExampleApp\\Home\\Control\\IndexResource'); $c['route/form'] = $mkres('ExampleApp\\Home\\Control\\FormResource'); $c['route/exception'] = $mkres('ExampleApp\\Home\\Control\\ExceptionResource'); }