private function request($method, $path, $data = array(), $optionalHeaders = array()) { // Capture STDOUT ob_start(); $options = array('REQUEST_METHOD' => strtoupper($method), 'PATH_INFO' => $path, 'SERVER_NAME' => 'local.dev'); if ($method === 'get') { $options['QUERY_STRING'] = http_build_query($data); } elseif (is_array($data)) { $options['slim.input'] = http_build_query($data); } else { $options['slim.input'] = $data; } // Prepare a mock environment Slim\Environment::mock(array_merge($options, $optionalHeaders)); $env = Slim\Environment::getInstance(); $this->app->router = new NoCacheRouter($this->app->router); $this->app->request = new Slim\Http\Request($env); // Custom headers $this->app->request->headers = new Slim\Http\Headers($env); $this->app->response = new Slim\Http\Response(); // Establish some useful references to the slim app properties $this->request = $this->app->request(); $this->response = $this->app->response(); // Execute our app $this->app->run(); // Return the application output. Also available in `response->body()` return ob_get_clean(); }
protected function setUrl($path, $params = '', $config = array()) { Environment::mock(array('REQUEST_METHOD' => 'GET', 'REMOTE_ADDR' => '127.0.0.1', 'SCRIPT_NAME' => '', 'PATH_INFO' => $path, 'QUERY_STRING' => $params, 'SERVER_NAME' => 'slim', 'SERVER_PORT' => 80, 'slim.url_scheme' => 'http', 'slim.input' => '', 'slim.errors' => fopen('php://stderr', 'w'), 'HTTP_HOST' => 'slim')); $this->env = Environment::getInstance(); $this->req = new Request($this->env); $this->res = new Response(); $this->app = new Slim(array_merge(array('controller.class_prefix' => '\\SlimController\\Tests\\Fixtures\\Controller', 'controller.class_suffix' => 'Controller', 'controller.method_suffix' => 'Action', 'controller.template_suffix' => 'php', 'templates.path' => __DIR__ . '/Fixtures/templates'), $config)); }
public function testBestFormatWithPriorities() { \Slim\Environment::mock(array('ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'negotiation.priorities' => array('xml'))); $s = new \Slim\Slim(); $s->add(new ContentNegotiation()); $s->run(); $env = \Slim\Environment::getInstance(); $bestFormat = $env['request.best_format']; $this->assertNotNull($bestFormat); $this->assertEquals('xml', $bestFormat); }
public function call() { $basePath = $this->app->request->getScriptName(); $virtualPath = $this->app->request->getPathInfo(); $pathChunk = explode("/", $virtualPath); if (count($pathChunk) > 1 && in_array($pathChunk[1], $this->availableLangs)) { $this->app->locale->set($pathChunk[1]); $pathChunk = array_slice($pathChunk, 2); } $_SERVER['REQUEST_URI'] = $basePath . "/" . implode("/", $pathChunk); $newEnv = \Slim\Environment::getInstance(true); $newRequest = new \Slim\Http\Request($newEnv); $this->app->container->request = $newRequest; $this->next->call(); }
/** * Our (marginally) smarter render function. The layout can be changed by * setting a "_layout" data key to the new layout file, or boolean false to * disable layout. * * @param string $template template name * @return string rendered template */ public function render($template) { $env = \Slim\Environment::getInstance(); $this->setData('_base', $env['SCRIPT_NAME']); $data = $this->getData(); if (isset($data['_layout'])) { $layout = $data['_layout']; } else { $layout = $this->layout; } $content = parent::render($template); if ($layout !== false) { $this->setData($data); $this->setData('content', $content); $content = parent::render($layout); } return $content; }
/** * performs a custom request * * @param string $method the request type (POST, DELETE, PUT, GET, ...) * @param string $target the taget URL * @param string $header an array with header informations * @param string $content the request content/body * * @return an array with the request result (status, header, content) * - ['headers'] = an array of header informations e.g. ['headers']['Content-Type'] * - ['content'] = the response content * - ['status'] = the status code e.g. 200,201,404,409,... */ public static function custom($method, $target, $header, $content, $authbool = true, $sessiondelete = false) { $begin = microtime(true); $done = false; if (!CConfig::$onload && strpos($target, 'http://localhost/') === 0 && file_exists(dirname(__FILE__) . '/request_cconfig.json')) { if (self::$components === null) { self::$components = CConfig::loadStaticConfig('', '', dirname(__FILE__), 'request_cconfig.json'); } $coms = self::$components->getLinks(); if ($coms != null) { if (!is_array($coms)) { $coms = array($coms); } $e = strlen(rtrim($_SERVER['DOCUMENT_ROOT'], '/')); $f = substr(str_replace("\\", "/", dirname(__FILE__)), $e); $g = substr(str_replace("\\", "/", $_SERVER['SCRIPT_FILENAME']), $e); $a = 0; for (; $a < strlen($g) && $a < strlen($f) && $f[$a] == $g[$a]; $a++) { } $h = substr(str_replace("\\", "/", $_SERVER['PHP_SELF']), 0, $a - 1); foreach ($coms as $com) { if ($com->getPrefix() === null || $com->getLocalPath() == null || $com->getClassFile() == null || $com->getClassName() == null) { Logger::Log('nodata: ' . $method . ' ' . $target, LogLevel::DEBUG, false, dirname(__FILE__) . '/../calls.log'); continue; } $url = 'http://localhost' . $h . '/' . $com->getLocalPath(); if (strpos($target, $url . '/') === 0) { $result = array(); $tar = dirname(__FILE__) . '/../' . $com->getLocalPath() . '/' . $com->getClassFile(); $tar = str_replace("\\", "/", $tar); if (!file_exists($tar)) { continue; } $add = substr($target, strlen($url)); $sid = CacheManager::getNextSid(); CacheManager::getTree($sid, $target, $method); $cachedData = CacheManager::getCachedDataByURL($sid, $target, $method); if ($cachedData !== null) { $result['content'] = $cachedData->content; $result['status'] = $cachedData->status; ///Logger::Log('out>> '.$method.' '.$target, LogLevel::DEBUG, false, dirname(__FILE__) . '/../calls.log'); CacheManager::cacheData($sid, $com->getTargetName(), $target, $result['content'], $result['status'], $method); } else { $args = array('REQUEST_METHOD' => $method, 'PATH_INFO' => $add, 'slim.input' => $content); if (isset($_SERVER['HTTP_SESSION'])) { $args['HTTP_SESSION'] = $_SERVER['HTTP_SESSION']; } if (isset($_SERVER['HTTP_USER'])) { $args['HTTP_USER'] = $_SERVER['HTTP_USER']; } if ($authbool) { if (isset($_SESSION['UID'])) { $args['HTTP_USER'] = $_SESSION['UID']; $_SERVER['HTTP_USER'] = $_SESSION['UID']; } if (isset($_SESSION['SESSION'])) { $args['HTTP_SESSION'] = $_SESSION['SESSION']; $_SERVER['HTTP_SESSION'] = $_SESSION['SESSION']; } if ($sessiondelete) { if (isset($_SERVER['REQUEST_TIME'])) { $args['HTTP_DATE'] = $_SERVER['REQUEST_TIME']; $_SERVER['HTTP_DATE'] = $_SERVER['REQUEST_TIME']; } } else { if (isset($_SESSION['LASTACTIVE'])) { $args['HTTP_DATE'] = $_SESSION['LASTACTIVE']; $_SERVER['HTTP_DATE'] = $_SESSION['LASTACTIVE']; } } } if (isset($_SERVER['HTTP_DATE'])) { $args['HTTP_DATE'] = $_SERVER['HTTP_DATE']; } $oldArgs = array('REQUEST_METHOD' => \Slim\Environment::getInstance()->offsetGet('REQUEST_METHOD'), 'PATH_INFO' => \Slim\Environment::getInstance()->offsetGet('PATH_INFO'), 'slim.input' => \Slim\Environment::getInstance()->offsetGet('slim.input'), 'HTTP_DATE' => \Slim\Environment::getInstance()->offsetGet('HTTP_DATE'), 'HTTP_USER' => \Slim\Environment::getInstance()->offsetGet('HTTP_USER'), 'HTTP_SESSION' => \Slim\Environment::getInstance()->offsetGet('HTTP_SESSION'), 'REQUEST_TIME' => \Slim\Environment::getInstance()->offsetGet('REQUEST_TIME')); $oldRequestURI = $_SERVER['REQUEST_URI']; $oldScriptName = $_SERVER['SCRIPT_NAME']; ///$oldRedirectURL = $_SERVER['REDIRECT_URL']; ///echo "old: ".$_SERVER['REQUEST_URI']."\n"; $_SERVER['REQUEST_URI'] = substr($target, strlen('http://localhost/') - 1); //$tar.$add; ///$_SERVER['REDIRECT_URL']= substr($target,strlen('http://localhost/')-1); ///echo "mein: ".substr($target,strlen('http://localhost/')-1)."\n"; $_SERVER['SCRIPT_NAME'] = $h . '/' . $com->getLocalPath() . '/' . $com->getClassFile(); //$tar; $_SERVER['QUERY_STRING'] = ''; $_SERVER['REQUEST_METHOD'] = $method; \Slim\Environment::mock($args); include_once $tar; $oldStatus = http_response_code(); $oldHeader = array_merge(array(), headers_list()); header_remove(); http_response_code(0); $name = $com->getClassName(); try { ob_start(); $obj = new $name(); if (isset($obj)) { unset($obj); } $result['content'] = ob_get_contents(); CacheManager::setETag($result['content']); $result['headers'] = array_merge(array(), self::http_parse_headers_short(headers_list())); header_remove(); if (!isset($result['headers']['Cachesid'])) { $newSid = CacheManager::getNextSid(); $result['headers']['Cachesid'] = $newSid; } ob_end_clean(); //header_remove(); $result['status'] = http_response_code(); } catch (Exception $e) { error_log($e->getMessage()); header_remove(); $result['status'] = '500'; $result['content'] = ''; $result['headers'] = array(); } $_SERVER['REQUEST_URI'] = $oldRequestURI; $_SERVER['SCRIPT_NAME'] = $oldScriptName; //$_SERVER['REDIRECT_URL'] = $oldRedirectURL; \Slim\Environment::mock($oldArgs); $_SERVER['REQUEST_METHOD'] = $oldArgs['REQUEST_METHOD']; http_response_code($oldStatus); header('Content-Type: text/html; charset=utf-8'); foreach ($oldHeader as $head) { header($head); } CacheManager::setCacheSid($sid); $targetSid = isset($result['headers']['Cachesid']) ? $result['headers']['Cachesid'] : null; CacheManager::addPath($sid, $targetSid, $com->getTargetName(), $target, $method, $result['status']); CacheManager::finishRequest($targetSid, $h . '/' . $com->getLocalPath(), $com->getTargetName(), $target, $result['content'], $result['status'], $method, $content); CacheManager::cacheData($sid, $com->getTargetName(), $target, $result['content'], $result['status'], $method); ///Logger::Log('in<< '.$method.' '.$com->getClassName().$add, LogLevel::DEBUG, false, dirname(__FILE__) . '/../calls.log'); } $done = true; break; } } } } if (!$done) { // creates a custom request Logger::Log("--" . $method . ' ' . $target, LogLevel::DEBUG, false, dirname(__FILE__) . '/../calls.log'); $ch = Request_CreateRequest::createCustom($method, $target, $header, $content, $authbool, $sessiondelete)->get(); $content = curl_exec($ch); // get the request result $result = curl_getinfo($ch); $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); // splits the received header info, to create an entry // in the $result['headers'] for each part of the header $result['headers'] = self::http_parse_headers(substr($content, 0, $header_size)); // seperates the content part $result['content'] = substr($content, $header_size); // sets the received status code $result['status'] = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); } Logger::Log($target . ' ' . round(microtime(true) - $begin, 2) . 's', LogLevel::DEBUG, false, dirname(__FILE__) . '/../executionTime.log'); return $result; }
public function __construct() { $this->environment = \Slim\Environment::getInstance(); }
public function __construct() { parent::__construct(\Slim\Environment::getInstance()); }
protected function parseQueryString() { // get the query strong from the environment $queryString = Environment::getInstance()->offsetGet('QUERY_STRING'); // get the parser $parser = $this->getParser(); try { // stash the parseResult; $this->parseResult = $parser->parse($queryString); } catch (Parser\ParserException $e) { $this->badRequest('Parse error: ' . $e->getMessage()); } }
public function validate() { $environment = \Slim\Environment::getInstance(); return !in_array($environment["REQUEST_METHOD"], $this->options["passthru"]); }
*/ $page_cnt = count($posts) / $count_per_page; $remain = count($posts) % $count_per_page; if ($remain > 0) { $page_cnt++; } for ($i = 1; $i <= $page_cnt; $i++) { if (!file_exists($out_path . '/pages/' . $i)) { mkdir($out_path . '/pages/' . $i, 0777, true); if ($debug) { echo 'created directory ' . $out_path . '/pages/' . $i . "\n"; } } $req_uri = '/pages/' . $i . '/index.html'; $_SERVER['REQUEST_URI'] = $script_name . $req_uri; $app->environment = \Slim\Environment::getInstance(true); ob_start(); require $pub_path . '/index.php'; $contents = ob_get_contents(); ob_end_clean(); file_put_contents($out_path . $req_uri, $contents); if ($debug) { echo 'wrote ' . $out_path . $req_uri . "\n"; } } /** * copy php file */ $files = glob($pub_path . '/*'); foreach ($files as $file) { if (!is_file($file)) {
public function __construct() { $env = \Slim\Environment::getInstance(); $this->request = new \Slim\Http\Request($env); $this->routes = array(); }
/** * Test valid resource handle to php://stdErr */ public function testErrorResource() { $env = \Slim\Environment::getInstance(true); $this->assertTrue(is_resource($env['slim.errors'])); }
/** * @return webApplicationBase * * @throws webApplicationException */ protected function app() { /** @var Slim $slimOriginal */ static $app, $router; if ($app === null) { $app = $this->getBaseApplication(); //MPCMF_DEBUG && self::log()->addDebug('Before bindings call...'); $app->beforeBindings(); $app->processBindings(); $env = Environment::getInstance(); $env['slim.input'] = http_build_query($_POST); $router = clone $app->slim()->router(); } else { /** @var mpcmfWeb $app */ //MPCMF_DEBUG && self::log()->addDebug('Before bindings call...'); $app->beforeBindings(); $env = Environment::getInstance(true); $env['slim.input'] = http_build_query($_POST); $slim = $app->slim(); unset($slim->request, $slim->response, $slim->router, $slim->environment); $slim->request = new Request($env); $slim->response = new Response(); $slim->router = clone $router; $slim->environment = $env; } return $app; }
/** * Führt das Modul entsprechend der Commands.json und Component.json Definitionen aus */ public function run() { // runs the CConfig $com = new CConfig($this->_prefix, $this->_path, $this->_noInfo, $this->_noHelp); // lädt die Konfiguration des Moduls if ($com->used()) { return; } $conf = $com->loadConfig(); $this->_conf = $conf; $this->_com = $com; $commands = $com->commands(array(), true, true); // multi Requests werden noch nicht unterstützt, das Model soll automatisch die Möglichkeit bieten, // mehrere Anfragen mit einmal zu beantworten ////$commands[] = array('name' => 'postMultiGetRequest','method' => 'POST', 'path' => '/multiGetRequest', 'inputType' => 'Link', 'outputType' => ''); // Erstellt für jeden angebotenen Befehl einen Router // Ein Router stellt einen erlaubten Aufruf dar (mit Methode und URI), sodass geprüft werden kann, // welcher für die Beantwortung zuständig ist $router = new \Slim\Router(); foreach ($commands as &$command) { if (!isset($command['name'])) { continue; } if (!isset($command['method'])) { $command['method'] = 'GET'; } if (!isset($command['callback'])) { $command['callback'] = $command['name']; } if (!isset($command['seqInput'])) { $command['seqInput'] = 'TRUE'; } if (!isset($command['singleOutput'])) { $command['singleOutput'] = 'FALSE'; } if (!isset($command['placeholder'])) { $command['placeholder'] = array(); } // Methoden können durch Komma getrennt aufgelistet sein $methods = explode(',', $command['method']); foreach ($methods as $method) { $route = new \Slim\Route($command['path'], array($this->_class, $command['callback']), false); $route->via(strtoupper($method)); $route->setName($command['name']); $router->map($route); // wenn es ein GET Befehl ist, wird automatisch HEAD unterstützt if (strtoupper($method) == 'GET') { // erzeugt einen HEAD Router $route = new \Slim\Route($command['path'], array($this->_class, $command['callback']), false); $route->via('HEAD'); $route->setName($command['name']); $router->map($route); } } } // hier wird die eingehende URI erzeugt // Bsp.: /user/1 $scriptName = $_SERVER['SCRIPT_NAME']; $requestUri = $_SERVER['REQUEST_URI']; $path = str_replace('?' . (isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : ''), '', substr_replace($requestUri, '', 0, strlen(strpos($requestUri, $scriptName) !== false ? $scriptName : str_replace('\\', '', dirname($scriptName))))); // ermittelt den zuständigen Befehl $matches = $router->getMatchedRoutes(strtoupper($_SERVER['REQUEST_METHOD']), $path); if (count($matches) > 0) { // mindestens ein zutreffender Befehl wurde gefunden (nimm den Ersten) $matches = $matches[0]; // suche den zugehörigen $commands Eintrag $selectedCommand = null; foreach ($commands as $command) { if ($command['name'] === $matches->getName()) { $selectedCommand = $command; break; } } if ($selectedCommand == null) { http_response_code(500); return; } // lies die eingehenden PHP Daten $rawInput = \Slim\Environment::getInstance()->offsetGet('slim.input'); if (!$rawInput) { $rawInput = @file_get_contents('php://input'); } // wir wollen wissen, ob die Eingabedaten als Liste rein kommen $arr = true; // wenn zu diesem Befehl ein inputType angegeben wurde, wird eine Type::decodeType() aufgerufen if (isset($selectedCommand['inputType']) && trim($selectedCommand['inputType']) != '') { $inputType = $selectedCommand['inputType']; $rawInput = call_user_func_array('\\' . $inputType . '::decode' . $inputType, array($rawInput)); if (!is_array($rawInput)) { // es ist keine Liste, also mach eine daraus (damit man sie einheitlich behandeln kann) $rawInput = array($rawInput); $arr = false; } } if (strtoupper($selectedCommand['seqInput']) != 'TRUE') { $arr = false; } $params = $matches->getParams(); $placeholder = array(); // prüfe die Bedingungen für die Platzhalter foreach ($selectedCommand['placeholder'] as $holder) { if (!isset($holder['name'])) { continue; } if (!isset($holder['regex'])) { continue; } $placeholder[$holder['name']] = $holder['regex']; } /*foreach ($params as $key => $value){ if (isset($placeholder[$key])){ if (is_array($value)){ // wenn es ein Array ist, wurde ein :Element+ verwendet (Slim) // daher wird der Ausdruck auf jedes Element angewendet foreach($value as $val){ $pregRes = @preg_match($placeholder[$key], $val); if ($pregRes === false){ error_log(__FILE__.':'.__LINE__.' '.$placeholder[$key].' konnte nicht interpretiert werden'); $this->finishRequest(self::isError()); return; } else if ($pregRes === 0){ error_log(__FILE__.':'.__LINE__.' '.$val.' passt nicht zu '.$placeholder[$key]); $this->finishRequest(self::isPreconditionError()); return; } } } else { // einzelnes Element für Slim verwendet :Element $pregRes = @preg_match($placeholder[$key], $value); if ($pregRes === false){ error_log(__FILE__.':'.__LINE__.' '.$placeholder[$key].' konnte nicht interpretiert werden'); $this->finishRequest(self::isError()); return; } else if ($pregRes === 0){ error_log(__FILE__.':'.__LINE__.' '.$value.' passt nicht zu '.$placeholder[$key]); $this->finishRequest(self::isPreconditionError()); return; } } } }*/ // nun soll die zugehörige Funktion im Modul aufgerufen werden if (isset($selectedCommand['inputType']) && trim($selectedCommand['inputType']) != '' && isset($rawInput)) { // initialisiert die Ausgabe positiv $result = array("status" => 201, "content" => array()); if (strtoupper($selectedCommand['seqInput']) == 'TRUE') { try { // für jede Eingabe wird die Funktion ausgeführt foreach ($rawInput as $input) { // Aufruf der Modulfunktion $res = call_user_func_array($matches->getCallable(), array($selectedCommand['name'], "input" => $input, $params)); // wenn es ein Ausgabeobjekt gibt, wird versucht dort einen Status zu setzen if (is_callable(array($res['content'], 'setStatus'))) { $res['content']->setStatus($res['status']); } // setze Status und Ausgabe $result["content"][] = $res['content']; if (isset($res['status'])) { $result["status"] = $res['status']; } } } catch (Exception $e) { header_remove(); error_log($e->getMessage()); $this->finishRequest(self::isError()); return; } } else { try { // Aufruf der Modulfunktion $res = call_user_func_array($matches->getCallable(), array($selectedCommand['name'], "input" => $rawInput, $params)); // wenn es ein Ausgabeobjekt gibt, wird versucht dort einen Status zu setzen if (is_callable(array($res['content'], 'setStatus'))) { $res['content']->setStatus($res['status']); } // setze Status und Ausgabe $result["content"] = $res['content']; if (isset($res['status'])) { $result["status"] = $res['status']; } } catch (Exception $e) { header_remove(); error_log($e->getMessage()); $this->finishRequest(self::isError()); return; } } } else { // wenn keinen vorgegebenen Eingabetyp gibt, wird die Eingabe direkt an die Modulfunktion weitergegeben $result = call_user_func_array($matches->getCallable(), array($selectedCommand['name'], "input" => $rawInput, $params)); } if ($selectedCommand['method'] == 'HEAD') { // Bei einer HEAD Funktion (die eventuell im Modul als GET bearbeitet wird), // kann die Ausgabe verworfen werden $result['content'] = ''; } elseif (isset($selectedCommand['outputType']) && trim($selectedCommand['outputType']) != '' && trim($selectedCommand['outputType']) != 'binary') { // wenn ein Ausgabetyp angegeben ist, wird eine Typ::encodeTyp() ausgeführt $outputType = $selectedCommand['outputType']; if (isset($result['content'])) { if (!is_array($result['content'])) { $result['content'] = array($result['content']); } if ($command['singleOutput'] !== 'FALSE' && count($result['content']) >= 1) { $result['content'] = $result['content'][0]; } elseif (!$arr && count($result['content']) == 1) { $result['content'] = $result['content'][0]; } $result['content'] = call_user_func_array('\\' . $outputType . '::encode' . $outputType, array($result['content'])); } header('Content-Type: application/json'); } elseif (isset($selectedCommand['outputType']) && trim($selectedCommand['outputType']) == 'binary') { // wenn der Ausgabetyp "binär" ist, erfolgt keine Anpassung } else { // selbst wenn nichts zutrifft, wird json kodiert if (isset($result['content'])) { $result['content'] = json_encode($result['content']); } header('Content-Type: application/json'); } } else { // es wurde kein zutreffender Befehl gefunden, also gibt es eine leere Antwort $this->finishRequest(self::isError()); return; } // ab hier werden die Ergebnisse ausgegeben $this->finishRequest($result); }
public function testDispatchWithoutCallable() { $this->setExpectedException('InvalidArgumentException'); \Slim\Environment::mock(array('REQUEST_METHOD' => 'GET', 'REMOTE_ADDR' => '127.0.0.1', 'SCRIPT_NAME' => '', 'PATH_INFO' => '/hello/josh', 'QUERY_STRING' => 'one=1&two=2&three=3', 'SERVER_NAME' => 'slim', 'SERVER_PORT' => 80, 'slim.url_scheme' => 'http', 'slim.input' => '', 'slim.errors' => fopen('php://stderr', 'w'), 'HTTP_HOST' => 'slim')); $env = \Slim\Environment::getInstance(); $req = new \Slim\Http\Request($env); $router = new \Slim\Router(); $route = new \Slim\Route('/hello/:name', 'foo'); // <-- Fail fast }
/** * Verify call with scopes using OR logic * * @test * @covers ::call * * @return void */ public function callWithEitherScope() { $storage = new \OAuth2\Storage\Memory(['access_tokens' => ['atokenvalue' => ['access_token' => 'atokenvalue', 'client_id' => 'a client id', 'user_id' => 'a user id', 'expires' => 99999999900, 'scope' => 'basicUser withPermission anExtraScope']]]); $server = new \OAuth2\Server($storage, ['enforce_state' => true, 'allow_implicit' => false, 'access_lifetime' => 3600]); \Slim\Environment::mock(['CONTENT_TYPE' => 'application/json', 'PATH_INFO' => '/foo']); $slim = self::getSlimInstance(); $authorization = new Authorization($server); $authorization->setApplication($slim); $slim->get('/foo', $authorization->withRequiredScope(['superUser', ['basicUser', 'withPermission']]), function () { }); $env = \Slim\Environment::getInstance(); $slim->request = new \Slim\Http\Request($env); $slim->request->headers->set('Authorization', 'Bearer atokenvalue'); $slim->response = new \Slim\Http\Response(); $slim->run(); $this->assertSame(200, $slim->response->status()); $this->assertSame(['access_token' => 'atokenvalue', 'client_id' => 'a client id', 'user_id' => 'a user id', 'expires' => 99999999900, 'scope' => 'basicUser withPermission anExtraScope'], $slim->token); }
/** * Constructor * @param array $userSettings Associative array of application settings */ public function __construct($userSettings = array()) { // Setup Slim application $this->settings = array_merge(self::getDefaultSettings(), $userSettings); $this->environment = \Slim\Environment::getInstance(); $this->request = new \Slim\Http\Request($this->environment); $this->response = new \Slim\Http\Response(); $this->router = new \Slim\Router($this->request->getResourceUri()); $this->middleware = array($this); $this->add(new \Slim\Middleware\Flash()); $this->add(new \Slim\Middleware\MethodOverride()); // Determine application mode $this->getMode(); // Setup view $this->view($this->config('view')); // Make default if first instance if (is_null(self::getInstance())) { $this->setName('default'); } // Set default logger that writes to stderr (may be overridden with middleware) $logWriter = $this->config('log.writer'); if (!$logWriter) { $logWriter = new \Slim\LogWriter($this->environment['slim.errors']); } $log = new \Slim\Log($logWriter); $log->setEnabled($this->config('log.enabled')); $log->setLevel($this->config('log.level')); $this->environment['slim.log'] = $log; }
public function testDispatchWithoutCallable() { \Slim\Environment::mock(array('REQUEST_METHOD' => 'GET', 'REMOTE_ADDR' => '127.0.0.1', 'SCRIPT_NAME' => '', 'PATH_INFO' => '/hello/josh', 'QUERY_STRING' => 'one=1&two=2&three=3', 'SERVER_NAME' => 'slim', 'SERVER_PORT' => 80, 'slim.url_scheme' => 'http', 'slim.input' => '', 'slim.errors' => fopen('php://stderr', 'w'), 'HTTP_HOST' => 'slim')); $env = \Slim\Environment::getInstance(); $req = new \Slim\Http\Request($env); $router = new \Slim\Router(); $router->setResourceUri($req->getResourceUri()); $route = new \Slim\Route('/hello/:name', 'foo'); $route->matches($req->getResourceUri()); //<-- Extracts params from resource URI $this->assertFalse($router->dispatch($route)); }
public function __invoke(\Slim\Slim $app) { $environment = \Slim\Environment::getInstance(); return !in_array($environment["REQUEST_METHOD"], $this->options["passthrough"]); }
// instantiate slim framework $options = array('debug' => $config['debug'], 'templates.path' => 'views/', 'mode' => $config['mode'], 'log.writer' => $logWriter, 'cookies.encrypt' => true, 'cookies.cipher' => MCRYPT_RIJNDAEL_256, 'cookies.secret_key' => md5('@!secret!@'), 'cookies.lifetime' => '20 minutes'); $app = new \Slim\Slim($options); $app->setName($config['appname']); // later in view for example: $app->getName() $app->hook('slim.before.router', function () use($app, $config) { $setting = new \BloggerCMS\Setting(); $app->view()->setData('app', $app); // we can now use $app in views $app->view()->setData('root', ltrim(dirname($_SERVER['SCRIPT_NAME']), '\\')); $app->view()->setData('layoutsDir', dirname(__FILE__) . '/layouts/'); $app->view()->setData('dateFormat', $config['dateFormat']); $app->view()->setData('blogURL', $setting->getBlogURL()); }); // slim environment $environment = \Slim\Environment::getInstance(); // logging $log = $app->getLog(); $log->setEnabled(false); if ($config['mode'] === 'development') { $app->configureMode('development', function () use($log) { /* $log->setLevel(\Slim\Log::DEBUG); $log->setEnabled(true); $log->debug("Application Started..."); */ }); } // routes file require_once 'routes.php'; $app->run();
/** * Constructor * @param array $userSettings Associative array of application settings */ public function __construct(array $userSettings = array()) { // Setup IoC container $this->container = new \Slim\Helper\Set(); $this->container['settings'] = array_merge(static::getDefaultSettings(), $userSettings); // Default environment $this->container->singleton('environment', function ($c) { return \Slim\Environment::getInstance(); }); // Default request $this->container->singleton('request', function ($c) { return new \Slim\Http\Request($c['environment']); }); // Default response $this->container->singleton('response', function ($c) { return new \Slim\Http\Response(); }); // Default router $this->container->singleton('router', function ($c) { return new \Slim\Router(); }); // Default view $this->container->singleton('view', function ($c) { $viewClass = $c['settings']['view']; return $viewClass instanceof \Slim\View ? $viewClass : new $viewClass(); }); // Default log writer $this->container->singleton('logWriter', function ($c) { $logWriter = $c['settings']['log.writer']; return is_object($logWriter) ? $logWriter : new \Slim\LogWriter($c['environment']['slim.errors']); }); // Default log $this->container->singleton('log', function ($c) { $log = new \Slim\Log($c['logWriter']); $log->setEnabled($c['settings']['log.enabled']); $log->setLevel($c['settings']['log.level']); $env = $c['environment']; $env['slim.log'] = $log; return $log; }); // Default mode $this->container['mode'] = function ($c) { $mode = $c['settings']['mode']; if (isset($_ENV['SLIM_MODE'])) { $mode = $_ENV['SLIM_MODE']; } else { $envMode = getenv('SLIM_MODE'); if ($envMode !== false) { $mode = $envMode; } } return $mode; }; // Define default middleware stack $this->middleware = array($this); $this->add(new \Slim\Middleware\Flash()); $this->add(new \Slim\Middleware\MethodOverride()); // Make default if first instance if (is_null(static::getInstance())) { $this->setName('default'); } }
/** * Constructor * @param array $userSettings Associative array of application settings */ public function __construct(array $userSettings = array()) { // Setup IoC container $this->container = new \Slim\Helper\Set(); $this->container['settings'] = array_merge(static::getDefaultSettings(), $userSettings); // Default environment $this->container->singleton('environment', function ($c) { return \Slim\Environment::getInstance(); }); // Default request $this->container->singleton('request', function ($c) { return new \Slim\Http\Request($c['environment']); }); // Default response $this->container->singleton('response', function ($c) { return new \Slim\Http\Response(); }); // Default router $this->container->singleton('router', function ($c) { return new \Slim\Router(); }); // Default view $this->container->singleton('view', function ($c) { $viewClass = $c['settings']['view']; $templatesPath = $c['settings']['templates.path']; $view = $viewClass instanceof \Slim\View ? $viewClass : new $viewClass(); $view->setTemplatesDirectory($templatesPath); return $view; }); // Default log writer $this->container->singleton('logWriter', function ($c) { $logWriter = $c['settings']['log.writer']; return is_object($logWriter) ? $logWriter : new \Slim\LogWriter($c['environment']['slim.errors']); }); // Default log $this->container->singleton('log', function ($c) { $log = new \Slim\Log($c['logWriter']); $log->setEnabled($c['settings']['log.enabled']); /** * set exception and message queue cnofiguration to logger * @author Mustafa Zeynel Dağlı */ $log->setExceptionsQueue($c['settings']['exceptions.rabbitMQ']); /** * set message queue logging format on message receiver * @author Mustafa Zeynel Dağlı */ $log->setExceptionsQueueLogging($c['settings']['exceptions.rabbitMQ.logging']); /** * set exception queue name * @author Mustafa Zeynel Dağlı */ $log->setExceptionsQueueName($c['settings']['exceptions.rabbitMQ.queue.name']); /** * set serial for message queue in log class * @author Mustafa Zeynel Dağlı */ $log->setSerial($c['settings']['request.serial']); //print_r('slim construct log level-->'.$c['settings']['log.level']); $log->setLevel($c['settings']['log.level']); $env = $c['environment']; $env['slim.log'] = $log; return $log; }); // Default mode $this->container['mode'] = function ($c) { $mode = $c['settings']['mode']; if (isset($_ENV['SLIM_MODE'])) { $mode = $_ENV['SLIM_MODE']; } else { $envMode = getenv('SLIM_MODE'); if ($envMode !== false) { $mode = $envMode; } } return $mode; }; // Define default middleware stack $this->middleware = array($this); //$this->add(new \Slim\Middleware\Flash()); $this->add(new \Slim\Middleware\MethodOverride()); //$this->add(new \Slim\Middleware\MiddlewareTest()); $this->add(new \Slim\Middleware\Flash()); //$this->add(new \Slim\Middleware\MethodOverride()); // Make default if first instance if (is_null(static::getInstance())) { $this->setName('default'); } }