From a47eb1c2632d20dc4ff7530345ea01e4dbec8a7e Mon Sep 17 00:00:00 2001 From: Andre Marques dos Santos Date: Sat, 9 Sep 2017 23:00:41 -0300 Subject: [PATCH] =?UTF-8?q?Atualiza=C3=A7=C3=A3o=20para=20utilizar=20com?= =?UTF-8?q?=20Slim=20v3.*?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 10 +- composer.json | 4 +- composer.lock | 283 ++- controllers/Pessoa.php | 43 +- index.php | 51 +- templates/default.php | 3 - vendor/autoload.php | 4 +- vendor/composer/ClassLoader.php | 58 +- vendor/composer/LICENSE | 2 +- vendor/composer/autoload_namespaces.php | 2 +- vendor/composer/autoload_psr4.php | 5 + vendor/composer/autoload_real.php | 53 +- vendor/composer/installed.json | 292 ++- vendor/slim/slim/.gitignore | 1 - vendor/slim/slim/.htaccess | 11 - vendor/slim/slim/.travis.yml | 11 - vendor/slim/slim/CONTRIBUTING.md | 20 - vendor/slim/slim/LICENSE | 19 - vendor/slim/slim/README.markdown | 208 --- vendor/slim/slim/Slim/Environment.php | 228 --- vendor/slim/slim/Slim/Exception/Pass.php | 49 - vendor/slim/slim/Slim/Exception/Stop.php | 47 - vendor/slim/slim/Slim/Helper/Set.php | 246 --- vendor/slim/slim/Slim/Http/Cookies.php | 220 ++- vendor/slim/slim/Slim/Http/Headers.php | 264 ++- vendor/slim/slim/Slim/Http/Request.php | 1285 +++++++++---- vendor/slim/slim/Slim/Http/Response.php | 654 +++---- vendor/slim/slim/Slim/Http/Util.php | 434 ----- vendor/slim/slim/Slim/Log.php | 354 ---- vendor/slim/slim/Slim/LogWriter.php | 75 - vendor/slim/slim/Slim/Middleware.php | 114 -- .../slim/Slim/Middleware/ContentTypes.php | 174 -- vendor/slim/slim/Slim/Middleware/Flash.php | 212 --- .../slim/Slim/Middleware/MethodOverride.php | 94 - .../slim/Slim/Middleware/PrettyExceptions.php | 116 -- .../slim/Slim/Middleware/SessionCookie.php | 205 -- vendor/slim/slim/Slim/Route.php | 550 +++--- vendor/slim/slim/Slim/Router.php | 498 +++-- vendor/slim/slim/Slim/Slim.php | 1444 -------------- vendor/slim/slim/Slim/View.php | 282 --- vendor/slim/slim/composer.json | 52 +- vendor/slim/slim/index.php | 169 -- vendor/slim/slim/phpunit.xml.dist | 25 - vendor/slim/slim/tests/EnvironmentTest.php | 376 ---- vendor/slim/slim/tests/Foo.php | 7 - vendor/slim/slim/tests/Helper/SetTest.php | 241 --- vendor/slim/slim/tests/Http/CookiesTest.php | 92 - vendor/slim/slim/tests/Http/HeadersTest.php | 59 - vendor/slim/slim/tests/Http/RequestTest.php | 949 ---------- vendor/slim/slim/tests/Http/ResponseTest.php | 271 --- vendor/slim/slim/tests/Http/UtilTest.php | 445 ----- vendor/slim/slim/tests/LogTest.php | 208 --- vendor/slim/slim/tests/LogWriterTest.php | 48 - .../tests/Middleware/ContentTypesTest.php | 162 -- .../slim/slim/tests/Middleware/FlashTest.php | 141 -- .../tests/Middleware/MethodOverrideTest.php | 149 -- .../tests/Middleware/PrettyExceptionsTest.php | 153 -- .../tests/Middleware/SessionCookieTest.php | 463 ----- vendor/slim/slim/tests/MiddlewareTest.php | 79 - vendor/slim/slim/tests/README | 18 - vendor/slim/slim/tests/RouteTest.php | 617 ------ vendor/slim/slim/tests/RouterTest.php | 250 --- vendor/slim/slim/tests/SlimTest.php | 1657 ----------------- vendor/slim/slim/tests/ViewTest.php | 199 -- vendor/slim/slim/tests/bootstrap.php | 22 - vendor/slim/slim/tests/templates/test.php | 1 - 66 files changed, 2934 insertions(+), 12544 deletions(-) delete mode 100644 templates/default.php delete mode 100644 vendor/slim/slim/.gitignore delete mode 100644 vendor/slim/slim/.htaccess delete mode 100644 vendor/slim/slim/.travis.yml delete mode 100644 vendor/slim/slim/CONTRIBUTING.md delete mode 100644 vendor/slim/slim/LICENSE delete mode 100644 vendor/slim/slim/README.markdown delete mode 100644 vendor/slim/slim/Slim/Environment.php delete mode 100644 vendor/slim/slim/Slim/Exception/Pass.php delete mode 100644 vendor/slim/slim/Slim/Exception/Stop.php delete mode 100644 vendor/slim/slim/Slim/Helper/Set.php delete mode 100644 vendor/slim/slim/Slim/Http/Util.php delete mode 100644 vendor/slim/slim/Slim/Log.php delete mode 100644 vendor/slim/slim/Slim/LogWriter.php delete mode 100644 vendor/slim/slim/Slim/Middleware.php delete mode 100644 vendor/slim/slim/Slim/Middleware/ContentTypes.php delete mode 100644 vendor/slim/slim/Slim/Middleware/Flash.php delete mode 100644 vendor/slim/slim/Slim/Middleware/MethodOverride.php delete mode 100644 vendor/slim/slim/Slim/Middleware/PrettyExceptions.php delete mode 100644 vendor/slim/slim/Slim/Middleware/SessionCookie.php delete mode 100644 vendor/slim/slim/Slim/Slim.php delete mode 100644 vendor/slim/slim/Slim/View.php delete mode 100644 vendor/slim/slim/index.php delete mode 100644 vendor/slim/slim/phpunit.xml.dist delete mode 100644 vendor/slim/slim/tests/EnvironmentTest.php delete mode 100644 vendor/slim/slim/tests/Foo.php delete mode 100644 vendor/slim/slim/tests/Helper/SetTest.php delete mode 100644 vendor/slim/slim/tests/Http/CookiesTest.php delete mode 100644 vendor/slim/slim/tests/Http/HeadersTest.php delete mode 100644 vendor/slim/slim/tests/Http/RequestTest.php delete mode 100644 vendor/slim/slim/tests/Http/ResponseTest.php delete mode 100644 vendor/slim/slim/tests/Http/UtilTest.php delete mode 100644 vendor/slim/slim/tests/LogTest.php delete mode 100644 vendor/slim/slim/tests/LogWriterTest.php delete mode 100644 vendor/slim/slim/tests/Middleware/ContentTypesTest.php delete mode 100644 vendor/slim/slim/tests/Middleware/FlashTest.php delete mode 100644 vendor/slim/slim/tests/Middleware/MethodOverrideTest.php delete mode 100644 vendor/slim/slim/tests/Middleware/PrettyExceptionsTest.php delete mode 100644 vendor/slim/slim/tests/Middleware/SessionCookieTest.php delete mode 100644 vendor/slim/slim/tests/MiddlewareTest.php delete mode 100644 vendor/slim/slim/tests/README delete mode 100644 vendor/slim/slim/tests/RouteTest.php delete mode 100644 vendor/slim/slim/tests/RouterTest.php delete mode 100644 vendor/slim/slim/tests/SlimTest.php delete mode 100644 vendor/slim/slim/tests/ViewTest.php delete mode 100644 vendor/slim/slim/tests/bootstrap.php delete mode 100644 vendor/slim/slim/tests/templates/test.php diff --git a/README.md b/README.md index df33f08..25d580e 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,16 @@ # api-php-slim-framework -API RESTful com PHP Slim Framework +API RESTful com PHP Slim Framework - adaptado para Slim v3.* -## Instalando +## Instalando - para Slim v3.* +```shell +git clone https://github.com/andre-msantos/api-php-slim-framework.git +``` + +## Instalando - para Slim v2.* ```shell git clone https://github.com/ClubeDosGeeksCoding/api-php-slim-framework.git ``` + Instale as dependencias com composer ```shell composer install diff --git a/composer.json b/composer.json index 8cb0b40..5698e4d 100644 --- a/composer.json +++ b/composer.json @@ -1,10 +1,10 @@ { "require": { - "slim/slim": "2.*" + "slim/slim": "^3.0" }, "autoload": { "psr-4": { "controllers\\": "controllers" } } -} +} \ No newline at end of file diff --git a/composer.lock b/composer.lock index e48c40e..05a89fa 100644 --- a/composer.lock +++ b/composer.lock @@ -4,33 +4,264 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "hash": "70c5485f99cd771d9dc749a9ef22335a", - "content-hash": "22d60a1750e0e5d3022134f0221b8dcf", + "content-hash": "3b0766dbcef4dfb1a4a2012fef8611d8", "packages": [ + { + "name": "container-interop/container-interop", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/container-interop/container-interop.git", + "reference": "79cbf1341c22ec75643d841642dd5d6acd83bdb8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/container-interop/container-interop/zipball/79cbf1341c22ec75643d841642dd5d6acd83bdb8", + "reference": "79cbf1341c22ec75643d841642dd5d6acd83bdb8", + "shasum": "" + }, + "require": { + "psr/container": "^1.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Interop\\Container\\": "src/Interop/Container/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Promoting the interoperability of container objects (DIC, SL, etc.)", + "homepage": "https://github.com/container-interop/container-interop", + "time": "2017-02-14T19:40:03+00:00" + }, + { + "name": "nikic/fast-route", + "version": "v1.2.0", + "source": { + "type": "git", + "url": "https://github.com/nikic/FastRoute.git", + "reference": "b5f95749071c82a8e0f58586987627054400cdf6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/FastRoute/zipball/b5f95749071c82a8e0f58586987627054400cdf6", + "reference": "b5f95749071c82a8e0f58586987627054400cdf6", + "shasum": "" + }, + "require": { + "php": ">=5.4.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "FastRoute\\": "src/" + }, + "files": [ + "src/functions.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov", + "email": "nikic@php.net" + } + ], + "description": "Fast request router for PHP", + "keywords": [ + "router", + "routing" + ], + "time": "2017-01-19T11:35:12+00:00" + }, + { + "name": "pimple/pimple", + "version": "v3.2.2", + "source": { + "type": "git", + "url": "https://github.com/silexphp/Pimple.git", + "reference": "4d45fb62d96418396ec58ba76e6f065bca16e10a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/silexphp/Pimple/zipball/4d45fb62d96418396ec58ba76e6f065bca16e10a", + "reference": "4d45fb62d96418396ec58ba76e6f065bca16e10a", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "psr/container": "^1.0" + }, + "require-dev": { + "symfony/phpunit-bridge": "^3.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.2.x-dev" + } + }, + "autoload": { + "psr-0": { + "Pimple": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + } + ], + "description": "Pimple, a simple Dependency Injection Container", + "homepage": "http://pimple.sensiolabs.org", + "keywords": [ + "container", + "dependency injection" + ], + "time": "2017-07-23T07:32:15+00:00" + }, + { + "name": "psr/container", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/b7ce3b176482dbbc1245ebf52b181af44c2cf55f", + "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "time": "2017-02-14T16:28:37+00:00" + }, + { + "name": "psr/http-message", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "time": "2016-08-06T14:39:51+00:00" + }, { "name": "slim/slim", - "version": "2.6.2", + "version": "3.8.1", "source": { "type": "git", "url": "https://github.com/slimphp/Slim.git", - "reference": "20a02782f76830b67ae56a5c08eb1f563c351a37" + "reference": "5385302707530b2bccee1769613ad769859b826d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/slimphp/Slim/zipball/20a02782f76830b67ae56a5c08eb1f563c351a37", - "reference": "20a02782f76830b67ae56a5c08eb1f563c351a37", + "url": "https://api.github.com/repos/slimphp/Slim/zipball/5385302707530b2bccee1769613ad769859b826d", + "reference": "5385302707530b2bccee1769613ad769859b826d", "shasum": "" }, "require": { - "php": ">=5.3.0" + "container-interop/container-interop": "^1.2", + "nikic/fast-route": "^1.0", + "php": ">=5.5.0", + "pimple/pimple": "^3.0", + "psr/container": "^1.0", + "psr/http-message": "^1.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" }, - "suggest": { - "ext-mcrypt": "Required for HTTP cookie encryption" + "require-dev": { + "phpunit/phpunit": "^4.0", + "squizlabs/php_codesniffer": "^2.5" }, "type": "library", "autoload": { - "psr-0": { - "Slim": "." + "psr-4": { + "Slim\\": "Slim" } }, "notification-url": "https://packagist.org/downloads/", @@ -38,20 +269,36 @@ "MIT" ], "authors": [ + { + "name": "Rob Allen", + "email": "rob@akrabat.com", + "homepage": "http://akrabat.com" + }, { "name": "Josh Lockhart", - "email": "info@joshlockhart.com", - "homepage": "http://www.joshlockhart.com/" + "email": "hello@joshlockhart.com", + "homepage": "https://joshlockhart.com" + }, + { + "name": "Gabriel Manricks", + "email": "gmanricks@me.com", + "homepage": "http://gabrielmanricks.com" + }, + { + "name": "Andrew Smith", + "email": "a.smith@silentworks.co.uk", + "homepage": "http://silentworks.co.uk" } ], - "description": "Slim Framework, a PHP micro framework", - "homepage": "http://github.com/codeguy/Slim", + "description": "Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs", + "homepage": "https://slimframework.com", "keywords": [ - "microframework", - "rest", + "api", + "framework", + "micro", "router" ], - "time": "2015-03-08 18:41:17" + "time": "2017-03-19T17:55:20+00:00" } ], "packages-dev": [], diff --git a/controllers/Pessoa.php b/controllers/Pessoa.php index 101ab81..0c1cc95 100644 --- a/controllers/Pessoa.php +++ b/controllers/Pessoa.php @@ -15,16 +15,18 @@ function __construct(){ $this->PDO = new \PDO('mysql:host=localhost;dbname=api', 'root', ''); //Conexão $this->PDO->setAttribute( \PDO::ATTR_ERRMODE,\PDO::ERRMODE_EXCEPTION ); //habilitando erros do PDO } + /* lista Listand pessoas */ public function lista(){ - global $app; + $sth = $this->PDO->prepare("SELECT * FROM pessoa"); $sth->execute(); $result = $sth->fetchAll(\PDO::FETCH_ASSOC); - $app->render('default.php',["data"=>$result],200); + + return $result; } /* get @@ -32,12 +34,14 @@ public function lista(){ Pega pessoa pelo id */ public function get($id){ - global $app; + $sth = $this->PDO->prepare("SELECT * FROM pessoa WHERE id = :id"); - $sth ->bindValue(':id',$id); + $sth ->bindValue( ':id' , $id ); $sth->execute(); $result = $sth->fetch(\PDO::FETCH_ASSOC); - $app->render('default.php',["data"=>$result],200); + + //retorna os dados para ser tratado via withJson + return ["data"=>$result]; } /* @@ -46,19 +50,28 @@ public function get($id){ */ public function nova(){ global $app; - $dados = json_decode($app->request->getBody(), true); + + //recupera a variável request do $app + $container = $app->getContainer(); + $request = $container['request']; + + //recupera as variáveis enviadas via post + $dados = $request->getParsedBody(); $dados = (sizeof($dados)==0)? $_POST : $dados; $keys = array_keys($dados); //Paga as chaves do array + /* O uso de prepare e bindValue é importante para se evitar SQL Injection */ + $sth = $this->PDO->prepare("INSERT INTO pessoa (".implode(',', $keys).") VALUES (:".implode(",:", $keys).")"); foreach ($dados as $key => $value) { $sth ->bindValue(':'.$key,$value); } $sth->execute(); //Retorna o id inserido - $app->render('default.php',["data"=>['id'=>$this->PDO->lastInsertId()]],200); + return ["data"=>['id'=>$this->PDO->lastInsertId()]]; + } /* @@ -68,9 +81,13 @@ public function nova(){ */ public function editar($id){ global $app; - $dados = json_decode($app->request->getBody(), true); + + $container = $app->getContainer(); + $request = $container['request']; + + $dados = $request->getParsedBody(); $dados = (sizeof($dados)==0)? $_POST : $dados; - $sets = []; + $sets = []; //criar variável array PHP >= 5.4 foreach ($dados as $key => $VALUES) { $sets[] = $key." = :".$key; } @@ -81,7 +98,8 @@ public function editar($id){ $sth ->bindValue(':'.$key,$value); } //Retorna status da edição - $app->render('default.php',["data"=>['status'=>$sth->execute()==1]],200); + return ["data"=>['status'=>$sth->execute()==1]]; + //$app->render('default.php',["data"=>['status'=>$sth->execute()==1]],200); } /* @@ -90,10 +108,11 @@ public function editar($id){ Excluindo pessoa */ public function excluir($id){ - global $app; + $sth = $this->PDO->prepare("DELETE FROM pessoa WHERE id = :id"); $sth ->bindValue(':id',$id); - $app->render('default.php',["data"=>['status'=>$sth->execute()==1]],200); + return ["data"=>['status'=>$sth->execute()==1]]; + } } } \ No newline at end of file diff --git a/index.php b/index.php index 290f522..396258a 100644 --- a/index.php +++ b/index.php @@ -1,36 +1,59 @@ [ + 'displayErrorDetails' => true, + ], +]; + //Instanciando objeto -$app = new \Slim\Slim(array( - 'templates.path' => 'templates' -)); +$app = new \Slim\App($configuration); + +//quando não é chamado nenhum método +$app->get('/', function() { + echo "Nenhum método foi chamado"; +}); //Listando todas -$app->get('/pessoas/', function() use ($app){ - (new \controllers\Pessoa($app))->lista(); +$app->get('/pessoas/', function() { + //$this->response->withJson() transforma o output em json e manda o header correto + return $this->response->withJson((new \controllers\Pessoa())->lista(),201); + }); //get pessoa -$app->get('/pessoas/:id', function($id) use ($app){ - (new \controllers\Pessoa($app))->get($id); +$app->get('/pessoas/{id}', function( $request , $response , $args ) { + $id = $args['id']; + + return $response->withJson( (new \controllers\Pessoa())->get($id) ); }); //nova pessoa -$app->post('/pessoas/', function() use ($app){ - (new \controllers\Pessoa($app))->nova(); +$app->post('/pessoas/', function( $request, $response ) use ( $app ) { + + return $response->withJson( (new \controllers\Pessoa($app))->nova() ); }); //edita pessoa -$app->put('/pessoas/:id', function($id) use ($app){ - (new \controllers\Pessoa($app))->editar($id); +$app->put('/pessoas/{id}', function( $request, $response, $args ) use ( $app ) { + + $id = $args['id']; + + return $response->withJson( (new \controllers\Pessoa($app))->editar($id) ); + }); //apaga pessoa -$app->delete('/pessoas/:id', function($id) use ($app){ - (new \controllers\Pessoa($app))->excluir($id); +$app->delete('/pessoas/{id}', function( $request, $response, $args ) { + + $id = $args['id']; + + return $response->withJson( (new \controllers\Pessoa())->excluir($id) ); }); //Rodando aplicação -$app->run(); +$app->run(); \ No newline at end of file diff --git a/templates/default.php b/templates/default.php deleted file mode 100644 index 5ade7a7..0000000 --- a/templates/default.php +++ /dev/null @@ -1,3 +0,0 @@ -classMapAuthoritative; } + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && ini_get('apc.enabled') ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + /** * Registers this instance as an autoloader. * @@ -313,29 +334,34 @@ public function loadClass($class) */ public function findFile($class) { - // work around for PHP 5.3.0 - 5.3.2 https://bugs.php.net/50731 - if ('\\' == $class[0]) { - $class = substr($class, 1); - } - // class map lookup if (isset($this->classMap[$class])) { return $this->classMap[$class]; } - if ($this->classMapAuthoritative) { + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { return false; } + if (null !== $this->apcuPrefix) { + $file = apcu_fetch($this->apcuPrefix.$class, $hit); + if ($hit) { + return $file; + } + } $file = $this->findFileWithExtension($class, '.php'); // Search for Hack files if we are running on HHVM - if ($file === null && defined('HHVM_VERSION')) { + if (false === $file && defined('HHVM_VERSION')) { $file = $this->findFileWithExtension($class, '.hh'); } - if ($file === null) { + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { // Remember that this class does not exist. - return $this->classMap[$class] = false; + $this->missingClasses[$class] = true; } return $file; @@ -348,9 +374,13 @@ private function findFileWithExtension($class, $ext) $first = $class[0]; if (isset($this->prefixLengthsPsr4[$first])) { - foreach ($this->prefixLengthsPsr4[$first] as $prefix => $length) { - if (0 === strpos($class, $prefix)) { - foreach ($this->prefixDirsPsr4[$prefix] as $dir) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath.'\\'; + if (isset($this->prefixDirsPsr4[$search])) { + foreach ($this->prefixDirsPsr4[$search] as $dir) { + $length = $this->prefixLengthsPsr4[$first][$search]; if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) { return $file; } @@ -399,6 +429,8 @@ private function findFileWithExtension($class, $ext) if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { return $file; } + + return false; } } diff --git a/vendor/composer/LICENSE b/vendor/composer/LICENSE index c8d57af..f27399a 100644 --- a/vendor/composer/LICENSE +++ b/vendor/composer/LICENSE @@ -1,5 +1,5 @@ -Copyright (c) 2015 Nils Adermann, Jordi Boggiano +Copyright (c) Nils Adermann, Jordi Boggiano Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/composer/autoload_namespaces.php b/vendor/composer/autoload_namespaces.php index 58e60b1..c3cd022 100644 --- a/vendor/composer/autoload_namespaces.php +++ b/vendor/composer/autoload_namespaces.php @@ -6,5 +6,5 @@ $baseDir = dirname($vendorDir); return array( - 'Slim' => array($vendorDir . '/slim/slim'), + 'Pimple' => array($vendorDir . '/pimple/pimple/src'), ); diff --git a/vendor/composer/autoload_psr4.php b/vendor/composer/autoload_psr4.php index 8ea2bcb..656ad00 100644 --- a/vendor/composer/autoload_psr4.php +++ b/vendor/composer/autoload_psr4.php @@ -7,4 +7,9 @@ return array( 'controllers\\' => array($baseDir . '/controllers'), + 'Slim\\' => array($vendorDir . '/slim/slim/Slim'), + 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'), + 'Psr\\Container\\' => array($vendorDir . '/psr/container/src'), + 'Interop\\Container\\' => array($vendorDir . '/container-interop/container-interop/src/Interop/Container'), + 'FastRoute\\' => array($vendorDir . '/nikic/fast-route/src'), ); diff --git a/vendor/composer/autoload_real.php b/vendor/composer/autoload_real.php index 77ed820..d8a3717 100644 --- a/vendor/composer/autoload_real.php +++ b/vendor/composer/autoload_real.php @@ -2,7 +2,7 @@ // autoload_real.php @generated by Composer -class ComposerAutoloaderInit108959cb314015d8862269752ccd16b5 +class ComposerAutoloaderInit3a90acccf0da8cf601e8ae07414403ca { private static $loader; @@ -19,27 +19,52 @@ public static function getLoader() return self::$loader; } - spl_autoload_register(array('ComposerAutoloaderInit108959cb314015d8862269752ccd16b5', 'loadClassLoader'), true, true); + spl_autoload_register(array('ComposerAutoloaderInit3a90acccf0da8cf601e8ae07414403ca', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(); - spl_autoload_unregister(array('ComposerAutoloaderInit108959cb314015d8862269752ccd16b5', 'loadClassLoader')); + spl_autoload_unregister(array('ComposerAutoloaderInit3a90acccf0da8cf601e8ae07414403ca', 'loadClassLoader')); - $map = require __DIR__ . '/autoload_namespaces.php'; - foreach ($map as $namespace => $path) { - $loader->set($namespace, $path); - } + $useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); + if ($useStaticLoader) { + require_once __DIR__ . '/autoload_static.php'; - $map = require __DIR__ . '/autoload_psr4.php'; - foreach ($map as $namespace => $path) { - $loader->setPsr4($namespace, $path); - } + call_user_func(\Composer\Autoload\ComposerStaticInit3a90acccf0da8cf601e8ae07414403ca::getInitializer($loader)); + } else { + $map = require __DIR__ . '/autoload_namespaces.php'; + foreach ($map as $namespace => $path) { + $loader->set($namespace, $path); + } + + $map = require __DIR__ . '/autoload_psr4.php'; + foreach ($map as $namespace => $path) { + $loader->setPsr4($namespace, $path); + } - $classMap = require __DIR__ . '/autoload_classmap.php'; - if ($classMap) { - $loader->addClassMap($classMap); + $classMap = require __DIR__ . '/autoload_classmap.php'; + if ($classMap) { + $loader->addClassMap($classMap); + } } $loader->register(true); + if ($useStaticLoader) { + $includeFiles = Composer\Autoload\ComposerStaticInit3a90acccf0da8cf601e8ae07414403ca::$files; + } else { + $includeFiles = require __DIR__ . '/autoload_files.php'; + } + foreach ($includeFiles as $fileIdentifier => $file) { + composerRequire3a90acccf0da8cf601e8ae07414403ca($fileIdentifier, $file); + } + return $loader; } } + +function composerRequire3a90acccf0da8cf601e8ae07414403ca($fileIdentifier, $file) +{ + if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { + require $file; + + $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; + } +} diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json index ea58c1a..e45917a 100644 --- a/vendor/composer/installed.json +++ b/vendor/composer/installed.json @@ -1,31 +1,140 @@ [ { - "name": "slim/slim", - "version": "2.6.2", - "version_normalized": "2.6.2.0", + "name": "psr/http-message", + "version": "1.0.1", + "version_normalized": "1.0.1.0", "source": { "type": "git", - "url": "https://github.com/slimphp/Slim.git", - "reference": "20a02782f76830b67ae56a5c08eb1f563c351a37" + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/slimphp/Slim/zipball/20a02782f76830b67ae56a5c08eb1f563c351a37", - "reference": "20a02782f76830b67ae56a5c08eb1f563c351a37", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", "shasum": "" }, "require": { "php": ">=5.3.0" }, - "suggest": { - "ext-mcrypt": "Required for HTTP cookie encryption" + "time": "2016-08-06T14:39:51+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ] + }, + { + "name": "psr/container", + "version": "1.0.0", + "version_normalized": "1.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/b7ce3b176482dbbc1245ebf52b181af44c2cf55f", + "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f", + "shasum": "" }, - "time": "2015-03-08 18:41:17", + "require": { + "php": ">=5.3.0" + }, + "time": "2017-02-14T16:28:37+00:00", "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ] + }, + { + "name": "pimple/pimple", + "version": "v3.2.2", + "version_normalized": "3.2.2.0", + "source": { + "type": "git", + "url": "https://github.com/silexphp/Pimple.git", + "reference": "4d45fb62d96418396ec58ba76e6f065bca16e10a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/silexphp/Pimple/zipball/4d45fb62d96418396ec58ba76e6f065bca16e10a", + "reference": "4d45fb62d96418396ec58ba76e6f065bca16e10a", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "psr/container": "^1.0" + }, + "require-dev": { + "symfony/phpunit-bridge": "^3.2" + }, + "time": "2017-07-23T07:32:15+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.2.x-dev" + } + }, "installation-source": "dist", "autoload": { "psr-0": { - "Slim": "." + "Pimple": "src/" } }, "notification-url": "https://packagist.org/downloads/", @@ -33,17 +142,166 @@ "MIT" ], "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + } + ], + "description": "Pimple, a simple Dependency Injection Container", + "homepage": "http://pimple.sensiolabs.org", + "keywords": [ + "container", + "dependency injection" + ] + }, + { + "name": "nikic/fast-route", + "version": "v1.2.0", + "version_normalized": "1.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/nikic/FastRoute.git", + "reference": "b5f95749071c82a8e0f58586987627054400cdf6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/FastRoute/zipball/b5f95749071c82a8e0f58586987627054400cdf6", + "reference": "b5f95749071c82a8e0f58586987627054400cdf6", + "shasum": "" + }, + "require": { + "php": ">=5.4.0" + }, + "time": "2017-01-19T11:35:12+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "FastRoute\\": "src/" + }, + "files": [ + "src/functions.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov", + "email": "nikic@php.net" + } + ], + "description": "Fast request router for PHP", + "keywords": [ + "router", + "routing" + ] + }, + { + "name": "container-interop/container-interop", + "version": "1.2.0", + "version_normalized": "1.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/container-interop/container-interop.git", + "reference": "79cbf1341c22ec75643d841642dd5d6acd83bdb8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/container-interop/container-interop/zipball/79cbf1341c22ec75643d841642dd5d6acd83bdb8", + "reference": "79cbf1341c22ec75643d841642dd5d6acd83bdb8", + "shasum": "" + }, + "require": { + "psr/container": "^1.0" + }, + "time": "2017-02-14T19:40:03+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Interop\\Container\\": "src/Interop/Container/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Promoting the interoperability of container objects (DIC, SL, etc.)", + "homepage": "https://github.com/container-interop/container-interop" + }, + { + "name": "slim/slim", + "version": "3.8.1", + "version_normalized": "3.8.1.0", + "source": { + "type": "git", + "url": "https://github.com/slimphp/Slim.git", + "reference": "5385302707530b2bccee1769613ad769859b826d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/slimphp/Slim/zipball/5385302707530b2bccee1769613ad769859b826d", + "reference": "5385302707530b2bccee1769613ad769859b826d", + "shasum": "" + }, + "require": { + "container-interop/container-interop": "^1.2", + "nikic/fast-route": "^1.0", + "php": ">=5.5.0", + "pimple/pimple": "^3.0", + "psr/container": "^1.0", + "psr/http-message": "^1.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0", + "squizlabs/php_codesniffer": "^2.5" + }, + "time": "2017-03-19T17:55:20+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Slim\\": "Slim" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Rob Allen", + "email": "rob@akrabat.com", + "homepage": "http://akrabat.com" + }, { "name": "Josh Lockhart", - "email": "info@joshlockhart.com", - "homepage": "http://www.joshlockhart.com/" + "email": "hello@joshlockhart.com", + "homepage": "https://joshlockhart.com" + }, + { + "name": "Gabriel Manricks", + "email": "gmanricks@me.com", + "homepage": "http://gabrielmanricks.com" + }, + { + "name": "Andrew Smith", + "email": "a.smith@silentworks.co.uk", + "homepage": "http://silentworks.co.uk" } ], - "description": "Slim Framework, a PHP micro framework", - "homepage": "http://github.com/codeguy/Slim", + "description": "Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs", + "homepage": "https://slimframework.com", "keywords": [ - "microframework", - "rest", + "api", + "framework", + "micro", "router" ] } diff --git a/vendor/slim/slim/.gitignore b/vendor/slim/slim/.gitignore deleted file mode 100644 index 485dee6..0000000 --- a/vendor/slim/slim/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.idea diff --git a/vendor/slim/slim/.htaccess b/vendor/slim/slim/.htaccess deleted file mode 100644 index c8b767a..0000000 --- a/vendor/slim/slim/.htaccess +++ /dev/null @@ -1,11 +0,0 @@ -RewriteEngine On - -# Some hosts may require you to use the `RewriteBase` directive. -# If you need to use the `RewriteBase` directive, it should be the -# absolute physical path to the directory that contains this htaccess file. -# -# RewriteBase / - -RewriteCond %{REQUEST_FILENAME} !-d -RewriteCond %{REQUEST_FILENAME} !-f -RewriteRule ^ index.php [QSA,L] diff --git a/vendor/slim/slim/.travis.yml b/vendor/slim/slim/.travis.yml deleted file mode 100644 index c70c36a..0000000 --- a/vendor/slim/slim/.travis.yml +++ /dev/null @@ -1,11 +0,0 @@ -language: php - -php: - - 5.3 - - 5.4 - - 5.5 - - 5.6 - - 7.0 - - hhvm - -script: phpunit --coverage-text diff --git a/vendor/slim/slim/CONTRIBUTING.md b/vendor/slim/slim/CONTRIBUTING.md deleted file mode 100644 index 9bbb6b1..0000000 --- a/vendor/slim/slim/CONTRIBUTING.md +++ /dev/null @@ -1,20 +0,0 @@ -# How to Contribute - -## Pull Requests - -1. Fork the Slim Framework repository -2. Create a new branch for each feature or improvement -3. Send a pull request from each feature branch to the **develop** branch - -It is very important to separate new features or improvements into separate feature branches, and to send a -pull request for each branch. This allows me to review and pull in new features or improvements individually. - -## Style Guide - -All pull requests must adhere to the [PSR-2 standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md). - -## Unit Testing - -All pull requests must be accompanied by passing unit tests and complete code coverage. The Slim Framework uses phpunit for testing. - -[Learn about PHPUnit](https://github.com/sebastianbergmann/phpunit/) diff --git a/vendor/slim/slim/LICENSE b/vendor/slim/slim/LICENSE deleted file mode 100644 index ec361cb..0000000 --- a/vendor/slim/slim/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2012 Josh Lockhart - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is furnished -to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/slim/slim/README.markdown b/vendor/slim/slim/README.markdown deleted file mode 100644 index 2bbe264..0000000 --- a/vendor/slim/slim/README.markdown +++ /dev/null @@ -1,208 +0,0 @@ -# Slim Framework - -[![Build Status](https://travis-ci.org/slimphp/Slim.svg?branch=master)](https://travis-ci.org/slimphp/Slim) - -Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs. -Slim is easy to use for both beginners and professionals. Slim favors cleanliness over terseness and common cases -over edge cases. Its interface is simple, intuitive, and extensively documented — both online and in the code itself. -Thank you for choosing the Slim Framework for your next project. I think you're going to love it. - -## Features - -* Powerful router - * Standard and custom HTTP methods - * Route parameters with wildcards and conditions - * Route redirect, halt, and pass - * Route middleware -* Resource Locator and DI container -* Template rendering with custom views -* Flash messages -* Encrypt cookie data -* HTTP caching -* Logging with custom log writers -* Error handling and debugging -* Middleware and hook architecture -* Simple configuration - -## Getting Started - -### Install - -You may install the Slim Framework with Composer (recommended) or manually. - -[Read how to install Slim](http://docs.slimframework.com/#Installation) - -### System Requirements - -You need **PHP >= 5.3.0**. If you use encrypted cookies, you'll also need the `mcrypt` extension. - -### Hello World Tutorial - -Instantiate a Slim application: - - $app = new \Slim\Slim(); - -Define a HTTP GET route: - - $app->get('/hello/:name', function ($name) { - echo "Hello, $name"; - }); - -Run the Slim application: - - $app->run(); - -### Setup your web server - -#### Apache - -Ensure the `.htaccess` and `index.php` files are in the same public-accessible directory. The `.htaccess` file -should contain this code: - - RewriteEngine On - RewriteCond %{REQUEST_FILENAME} !-f - RewriteRule ^ index.php [QSA,L] - -Additionally, make sure your virtual host is configured with the AllowOverride option so that the .htaccess rewrite rules can be used: - - AllowOverride All - -#### Nginx - -The nginx configuration file should contain this code (along with other settings you may need) in your `location` block: - - try_files $uri $uri/ /index.php?$args; - -This assumes that Slim's `index.php` is in the root folder of your project (www root). - -#### HipHop Virtual Machine for PHP - -Your HipHop Virtual Machine configuration file should contain this code (along with other settings you may need). -Be sure you change the `ServerRoot` setting to point to your Slim app's document root directory. - - Server { - SourceRoot = /path/to/public/directory - } - - ServerVariables { - SCRIPT_NAME = /index.php - } - - VirtualHost { - * { - Pattern = .* - RewriteRules { - * { - pattern = ^(.*)$ - to = index.php/$1 - qsa = true - } - } - } - } - -#### lighttpd #### - -Your lighttpd configuration file should contain this code (along with other settings you may need). This code requires -lighttpd >= 1.4.24. - - url.rewrite-if-not-file = ("(.*)" => "/index.php/$0") - -This assumes that Slim's `index.php` is in the root folder of your project (www root). - -#### IIS - -Ensure the `Web.config` and `index.php` files are in the same public-accessible directory. The `Web.config` file should contain this code: - - - - - - - - - - - - - - - - - - - -#### Google App Engine - -Two steps are required to successfully run your Slim application on Google App Engine. First, ensure the `app.yaml` file includes a default handler to `index.php`: - - application: your-app-name - version: 1 - runtime: php - api_version: 1 - - handlers: - # ... - - url: /.* - script: public_html/index.php - -Next, edit your `index.php` file so Slim knows about the incoming URI: - - $app = new Slim(); - - // Google App Engine doesn't set $_SERVER['PATH_INFO'] - $app->environment['PATH_INFO'] = $_SERVER['REQUEST_URI']; - - // ... - $app->run(); - - -## Documentation - - - -## How to Contribute - -### Pull Requests - -1. Fork the Slim Framework repository -2. Create a new branch for each feature or improvement -3. Send a pull request from each feature branch to the **develop** branch - -It is very important to separate new features or improvements into separate feature branches, and to send a pull -request for each branch. This allows me to review and pull in new features or improvements individually. - -### Style Guide - -All pull requests must adhere to the [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) standard. - -### Unit Testing - -All pull requests must be accompanied by passing unit tests and complete code coverage. The Slim Framework uses -`phpunit` for testing. - -[Learn about PHPUnit](https://github.com/sebastianbergmann/phpunit/) - -## Community - -### Forum and Knowledgebase - -Visit Slim's official forum and knowledge base at where you can find announcements, -chat with fellow Slim users, ask questions, help others, or show off your cool Slim Framework apps. - -### Twitter - -Follow [@slimphp](http://www.twitter.com/slimphp) on Twitter to receive news and updates about the framework. - -## Author - -The Slim Framework is created and maintained by [Josh Lockhart](http://www.joshlockhart.com). Josh is a senior -web developer at [New Media Campaigns](http://www.newmediacampaigns.com/). Josh also created and maintains -[PHP: The Right Way](http://www.phptherightway.com/), a popular movement in the PHP community to introduce new -PHP programmers to best practices and good information. - -## License - -The Slim Framework is released under the MIT public license. - - diff --git a/vendor/slim/slim/Slim/Environment.php b/vendor/slim/slim/Slim/Environment.php deleted file mode 100644 index 3459783..0000000 --- a/vendor/slim/slim/Slim/Environment.php +++ /dev/null @@ -1,228 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -namespace Slim; - -/** - * Environment - * - * This class creates and returns a key/value array of common - * environment variables for the current HTTP request. - * - * This is a singleton class; derived environment variables will - * be common across multiple Slim applications. - * - * This class matches the Rack (Ruby) specification as closely - * as possible. More information available below. - * - * @package Slim - * @author Josh Lockhart - * @since 1.6.0 - */ -class Environment implements \ArrayAccess, \IteratorAggregate -{ - /** - * @var array - */ - protected $properties; - - /** - * @var \Slim\Environment - */ - protected static $environment; - - /** - * Get environment instance (singleton) - * - * This creates and/or returns an environment instance (singleton) - * derived from $_SERVER variables. You may override the global server - * variables by using `\Slim\Environment::mock()` instead. - * - * @param bool $refresh Refresh properties using global server variables? - * @return \Slim\Environment - */ - public static function getInstance($refresh = false) - { - if (is_null(self::$environment) || $refresh) { - self::$environment = new self(); - } - - return self::$environment; - } - - /** - * Get mock environment instance - * - * @param array $userSettings - * @return \Slim\Environment - */ - public static function mock($userSettings = array()) - { - $defaults = array( - 'REQUEST_METHOD' => 'GET', - 'SCRIPT_NAME' => '', - 'PATH_INFO' => '', - 'QUERY_STRING' => '', - 'SERVER_NAME' => 'localhost', - 'SERVER_PORT' => 80, - 'ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', - 'ACCEPT_LANGUAGE' => 'en-US,en;q=0.8', - 'ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', - 'USER_AGENT' => 'Slim Framework', - 'REMOTE_ADDR' => '127.0.0.1', - 'slim.url_scheme' => 'http', - 'slim.input' => '', - 'slim.errors' => @fopen('php://stderr', 'w') - ); - self::$environment = new self(array_merge($defaults, $userSettings)); - - return self::$environment; - } - - /** - * Constructor (private access) - * - * @param array|null $settings If present, these are used instead of global server variables - */ - private function __construct($settings = null) - { - if ($settings) { - $this->properties = $settings; - } else { - $env = array(); - - //The HTTP request method - $env['REQUEST_METHOD'] = $_SERVER['REQUEST_METHOD']; - - //The IP - $env['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR']; - - // Server params - $scriptName = $_SERVER['SCRIPT_NAME']; // <-- "/foo/index.php" - $requestUri = $_SERVER['REQUEST_URI']; // <-- "/foo/bar?test=abc" or "/foo/index.php/bar?test=abc" - $queryString = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : ''; // <-- "test=abc" or "" - - // Physical path - if (strpos($requestUri, $scriptName) !== false) { - $physicalPath = $scriptName; // <-- Without rewriting - } else { - $physicalPath = str_replace('\\', '', dirname($scriptName)); // <-- With rewriting - } - $env['SCRIPT_NAME'] = rtrim($physicalPath, '/'); // <-- Remove trailing slashes - - // Virtual path - $env['PATH_INFO'] = $requestUri; - if (substr($requestUri, 0, strlen($physicalPath)) == $physicalPath) { - $env['PATH_INFO'] = substr($requestUri, strlen($physicalPath)); // <-- Remove physical path - } - $env['PATH_INFO'] = str_replace('?' . $queryString, '', $env['PATH_INFO']); // <-- Remove query string - $env['PATH_INFO'] = '/' . ltrim($env['PATH_INFO'], '/'); // <-- Ensure leading slash - - // Query string (without leading "?") - $env['QUERY_STRING'] = $queryString; - - //Name of server host that is running the script - $env['SERVER_NAME'] = $_SERVER['SERVER_NAME']; - - //Number of server port that is running the script - //Fixes: https://github.com/slimphp/Slim/issues/962 - $env['SERVER_PORT'] = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80; - - //HTTP request headers (retains HTTP_ prefix to match $_SERVER) - $headers = \Slim\Http\Headers::extract($_SERVER); - foreach ($headers as $key => $value) { - $env[$key] = $value; - } - - //Is the application running under HTTPS or HTTP protocol? - $env['slim.url_scheme'] = empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off' ? 'http' : 'https'; - - //Input stream (readable one time only; not available for multipart/form-data requests) - $rawInput = @file_get_contents('php://input'); - if (!$rawInput) { - $rawInput = ''; - } - $env['slim.input'] = $rawInput; - - //Error stream - $env['slim.errors'] = @fopen('php://stderr', 'w'); - - $this->properties = $env; - } - } - - /** - * Array Access: Offset Exists - */ - public function offsetExists($offset) - { - return isset($this->properties[$offset]); - } - - /** - * Array Access: Offset Get - */ - public function offsetGet($offset) - { - if (isset($this->properties[$offset])) { - return $this->properties[$offset]; - } - - return null; - } - - /** - * Array Access: Offset Set - */ - public function offsetSet($offset, $value) - { - $this->properties[$offset] = $value; - } - - /** - * Array Access: Offset Unset - */ - public function offsetUnset($offset) - { - unset($this->properties[$offset]); - } - - /** - * IteratorAggregate - * - * @return \ArrayIterator - */ - public function getIterator() - { - return new \ArrayIterator($this->properties); - } -} diff --git a/vendor/slim/slim/Slim/Exception/Pass.php b/vendor/slim/slim/Slim/Exception/Pass.php deleted file mode 100644 index 30a3a1d..0000000 --- a/vendor/slim/slim/Slim/Exception/Pass.php +++ /dev/null @@ -1,49 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -namespace Slim\Exception; - -/** - * Pass Exception - * - * This Exception will cause the Router::dispatch method - * to skip the current matching route and continue to the next - * matching route. If no subsequent routes are found, a - * HTTP 404 Not Found response will be sent to the client. - * - * @package Slim - * @author Josh Lockhart - * @since 1.0.0 - */ -class Pass extends \Exception -{ -} diff --git a/vendor/slim/slim/Slim/Exception/Stop.php b/vendor/slim/slim/Slim/Exception/Stop.php deleted file mode 100644 index 28aba78..0000000 --- a/vendor/slim/slim/Slim/Exception/Stop.php +++ /dev/null @@ -1,47 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -namespace Slim\Exception; - -/** - * Stop Exception - * - * This Exception is thrown when the Slim application needs to abort - * processing and return control flow to the outer PHP script. - * - * @package Slim - * @author Josh Lockhart - * @since 1.0.0 - */ -class Stop extends \Exception -{ -} diff --git a/vendor/slim/slim/Slim/Helper/Set.php b/vendor/slim/slim/Slim/Helper/Set.php deleted file mode 100644 index bf6e895..0000000 --- a/vendor/slim/slim/Slim/Helper/Set.php +++ /dev/null @@ -1,246 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -namespace Slim\Helper; - -class Set implements \ArrayAccess, \Countable, \IteratorAggregate -{ - /** - * Key-value array of arbitrary data - * @var array - */ - protected $data = array(); - - /** - * Constructor - * @param array $items Pre-populate set with this key-value array - */ - public function __construct($items = array()) - { - $this->replace($items); - } - - /** - * Normalize data key - * - * Used to transform data key into the necessary - * key format for this set. Used in subclasses - * like \Slim\Http\Headers. - * - * @param string $key The data key - * @return mixed The transformed/normalized data key - */ - protected function normalizeKey($key) - { - return $key; - } - - /** - * Set data key to value - * @param string $key The data key - * @param mixed $value The data value - */ - public function set($key, $value) - { - $this->data[$this->normalizeKey($key)] = $value; - } - - /** - * Get data value with key - * @param string $key The data key - * @param mixed $default The value to return if data key does not exist - * @return mixed The data value, or the default value - */ - public function get($key, $default = null) - { - if ($this->has($key)) { - $isInvokable = is_object($this->data[$this->normalizeKey($key)]) && method_exists($this->data[$this->normalizeKey($key)], '__invoke'); - - return $isInvokable ? $this->data[$this->normalizeKey($key)]($this) : $this->data[$this->normalizeKey($key)]; - } - - return $default; - } - - /** - * Add data to set - * @param array $items Key-value array of data to append to this set - */ - public function replace($items) - { - foreach ($items as $key => $value) { - $this->set($key, $value); // Ensure keys are normalized - } - } - - /** - * Fetch set data - * @return array This set's key-value data array - */ - public function all() - { - return $this->data; - } - - /** - * Fetch set data keys - * @return array This set's key-value data array keys - */ - public function keys() - { - return array_keys($this->data); - } - - /** - * Does this set contain a key? - * @param string $key The data key - * @return boolean - */ - public function has($key) - { - return array_key_exists($this->normalizeKey($key), $this->data); - } - - /** - * Remove value with key from this set - * @param string $key The data key - */ - public function remove($key) - { - unset($this->data[$this->normalizeKey($key)]); - } - - /** - * Property Overloading - */ - - public function __get($key) - { - return $this->get($key); - } - - public function __set($key, $value) - { - $this->set($key, $value); - } - - public function __isset($key) - { - return $this->has($key); - } - - public function __unset($key) - { - $this->remove($key); - } - - /** - * Clear all values - */ - public function clear() - { - $this->data = array(); - } - - /** - * Array Access - */ - - public function offsetExists($offset) - { - return $this->has($offset); - } - - public function offsetGet($offset) - { - return $this->get($offset); - } - - public function offsetSet($offset, $value) - { - $this->set($offset, $value); - } - - public function offsetUnset($offset) - { - $this->remove($offset); - } - - /** - * Countable - */ - - public function count() - { - return count($this->data); - } - - /** - * IteratorAggregate - */ - - public function getIterator() - { - return new \ArrayIterator($this->data); - } - - /** - * Ensure a value or object will remain globally unique - * @param string $key The value or object name - * @param \Closure $value The closure that defines the object - * @return mixed - */ - public function singleton($key, $value) - { - $this->set($key, function ($c) use ($value) { - static $object; - - if (null === $object) { - $object = $value($c); - } - - return $object; - }); - } - - /** - * Protect closure from being directly invoked - * @param \Closure $callable A closure to keep from being invoked and evaluated - * @return \Closure - */ - public function protect(\Closure $callable) - { - return function () use ($callable) { - return $callable; - }; - } -} diff --git a/vendor/slim/slim/Slim/Http/Cookies.php b/vendor/slim/slim/Slim/Http/Cookies.php index 3b2e11e..c07c96f 100644 --- a/vendor/slim/slim/Slim/Http/Cookies.php +++ b/vendor/slim/slim/Slim/Http/Cookies.php @@ -1,91 +1,195 @@ - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * @link https://github.com/slimphp/Slim + * @copyright Copyright (c) 2011-2017 Josh Lockhart + * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License) */ namespace Slim\Http; -class Cookies extends \Slim\Helper\Set +use InvalidArgumentException; +use Slim\Interfaces\Http\CookiesInterface; + +/** + * Cookie helper + */ +class Cookies implements CookiesInterface { /** - * Default cookie settings + * Cookies from HTTP request + * * @var array */ - protected $defaults = array( + protected $requestCookies = []; + + /** + * Cookies for HTTP response + * + * @var array + */ + protected $responseCookies = []; + + /** + * Default cookie properties + * + * @var array + */ + protected $defaults = [ 'value' => '', 'domain' => null, + 'hostonly' => null, 'path' => null, 'expires' => null, 'secure' => false, 'httponly' => false - ); + ]; /** - * Set cookie + * Create new cookies helper * - * The second argument may be a single scalar value, in which case - * it will be merged with the default settings and considered the `value` - * of the merged result. + * @param array $cookies + */ + public function __construct(array $cookies = []) + { + $this->requestCookies = $cookies; + } + + /** + * Set default cookie properties + * + * @param array $settings + */ + public function setDefaults(array $settings) + { + $this->defaults = array_replace($this->defaults, $settings); + } + + /** + * Get request cookie * - * The second argument may also be an array containing any or all of - * the keys shown in the default settings above. This array will be - * merged with the defaults shown above. + * @param string $name Cookie name + * @param mixed $default Cookie default value * - * @param string $key Cookie name - * @param mixed $value Cookie settings + * @return mixed Cookie value if present, else default */ - public function set($key, $value) + public function get($name, $default = null) { - if (is_array($value)) { - $cookieSettings = array_replace($this->defaults, $value); - } else { - $cookieSettings = array_replace($this->defaults, array('value' => $value)); + return isset($this->requestCookies[$name]) ? $this->requestCookies[$name] : $default; + } + + /** + * Set response cookie + * + * @param string $name Cookie name + * @param string|array $value Cookie value, or cookie properties + */ + public function set($name, $value) + { + if (!is_array($value)) { + $value = ['value' => (string)$value]; } - parent::set($key, $cookieSettings); + $this->responseCookies[$name] = array_replace($this->defaults, $value); } /** - * Remove cookie + * Convert to `Set-Cookie` headers * - * Unlike \Slim\Helper\Set, this will actually *set* a cookie with - * an expiration date in the past. This expiration date will force - * the client-side cache to remove its cookie with the given name - * and settings. + * @return string[] + */ + public function toHeaders() + { + $headers = []; + foreach ($this->responseCookies as $name => $properties) { + $headers[] = $this->toHeader($name, $properties); + } + + return $headers; + } + + /** + * Convert to `Set-Cookie` header + * + * @param string $name Cookie name + * @param array $properties Cookie properties + * + * @return string + */ + protected function toHeader($name, array $properties) + { + $result = urlencode($name) . '=' . urlencode($properties['value']); + + if (isset($properties['domain'])) { + $result .= '; domain=' . $properties['domain']; + } + + if (isset($properties['path'])) { + $result .= '; path=' . $properties['path']; + } + + if (isset($properties['expires'])) { + if (is_string($properties['expires'])) { + $timestamp = strtotime($properties['expires']); + } else { + $timestamp = (int)$properties['expires']; + } + if ($timestamp !== 0) { + $result .= '; expires=' . gmdate('D, d-M-Y H:i:s e', $timestamp); + } + } + + if (isset($properties['secure']) && $properties['secure']) { + $result .= '; secure'; + } + + if (isset($properties['hostonly']) && $properties['hostonly']) { + $result .= '; HostOnly'; + } + + if (isset($properties['httponly']) && $properties['httponly']) { + $result .= '; HttpOnly'; + } + + return $result; + } + + /** + * Parse HTTP request `Cookie:` header and extract + * into a PHP associative array. + * + * @param string $header The raw HTTP request `Cookie:` header + * + * @return array Associative array of cookie names and values * - * @param string $key Cookie name - * @param array $settings Optional cookie settings + * @throws InvalidArgumentException if the cookie data cannot be parsed */ - public function remove($key, $settings = array()) + public static function parseHeader($header) { - $settings['value'] = ''; - $settings['expires'] = time() - 86400; - $this->set($key, array_replace($this->defaults, $settings)); + if (is_array($header) === true) { + $header = isset($header[0]) ? $header[0] : ''; + } + + if (is_string($header) === false) { + throw new InvalidArgumentException('Cannot parse Cookie data. Header value must be a string.'); + } + + $header = rtrim($header, "\r\n"); + $pieces = preg_split('@[;]\s*@', $header); + $cookies = []; + + foreach ($pieces as $cookie) { + $cookie = explode('=', $cookie, 2); + + if (count($cookie) === 2) { + $key = urldecode($cookie[0]); + $value = urldecode($cookie[1]); + + if (!isset($cookies[$key])) { + $cookies[$key] = $value; + } + } + } + + return $cookies; } } diff --git a/vendor/slim/slim/Slim/Http/Headers.php b/vendor/slim/slim/Slim/Http/Headers.php index c5e08f2..f8c4ac1 100644 --- a/vendor/slim/slim/Slim/Http/Headers.php +++ b/vendor/slim/slim/Slim/Http/Headers.php @@ -1,103 +1,221 @@ - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * @link https://github.com/slimphp/Slim + * @copyright Copyright (c) 2011-2017 Josh Lockhart + * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License) */ namespace Slim\Http; - /** - * HTTP Headers - * - * @package Slim - * @author Josh Lockhart - * @since 1.6.0 - */ -class Headers extends \Slim\Helper\Set -{ - /******************************************************************************** - * Static interface - *******************************************************************************/ +use Slim\Collection; +use Slim\Interfaces\Http\HeadersInterface; +/** + * Headers + * + * This class represents a collection of HTTP headers + * that is used in both the HTTP request and response objects. + * It also enables header name case-insensitivity when + * getting or setting a header value. + * + * Each HTTP header can have multiple values. This class + * stores values into an array for each header name. When + * you request a header value, you receive an array of values + * for that header. + */ +class Headers extends Collection implements HeadersInterface +{ /** - * Special-case HTTP headers that are otherwise unidentifiable as HTTP headers. - * Typically, HTTP headers in the $_SERVER array will be prefixed with - * `HTTP_` or `X_`. These are not so we list them here for later reference. + * Special HTTP headers that do not have the "HTTP_" prefix * * @var array */ - protected static $special = array( - 'CONTENT_TYPE', - 'CONTENT_LENGTH', - 'PHP_AUTH_USER', - 'PHP_AUTH_PW', - 'PHP_AUTH_DIGEST', - 'AUTH_TYPE' - ); + protected static $special = [ + 'CONTENT_TYPE' => 1, + 'CONTENT_LENGTH' => 1, + 'PHP_AUTH_USER' => 1, + 'PHP_AUTH_PW' => 1, + 'PHP_AUTH_DIGEST' => 1, + 'AUTH_TYPE' => 1, + ]; /** - * Extract HTTP headers from an array of data (e.g. $_SERVER) - * @param array $data - * @return array + * Create new headers collection with data extracted from + * the application Environment object + * + * @param Environment $environment The Slim application Environment + * + * @return self */ - public static function extract($data) + public static function createFromEnvironment(Environment $environment) { - $results = array(); - foreach ($data as $key => $value) { + $data = []; + $environment = self::determineAuthorization($environment); + foreach ($environment as $key => $value) { $key = strtoupper($key); - if (strpos($key, 'X_') === 0 || strpos($key, 'HTTP_') === 0 || in_array($key, static::$special)) { - if ($key === 'HTTP_CONTENT_LENGTH') { - continue; + if (isset(static::$special[$key]) || strpos($key, 'HTTP_') === 0) { + if ($key !== 'HTTP_CONTENT_LENGTH') { + $data[$key] = $value; } - $results[$key] = $value; } } - return $results; + return new static($data); + } + + /** + * If HTTP_AUTHORIZATION does not exist tries to get it from + * getallheaders() when available. + * + * @param Environment $environment The Slim application Environment + * + * @return Environment + */ + + public static function determineAuthorization(Environment $environment) + { + $authorization = $environment->get('HTTP_AUTHORIZATION'); + + if (null === $authorization && is_callable('getallheaders')) { + $headers = getallheaders(); + $headers = array_change_key_case($headers, CASE_LOWER); + if (isset($headers['authorization'])) { + $environment->set('HTTP_AUTHORIZATION', $headers['authorization']); + } + } + + return $environment; } - /******************************************************************************** - * Instance interface - *******************************************************************************/ + /** + * Return array of HTTP header names and values. + * This method returns the _original_ header name + * as specified by the end user. + * + * @return array + */ + public function all() + { + $all = parent::all(); + $out = []; + foreach ($all as $key => $props) { + $out[$props['originalKey']] = $props['value']; + } + + return $out; + } + + /** + * Set HTTP header value + * + * This method sets a header value. It replaces + * any values that may already exist for the header name. + * + * @param string $key The case-insensitive header name + * @param string $value The header value + */ + public function set($key, $value) + { + if (!is_array($value)) { + $value = [$value]; + } + parent::set($this->normalizeKey($key), [ + 'value' => $value, + 'originalKey' => $key + ]); + } /** - * Transform header name into canonical form - * @param string $key + * Get HTTP header value + * + * @param string $key The case-insensitive header name + * @param mixed $default The default value if key does not exist + * + * @return string[] + */ + public function get($key, $default = null) + { + if ($this->has($key)) { + return parent::get($this->normalizeKey($key))['value']; + } + + return $default; + } + + /** + * Get HTTP header key as originally specified + * + * @param string $key The case-insensitive header name + * @param mixed $default The default value if key does not exist + * * @return string */ - protected function normalizeKey($key) + public function getOriginalKey($key, $default = null) { - $key = strtolower($key); - $key = str_replace(array('-', '_'), ' ', $key); - $key = preg_replace('#^http #', '', $key); - $key = ucwords($key); - $key = str_replace(' ', '-', $key); + if ($this->has($key)) { + return parent::get($this->normalizeKey($key))['originalKey']; + } + + return $default; + } + + /** + * Add HTTP header value + * + * This method appends a header value. Unlike the set() method, + * this method _appends_ this new value to any values + * that already exist for this header name. + * + * @param string $key The case-insensitive header name + * @param array|string $value The new header value(s) + */ + public function add($key, $value) + { + $oldValues = $this->get($key, []); + $newValues = is_array($value) ? $value : [$value]; + $this->set($key, array_merge($oldValues, array_values($newValues))); + } + + /** + * Does this collection have a given header? + * + * @param string $key The case-insensitive header name + * + * @return bool + */ + public function has($key) + { + return parent::has($this->normalizeKey($key)); + } + + /** + * Remove header from collection + * + * @param string $key The case-insensitive header name + */ + public function remove($key) + { + parent::remove($this->normalizeKey($key)); + } + + /** + * Normalize header name + * + * This method transforms header names into a + * normalized form. This is how we enable case-insensitive + * header names in the other methods in this class. + * + * @param string $key The case-insensitive header name + * + * @return string Normalized header name + */ + public function normalizeKey($key) + { + $key = strtr(strtolower($key), '_', '-'); + if (strpos($key, 'http-') === 0) { + $key = substr($key, 5); + } return $key; } diff --git a/vendor/slim/slim/Slim/Http/Request.php b/vendor/slim/slim/Slim/Http/Request.php index 2cd88b4..f67050b 100644 --- a/vendor/slim/slim/Slim/Http/Request.php +++ b/vendor/slim/slim/Slim/Http/Request.php @@ -1,416 +1,626 @@ - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * @link https://github.com/slimphp/Slim + * @copyright Copyright (c) 2011-2017 Josh Lockhart + * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License) */ namespace Slim\Http; +use Closure; +use InvalidArgumentException; +use Psr\Http\Message\UploadedFileInterface; +use RuntimeException; +use Psr\Http\Message\ServerRequestInterface; +use Psr\Http\Message\UriInterface; +use Psr\Http\Message\StreamInterface; +use Slim\Collection; +use Slim\Exception\InvalidMethodException; +use Slim\Exception\MethodNotAllowedException; +use Slim\Interfaces\Http\HeadersInterface; + /** - * Slim HTTP Request + * Request * - * This class provides a human-friendly interface to the Slim environment variables; - * environment variables are passed by reference and will be modified directly. + * This class represents an HTTP request. It manages + * the request method, URI, headers, cookies, and body + * according to the PSR-7 standard. * - * @package Slim - * @author Josh Lockhart - * @since 1.0.0 + * @link https://github.com/php-fig/http-message/blob/master/src/MessageInterface.php + * @link https://github.com/php-fig/http-message/blob/master/src/RequestInterface.php + * @link https://github.com/php-fig/http-message/blob/master/src/ServerRequestInterface.php */ -class Request +class Request extends Message implements ServerRequestInterface { - const METHOD_HEAD = 'HEAD'; - const METHOD_GET = 'GET'; - const METHOD_POST = 'POST'; - const METHOD_PUT = 'PUT'; - const METHOD_PATCH = 'PATCH'; - const METHOD_DELETE = 'DELETE'; - const METHOD_OPTIONS = 'OPTIONS'; - const METHOD_OVERRIDE = '_METHOD'; + /** + * The request method + * + * @var string + */ + protected $method; + + /** + * The original request method (ignoring override) + * + * @var string + */ + protected $originalMethod; /** + * The request URI object + * + * @var \Psr\Http\Message\UriInterface + */ + protected $uri; + + /** + * The request URI target (path + query string) + * + * @var string + */ + protected $requestTarget; + + /** + * The request query string params + * * @var array */ - protected static $formDataMediaTypes = array('application/x-www-form-urlencoded'); + protected $queryParams; /** - * Application Environment - * @var \Slim\Environment + * The request cookies + * + * @var array */ - protected $env; + protected $cookies; /** - * HTTP Headers - * @var \Slim\Http\Headers + * The server environment variables at the time the request was created. + * + * @var array + */ + protected $serverParams; + + /** + * The request attributes (route segment names and values) + * + * @var \Slim\Collection + */ + protected $attributes; + + /** + * The request body parsed (if possible) into a PHP array or object + * + * @var null|array|object */ - public $headers; + protected $bodyParsed = false; /** - * HTTP Cookies - * @var \Slim\Helper\Set + * List of request body parsers (e.g., url-encoded, JSON, XML, multipart) + * + * @var callable[] */ - public $cookies; + protected $bodyParsers = []; /** - * Constructor - * @param \Slim\Environment $env + * List of uploaded files + * + * @var UploadedFileInterface[] */ - public function __construct(\Slim\Environment $env) + protected $uploadedFiles; + + /** + * Valid request methods + * + * @var string[] + */ + protected $validMethods = [ + 'CONNECT' => 1, + 'DELETE' => 1, + 'GET' => 1, + 'HEAD' => 1, + 'OPTIONS' => 1, + 'PATCH' => 1, + 'POST' => 1, + 'PUT' => 1, + 'TRACE' => 1, + ]; + + /** + * Create new HTTP request with data extracted from the application + * Environment object + * + * @param Environment $environment The Slim application Environment + * + * @return static + */ + public static function createFromEnvironment(Environment $environment) { - $this->env = $env; - $this->headers = new \Slim\Http\Headers(\Slim\Http\Headers::extract($env)); - $this->cookies = new \Slim\Helper\Set(\Slim\Http\Util::parseCookieHeader($env['HTTP_COOKIE'])); + $method = $environment['REQUEST_METHOD']; + $uri = Uri::createFromEnvironment($environment); + $headers = Headers::createFromEnvironment($environment); + $cookies = Cookies::parseHeader($headers->get('Cookie', [])); + $serverParams = $environment->all(); + $body = new RequestBody(); + $uploadedFiles = UploadedFile::createFromEnvironment($environment); + + $request = new static($method, $uri, $headers, $cookies, $serverParams, $body, $uploadedFiles); + + if ($method === 'POST' && + in_array($request->getMediaType(), ['application/x-www-form-urlencoded', 'multipart/form-data']) + ) { + // parsed body must be $_POST + $request = $request->withParsedBody($_POST); + } + return $request; } /** - * Get HTTP method - * @return string + * Create new HTTP request. + * + * Adds a host header when none was provided and a host is defined in uri. + * + * @param string $method The request method + * @param UriInterface $uri The request URI object + * @param HeadersInterface $headers The request headers collection + * @param array $cookies The request cookies collection + * @param array $serverParams The server environment variables + * @param StreamInterface $body The request body object + * @param array $uploadedFiles The request uploadedFiles collection + * @throws InvalidMethodException on invalid HTTP method */ - public function getMethod() - { - return $this->env['REQUEST_METHOD']; + public function __construct( + $method, + UriInterface $uri, + HeadersInterface $headers, + array $cookies, + array $serverParams, + StreamInterface $body, + array $uploadedFiles = [] + ) { + try { + $this->originalMethod = $this->filterMethod($method); + } catch (InvalidMethodException $e) { + $this->originalMethod = $method; + } + + $this->uri = $uri; + $this->headers = $headers; + $this->cookies = $cookies; + $this->serverParams = $serverParams; + $this->attributes = new Collection(); + $this->body = $body; + $this->uploadedFiles = $uploadedFiles; + + if (isset($serverParams['SERVER_PROTOCOL'])) { + $this->protocolVersion = str_replace('HTTP/', '', $serverParams['SERVER_PROTOCOL']); + } + + if (!$this->headers->has('Host') || $this->uri->getHost() !== '') { + $this->headers->set('Host', $this->uri->getHost()); + } + + $this->registerMediaTypeParser('application/json', function ($input) { + $result = json_decode($input, true); + if (!is_array($result)) { + return null; + } + return $result; + }); + + $this->registerMediaTypeParser('application/xml', function ($input) { + $backup = libxml_disable_entity_loader(true); + $backup_errors = libxml_use_internal_errors(true); + $result = simplexml_load_string($input); + libxml_disable_entity_loader($backup); + libxml_clear_errors(); + libxml_use_internal_errors($backup_errors); + if ($result === false) { + return null; + } + return $result; + }); + + $this->registerMediaTypeParser('text/xml', function ($input) { + $backup = libxml_disable_entity_loader(true); + $backup_errors = libxml_use_internal_errors(true); + $result = simplexml_load_string($input); + libxml_disable_entity_loader($backup); + libxml_clear_errors(); + libxml_use_internal_errors($backup_errors); + if ($result === false) { + return null; + } + return $result; + }); + + $this->registerMediaTypeParser('application/x-www-form-urlencoded', function ($input) { + parse_str($input, $data); + return $data; + }); + + // if the request had an invalid method, we can throw it now + if (isset($e) && $e instanceof InvalidMethodException) { + throw $e; + } } /** - * Is this a GET request? - * @return bool + * This method is applied to the cloned object + * after PHP performs an initial shallow-copy. This + * method completes a deep-copy by creating new objects + * for the cloned object's internal reference pointers. */ - public function isGet() + public function __clone() { - return $this->getMethod() === self::METHOD_GET; + $this->headers = clone $this->headers; + $this->attributes = clone $this->attributes; + $this->body = clone $this->body; } + /******************************************************************************* + * Method + ******************************************************************************/ + /** - * Is this a POST request? - * @return bool + * Retrieves the HTTP method of the request. + * + * @return string Returns the request method. */ - public function isPost() + public function getMethod() { - return $this->getMethod() === self::METHOD_POST; + if ($this->method === null) { + $this->method = $this->originalMethod; + $customMethod = $this->getHeaderLine('X-Http-Method-Override'); + + if ($customMethod) { + $this->method = $this->filterMethod($customMethod); + } elseif ($this->originalMethod === 'POST') { + $overrideMethod = $this->filterMethod($this->getParsedBodyParam('_METHOD')); + if ($overrideMethod !== null) { + $this->method = $overrideMethod; + } + + if ($this->getBody()->eof()) { + $this->getBody()->rewind(); + } + } + } + + return $this->method; } /** - * Is this a PUT request? - * @return bool + * Get the original HTTP method (ignore override). + * + * Note: This method is not part of the PSR-7 standard. + * + * @return string */ - public function isPut() + public function getOriginalMethod() { - return $this->getMethod() === self::METHOD_PUT; + return $this->originalMethod; } /** - * Is this a PATCH request? - * @return bool + * Return an instance with the provided HTTP method. + * + * While HTTP method names are typically all uppercase characters, HTTP + * method names are case-sensitive and thus implementations SHOULD NOT + * modify the given string. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * changed request method. + * + * @param string $method Case-sensitive method. + * @return static + * @throws \InvalidArgumentException for invalid HTTP methods. */ - public function isPatch() + public function withMethod($method) { - return $this->getMethod() === self::METHOD_PATCH; + $method = $this->filterMethod($method); + $clone = clone $this; + $clone->originalMethod = $method; + $clone->method = $method; + + return $clone; } /** - * Is this a DELETE request? - * @return bool + * Validate the HTTP method + * + * @param null|string $method + * @return null|string + * @throws \InvalidArgumentException on invalid HTTP method. */ - public function isDelete() + protected function filterMethod($method) { - return $this->getMethod() === self::METHOD_DELETE; + if ($method === null) { + return $method; + } + + if (!is_string($method)) { + throw new InvalidArgumentException(sprintf( + 'Unsupported HTTP method; must be a string, received %s', + (is_object($method) ? get_class($method) : gettype($method)) + )); + } + + $method = strtoupper($method); + if (!isset($this->validMethods[$method])) { + throw new InvalidMethodException($this, $method); + } + + return $method; } /** - * Is this a HEAD request? + * Does this request use a given method? + * + * Note: This method is not part of the PSR-7 standard. + * + * @param string $method HTTP method * @return bool */ - public function isHead() + public function isMethod($method) { - return $this->getMethod() === self::METHOD_HEAD; + return $this->getMethod() === $method; } /** - * Is this a OPTIONS request? + * Is this a GET request? + * + * Note: This method is not part of the PSR-7 standard. + * * @return bool */ - public function isOptions() + public function isGet() { - return $this->getMethod() === self::METHOD_OPTIONS; + return $this->isMethod('GET'); } /** - * Is this an AJAX request? + * Is this a POST request? + * + * Note: This method is not part of the PSR-7 standard. + * * @return bool */ - public function isAjax() + public function isPost() { - if ($this->params('isajax')) { - return true; - } elseif (isset($this->headers['X_REQUESTED_WITH']) && $this->headers['X_REQUESTED_WITH'] === 'XMLHttpRequest') { - return true; - } - - return false; + return $this->isMethod('POST'); } /** - * Is this an XHR request? (alias of Slim_Http_Request::isAjax) + * Is this a PUT request? + * + * Note: This method is not part of the PSR-7 standard. + * * @return bool */ - public function isXhr() + public function isPut() { - return $this->isAjax(); + return $this->isMethod('PUT'); } /** - * Fetch GET and POST data + * Is this a PATCH request? * - * This method returns a union of GET and POST data as a key-value array, or the value - * of the array key if requested; if the array key does not exist, NULL is returned, - * unless there is a default value specified. + * Note: This method is not part of the PSR-7 standard. * - * @param string $key - * @param mixed $default - * @return array|mixed|null + * @return bool */ - public function params($key = null, $default = null) + public function isPatch() { - $union = array_merge($this->get(), $this->post()); - if ($key) { - return isset($union[$key]) ? $union[$key] : $default; - } - - return $union; + return $this->isMethod('PATCH'); } /** - * Fetch GET data + * Is this a DELETE request? * - * This method returns a key-value array of data sent in the HTTP request query string, or - * the value of the array key if requested; if the array key does not exist, NULL is returned. + * Note: This method is not part of the PSR-7 standard. * - * @param string $key - * @param mixed $default Default return value when key does not exist - * @return array|mixed|null + * @return bool */ - public function get($key = null, $default = null) + public function isDelete() { - if (!isset($this->env['slim.request.query_hash'])) { - $output = array(); - if (function_exists('mb_parse_str') && !isset($this->env['slim.tests.ignore_multibyte'])) { - mb_parse_str($this->env['QUERY_STRING'], $output); - } else { - parse_str($this->env['QUERY_STRING'], $output); - } - $this->env['slim.request.query_hash'] = Util::stripSlashesIfMagicQuotes($output); - } - if ($key) { - if (isset($this->env['slim.request.query_hash'][$key])) { - return $this->env['slim.request.query_hash'][$key]; - } else { - return $default; - } - } else { - return $this->env['slim.request.query_hash']; - } + return $this->isMethod('DELETE'); } /** - * Fetch POST data + * Is this a HEAD request? * - * This method returns a key-value array of data sent in the HTTP request body, or - * the value of a hash key if requested; if the array key does not exist, NULL is returned. + * Note: This method is not part of the PSR-7 standard. * - * @param string $key - * @param mixed $default Default return value when key does not exist - * @return array|mixed|null - * @throws \RuntimeException If environment input is not available + * @return bool */ - public function post($key = null, $default = null) + public function isHead() { - if (!isset($this->env['slim.input'])) { - throw new \RuntimeException('Missing slim.input in environment variables'); - } - if (!isset($this->env['slim.request.form_hash'])) { - $this->env['slim.request.form_hash'] = array(); - if ($this->isFormData() && is_string($this->env['slim.input'])) { - $output = array(); - if (function_exists('mb_parse_str') && !isset($this->env['slim.tests.ignore_multibyte'])) { - mb_parse_str($this->env['slim.input'], $output); - } else { - parse_str($this->env['slim.input'], $output); - } - $this->env['slim.request.form_hash'] = Util::stripSlashesIfMagicQuotes($output); - } else { - $this->env['slim.request.form_hash'] = Util::stripSlashesIfMagicQuotes($_POST); - } - } - if ($key) { - if (isset($this->env['slim.request.form_hash'][$key])) { - return $this->env['slim.request.form_hash'][$key]; - } else { - return $default; - } - } else { - return $this->env['slim.request.form_hash']; - } + return $this->isMethod('HEAD'); } /** - * Fetch PUT data (alias for \Slim\Http\Request::post) - * @param string $key - * @param mixed $default Default return value when key does not exist - * @return array|mixed|null + * Is this a OPTIONS request? + * + * Note: This method is not part of the PSR-7 standard. + * + * @return bool */ - public function put($key = null, $default = null) + public function isOptions() { - return $this->post($key, $default); + return $this->isMethod('OPTIONS'); } /** - * Fetch PATCH data (alias for \Slim\Http\Request::post) - * @param string $key - * @param mixed $default Default return value when key does not exist - * @return array|mixed|null + * Is this an XHR request? + * + * Note: This method is not part of the PSR-7 standard. + * + * @return bool */ - public function patch($key = null, $default = null) + public function isXhr() { - return $this->post($key, $default); + return $this->getHeaderLine('X-Requested-With') === 'XMLHttpRequest'; } + /******************************************************************************* + * URI + ******************************************************************************/ + /** - * Fetch DELETE data (alias for \Slim\Http\Request::post) - * @param string $key - * @param mixed $default Default return value when key does not exist - * @return array|mixed|null + * Retrieves the message's request target. + * + * Retrieves the message's request-target either as it will appear (for + * clients), as it appeared at request (for servers), or as it was + * specified for the instance (see withRequestTarget()). + * + * In most cases, this will be the origin-form of the composed URI, + * unless a value was provided to the concrete implementation (see + * withRequestTarget() below). + * + * If no URI is available, and no request-target has been specifically + * provided, this method MUST return the string "/". + * + * @return string */ - public function delete($key = null, $default = null) + public function getRequestTarget() { - return $this->post($key, $default); + if ($this->requestTarget) { + return $this->requestTarget; + } + + if ($this->uri === null) { + return '/'; + } + + $basePath = $this->uri->getBasePath(); + $path = $this->uri->getPath(); + $path = $basePath . '/' . ltrim($path, '/'); + + $query = $this->uri->getQuery(); + if ($query) { + $path .= '?' . $query; + } + $this->requestTarget = $path; + + return $this->requestTarget; } /** - * Fetch COOKIE data + * Return an instance with the specific request-target. + * + * If the request needs a non-origin-form request-target — e.g., for + * specifying an absolute-form, authority-form, or asterisk-form — + * this method may be used to create an instance with the specified + * request-target, verbatim. * - * This method returns a key-value array of Cookie data sent in the HTTP request, or - * the value of a array key if requested; if the array key does not exist, NULL is returned. + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * changed request target. * - * @param string $key - * @return array|string|null + * @link http://tools.ietf.org/html/rfc7230#section-2.7 (for the various + * request-target forms allowed in request messages) + * @param mixed $requestTarget + * @return static + * @throws InvalidArgumentException if the request target is invalid */ - public function cookies($key = null) + public function withRequestTarget($requestTarget) { - if ($key) { - return $this->cookies->get($key); + if (preg_match('#\s#', $requestTarget)) { + throw new InvalidArgumentException( + 'Invalid request target provided; must be a string and cannot contain whitespace' + ); } + $clone = clone $this; + $clone->requestTarget = $requestTarget; - return $this->cookies; - // if (!isset($this->env['slim.request.cookie_hash'])) { - // $cookieHeader = isset($this->env['COOKIE']) ? $this->env['COOKIE'] : ''; - // $this->env['slim.request.cookie_hash'] = Util::parseCookieHeader($cookieHeader); - // } - // if ($key) { - // if (isset($this->env['slim.request.cookie_hash'][$key])) { - // return $this->env['slim.request.cookie_hash'][$key]; - // } else { - // return null; - // } - // } else { - // return $this->env['slim.request.cookie_hash']; - // } - } - - /** - * Does the Request body contain parsed form data? - * @return bool + return $clone; + } + + /** + * Retrieves the URI instance. + * + * This method MUST return a UriInterface instance. + * + * @link http://tools.ietf.org/html/rfc3986#section-4.3 + * @return UriInterface Returns a UriInterface instance + * representing the URI of the request. */ - public function isFormData() + public function getUri() { - $method = isset($this->env['slim.method_override.original_method']) ? $this->env['slim.method_override.original_method'] : $this->getMethod(); - - return ($method === self::METHOD_POST && is_null($this->getContentType())) || in_array($this->getMediaType(), self::$formDataMediaTypes); + return $this->uri; } /** - * Get Headers + * Returns an instance with the provided URI. * - * This method returns a key-value array of headers sent in the HTTP request, or - * the value of a hash key if requested; if the array key does not exist, NULL is returned. + * This method MUST update the Host header of the returned request by + * default if the URI contains a host component. If the URI does not + * contain a host component, any pre-existing Host header MUST be carried + * over to the returned request. * - * @param string $key - * @param mixed $default The default value returned if the requested header is not available - * @return mixed + * You can opt-in to preserving the original state of the Host header by + * setting `$preserveHost` to `true`. When `$preserveHost` is set to + * `true`, this method interacts with the Host header in the following ways: + * + * - If the the Host header is missing or empty, and the new URI contains + * a host component, this method MUST update the Host header in the returned + * request. + * - If the Host header is missing or empty, and the new URI does not contain a + * host component, this method MUST NOT update the Host header in the returned + * request. + * - If a Host header is present and non-empty, this method MUST NOT update + * the Host header in the returned request. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new UriInterface instance. + * + * @link http://tools.ietf.org/html/rfc3986#section-4.3 + * @param UriInterface $uri New request URI to use. + * @param bool $preserveHost Preserve the original state of the Host header. + * @return static */ - public function headers($key = null, $default = null) + public function withUri(UriInterface $uri, $preserveHost = false) { - if ($key) { - return $this->headers->get($key, $default); + $clone = clone $this; + $clone->uri = $uri; + + if (!$preserveHost) { + if ($uri->getHost() !== '') { + $clone->headers->set('Host', $uri->getHost()); + } + } else { + if ($uri->getHost() !== '' && (!$this->hasHeader('Host') || $this->getHeaderLine('Host') === '')) { + $clone->headers->set('Host', $uri->getHost()); + } } - return $this->headers; - // if ($key) { - // $key = strtoupper($key); - // $key = str_replace('-', '_', $key); - // $key = preg_replace('@^HTTP_@', '', $key); - // if (isset($this->env[$key])) { - // return $this->env[$key]; - // } else { - // return $default; - // } - // } else { - // $headers = array(); - // foreach ($this->env as $key => $value) { - // if (strpos($key, 'slim.') !== 0) { - // $headers[$key] = $value; - // } - // } - // - // return $headers; - // } - } - - /** - * Get Body - * @return string - */ - public function getBody() - { - return $this->env['slim.input']; + return $clone; } /** - * Get Content Type - * @return string|null + * Get request content type. + * + * Note: This method is not part of the PSR-7 standard. + * + * @return string|null The request content type, if known */ public function getContentType() { - return $this->headers->get('CONTENT_TYPE'); + $result = $this->getHeader('Content-Type'); + + return $result ? $result[0] : null; } /** - * Get Media Type (type/subtype within Content Type header) - * @return string|null + * Get request media type, if known. + * + * Note: This method is not part of the PSR-7 standard. + * + * @return string|null The request media type, minus content-type params */ public function getMediaType() { @@ -425,13 +635,16 @@ public function getMediaType() } /** - * Get Media Type Params + * Get request media type params, if known. + * + * Note: This method is not part of the PSR-7 standard. + * * @return array */ public function getMediaTypeParams() { $contentType = $this->getContentType(); - $contentTypeParams = array(); + $contentTypeParams = []; if ($contentType) { $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); $contentTypePartsLength = count($contentTypeParts); @@ -445,7 +658,10 @@ public function getMediaTypeParams() } /** - * Get Content Charset + * Get request content character set, if known. + * + * Note: This method is not part of the PSR-7 standard. + * * @return string|null */ public function getContentCharset() @@ -459,159 +675,542 @@ public function getContentCharset() } /** - * Get Content-Length - * @return int + * Get request content length, if known. + * + * Note: This method is not part of the PSR-7 standard. + * + * @return int|null */ public function getContentLength() { - return $this->headers->get('CONTENT_LENGTH', 0); + $result = $this->headers->get('Content-Length'); + + return $result ? (int)$result[0] : null; } + /******************************************************************************* + * Cookies + ******************************************************************************/ + /** - * Get Host - * @return string + * Retrieve cookies. + * + * Retrieves cookies sent by the client to the server. + * + * The data MUST be compatible with the structure of the $_COOKIE + * superglobal. + * + * @return array */ - public function getHost() + public function getCookieParams() { - if (isset($this->env['HTTP_HOST'])) { - if (strpos($this->env['HTTP_HOST'], ':') !== false) { - $hostParts = explode(':', $this->env['HTTP_HOST']); + return $this->cookies; + } - return $hostParts[0]; - } + /** + * Fetch cookie value from cookies sent by the client to the server. + * + * Note: This method is not part of the PSR-7 standard. + * + * @param string $key The attribute name. + * @param mixed $default Default value to return if the attribute does not exist. + * + * @return mixed + */ + public function getCookieParam($key, $default = null) + { + $cookies = $this->getCookieParams(); + $result = $default; + if (isset($cookies[$key])) { + $result = $cookies[$key]; + } + + return $result; + } + + /** + * Return an instance with the specified cookies. + * + * The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST + * be compatible with the structure of $_COOKIE. Typically, this data will + * be injected at instantiation. + * + * This method MUST NOT update the related Cookie header of the request + * instance, nor related values in the server params. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated cookie values. + * + * @param array $cookies Array of key/value pairs representing cookies. + * @return static + */ + public function withCookieParams(array $cookies) + { + $clone = clone $this; + $clone->cookies = $cookies; + + return $clone; + } + + /******************************************************************************* + * Query Params + ******************************************************************************/ + + /** + * Retrieve query string arguments. + * + * Retrieves the deserialized query string arguments, if any. + * + * Note: the query params might not be in sync with the URI or server + * params. If you need to ensure you are only getting the original + * values, you may need to parse the query string from `getUri()->getQuery()` + * or from the `QUERY_STRING` server param. + * + * @return array + */ + public function getQueryParams() + { + if (is_array($this->queryParams)) { + return $this->queryParams; + } - return $this->env['HTTP_HOST']; + if ($this->uri === null) { + return []; } - return $this->env['SERVER_NAME']; + parse_str($this->uri->getQuery(), $this->queryParams); // <-- URL decodes data + + return $this->queryParams; } /** - * Get Host with Port - * @return string + * Return an instance with the specified query string arguments. + * + * These values SHOULD remain immutable over the course of the incoming + * request. They MAY be injected during instantiation, such as from PHP's + * $_GET superglobal, or MAY be derived from some other value such as the + * URI. In cases where the arguments are parsed from the URI, the data + * MUST be compatible with what PHP's parse_str() would return for + * purposes of how duplicate query parameters are handled, and how nested + * sets are handled. + * + * Setting query string arguments MUST NOT change the URI stored by the + * request, nor the values in the server params. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated query string arguments. + * + * @param array $query Array of query string arguments, typically from + * $_GET. + * @return static */ - public function getHostWithPort() + public function withQueryParams(array $query) { - return sprintf('%s:%s', $this->getHost(), $this->getPort()); + $clone = clone $this; + $clone->queryParams = $query; + + return $clone; } + /******************************************************************************* + * File Params + ******************************************************************************/ + /** - * Get Port - * @return int + * Retrieve normalized file upload data. + * + * This method returns upload metadata in a normalized tree, with each leaf + * an instance of Psr\Http\Message\UploadedFileInterface. + * + * These values MAY be prepared from $_FILES or the message body during + * instantiation, or MAY be injected via withUploadedFiles(). + * + * @return array An array tree of UploadedFileInterface instances; an empty + * array MUST be returned if no data is present. */ - public function getPort() + public function getUploadedFiles() { - return (int)$this->env['SERVER_PORT']; + return $this->uploadedFiles; } /** - * Get Scheme (https or http) - * @return string + * Create a new instance with the specified uploaded files. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param array $uploadedFiles An array tree of UploadedFileInterface instances. + * @return static + * @throws \InvalidArgumentException if an invalid structure is provided. */ - public function getScheme() + public function withUploadedFiles(array $uploadedFiles) { - return $this->env['slim.url_scheme']; + $clone = clone $this; + $clone->uploadedFiles = $uploadedFiles; + + return $clone; } + /******************************************************************************* + * Server Params + ******************************************************************************/ + /** - * Get Script Name (physical path) - * @return string + * Retrieve server parameters. + * + * Retrieves data related to the incoming request environment, + * typically derived from PHP's $_SERVER superglobal. The data IS NOT + * REQUIRED to originate from $_SERVER. + * + * @return array */ - public function getScriptName() + public function getServerParams() { - return $this->env['SCRIPT_NAME']; + return $this->serverParams; } /** - * LEGACY: Get Root URI (alias for Slim_Http_Request::getScriptName) - * @return string + * Retrieve a server parameter. + * + * Note: This method is not part of the PSR-7 standard. + * + * @param string $key + * @param mixed $default + * @return mixed */ - public function getRootUri() + public function getServerParam($key, $default = null) { - return $this->getScriptName(); + $serverParams = $this->getServerParams(); + + return isset($serverParams[$key]) ? $serverParams[$key] : $default; } + /******************************************************************************* + * Attributes + ******************************************************************************/ + /** - * Get Path (physical path + virtual path) - * @return string + * Retrieve attributes derived from the request. + * + * The request "attributes" may be used to allow injection of any + * parameters derived from the request: e.g., the results of path + * match operations; the results of decrypting cookies; the results of + * deserializing non-form-encoded message bodies; etc. Attributes + * will be application and request specific, and CAN be mutable. + * + * @return array Attributes derived from the request. */ - public function getPath() + public function getAttributes() { - return $this->getScriptName() . $this->getPathInfo(); + return $this->attributes->all(); } /** - * Get Path Info (virtual path) - * @return string + * Retrieve a single derived request attribute. + * + * Retrieves a single derived request attribute as described in + * getAttributes(). If the attribute has not been previously set, returns + * the default value as provided. + * + * This method obviates the need for a hasAttribute() method, as it allows + * specifying a default value to return if the attribute is not found. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $default Default value to return if the attribute does not exist. + * @return mixed */ - public function getPathInfo() + public function getAttribute($name, $default = null) { - return $this->env['PATH_INFO']; + return $this->attributes->get($name, $default); } /** - * LEGACY: Get Resource URI (alias for Slim_Http_Request::getPathInfo) - * @return string + * Return an instance with the specified derived request attribute. + * + * This method allows setting a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $value The value of the attribute. + * @return static */ - public function getResourceUri() + public function withAttribute($name, $value) { - return $this->getPathInfo(); + $clone = clone $this; + $clone->attributes->set($name, $value); + + return $clone; } /** - * Get URL (scheme + host [ + port if non-standard ]) - * @return string + * Create a new instance with the specified derived request attributes. + * + * Note: This method is not part of the PSR-7 standard. + * + * This method allows setting all new derived request attributes as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return a new instance that has the + * updated attributes. + * + * @param array $attributes New attributes + * @return static */ - public function getUrl() + public function withAttributes(array $attributes) { - $url = $this->getScheme() . '://' . $this->getHost(); - if (($this->getScheme() === 'https' && $this->getPort() !== 443) || ($this->getScheme() === 'http' && $this->getPort() !== 80)) { - $url .= sprintf(':%s', $this->getPort()); - } + $clone = clone $this; + $clone->attributes = new Collection($attributes); - return $url; + return $clone; } /** - * Get IP - * @return string + * Return an instance that removes the specified derived request attribute. + * + * This method allows removing a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @return static + */ + public function withoutAttribute($name) + { + $clone = clone $this; + $clone->attributes->remove($name); + + return $clone; + } + + /******************************************************************************* + * Body + ******************************************************************************/ + + /** + * Retrieve any parameters provided in the request body. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, this method MUST + * return the contents of $_POST. + * + * Otherwise, this method may return any results of deserializing + * the request body content; as parsing returns structured content, the + * potential types MUST be arrays or objects only. A null value indicates + * the absence of body content. + * + * @return null|array|object The deserialized body parameters, if any. + * These will typically be an array or object. + * @throws RuntimeException if the request body media type parser returns an invalid value */ - public function getIp() + public function getParsedBody() { - $keys = array('X_FORWARDED_FOR', 'HTTP_X_FORWARDED_FOR', 'CLIENT_IP', 'REMOTE_ADDR'); - foreach ($keys as $key) { - if (isset($this->env[$key])) { - return $this->env[$key]; + if ($this->bodyParsed !== false) { + return $this->bodyParsed; + } + + if (!$this->body) { + return null; + } + + $mediaType = $this->getMediaType(); + + // look for a media type with a structured syntax suffix (RFC 6839) + $parts = explode('+', $mediaType); + if (count($parts) >= 2) { + $mediaType = 'application/' . $parts[count($parts)-1]; + } + + if (isset($this->bodyParsers[$mediaType]) === true) { + $body = (string)$this->getBody(); + $parsed = $this->bodyParsers[$mediaType]($body); + + if (!is_null($parsed) && !is_object($parsed) && !is_array($parsed)) { + throw new RuntimeException( + 'Request body media type parser return value must be an array, an object, or null' + ); } + $this->bodyParsed = $parsed; + return $this->bodyParsed; } - return $this->env['REMOTE_ADDR']; + return null; } /** - * Get Referrer - * @return string|null + * Return an instance with the specified body parameters. + * + * These MAY be injected during instantiation. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, use this method + * ONLY to inject the contents of $_POST. + * + * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of + * deserializing the request body content. Deserialization/parsing returns + * structured data, and, as such, this method ONLY accepts arrays or objects, + * or a null value if nothing was available to parse. + * + * As an example, if content negotiation determines that the request data + * is a JSON payload, this method could be used to create a request + * instance with the deserialized parameters. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param null|array|object $data The deserialized body data. This will + * typically be in an array or object. + * @return static + * @throws \InvalidArgumentException if an unsupported argument type is + * provided. */ - public function getReferrer() + public function withParsedBody($data) { - return $this->headers->get('HTTP_REFERER'); + if (!is_null($data) && !is_object($data) && !is_array($data)) { + throw new InvalidArgumentException('Parsed body value must be an array, an object, or null'); + } + + $clone = clone $this; + $clone->bodyParsed = $data; + + return $clone; } /** - * Get Referer (for those who can't spell) - * @return string|null + * Force Body to be parsed again. + * + * Note: This method is not part of the PSR-7 standard. + * + * @return $this + */ + public function reparseBody() + { + $this->bodyParsed = false; + + return $this; + } + + /** + * Register media type parser. + * + * Note: This method is not part of the PSR-7 standard. + * + * @param string $mediaType A HTTP media type (excluding content-type + * params). + * @param callable $callable A callable that returns parsed contents for + * media type. */ - public function getReferer() + public function registerMediaTypeParser($mediaType, callable $callable) { - return $this->getReferrer(); + if ($callable instanceof Closure) { + $callable = $callable->bindTo($this); + } + $this->bodyParsers[(string)$mediaType] = $callable; } + /******************************************************************************* + * Parameters (e.g., POST and GET data) + ******************************************************************************/ + /** - * Get User Agent - * @return string|null + * Fetch request parameter value from body or query string (in that order). + * + * Note: This method is not part of the PSR-7 standard. + * + * @param string $key The parameter key. + * @param string $default The default value. + * + * @return mixed The parameter value. + */ + public function getParam($key, $default = null) + { + $postParams = $this->getParsedBody(); + $getParams = $this->getQueryParams(); + $result = $default; + if (is_array($postParams) && isset($postParams[$key])) { + $result = $postParams[$key]; + } elseif (is_object($postParams) && property_exists($postParams, $key)) { + $result = $postParams->$key; + } elseif (isset($getParams[$key])) { + $result = $getParams[$key]; + } + + return $result; + } + + /** + * Fetch parameter value from request body. + * + * Note: This method is not part of the PSR-7 standard. + * + * @param string $key + * @param mixed $default + * + * @return mixed */ - public function getUserAgent() + public function getParsedBodyParam($key, $default = null) { - return $this->headers->get('HTTP_USER_AGENT'); + $postParams = $this->getParsedBody(); + $result = $default; + if (is_array($postParams) && isset($postParams[$key])) { + $result = $postParams[$key]; + } elseif (is_object($postParams) && property_exists($postParams, $key)) { + $result = $postParams->$key; + } + + return $result; + } + + /** + * Fetch parameter value from query string. + * + * Note: This method is not part of the PSR-7 standard. + * + * @param string $key + * @param mixed $default + * + * @return mixed + */ + public function getQueryParam($key, $default = null) + { + $getParams = $this->getQueryParams(); + $result = $default; + if (isset($getParams[$key])) { + $result = $getParams[$key]; + } + + return $result; + } + + /** + * Fetch associative array of body and query string parameters. + * + * Note: This method is not part of the PSR-7 standard. + * + * @return array + */ + public function getParams() + { + $params = $this->getQueryParams(); + $postParams = $this->getParsedBody(); + if ($postParams) { + $params = array_merge($params, (array)$postParams); + } + + return $params; } } diff --git a/vendor/slim/slim/Slim/Http/Response.php b/vendor/slim/slim/Slim/Http/Response.php index 48c76d8..dd96505 100644 --- a/vendor/slim/slim/Slim/Http/Response.php +++ b/vendor/slim/slim/Slim/Http/Response.php @@ -1,520 +1,480 @@ - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * @link https://github.com/slimphp/Slim + * @copyright Copyright (c) 2011-2017 Josh Lockhart + * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License) */ namespace Slim\Http; +use InvalidArgumentException; +use Psr\Http\Message\ResponseInterface; +use Psr\Http\Message\StreamInterface; +use Psr\Http\Message\UriInterface; +use Slim\Interfaces\Http\HeadersInterface; + /** * Response * - * This is a simple abstraction over top an HTTP response. This - * provides methods to set the HTTP status, the HTTP headers, - * and the HTTP body. + * This class represents an HTTP response. It manages + * the response status, headers, and body + * according to the PSR-7 standard. * - * @package Slim - * @author Josh Lockhart - * @since 1.0.0 + * @link https://github.com/php-fig/http-message/blob/master/src/MessageInterface.php + * @link https://github.com/php-fig/http-message/blob/master/src/ResponseInterface.php */ -class Response implements \ArrayAccess, \Countable, \IteratorAggregate +class Response extends Message implements ResponseInterface { /** - * @var int HTTP status code - */ - protected $status; - - /** - * @var \Slim\Http\Headers - */ - public $headers; - - /** - * @var \Slim\Http\Cookies - */ - public $cookies; - - /** - * @var string HTTP response body + * Status code + * + * @var int */ - protected $body; + protected $status = 200; /** - * @var int Length of HTTP response body + * Reason phrase + * + * @var string */ - protected $length; + protected $reasonPhrase = ''; /** - * @var array HTTP response codes and messages + * Status codes and reason phrases + * + * @var array */ - protected static $messages = array( + protected static $messages = [ //Informational 1xx - 100 => '100 Continue', - 101 => '101 Switching Protocols', + 100 => 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', //Successful 2xx - 200 => '200 OK', - 201 => '201 Created', - 202 => '202 Accepted', - 203 => '203 Non-Authoritative Information', - 204 => '204 No Content', - 205 => '205 Reset Content', - 206 => '206 Partial Content', - 226 => '226 IM Used', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-Status', + 208 => 'Already Reported', + 226 => 'IM Used', //Redirection 3xx - 300 => '300 Multiple Choices', - 301 => '301 Moved Permanently', - 302 => '302 Found', - 303 => '303 See Other', - 304 => '304 Not Modified', - 305 => '305 Use Proxy', - 306 => '306 (Unused)', - 307 => '307 Temporary Redirect', + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 306 => '(Unused)', + 307 => 'Temporary Redirect', + 308 => 'Permanent Redirect', //Client Error 4xx - 400 => '400 Bad Request', - 401 => '401 Unauthorized', - 402 => '402 Payment Required', - 403 => '403 Forbidden', - 404 => '404 Not Found', - 405 => '405 Method Not Allowed', - 406 => '406 Not Acceptable', - 407 => '407 Proxy Authentication Required', - 408 => '408 Request Timeout', - 409 => '409 Conflict', - 410 => '410 Gone', - 411 => '411 Length Required', - 412 => '412 Precondition Failed', - 413 => '413 Request Entity Too Large', - 414 => '414 Request-URI Too Long', - 415 => '415 Unsupported Media Type', - 416 => '416 Requested Range Not Satisfiable', - 417 => '417 Expectation Failed', - 418 => '418 I\'m a teapot', - 422 => '422 Unprocessable Entity', - 423 => '423 Locked', - 426 => '426 Upgrade Required', - 428 => '428 Precondition Required', - 429 => '429 Too Many Requests', - 431 => '431 Request Header Fields Too Large', + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Timeout', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Long', + 415 => 'Unsupported Media Type', + 416 => 'Requested Range Not Satisfiable', + 417 => 'Expectation Failed', + 418 => 'I\'m a teapot', + 421 => 'Misdirected Request', + 422 => 'Unprocessable Entity', + 423 => 'Locked', + 424 => 'Failed Dependency', + 426 => 'Upgrade Required', + 428 => 'Precondition Required', + 429 => 'Too Many Requests', + 431 => 'Request Header Fields Too Large', + 444 => 'Connection Closed Without Response', + 451 => 'Unavailable For Legal Reasons', + 499 => 'Client Closed Request', //Server Error 5xx - 500 => '500 Internal Server Error', - 501 => '501 Not Implemented', - 502 => '502 Bad Gateway', - 503 => '503 Service Unavailable', - 504 => '504 Gateway Timeout', - 505 => '505 HTTP Version Not Supported', - 506 => '506 Variant Also Negotiates', - 510 => '510 Not Extended', - 511 => '511 Network Authentication Required' - ); - - /** - * Constructor - * @param string $body The HTTP response body - * @param int $status The HTTP response status - * @param \Slim\Http\Headers|array $headers The HTTP response headers + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported', + 506 => 'Variant Also Negotiates', + 507 => 'Insufficient Storage', + 508 => 'Loop Detected', + 510 => 'Not Extended', + 511 => 'Network Authentication Required', + 599 => 'Network Connect Timeout Error', + ]; + + /** + * EOL characters used for HTTP response. + * + * @var string */ - public function __construct($body = '', $status = 200, $headers = array()) - { - $this->setStatus($status); - $this->headers = new \Slim\Http\Headers(array('Content-Type' => 'text/html')); - $this->headers->replace($headers); - $this->cookies = new \Slim\Http\Cookies(); - $this->write($body); - } - - public function getStatus() - { - return $this->status; - } - - public function setStatus($status) - { - $this->status = (int)$status; - } + const EOL = "\r\n"; /** - * DEPRECATION WARNING! Use `getStatus` or `setStatus` instead. + * Create new HTTP response. * - * Get and set status - * @param int|null $status - * @return int + * @param int $status The response status code. + * @param HeadersInterface|null $headers The response headers. + * @param StreamInterface|null $body The response body. */ - public function status($status = null) + public function __construct($status = 200, HeadersInterface $headers = null, StreamInterface $body = null) { - if (!is_null($status)) { - $this->status = (int) $status; - } - - return $this->status; + $this->status = $this->filterStatus($status); + $this->headers = $headers ? $headers : new Headers(); + $this->body = $body ? $body : new Body(fopen('php://temp', 'r+')); } /** - * DEPRECATION WARNING! Access `headers` property directly. - * - * Get and set header - * @param string $name Header name - * @param string|null $value Header value - * @return string Header value + * This method is applied to the cloned object + * after PHP performs an initial shallow-copy. This + * method completes a deep-copy by creating new objects + * for the cloned object's internal reference pointers. */ - public function header($name, $value = null) + public function __clone() { - if (!is_null($value)) { - $this->headers->set($name, $value); - } - - return $this->headers->get($name); + $this->headers = clone $this->headers; } + /******************************************************************************* + * Status + ******************************************************************************/ + /** - * DEPRECATION WARNING! Access `headers` property directly. + * Gets the response status code. * - * Get headers - * @return \Slim\Http\Headers + * The status code is a 3-digit integer result code of the server's attempt + * to understand and satisfy the request. + * + * @return int Status code. */ - public function headers() - { - return $this->headers; - } - - public function getBody() + public function getStatusCode() { - return $this->body; - } - - public function setBody($content) - { - $this->write($content, true); + return $this->status; } /** - * DEPRECATION WARNING! use `getBody` or `setBody` instead. + * Return an instance with the specified status code and, optionally, reason phrase. * - * Get and set body - * @param string|null $body Content of HTTP response body - * @return string + * If no reason phrase is specified, implementations MAY choose to default + * to the RFC 7231 or IANA recommended reason phrase for the response's + * status code. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated status and reason phrase. + * + * @link http://tools.ietf.org/html/rfc7231#section-6 + * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml + * @param int $code The 3-digit integer result code to set. + * @param string $reasonPhrase The reason phrase to use with the + * provided status code; if none is provided, implementations MAY + * use the defaults as suggested in the HTTP specification. + * @return static + * @throws \InvalidArgumentException For invalid status code arguments. */ - public function body($body = null) + public function withStatus($code, $reasonPhrase = '') { - if (!is_null($body)) { - $this->write($body, true); + $code = $this->filterStatus($code); + + if (!is_string($reasonPhrase) && !method_exists($reasonPhrase, '__toString')) { + throw new InvalidArgumentException('ReasonPhrase must be a string'); } - return $this->body; - } + $clone = clone $this; + $clone->status = $code; + if ($reasonPhrase === '' && isset(static::$messages[$code])) { + $reasonPhrase = static::$messages[$code]; + } - /** - * Append HTTP response body - * @param string $body Content to append to the current HTTP response body - * @param bool $replace Overwrite existing response body? - * @return string The updated HTTP response body - */ - public function write($body, $replace = false) - { - if ($replace) { - $this->body = $body; - } else { - $this->body .= (string)$body; + if ($reasonPhrase === '') { + throw new InvalidArgumentException('ReasonPhrase must be supplied for this code'); } - $this->length = strlen($this->body); - return $this->body; - } + $clone->reasonPhrase = $reasonPhrase; - public function getLength() - { - return $this->length; + return $clone; } /** - * DEPRECATION WARNING! Use `getLength` or `write` or `body` instead. + * Filter HTTP status code. * - * Get and set length - * @param int|null $length + * @param int $status HTTP status code. * @return int + * @throws \InvalidArgumentException If an invalid HTTP status code is provided. */ - public function length($length = null) + protected function filterStatus($status) { - if (!is_null($length)) { - $this->length = (int) $length; + if (!is_integer($status) || $status<100 || $status>599) { + throw new InvalidArgumentException('Invalid HTTP status code'); } - return $this->length; + return $status; } /** - * Finalize + * Gets the response reason phrase associated with the status code. * - * This prepares this response and returns an array - * of [status, headers, body]. This array is passed to outer middleware - * if available or directly to the Slim run method. + * Because a reason phrase is not a required element in a response + * status line, the reason phrase value MAY be null. Implementations MAY + * choose to return the default RFC 7231 recommended reason phrase (or those + * listed in the IANA HTTP Status Code Registry) for the response's + * status code. * - * @return array[int status, array headers, string body] + * @link http://tools.ietf.org/html/rfc7231#section-6 + * @link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml + * @return string Reason phrase; must return an empty string if none present. */ - public function finalize() + public function getReasonPhrase() { - // Prepare response - if (in_array($this->status, array(204, 304))) { - $this->headers->remove('Content-Type'); - $this->headers->remove('Content-Length'); - $this->setBody(''); + if ($this->reasonPhrase) { + return $this->reasonPhrase; } - - return array($this->status, $this->headers, $this->body); + if (isset(static::$messages[$this->status])) { + return static::$messages[$this->status]; + } + return ''; } + /******************************************************************************* + * Body + ******************************************************************************/ + /** - * DEPRECATION WARNING! Access `cookies` property directly. + * Write data to the response body. * - * Set cookie + * Note: This method is not part of the PSR-7 standard. * - * Instead of using PHP's `setcookie()` function, Slim manually constructs the HTTP `Set-Cookie` - * header on its own and delegates this responsibility to the `Slim_Http_Util` class. This - * response's header is passed by reference to the utility class and is directly modified. By not - * relying on PHP's native implementation, Slim allows middleware the opportunity to massage or - * analyze the raw header before the response is ultimately delivered to the HTTP client. + * Proxies to the underlying stream and writes the provided data to it. * - * @param string $name The name of the cookie - * @param string|array $value If string, the value of cookie; if array, properties for - * cookie including: value, expire, path, domain, secure, httponly + * @param string $data + * @return $this */ - public function setCookie($name, $value) + public function write($data) { - // Util::setCookieHeader($this->header, $name, $value); - $this->cookies->set($name, $value); + $this->getBody()->write($data); + + return $this; } + /******************************************************************************* + * Response Helpers + ******************************************************************************/ + /** - * DEPRECATION WARNING! Access `cookies` property directly. + * Redirect. * - * Delete cookie + * Note: This method is not part of the PSR-7 standard. * - * Instead of using PHP's `setcookie()` function, Slim manually constructs the HTTP `Set-Cookie` - * header on its own and delegates this responsibility to the `Slim_Http_Util` class. This - * response's header is passed by reference to the utility class and is directly modified. By not - * relying on PHP's native implementation, Slim allows middleware the opportunity to massage or - * analyze the raw header before the response is ultimately delivered to the HTTP client. + * This method prepares the response object to return an HTTP Redirect + * response to the client. * - * This method will set a cookie with the given name that has an expiration time in the past; this will - * prompt the HTTP client to invalidate and remove the client-side cookie. Optionally, you may - * also pass a key/value array as the second argument. If the "domain" key is present in this - * array, only the Cookie with the given name AND domain will be removed. The invalidating cookie - * sent with this response will adopt all properties of the second argument. - * - * @param string $name The name of the cookie - * @param array $settings Properties for cookie including: value, expire, path, domain, secure, httponly + * @param string|UriInterface $url The redirect destination. + * @param int|null $status The redirect HTTP status code. + * @return static */ - public function deleteCookie($name, $settings = array()) + public function withRedirect($url, $status = null) { - $this->cookies->remove($name, $settings); - // Util::deleteCookieHeader($this->header, $name, $value); + $responseWithRedirect = $this->withHeader('Location', (string)$url); + + if (is_null($status) && $this->getStatusCode() === 200) { + $status = 302; + } + + if (!is_null($status)) { + return $responseWithRedirect->withStatus($status); + } + + return $responseWithRedirect; } /** - * Redirect + * Json. * - * This method prepares this response to return an HTTP Redirect response - * to the HTTP client. + * Note: This method is not part of the PSR-7 standard. * - * @param string $url The redirect destination - * @param int $status The redirect HTTP status code + * This method prepares the response object to return an HTTP Json + * response to the client. + * + * @param mixed $data The data + * @param int $status The HTTP status code. + * @param int $encodingOptions Json encoding options + * @throws \RuntimeException + * @return static */ - public function redirect ($url, $status = 302) + public function withJson($data, $status = null, $encodingOptions = 0) { - $this->setStatus($status); - $this->headers->set('Location', $url); + $response = $this->withBody(new Body(fopen('php://temp', 'r+'))); + $response->body->write($json = json_encode($data, $encodingOptions)); + + // Ensure that the json encoding passed successfully + if ($json === false) { + throw new \RuntimeException(json_last_error_msg(), json_last_error()); + } + + $responseWithJson = $response->withHeader('Content-Type', 'application/json;charset=utf-8'); + if (isset($status)) { + return $responseWithJson->withStatus($status); + } + return $responseWithJson; } /** - * Helpers: Empty? + * Is this response empty? + * + * Note: This method is not part of the PSR-7 standard. + * * @return bool */ public function isEmpty() { - return in_array($this->status, array(201, 204, 304)); + return in_array($this->getStatusCode(), [204, 205, 304]); } /** - * Helpers: Informational? + * Is this response informational? + * + * Note: This method is not part of the PSR-7 standard. + * * @return bool */ public function isInformational() { - return $this->status >= 100 && $this->status < 200; + return $this->getStatusCode() >= 100 && $this->getStatusCode() < 200; } /** - * Helpers: OK? + * Is this response OK? + * + * Note: This method is not part of the PSR-7 standard. + * * @return bool */ public function isOk() { - return $this->status === 200; + return $this->getStatusCode() === 200; } /** - * Helpers: Successful? + * Is this response successful? + * + * Note: This method is not part of the PSR-7 standard. + * * @return bool */ public function isSuccessful() { - return $this->status >= 200 && $this->status < 300; + return $this->getStatusCode() >= 200 && $this->getStatusCode() < 300; } /** - * Helpers: Redirect? + * Is this response a redirect? + * + * Note: This method is not part of the PSR-7 standard. + * * @return bool */ public function isRedirect() { - return in_array($this->status, array(301, 302, 303, 307)); + return in_array($this->getStatusCode(), [301, 302, 303, 307]); } /** - * Helpers: Redirection? + * Is this response a redirection? + * + * Note: This method is not part of the PSR-7 standard. + * * @return bool */ public function isRedirection() { - return $this->status >= 300 && $this->status < 400; + return $this->getStatusCode() >= 300 && $this->getStatusCode() < 400; } /** - * Helpers: Forbidden? + * Is this response forbidden? + * + * Note: This method is not part of the PSR-7 standard. + * * @return bool + * @api */ public function isForbidden() { - return $this->status === 403; + return $this->getStatusCode() === 403; } /** - * Helpers: Not Found? + * Is this response not Found? + * + * Note: This method is not part of the PSR-7 standard. + * * @return bool */ public function isNotFound() { - return $this->status === 404; + return $this->getStatusCode() === 404; } /** - * Helpers: Client error? + * Is this response a client error? + * + * Note: This method is not part of the PSR-7 standard. + * * @return bool */ public function isClientError() { - return $this->status >= 400 && $this->status < 500; + return $this->getStatusCode() >= 400 && $this->getStatusCode() < 500; } /** - * Helpers: Server Error? + * Is this response a server error? + * + * Note: This method is not part of the PSR-7 standard. + * * @return bool */ public function isServerError() { - return $this->status >= 500 && $this->status < 600; - } - - /** - * DEPRECATION WARNING! ArrayAccess interface will be removed from \Slim\Http\Response. - * Iterate `headers` or `cookies` properties directly. - */ - - /** - * Array Access: Offset Exists - */ - public function offsetExists($offset) - { - return isset($this->headers[$offset]); + return $this->getStatusCode() >= 500 && $this->getStatusCode() < 600; } /** - * Array Access: Offset Get - */ - public function offsetGet($offset) - { - return $this->headers[$offset]; - } - - /** - * Array Access: Offset Set - */ - public function offsetSet($offset, $value) - { - $this->headers[$offset] = $value; - } - - /** - * Array Access: Offset Unset - */ - public function offsetUnset($offset) - { - unset($this->headers[$offset]); - } - - /** - * DEPRECATION WARNING! Countable interface will be removed from \Slim\Http\Response. - * Call `count` on `headers` or `cookies` properties directly. - * - * Countable: Count - */ - public function count() - { - return count($this->headers); - } - - /** - * DEPRECATION WARNING! IteratorAggregate interface will be removed from \Slim\Http\Response. - * Iterate `headers` or `cookies` properties directly. - * - * Get Iterator + * Convert response to string. * - * This returns the contained `\Slim\Http\Headers` instance which - * is itself iterable. + * Note: This method is not part of the PSR-7 standard. * - * @return \Slim\Http\Headers - */ - public function getIterator() - { - return $this->headers->getIterator(); - } - - /** - * Get message for HTTP status code - * @param int $status - * @return string|null + * @return string */ - public static function getMessageForCode($status) - { - if (isset(self::$messages[$status])) { - return self::$messages[$status]; - } else { - return null; + public function __toString() + { + $output = sprintf( + 'HTTP/%s %s %s', + $this->getProtocolVersion(), + $this->getStatusCode(), + $this->getReasonPhrase() + ); + $output .= Response::EOL; + foreach ($this->getHeaders() as $name => $values) { + $output .= sprintf('%s: %s', $name, $this->getHeaderLine($name)) . Response::EOL; } + $output .= Response::EOL; + $output .= (string)$this->getBody(); + + return $output; } } diff --git a/vendor/slim/slim/Slim/Http/Util.php b/vendor/slim/slim/Slim/Http/Util.php deleted file mode 100644 index 00cac0e..0000000 --- a/vendor/slim/slim/Slim/Http/Util.php +++ /dev/null @@ -1,434 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -namespace Slim\Http; - -/** - * Slim HTTP Utilities - * - * This class provides useful methods for handling HTTP requests. - * - * @package Slim - * @author Josh Lockhart - * @since 1.0.0 - */ -class Util -{ - /** - * Strip slashes from string or array - * - * This method strips slashes from its input. By default, this method will only - * strip slashes from its input if magic quotes are enabled. Otherwise, you may - * override the magic quotes setting with either TRUE or FALSE as the send argument - * to force this method to strip or not strip slashes from its input. - * - * @param array|string $rawData - * @param bool $overrideStripSlashes - * @return array|string - */ - public static function stripSlashesIfMagicQuotes($rawData, $overrideStripSlashes = null) - { - $strip = is_null($overrideStripSlashes) ? get_magic_quotes_gpc() : $overrideStripSlashes; - if ($strip) { - return self::stripSlashes($rawData); - } - - return $rawData; - } - - /** - * Strip slashes from string or array - * @param array|string $rawData - * @return array|string - */ - protected static function stripSlashes($rawData) - { - return is_array($rawData) ? array_map(array('self', 'stripSlashes'), $rawData) : stripslashes($rawData); - } - - /** - * Encrypt data - * - * This method will encrypt data using a given key, vector, and cipher. - * By default, this will encrypt data using the RIJNDAEL/AES 256 bit cipher. You - * may override the default cipher and cipher mode by passing your own desired - * cipher and cipher mode as the final key-value array argument. - * - * @param string $data The unencrypted data - * @param string $key The encryption key - * @param string $iv The encryption initialization vector - * @param array $settings Optional key-value array with custom algorithm and mode - * @return string - */ - public static function encrypt($data, $key, $iv, $settings = array()) - { - if ($data === '' || !extension_loaded('mcrypt')) { - return $data; - } - - //Merge settings with defaults - $defaults = array( - 'algorithm' => MCRYPT_RIJNDAEL_256, - 'mode' => MCRYPT_MODE_CBC - ); - $settings = array_merge($defaults, $settings); - - //Get module - $module = mcrypt_module_open($settings['algorithm'], '', $settings['mode'], ''); - - //Validate IV - $ivSize = mcrypt_enc_get_iv_size($module); - if (strlen($iv) > $ivSize) { - $iv = substr($iv, 0, $ivSize); - } - - //Validate key - $keySize = mcrypt_enc_get_key_size($module); - if (strlen($key) > $keySize) { - $key = substr($key, 0, $keySize); - } - - //Encrypt value - mcrypt_generic_init($module, $key, $iv); - $res = @mcrypt_generic($module, $data); - mcrypt_generic_deinit($module); - - return $res; - } - - /** - * Decrypt data - * - * This method will decrypt data using a given key, vector, and cipher. - * By default, this will decrypt data using the RIJNDAEL/AES 256 bit cipher. You - * may override the default cipher and cipher mode by passing your own desired - * cipher and cipher mode as the final key-value array argument. - * - * @param string $data The encrypted data - * @param string $key The encryption key - * @param string $iv The encryption initialization vector - * @param array $settings Optional key-value array with custom algorithm and mode - * @return string - */ - public static function decrypt($data, $key, $iv, $settings = array()) - { - if ($data === '' || !extension_loaded('mcrypt')) { - return $data; - } - - //Merge settings with defaults - $defaults = array( - 'algorithm' => MCRYPT_RIJNDAEL_256, - 'mode' => MCRYPT_MODE_CBC - ); - $settings = array_merge($defaults, $settings); - - //Get module - $module = mcrypt_module_open($settings['algorithm'], '', $settings['mode'], ''); - - //Validate IV - $ivSize = mcrypt_enc_get_iv_size($module); - if (strlen($iv) > $ivSize) { - $iv = substr($iv, 0, $ivSize); - } - - //Validate key - $keySize = mcrypt_enc_get_key_size($module); - if (strlen($key) > $keySize) { - $key = substr($key, 0, $keySize); - } - - //Decrypt value - mcrypt_generic_init($module, $key, $iv); - $decryptedData = @mdecrypt_generic($module, $data); - $res = rtrim($decryptedData, "\0"); - mcrypt_generic_deinit($module); - - return $res; - } - - /** - * Serialize Response cookies into raw HTTP header - * @param \Slim\Http\Headers $headers The Response headers - * @param \Slim\Http\Cookies $cookies The Response cookies - * @param array $config The Slim app settings - */ - public static function serializeCookies(\Slim\Http\Headers &$headers, \Slim\Http\Cookies $cookies, array $config) - { - if ($config['cookies.encrypt']) { - foreach ($cookies as $name => $settings) { - if (is_string($settings['expires'])) { - $expires = strtotime($settings['expires']); - } else { - $expires = (int) $settings['expires']; - } - - $settings['value'] = static::encodeSecureCookie( - $settings['value'], - $expires, - $config['cookies.secret_key'], - $config['cookies.cipher'], - $config['cookies.cipher_mode'] - ); - static::setCookieHeader($headers, $name, $settings); - } - } else { - foreach ($cookies as $name => $settings) { - static::setCookieHeader($headers, $name, $settings); - } - } - } - - /** - * Encode secure cookie value - * - * This method will create the secure value of an HTTP cookie. The - * cookie value is encrypted and hashed so that its value is - * secure and checked for integrity when read in subsequent requests. - * - * @param string $value The insecure HTTP cookie value - * @param int $expires The UNIX timestamp at which this cookie will expire - * @param string $secret The secret key used to hash the cookie value - * @param int $algorithm The algorithm to use for encryption - * @param int $mode The algorithm mode to use for encryption - * @return string - */ - public static function encodeSecureCookie($value, $expires, $secret, $algorithm, $mode) - { - $key = hash_hmac('sha1', (string) $expires, $secret); - $iv = self::getIv($expires, $secret); - $secureString = base64_encode( - self::encrypt( - $value, - $key, - $iv, - array( - 'algorithm' => $algorithm, - 'mode' => $mode - ) - ) - ); - $verificationString = hash_hmac('sha1', $expires . $value, $key); - - return implode('|', array($expires, $secureString, $verificationString)); - } - - /** - * Decode secure cookie value - * - * This method will decode the secure value of an HTTP cookie. The - * cookie value is encrypted and hashed so that its value is - * secure and checked for integrity when read in subsequent requests. - * - * @param string $value The secure HTTP cookie value - * @param string $secret The secret key used to hash the cookie value - * @param int $algorithm The algorithm to use for encryption - * @param int $mode The algorithm mode to use for encryption - * @return bool|string - */ - public static function decodeSecureCookie($value, $secret, $algorithm, $mode) - { - if ($value) { - $value = explode('|', $value); - if (count($value) === 3 && ((int) $value[0] === 0 || (int) $value[0] > time())) { - $key = hash_hmac('sha1', $value[0], $secret); - $iv = self::getIv($value[0], $secret); - $data = self::decrypt( - base64_decode($value[1]), - $key, - $iv, - array( - 'algorithm' => $algorithm, - 'mode' => $mode - ) - ); - $verificationString = hash_hmac('sha1', $value[0] . $data, $key); - if ($verificationString === $value[2]) { - return $data; - } - } - } - - return false; - } - - /** - * Set HTTP cookie header - * - * This method will construct and set the HTTP `Set-Cookie` header. Slim - * uses this method instead of PHP's native `setcookie` method. This allows - * more control of the HTTP header irrespective of the native implementation's - * dependency on PHP versions. - * - * This method accepts the Slim_Http_Headers object by reference as its - * first argument; this method directly modifies this object instead of - * returning a value. - * - * @param array $header - * @param string $name - * @param string $value - */ - public static function setCookieHeader(&$header, $name, $value) - { - //Build cookie header - if (is_array($value)) { - $domain = ''; - $path = ''; - $expires = ''; - $secure = ''; - $httponly = ''; - if (isset($value['domain']) && $value['domain']) { - $domain = '; domain=' . $value['domain']; - } - if (isset($value['path']) && $value['path']) { - $path = '; path=' . $value['path']; - } - if (isset($value['expires'])) { - if (is_string($value['expires'])) { - $timestamp = strtotime($value['expires']); - } else { - $timestamp = (int) $value['expires']; - } - if ($timestamp !== 0) { - $expires = '; expires=' . gmdate('D, d-M-Y H:i:s e', $timestamp); - } - } - if (isset($value['secure']) && $value['secure']) { - $secure = '; secure'; - } - if (isset($value['httponly']) && $value['httponly']) { - $httponly = '; HttpOnly'; - } - $cookie = sprintf('%s=%s%s', urlencode($name), urlencode((string) $value['value']), $domain . $path . $expires . $secure . $httponly); - } else { - $cookie = sprintf('%s=%s', urlencode($name), urlencode((string) $value)); - } - - //Set cookie header - if (!isset($header['Set-Cookie']) || $header['Set-Cookie'] === '') { - $header['Set-Cookie'] = $cookie; - } else { - $header['Set-Cookie'] = implode("\n", array($header['Set-Cookie'], $cookie)); - } - } - - /** - * Delete HTTP cookie header - * - * This method will construct and set the HTTP `Set-Cookie` header to invalidate - * a client-side HTTP cookie. If a cookie with the same name (and, optionally, domain) - * is already set in the HTTP response, it will also be removed. Slim uses this method - * instead of PHP's native `setcookie` method. This allows more control of the HTTP header - * irrespective of PHP's native implementation's dependency on PHP versions. - * - * This method accepts the Slim_Http_Headers object by reference as its - * first argument; this method directly modifies this object instead of - * returning a value. - * - * @param array $header - * @param string $name - * @param array $value - */ - public static function deleteCookieHeader(&$header, $name, $value = array()) - { - //Remove affected cookies from current response header - $cookiesOld = array(); - $cookiesNew = array(); - if (isset($header['Set-Cookie'])) { - $cookiesOld = explode("\n", $header['Set-Cookie']); - } - foreach ($cookiesOld as $c) { - if (isset($value['domain']) && $value['domain']) { - $regex = sprintf('@%s=.*domain=%s@', urlencode($name), preg_quote($value['domain'])); - } else { - $regex = sprintf('@%s=@', urlencode($name)); - } - if (preg_match($regex, $c) === 0) { - $cookiesNew[] = $c; - } - } - if ($cookiesNew) { - $header['Set-Cookie'] = implode("\n", $cookiesNew); - } else { - unset($header['Set-Cookie']); - } - - //Set invalidating cookie to clear client-side cookie - self::setCookieHeader($header, $name, array_merge(array('value' => '', 'path' => null, 'domain' => null, 'expires' => time() - 100), $value)); - } - - /** - * Parse cookie header - * - * This method will parse the HTTP request's `Cookie` header - * and extract cookies into an associative array. - * - * @param string - * @return array - */ - public static function parseCookieHeader($header) - { - $cookies = array(); - $header = rtrim($header, "\r\n"); - $headerPieces = preg_split('@\s*[;,]\s*@', $header); - foreach ($headerPieces as $c) { - $cParts = explode('=', $c, 2); - if (count($cParts) === 2) { - $key = urldecode($cParts[0]); - $value = urldecode($cParts[1]); - if (!isset($cookies[$key])) { - $cookies[$key] = $value; - } - } - } - - return $cookies; - } - - /** - * Generate a random IV - * - * This method will generate a non-predictable IV for use with - * the cookie encryption - * - * @param int $expires The UNIX timestamp at which this cookie will expire - * @param string $secret The secret key used to hash the cookie value - * @return string Hash - */ - private static function getIv($expires, $secret) - { - $data1 = hash_hmac('sha1', 'a'.$expires.'b', $secret); - $data2 = hash_hmac('sha1', 'z'.$expires.'y', $secret); - - return pack("h*", $data1.$data2); - } -} diff --git a/vendor/slim/slim/Slim/Log.php b/vendor/slim/slim/Slim/Log.php deleted file mode 100644 index 13cb825..0000000 --- a/vendor/slim/slim/Slim/Log.php +++ /dev/null @@ -1,354 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -namespace Slim; - -/** - * Log - * - * This is the primary logger for a Slim application. You may provide - * a Log Writer in conjunction with this Log to write to various output - * destinations (e.g. a file). This class provides this interface: - * - * debug( mixed $object, array $context ) - * info( mixed $object, array $context ) - * notice( mixed $object, array $context ) - * warning( mixed $object, array $context ) - * error( mixed $object, array $context ) - * critical( mixed $object, array $context ) - * alert( mixed $object, array $context ) - * emergency( mixed $object, array $context ) - * log( mixed $level, mixed $object, array $context ) - * - * This class assumes only that your Log Writer has a public `write()` method - * that accepts any object as its one and only argument. The Log Writer - * class may write or send its argument anywhere: a file, STDERR, - * a remote web API, etc. The possibilities are endless. - * - * @package Slim - * @author Josh Lockhart - * @since 1.0.0 - */ -class Log -{ - const EMERGENCY = 1; - const ALERT = 2; - const CRITICAL = 3; - const FATAL = 3; //DEPRECATED replace with CRITICAL - const ERROR = 4; - const WARN = 5; - const NOTICE = 6; - const INFO = 7; - const DEBUG = 8; - - /** - * @var array - */ - protected static $levels = array( - self::EMERGENCY => 'EMERGENCY', - self::ALERT => 'ALERT', - self::CRITICAL => 'CRITICAL', - self::ERROR => 'ERROR', - self::WARN => 'WARNING', - self::NOTICE => 'NOTICE', - self::INFO => 'INFO', - self::DEBUG => 'DEBUG' - ); - - /** - * @var mixed - */ - protected $writer; - - /** - * @var bool - */ - protected $enabled; - - /** - * @var int - */ - protected $level; - - /** - * Constructor - * @param mixed $writer - */ - public function __construct($writer) - { - $this->writer = $writer; - $this->enabled = true; - $this->level = self::DEBUG; - } - - /** - * Is logging enabled? - * @return bool - */ - public function getEnabled() - { - return $this->enabled; - } - - /** - * Enable or disable logging - * @param bool $enabled - */ - public function setEnabled($enabled) - { - if ($enabled) { - $this->enabled = true; - } else { - $this->enabled = false; - } - } - - /** - * Set level - * @param int $level - * @throws \InvalidArgumentException If invalid log level specified - */ - public function setLevel($level) - { - if (!isset(self::$levels[$level])) { - throw new \InvalidArgumentException('Invalid log level'); - } - $this->level = $level; - } - - /** - * Get level - * @return int - */ - public function getLevel() - { - return $this->level; - } - - /** - * Set writer - * @param mixed $writer - */ - public function setWriter($writer) - { - $this->writer = $writer; - } - - /** - * Get writer - * @return mixed - */ - public function getWriter() - { - return $this->writer; - } - - /** - * Is logging enabled? - * @return bool - */ - public function isEnabled() - { - return $this->enabled; - } - - /** - * Log debug message - * @param mixed $object - * @param array $context - * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled - */ - public function debug($object, $context = array()) - { - return $this->log(self::DEBUG, $object, $context); - } - - /** - * Log info message - * @param mixed $object - * @param array $context - * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled - */ - public function info($object, $context = array()) - { - return $this->log(self::INFO, $object, $context); - } - - /** - * Log notice message - * @param mixed $object - * @param array $context - * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled - */ - public function notice($object, $context = array()) - { - return $this->log(self::NOTICE, $object, $context); - } - - /** - * Log warning message - * @param mixed $object - * @param array $context - * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled - */ - public function warning($object, $context = array()) - { - return $this->log(self::WARN, $object, $context); - } - - /** - * DEPRECATED for function warning - * Log warning message - * @param mixed $object - * @param array $context - * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled - */ - public function warn($object, $context = array()) - { - return $this->log(self::WARN, $object, $context); - } - - /** - * Log error message - * @param mixed $object - * @param array $context - * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled - */ - public function error($object, $context = array()) - { - return $this->log(self::ERROR, $object, $context); - } - - /** - * Log critical message - * @param mixed $object - * @param array $context - * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled - */ - public function critical($object, $context = array()) - { - return $this->log(self::CRITICAL, $object, $context); - } - - /** - * DEPRECATED for function critical - * Log fatal message - * @param mixed $object - * @param array $context - * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled - */ - public function fatal($object, $context = array()) - { - return $this->log(self::CRITICAL, $object, $context); - } - - /** - * Log alert message - * @param mixed $object - * @param array $context - * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled - */ - public function alert($object, $context = array()) - { - return $this->log(self::ALERT, $object, $context); - } - - /** - * Log emergency message - * @param mixed $object - * @param array $context - * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled - */ - public function emergency($object, $context = array()) - { - return $this->log(self::EMERGENCY, $object, $context); - } - - /** - * Log message - * @param mixed $level - * @param mixed $object - * @param array $context - * @return mixed|bool What the Logger returns, or false if Logger not set or not enabled - * @throws \InvalidArgumentException If invalid log level - */ - public function log($level, $object, $context = array()) - { - if (!isset(self::$levels[$level])) { - throw new \InvalidArgumentException('Invalid log level supplied to function'); - } else if ($this->enabled && $this->writer && $level <= $this->level) { - if (is_array($object) || (is_object($object) && !method_exists($object, "__toString"))) { - $message = print_r($object, true); - } else { - $message = (string) $object; - } - - if (count($context) > 0) { - if (isset($context['exception']) && $context['exception'] instanceof \Exception) { - $message .= ' - ' . $context['exception']; - unset($context['exception']); - } - $message = $this->interpolate($message, $context); - } - return $this->writer->write($message, $level); - } else { - return false; - } - } - - /** - * DEPRECATED for function log - * Log message - * @param mixed $object The object to log - * @param int $level The message level - * @return int|bool - */ - protected function write($object, $level) - { - return $this->log($level, $object); - } - - /** - * Interpolate log message - * @param mixed $message The log message - * @param array $context An array of placeholder values - * @return string The processed string - */ - protected function interpolate($message, $context = array()) - { - $replace = array(); - foreach ($context as $key => $value) { - $replace['{' . $key . '}'] = $value; - } - return strtr($message, $replace); - } -} diff --git a/vendor/slim/slim/Slim/LogWriter.php b/vendor/slim/slim/Slim/LogWriter.php deleted file mode 100644 index afa3ae9..0000000 --- a/vendor/slim/slim/Slim/LogWriter.php +++ /dev/null @@ -1,75 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -namespace Slim; - -/** - * Log Writer - * - * This class is used by Slim_Log to write log messages to a valid, writable - * resource handle (e.g. a file or STDERR). - * - * @package Slim - * @author Josh Lockhart - * @since 1.6.0 - */ -class LogWriter -{ - /** - * @var resource - */ - protected $resource; - - /** - * Constructor - * @param resource $resource - * @throws \InvalidArgumentException If invalid resource - */ - public function __construct($resource) - { - if (!is_resource($resource)) { - throw new \InvalidArgumentException('Cannot create LogWriter. Invalid resource handle.'); - } - $this->resource = $resource; - } - - /** - * Write message - * @param mixed $message - * @param int $level - * @return int|bool - */ - public function write($message, $level = null) - { - return fwrite($this->resource, (string) $message . PHP_EOL); - } -} diff --git a/vendor/slim/slim/Slim/Middleware.php b/vendor/slim/slim/Slim/Middleware.php deleted file mode 100644 index 79fbb1e..0000000 --- a/vendor/slim/slim/Slim/Middleware.php +++ /dev/null @@ -1,114 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -namespace Slim; - -/** - * Middleware - * - * @package Slim - * @author Josh Lockhart - * @since 1.6.0 - */ -abstract class Middleware -{ - /** - * @var \Slim\Slim Reference to the primary application instance - */ - protected $app; - - /** - * @var mixed Reference to the next downstream middleware - */ - protected $next; - - /** - * Set application - * - * This method injects the primary Slim application instance into - * this middleware. - * - * @param \Slim\Slim $application - */ - final public function setApplication($application) - { - $this->app = $application; - } - - /** - * Get application - * - * This method retrieves the application previously injected - * into this middleware. - * - * @return \Slim\Slim - */ - final public function getApplication() - { - return $this->app; - } - - /** - * Set next middleware - * - * This method injects the next downstream middleware into - * this middleware so that it may optionally be called - * when appropriate. - * - * @param \Slim|\Slim\Middleware - */ - final public function setNextMiddleware($nextMiddleware) - { - $this->next = $nextMiddleware; - } - - /** - * Get next middleware - * - * This method retrieves the next downstream middleware - * previously injected into this middleware. - * - * @return \Slim\Slim|\Slim\Middleware - */ - final public function getNextMiddleware() - { - return $this->next; - } - - /** - * Call - * - * Perform actions specific to this middleware and optionally - * call the next downstream middleware. - */ - abstract public function call(); -} diff --git a/vendor/slim/slim/Slim/Middleware/ContentTypes.php b/vendor/slim/slim/Slim/Middleware/ContentTypes.php deleted file mode 100644 index fcc2242..0000000 --- a/vendor/slim/slim/Slim/Middleware/ContentTypes.php +++ /dev/null @@ -1,174 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -namespace Slim\Middleware; - - /** - * Content Types - * - * This is middleware for a Slim application that intercepts - * the HTTP request body and parses it into the appropriate - * PHP data structure if possible; else it returns the HTTP - * request body unchanged. This is particularly useful - * for preparing the HTTP request body for an XML or JSON API. - * - * @package Slim - * @author Josh Lockhart - * @since 1.6.0 - */ -class ContentTypes extends \Slim\Middleware -{ - /** - * @var array - */ - protected $contentTypes; - - /** - * Constructor - * @param array $settings - */ - public function __construct($settings = array()) - { - $defaults = array( - 'application/json' => array($this, 'parseJson'), - 'application/xml' => array($this, 'parseXml'), - 'text/xml' => array($this, 'parseXml'), - 'text/csv' => array($this, 'parseCsv') - ); - $this->contentTypes = array_merge($defaults, $settings); - } - - /** - * Call - */ - public function call() - { - $mediaType = $this->app->request()->getMediaType(); - if ($mediaType) { - $env = $this->app->environment(); - $env['slim.input_original'] = $env['slim.input']; - $env['slim.input'] = $this->parse($env['slim.input'], $mediaType); - } - $this->next->call(); - } - - /** - * Parse input - * - * This method will attempt to parse the request body - * based on its content type if available. - * - * @param string $input - * @param string $contentType - * @return mixed - */ - protected function parse ($input, $contentType) - { - if (isset($this->contentTypes[$contentType]) && is_callable($this->contentTypes[$contentType])) { - $result = call_user_func($this->contentTypes[$contentType], $input); - if ($result) { - return $result; - } - } - - return $input; - } - - /** - * Parse JSON - * - * This method converts the raw JSON input - * into an associative array. - * - * @param string $input - * @return array|string - */ - protected function parseJson($input) - { - if (function_exists('json_decode')) { - $result = json_decode($input, true); - if(json_last_error() === JSON_ERROR_NONE) { - return $result; - } - } - } - - /** - * Parse XML - * - * This method creates a SimpleXMLElement - * based upon the XML input. If the SimpleXML - * extension is not available, the raw input - * will be returned unchanged. - * - * @param string $input - * @return \SimpleXMLElement|string - */ - protected function parseXml($input) - { - if (class_exists('SimpleXMLElement')) { - try { - $backup = libxml_disable_entity_loader(true); - $result = new \SimpleXMLElement($input); - libxml_disable_entity_loader($backup); - return $result; - } catch (\Exception $e) { - // Do nothing - } - } - - return $input; - } - - /** - * Parse CSV - * - * This method parses CSV content into a numeric array - * containing an array of data for each CSV line. - * - * @param string $input - * @return array - */ - protected function parseCsv($input) - { - $temp = fopen('php://memory', 'rw'); - fwrite($temp, $input); - fseek($temp, 0); - $res = array(); - while (($data = fgetcsv($temp)) !== false) { - $res[] = $data; - } - fclose($temp); - - return $res; - } -} diff --git a/vendor/slim/slim/Slim/Middleware/Flash.php b/vendor/slim/slim/Slim/Middleware/Flash.php deleted file mode 100644 index 593082f..0000000 --- a/vendor/slim/slim/Slim/Middleware/Flash.php +++ /dev/null @@ -1,212 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -namespace Slim\Middleware; - - /** - * Flash - * - * This is middleware for a Slim application that enables - * Flash messaging between HTTP requests. This allows you - * set Flash messages for the current request, for the next request, - * or to retain messages from the previous request through to - * the next request. - * - * @package Slim - * @author Josh Lockhart - * @since 1.6.0 - */ -class Flash extends \Slim\Middleware implements \ArrayAccess, \IteratorAggregate, \Countable -{ - /** - * @var array - */ - protected $settings; - - /** - * @var array - */ - protected $messages; - - /** - * Constructor - * @param array $settings - */ - public function __construct($settings = array()) - { - $this->settings = array_merge(array('key' => 'slim.flash'), $settings); - $this->messages = array( - 'prev' => array(), //flash messages from prev request (loaded when middleware called) - 'next' => array(), //flash messages for next request - 'now' => array() //flash messages for current request - ); - } - - /** - * Call - */ - public function call() - { - //Read flash messaging from previous request if available - $this->loadMessages(); - - //Prepare flash messaging for current request - $env = $this->app->environment(); - $env['slim.flash'] = $this; - $this->next->call(); - $this->save(); - } - - /** - * Now - * - * Specify a flash message for a given key to be shown for the current request - * - * @param string $key - * @param string $value - */ - public function now($key, $value) - { - $this->messages['now'][(string) $key] = $value; - } - - /** - * Set - * - * Specify a flash message for a given key to be shown for the next request - * - * @param string $key - * @param string $value - */ - public function set($key, $value) - { - $this->messages['next'][(string) $key] = $value; - } - - /** - * Keep - * - * Retain flash messages from the previous request for the next request - */ - public function keep() - { - foreach ($this->messages['prev'] as $key => $val) { - $this->messages['next'][$key] = $val; - } - } - - /** - * Save - */ - public function save() - { - $_SESSION[$this->settings['key']] = $this->messages['next']; - } - - /** - * Load messages from previous request if available - */ - public function loadMessages() - { - if (isset($_SESSION[$this->settings['key']])) { - $this->messages['prev'] = $_SESSION[$this->settings['key']]; - } - } - - /** - * Return array of flash messages to be shown for the current request - * - * @return array - */ - public function getMessages() - { - return array_merge($this->messages['prev'], $this->messages['now']); - } - - /** - * Array Access: Offset Exists - */ - public function offsetExists($offset) - { - $messages = $this->getMessages(); - - return isset($messages[$offset]); - } - - /** - * Array Access: Offset Get - */ - public function offsetGet($offset) - { - $messages = $this->getMessages(); - - return isset($messages[$offset]) ? $messages[$offset] : null; - } - - /** - * Array Access: Offset Set - */ - public function offsetSet($offset, $value) - { - $this->now($offset, $value); - } - - /** - * Array Access: Offset Unset - */ - public function offsetUnset($offset) - { - unset($this->messages['prev'][$offset], $this->messages['now'][$offset]); - } - - /** - * Iterator Aggregate: Get Iterator - * @return \ArrayIterator - */ - public function getIterator() - { - $messages = $this->getMessages(); - - return new \ArrayIterator($messages); - } - - /** - * Countable: Count - */ - public function count() - { - return count($this->getMessages()); - } - - - -} diff --git a/vendor/slim/slim/Slim/Middleware/MethodOverride.php b/vendor/slim/slim/Slim/Middleware/MethodOverride.php deleted file mode 100644 index 1298767..0000000 --- a/vendor/slim/slim/Slim/Middleware/MethodOverride.php +++ /dev/null @@ -1,94 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -namespace Slim\Middleware; - - /** - * HTTP Method Override - * - * This is middleware for a Slim application that allows traditional - * desktop browsers to submit pseudo PUT and DELETE requests by relying - * on a pre-determined request parameter. Without this middleware, - * desktop browsers are only able to submit GET and POST requests. - * - * This middleware is included automatically! - * - * @package Slim - * @author Josh Lockhart - * @since 1.6.0 - */ -class MethodOverride extends \Slim\Middleware -{ - /** - * @var array - */ - protected $settings; - - /** - * Constructor - * @param array $settings - */ - public function __construct($settings = array()) - { - $this->settings = array_merge(array('key' => '_METHOD'), $settings); - } - - /** - * Call - * - * Implements Slim middleware interface. This method is invoked and passed - * an array of environment variables. This middleware inspects the environment - * variables for the HTTP method override parameter; if found, this middleware - * modifies the environment settings so downstream middleware and/or the Slim - * application will treat the request with the desired HTTP method. - * - * @return array[status, header, body] - */ - public function call() - { - $env = $this->app->environment(); - if (isset($env['HTTP_X_HTTP_METHOD_OVERRIDE'])) { - // Header commonly used by Backbone.js and others - $env['slim.method_override.original_method'] = $env['REQUEST_METHOD']; - $env['REQUEST_METHOD'] = strtoupper($env['HTTP_X_HTTP_METHOD_OVERRIDE']); - } elseif (isset($env['REQUEST_METHOD']) && $env['REQUEST_METHOD'] === 'POST') { - // HTML Form Override - $req = new \Slim\Http\Request($env); - $method = $req->post($this->settings['key']); - if ($method) { - $env['slim.method_override.original_method'] = $env['REQUEST_METHOD']; - $env['REQUEST_METHOD'] = strtoupper($method); - } - } - $this->next->call(); - } -} diff --git a/vendor/slim/slim/Slim/Middleware/PrettyExceptions.php b/vendor/slim/slim/Slim/Middleware/PrettyExceptions.php deleted file mode 100644 index aafda0f..0000000 --- a/vendor/slim/slim/Slim/Middleware/PrettyExceptions.php +++ /dev/null @@ -1,116 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -namespace Slim\Middleware; - -/** - * Pretty Exceptions - * - * This middleware catches any Exception thrown by the surrounded - * application and displays a developer-friendly diagnostic screen. - * - * @package Slim - * @author Josh Lockhart - * @since 1.0.0 - */ -class PrettyExceptions extends \Slim\Middleware -{ - /** - * @var array - */ - protected $settings; - - /** - * Constructor - * @param array $settings - */ - public function __construct($settings = array()) - { - $this->settings = $settings; - } - - /** - * Call - */ - public function call() - { - try { - $this->next->call(); - } catch (\Exception $e) { - $log = $this->app->getLog(); // Force Slim to append log to env if not already - $env = $this->app->environment(); - $env['slim.log'] = $log; - $env['slim.log']->error($e); - $this->app->contentType('text/html'); - $this->app->response()->status(500); - $this->app->response()->body($this->renderBody($env, $e)); - } - } - - /** - * Render response body - * @param array $env - * @param \Exception $exception - * @return string - */ - protected function renderBody(&$env, $exception) - { - $title = 'Slim Application Error'; - $code = $exception->getCode(); - $message = $exception->getMessage(); - $file = $exception->getFile(); - $line = $exception->getLine(); - $trace = str_replace(array('#', "\n"), array('
#', '
'), $exception->getTraceAsString()); - $html = sprintf('

%s

', $title); - $html .= '

The application could not run because of the following error:

'; - $html .= '

Details

'; - $html .= sprintf('
Type: %s
', get_class($exception)); - if ($code) { - $html .= sprintf('
Code: %s
', $code); - } - if ($message) { - $html .= sprintf('
Message: %s
', $message); - } - if ($file) { - $html .= sprintf('
File: %s
', $file); - } - if ($line) { - $html .= sprintf('
Line: %s
', $line); - } - if ($trace) { - $html .= '

Trace

'; - $html .= sprintf('
%s
', $trace); - } - - return sprintf("%s%s", $title, $html); - } -} diff --git a/vendor/slim/slim/Slim/Middleware/SessionCookie.php b/vendor/slim/slim/Slim/Middleware/SessionCookie.php deleted file mode 100644 index 939c977..0000000 --- a/vendor/slim/slim/Slim/Middleware/SessionCookie.php +++ /dev/null @@ -1,205 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -namespace Slim\Middleware; - -/** - * Session Cookie - * - * This class provides an HTTP cookie storage mechanism - * for session data. This class avoids using a PHP session - * and instead serializes/unserializes the $_SESSION global - * variable to/from an HTTP cookie. - * - * You should NEVER store sensitive data in a client-side cookie - * in any format, encrypted (with cookies.encrypt) or not. If you - * need to store sensitive user information in a session, you should - * rely on PHP's native session implementation, or use other middleware - * to store session data in a database or alternative server-side cache. - * - * Because this class stores serialized session data in an HTTP cookie, - * you are inherently limited to 4 Kb. If you attempt to store - * more than this amount, serialization will fail. - * - * @package Slim - * @author Josh Lockhart - * @since 1.6.0 - */ -class SessionCookie extends \Slim\Middleware -{ - /** - * @var array - */ - protected $settings; - - /** - * Constructor - * - * @param array $settings - */ - public function __construct($settings = array()) - { - $defaults = array( - 'expires' => '20 minutes', - 'path' => '/', - 'domain' => null, - 'secure' => false, - 'httponly' => false, - 'name' => 'slim_session', - ); - $this->settings = array_merge($defaults, $settings); - if (is_string($this->settings['expires'])) { - $this->settings['expires'] = strtotime($this->settings['expires']); - } - - /** - * Session - * - * We must start a native PHP session to initialize the $_SESSION superglobal. - * However, we won't be using the native session store for persistence, so we - * disable the session cookie and cache limiter. We also set the session - * handler to this class instance to avoid PHP's native session file locking. - */ - ini_set('session.use_cookies', 0); - session_cache_limiter(false); - session_set_save_handler( - array($this, 'open'), - array($this, 'close'), - array($this, 'read'), - array($this, 'write'), - array($this, 'destroy'), - array($this, 'gc') - ); - } - - /** - * Call - */ - public function call() - { - $this->loadSession(); - $this->next->call(); - $this->saveSession(); - } - - /** - * Load session - */ - protected function loadSession() - { - if (session_id() === '') { - session_start(); - } - $value = $this->app->getCookie($this->settings['name']); - if ($value) { - $value = json_decode($value, true); - $_SESSION = is_array($value) ? $value : array(); - } else { - $_SESSION = array(); - } - } - - /** - * Save session - */ - protected function saveSession() - { - $value = json_encode($_SESSION); - - if (strlen($value) > 4096) { - $this->app->getLog()->error('WARNING! Slim\Middleware\SessionCookie data size is larger than 4KB. Content save failed.'); - } else { - $this->app->setCookie( - $this->settings['name'], - $value, - $this->settings['expires'], - $this->settings['path'], - $this->settings['domain'], - $this->settings['secure'], - $this->settings['httponly'] - ); - } - // session_destroy(); - } - - /******************************************************************************** - * Session Handler - *******************************************************************************/ - - /** - * @codeCoverageIgnore - */ - public function open($savePath, $sessionName) - { - return true; - } - - /** - * @codeCoverageIgnore - */ - public function close() - { - return true; - } - - /** - * @codeCoverageIgnore - */ - public function read($id) - { - return ''; - } - - /** - * @codeCoverageIgnore - */ - public function write($id, $data) - { - return true; - } - - /** - * @codeCoverageIgnore - */ - public function destroy($id) - { - return true; - } - - /** - * @codeCoverageIgnore - */ - public function gc($maxlifetime) - { - return true; - } -} diff --git a/vendor/slim/slim/Slim/Route.php b/vendor/slim/slim/Slim/Route.php index 2127e62..6a44b3f 100644 --- a/vendor/slim/slim/Slim/Route.php +++ b/vendor/slim/slim/Slim/Route.php @@ -1,153 +1,128 @@ - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * @link https://github.com/slimphp/Slim + * @copyright Copyright (c) 2011-2017 Josh Lockhart + * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License) */ namespace Slim; +use Exception; +use Throwable; +use InvalidArgumentException; +use Psr\Http\Message\ServerRequestInterface; +use Psr\Http\Message\ResponseInterface; +use Slim\Exception\SlimException; +use Slim\Handlers\Strategies\RequestResponse; +use Slim\Interfaces\InvocationStrategyInterface; +use Slim\Interfaces\RouteInterface; + /** * Route - * @package Slim - * @author Josh Lockhart, Thomas Bley - * @since 1.0.0 */ -class Route +class Route extends Routable implements RouteInterface { - /** - * @var string The route pattern (e.g. "/books/:id") - */ - protected $pattern; + use MiddlewareAwareTrait; /** - * @var mixed The route callable - */ - protected $callable; - - /** - * @var array Conditions for this route's URL parameters + * HTTP methods supported by this route + * + * @var string[] */ - protected $conditions = array(); + protected $methods = []; /** - * @var array Default conditions applied to all route instances + * Route identifier + * + * @var string */ - protected static $defaultConditions = array(); + protected $identifier; /** - * @var string The name of this route (optional) + * Route name + * + * @var null|string */ protected $name; /** - * @var array Key-value array of URL parameters - */ - protected $params = array(); - - /** - * @var array value array of URL parameter names + * Parent route groups + * + * @var RouteGroup[] */ - protected $paramNames = array(); + protected $groups; - /** - * @var array key array of URL parameter names with + at the end - */ - protected $paramNamesPath = array(); + private $finalized = false; /** - * @var array HTTP methods supported by this Route + * Output buffering mode + * + * One of: false, 'prepend' or 'append' + * + * @var boolean|string */ - protected $methods = array(); + protected $outputBuffering = 'append'; /** - * @var array[Callable] Middleware to be run before only this route instance + * Route parameters + * + * @var array */ - protected $middleware = array(); + protected $arguments = []; /** - * @var bool Whether or not this route should be matched in a case-sensitive manner + * The callable payload + * + * @var callable */ - protected $caseSensitive; + protected $callable; /** - * Constructor - * @param string $pattern The URL pattern (e.g. "/books/:id") - * @param mixed $callable Anything that returns TRUE for is_callable() - * @param bool $caseSensitive Whether or not this route should be matched in a case-sensitive manner + * Create new route + * + * @param string|string[] $methods The route HTTP methods + * @param string $pattern The route pattern + * @param callable $callable The route callable + * @param RouteGroup[] $groups The parent route groups + * @param int $identifier The route identifier */ - public function __construct($pattern, $callable, $caseSensitive = true) + public function __construct($methods, $pattern, $callable, $groups = [], $identifier = 0) { - $this->setPattern($pattern); - $this->setCallable($callable); - $this->setConditions(self::getDefaultConditions()); - $this->caseSensitive = $caseSensitive; + $this->methods = is_string($methods) ? [$methods] : $methods; + $this->pattern = $pattern; + $this->callable = $callable; + $this->groups = $groups; + $this->identifier = 'route' . $identifier; } /** - * Set default route conditions for all instances - * @param array $defaultConditions + * Finalize the route in preparation for dispatching */ - public static function setDefaultConditions(array $defaultConditions) + public function finalize() { - self::$defaultConditions = $defaultConditions; - } + if ($this->finalized) { + return; + } - /** - * Get default route conditions for all instances - * @return array - */ - public static function getDefaultConditions() - { - return self::$defaultConditions; - } + $groupMiddleware = []; + foreach ($this->getGroups() as $group) { + $groupMiddleware = array_merge($group->getMiddleware(), $groupMiddleware); + } - /** - * Get route pattern - * @return string - */ - public function getPattern() - { - return $this->pattern; - } + $this->middleware = array_merge($this->middleware, $groupMiddleware); - /** - * Set route pattern - * @param string $pattern - */ - public function setPattern($pattern) - { - $this->pattern = $pattern; + foreach ($this->getMiddleware() as $middleware) { + $this->addMiddleware($middleware); + } + + $this->finalized = true; } /** * Get route callable - * @return mixed + * + * @return callable */ public function getCallable() { @@ -155,53 +130,39 @@ public function getCallable() } /** - * Set route callable - * @param mixed $callable - * @throws \InvalidArgumentException If argument is not callable + * This method enables you to override the Route's callable + * + * @param string|\Closure $callable */ public function setCallable($callable) { - $matches = array(); - if (is_string($callable) && preg_match('!^([^\:]+)\:([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)$!', $callable, $matches)) { - $class = $matches[1]; - $method = $matches[2]; - $callable = function() use ($class, $method) { - static $obj = null; - if ($obj === null) { - $obj = new $class; - } - return call_user_func_array(array($obj, $method), func_get_args()); - }; - } - - if (!is_callable($callable)) { - throw new \InvalidArgumentException('Route callable must be callable'); - } - $this->callable = $callable; } /** - * Get route conditions - * @return array + * Get route methods + * + * @return string[] */ - public function getConditions() + public function getMethods() { - return $this->conditions; + return $this->methods; } /** - * Set route conditions - * @param array $conditions + * Get parent route groups + * + * @return RouteGroup[] */ - public function setConditions(array $conditions) + public function getGroups() { - $this->conditions = $conditions; + return $this->groups; } /** * Get route name - * @return string|null + * + * @return null|string */ public function getName() { @@ -209,263 +170,212 @@ public function getName() } /** - * Set route name - * @param string $name - */ - public function setName($name) - { - $this->name = (string)$name; - } - - /** - * Get route parameters - * @return array - */ - public function getParams() - { - return $this->params; - } - - /** - * Set route parameters - * @param array $params - */ - public function setParams($params) - { - $this->params = $params; - } - - /** - * Get route parameter value - * @param string $index Name of URL parameter + * Get route identifier + * * @return string - * @throws \InvalidArgumentException If route parameter does not exist at index */ - public function getParam($index) + public function getIdentifier() { - if (!isset($this->params[$index])) { - throw new \InvalidArgumentException('Route parameter does not exist at specified index'); - } - - return $this->params[$index]; - } - - /** - * Set route parameter value - * @param string $index Name of URL parameter - * @param mixed $value The new parameter value - * @throws \InvalidArgumentException If route parameter does not exist at index - */ - public function setParam($index, $value) - { - if (!isset($this->params[$index])) { - throw new \InvalidArgumentException('Route parameter does not exist at specified index'); - } - $this->params[$index] = $value; + return $this->identifier; } /** - * Add supported HTTP method(s) - */ - public function setHttpMethods() - { - $args = func_get_args(); - $this->methods = $args; - } - - /** - * Get supported HTTP methods - * @return array + * Get output buffering mode + * + * @return boolean|string */ - public function getHttpMethods() + public function getOutputBuffering() { - return $this->methods; + return $this->outputBuffering; } /** - * Append supported HTTP methods + * Set output buffering mode + * + * One of: false, 'prepend' or 'append' + * + * @param boolean|string $mode + * + * @throws InvalidArgumentException If an unknown buffering mode is specified */ - public function appendHttpMethods() + public function setOutputBuffering($mode) { - $args = func_get_args(); - if(count($args) && is_array($args[0])){ - $args = $args[0]; + if (!in_array($mode, [false, 'prepend', 'append'], true)) { + throw new InvalidArgumentException('Unknown output buffering mode'); } - $this->methods = array_merge($this->methods, $args); + $this->outputBuffering = $mode; } /** - * Append supported HTTP methods (alias for Route::appendHttpMethods) - * @return \Slim\Route + * Set route name + * + * @param string $name + * + * @return self + * + * @throws InvalidArgumentException if the route name is not a string */ - public function via() + public function setName($name) { - $args = func_get_args(); - if(count($args) && is_array($args[0])){ - $args = $args[0]; + if (!is_string($name)) { + throw new InvalidArgumentException('Route name must be a string'); } - $this->methods = array_merge($this->methods, $args); - + $this->name = $name; return $this; } /** - * Detect support for an HTTP method - * @param string $method - * @return bool + * Set a route argument + * + * @param string $name + * @param string $value + * + * @return self */ - public function supportsHttpMethod($method) + public function setArgument($name, $value) { - return in_array($method, $this->methods); + $this->arguments[$name] = $value; + return $this; } /** - * Get middleware - * @return array[Callable] + * Replace route arguments + * + * @param array $arguments + * + * @return self */ - public function getMiddleware() + public function setArguments(array $arguments) { - return $this->middleware; + $this->arguments = $arguments; + return $this; } /** - * Set middleware - * - * This method allows middleware to be assigned to a specific Route. - * If the method argument `is_callable` (including callable arrays!), - * we directly append the argument to `$this->middleware`. Else, we - * assume the argument is an array of callables and merge the array - * with `$this->middleware`. Each middleware is checked for is_callable() - * and an InvalidArgumentException is thrown immediately if it isn't. - * - * @param Callable|array[Callable] - * @return \Slim\Route - * @throws \InvalidArgumentException If argument is not callable or not an array of callables. + * Retrieve route arguments + * + * @return array */ - public function setMiddleware($middleware) + public function getArguments() { - if (is_callable($middleware)) { - $this->middleware[] = $middleware; - } elseif (is_array($middleware)) { - foreach ($middleware as $callable) { - if (!is_callable($callable)) { - throw new \InvalidArgumentException('All Route middleware must be callable'); - } - } - $this->middleware = array_merge($this->middleware, $middleware); - } else { - throw new \InvalidArgumentException('Route middleware must be callable or an array of callables'); - } - - return $this; + return $this->arguments; } /** - * Matches URI? + * Retrieve a specific route argument * - * Parse this route's pattern, and then compare it to an HTTP resource URI - * This method was modeled after the techniques demonstrated by Dan Sosedoff at: + * @param string $name + * @param string|null $default * - * http://blog.sosedoff.com/2009/09/20/rails-like-php-url-router/ - * - * @param string $resourceUri A Request URI - * @return bool + * @return mixed */ - public function matches($resourceUri) + public function getArgument($name, $default = null) { - //Convert URL params into regex patterns, construct a regex for this route, init params - $patternAsRegex = preg_replace_callback( - '#:([\w]+)\+?#', - array($this, 'matchesCallback'), - str_replace(')', ')?', (string)$this->pattern) - ); - if (substr($this->pattern, -1) === '/') { - $patternAsRegex .= '?'; - } - - $regex = '#^' . $patternAsRegex . '$#'; - - if ($this->caseSensitive === false) { - $regex .= 'i'; + if (array_key_exists($name, $this->arguments)) { + return $this->arguments[$name]; } - - //Cache URL params' names and values if this route matches the current HTTP request - if (!preg_match($regex, $resourceUri, $paramValues)) { - return false; - } - foreach ($this->paramNames as $name) { - if (isset($paramValues[$name])) { - if (isset($this->paramNamesPath[$name])) { - $this->params[$name] = explode('/', urldecode($paramValues[$name])); - } else { - $this->params[$name] = urldecode($paramValues[$name]); - } - } - } - - return true; + return $default; } - /** - * Convert a URL parameter (e.g. ":id", ":id+") into a regular expression - * @param array $m URL parameters - * @return string Regular expression for URL parameter - */ - protected function matchesCallback($m) - { - $this->paramNames[] = $m[1]; - if (isset($this->conditions[$m[1]])) { - return '(?P<' . $m[1] . '>' . $this->conditions[$m[1]] . ')'; - } - if (substr($m[0], -1) === '+') { - $this->paramNamesPath[$m[1]] = 1; - - return '(?P<' . $m[1] . '>.+)'; - } - - return '(?P<' . $m[1] . '>[^/]+)'; - } + /******************************************************************************** + * Route Runner + *******************************************************************************/ /** - * Set route name - * @param string $name The name of the route - * @return \Slim\Route + * Prepare the route for use + * + * @param ServerRequestInterface $request + * @param array $arguments */ - public function name($name) + public function prepare(ServerRequestInterface $request, array $arguments) { - $this->setName($name); - - return $this; + // Add the arguments + foreach ($arguments as $k => $v) { + $this->setArgument($k, $v); + } } /** - * Merge route conditions - * @param array $conditions Key-value array of URL parameter conditions - * @return \Slim\Route + * Run route + * + * This method traverses the middleware stack, including the route's callable + * and captures the resultant HTTP response object. It then sends the response + * back to the Application. + * + * @param ServerRequestInterface $request + * @param ResponseInterface $response + * + * @return ResponseInterface */ - public function conditions(array $conditions) + public function run(ServerRequestInterface $request, ResponseInterface $response) { - $this->conditions = array_merge($this->conditions, $conditions); + // Finalise route now that we are about to run it + $this->finalize(); - return $this; + // Traverse middleware stack and fetch updated response + return $this->callMiddlewareStack($request, $response); } /** - * Dispatch route + * Dispatch route callable against current Request and Response objects * * This method invokes the route object's callable. If middleware is * registered for the route, each callable middleware is invoked in * the order specified. * - * @return bool + * @param ServerRequestInterface $request The current Request object + * @param ResponseInterface $response The current Response object + * @return \Psr\Http\Message\ResponseInterface + * @throws \Exception if the route callable throws an exception */ - public function dispatch() + public function __invoke(ServerRequestInterface $request, ResponseInterface $response) { - foreach ($this->middleware as $mw) { - call_user_func_array($mw, array($this)); + $this->callable = $this->resolveCallable($this->callable); + + /** @var InvocationStrategyInterface $handler */ + $handler = isset($this->container) ? $this->container->get('foundHandler') : new RequestResponse(); + + // invoke route callable + if ($this->outputBuffering === false) { + $newResponse = $handler($this->callable, $request, $response, $this->arguments); + } else { + try { + ob_start(); + $newResponse = $handler($this->callable, $request, $response, $this->arguments); + $output = ob_get_clean(); + // @codeCoverageIgnoreStart + } catch (Throwable $e) { + ob_end_clean(); + throw $e; + // @codeCoverageIgnoreEnd + } catch (Exception $e) { + ob_end_clean(); + throw $e; + } + } + + if ($newResponse instanceof ResponseInterface) { + // if route callback returns a ResponseInterface, then use it + $response = $newResponse; + } elseif (is_string($newResponse)) { + // if route callback returns a string, then append it to the response + if ($response->getBody()->isWritable()) { + $response->getBody()->write($newResponse); + } + } + + if (!empty($output) && $response->getBody()->isWritable()) { + if ($this->outputBuffering === 'prepend') { + // prepend output buffer content + $body = new Http\Body(fopen('php://temp', 'r+')); + $body->write($output . $response->getBody()); + $response = $response->withBody($body); + } elseif ($this->outputBuffering === 'append') { + // append output buffer content + $response->getBody()->write($output); + } } - $return = call_user_func_array($this->getCallable(), array_values($this->getParams())); - return ($return === false) ? false : true; + return $response; } } diff --git a/vendor/slim/slim/Slim/Router.php b/vendor/slim/slim/Slim/Router.php index 87e06ed..8311628 100644 --- a/vendor/slim/slim/Slim/Router.php +++ b/vendor/slim/slim/Slim/Router.php @@ -1,257 +1,455 @@ - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * @link https://github.com/slimphp/Slim + * @copyright Copyright (c) 2011-2017 Josh Lockhart + * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License) */ namespace Slim; +use FastRoute\Dispatcher; +use Psr\Container\ContainerInterface; +use InvalidArgumentException; +use RuntimeException; +use Psr\Http\Message\ServerRequestInterface; +use FastRoute\RouteCollector; +use FastRoute\RouteParser; +use FastRoute\RouteParser\Std as StdParser; +use Slim\Interfaces\RouteGroupInterface; +use Slim\Interfaces\RouterInterface; +use Slim\Interfaces\RouteInterface; + /** * Router * - * This class organizes, iterates, and dispatches \Slim\Route objects. - * - * @package Slim - * @author Josh Lockhart - * @since 1.0.0 + * This class organizes Slim application route objects. It is responsible + * for registering route objects, assigning names to route objects, + * finding routes that match the current HTTP request, and creating + * URLs for a named route. */ -class Router +class Router implements RouterInterface { /** - * @var Route The current route (most recently dispatched) + * Container Interface + * + * @var ContainerInterface */ - protected $currentRoute; + protected $container; /** - * @var array Lookup hash of all route objects + * Parser + * + * @var \FastRoute\RouteParser */ - protected $routes; + protected $routeParser; /** - * @var array Lookup hash of named route objects, keyed by route name (lazy-loaded) + * Base path used in pathFor() + * + * @var string */ - protected $namedRoutes; + protected $basePath = ''; /** - * @var array Array of route objects that match the request URI (lazy-loaded) + * Path to fast route cache file. Set to false to disable route caching + * + * @var string|False */ - protected $matchedRoutes; + protected $cacheFile = false; /** - * @var array Array containing all route groups + * Routes + * + * @var Route[] */ - protected $routeGroups; + protected $routes = []; /** - * Constructor + * Route counter incrementer + * @var int */ - public function __construct() + protected $routeCounter = 0; + + /** + * Route groups + * + * @var RouteGroup[] + */ + protected $routeGroups = []; + + /** + * @var \FastRoute\Dispatcher + */ + protected $dispatcher; + + /** + * Create new router + * + * @param RouteParser $parser + */ + public function __construct(RouteParser $parser = null) { - $this->routes = array(); - $this->routeGroups = array(); + $this->routeParser = $parser ?: new StdParser; } /** - * Get Current Route object or the first matched one if matching has been performed - * @return \Slim\Route|null + * Set the base path used in pathFor() + * + * @param string $basePath + * + * @return self */ - public function getCurrentRoute() + public function setBasePath($basePath) { - if ($this->currentRoute !== null) { - return $this->currentRoute; + if (!is_string($basePath)) { + throw new InvalidArgumentException('Router basePath must be a string'); } - if (is_array($this->matchedRoutes) && count($this->matchedRoutes) > 0) { - return $this->matchedRoutes[0]; - } + $this->basePath = $basePath; - return null; + return $this; } /** - * Return route objects that match the given HTTP method and URI - * @param string $httpMethod The HTTP method to match against - * @param string $resourceUri The resource URI to match against - * @param bool $reload Should matching routes be re-parsed? - * @return array[\Slim\Route] + * Set path to fast route cache file. If this is false then route caching is disabled. + * + * @param string|false $cacheFile + * + * @return self */ - public function getMatchedRoutes($httpMethod, $resourceUri, $reload = false) + public function setCacheFile($cacheFile) { - if ($reload || is_null($this->matchedRoutes)) { - $this->matchedRoutes = array(); - foreach ($this->routes as $route) { - if (!$route->supportsHttpMethod($httpMethod) && !$route->supportsHttpMethod("ANY")) { - continue; - } + if (!is_string($cacheFile) && $cacheFile !== false) { + throw new InvalidArgumentException('Router cacheFile must be a string or false'); + } - if ($route->matches($resourceUri)) { - $this->matchedRoutes[] = $route; - } - } + $this->cacheFile = $cacheFile; + + if ($cacheFile !== false && !is_writable(dirname($cacheFile))) { + throw new RuntimeException('Router cacheFile directory must be writable'); } - return $this->matchedRoutes; + + return $this; } /** - * Add a route object to the router - * @param \Slim\Route $route The Slim Route + * @param ContainerInterface $container */ - public function map(\Slim\Route $route) + public function setContainer(ContainerInterface $container) { - list($groupPattern, $groupMiddleware) = $this->processGroups(); + $this->container = $container; + } - $route->setPattern($groupPattern . $route->getPattern()); - $this->routes[] = $route; + /** + * Add route + * + * @param string[] $methods Array of HTTP methods + * @param string $pattern The route pattern + * @param callable $handler The route callable + * + * @return RouteInterface + * + * @throws InvalidArgumentException if the route pattern isn't a string + */ + public function map($methods, $pattern, $handler) + { + if (!is_string($pattern)) { + throw new InvalidArgumentException('Route pattern must be a string'); + } + + // Prepend parent group pattern(s) + if ($this->routeGroups) { + $pattern = $this->processGroups() . $pattern; + } + + // According to RFC methods are defined in uppercase (See RFC 7231) + $methods = array_map("strtoupper", $methods); + + // Add route + $route = $this->createRoute($methods, $pattern, $handler); + $this->routes[$route->getIdentifier()] = $route; + $this->routeCounter++; + + return $route; + } + + /** + * Dispatch router for HTTP request + * + * @param ServerRequestInterface $request The current HTTP request object + * + * @return array + * + * @link https://github.com/nikic/FastRoute/blob/master/src/Dispatcher.php + */ + public function dispatch(ServerRequestInterface $request) + { + $uri = '/' . ltrim($request->getUri()->getPath(), '/'); + return $this->createDispatcher()->dispatch( + $request->getMethod(), + $uri + ); + } - foreach ($groupMiddleware as $middleware) { - $route->setMiddleware($middleware); + /** + * Create a new Route object + * + * @param string[] $methods Array of HTTP methods + * @param string $pattern The route pattern + * @param callable $callable The route callable + * + * @return \Slim\Interfaces\RouteInterface + */ + protected function createRoute($methods, $pattern, $callable) + { + $route = new Route($methods, $pattern, $callable, $this->routeGroups, $this->routeCounter); + if (!empty($this->container)) { + $route->setContainer($this->container); } + + return $route; } /** - * A helper function for processing the group's pattern and middleware - * @return array Returns an array with the elements: pattern, middlewareArr + * @return \FastRoute\Dispatcher */ - protected function processGroups() + protected function createDispatcher() { - $pattern = ""; - $middleware = array(); - foreach ($this->routeGroups as $group) { - $k = key($group); - $pattern .= $k; - if (is_array($group[$k])) { - $middleware = array_merge($middleware, $group[$k]); + if ($this->dispatcher) { + return $this->dispatcher; + } + + $routeDefinitionCallback = function (RouteCollector $r) { + foreach ($this->getRoutes() as $route) { + $r->addRoute($route->getMethods(), $route->getPattern(), $route->getIdentifier()); } + }; + + if ($this->cacheFile) { + $this->dispatcher = \FastRoute\cachedDispatcher($routeDefinitionCallback, [ + 'routeParser' => $this->routeParser, + 'cacheFile' => $this->cacheFile, + ]); + } else { + $this->dispatcher = \FastRoute\simpleDispatcher($routeDefinitionCallback, [ + 'routeParser' => $this->routeParser, + ]); } - return array($pattern, $middleware); + + return $this->dispatcher; } /** - * Add a route group to the array - * @param string $group The group pattern (ie. "/books/:id") - * @param array|null $middleware Optional parameter array of middleware - * @return int The index of the new group + * @param \FastRoute\Dispatcher $dispatcher */ - public function pushGroup($group, $middleware = array()) + public function setDispatcher(Dispatcher $dispatcher) { - return array_push($this->routeGroups, array($group => $middleware)); + $this->dispatcher = $dispatcher; } /** - * Removes the last route group from the array - * @return bool True if successful, else False + * Get route objects + * + * @return Route[] */ - public function popGroup() + public function getRoutes() { - return (array_pop($this->routeGroups) !== null); + return $this->routes; } /** - * Get URL for named route - * @param string $name The name of the route - * @param array $params Associative array of URL parameter names and replacement values - * @throws \RuntimeException If named route not found - * @return string The URL for the given route populated with provided replacement values + * Get named route object + * + * @param string $name Route name + * + * @return Route + * + * @throws RuntimeException If named route does not exist */ - public function urlFor($name, $params = array()) + public function getNamedRoute($name) { - if (!$this->hasNamedRoute($name)) { - throw new \RuntimeException('Named route not found for name: ' . $name); - } - $search = array(); - foreach ($params as $key => $value) { - $search[] = '#:' . preg_quote($key, '#') . '\+?(?!\w)#'; + foreach ($this->routes as $route) { + if ($name == $route->getName()) { + return $route; + } } - $pattern = preg_replace($search, $params, $this->getNamedRoute($name)->getPattern()); + throw new RuntimeException('Named route does not exist for name: ' . $name); + } + + /** + * Remove named route + * + * @param string $name Route name + * + * @throws RuntimeException If named route does not exist + */ + public function removeNamedRoute($name) + { + $route = $this->getNamedRoute($name); - //Remove remnants of unpopulated, trailing optional pattern segments, escaped special characters - return preg_replace('#\(/?:.+\)|\(|\)|\\\\#', '', $pattern); + // no exception, route exists, now remove by id + unset($this->routes[$route->getIdentifier()]); } /** - * Add named route - * @param string $name The route name - * @param \Slim\Route $route The route object - * @throws \RuntimeException If a named route already exists with the same name + * Process route groups + * + * @return string A group pattern to prefix routes with */ - public function addNamedRoute($name, \Slim\Route $route) + protected function processGroups() { - if ($this->hasNamedRoute($name)) { - throw new \RuntimeException('Named route already exists with name: ' . $name); + $pattern = ""; + foreach ($this->routeGroups as $group) { + $pattern .= $group->getPattern(); } - $this->namedRoutes[(string) $name] = $route; + return $pattern; } /** - * Has named route - * @param string $name The route name - * @return bool + * Add a route group to the array + * + * @param string $pattern + * @param callable $callable + * + * @return RouteGroupInterface */ - public function hasNamedRoute($name) + public function pushGroup($pattern, $callable) { - $this->getNamedRoutes(); + $group = new RouteGroup($pattern, $callable); + array_push($this->routeGroups, $group); + return $group; + } - return isset($this->namedRoutes[(string) $name]); + /** + * Removes the last route group from the array + * + * @return RouteGroup|bool The RouteGroup if successful, else False + */ + public function popGroup() + { + $group = array_pop($this->routeGroups); + return $group instanceof RouteGroup ? $group : false; } /** - * Get named route - * @param string $name - * @return \Slim\Route|null + * @param $identifier + * @return \Slim\Interfaces\RouteInterface */ - public function getNamedRoute($name) + public function lookupRoute($identifier) { - $this->getNamedRoutes(); - if ($this->hasNamedRoute($name)) { - return $this->namedRoutes[(string) $name]; + if (!isset($this->routes[$identifier])) { + throw new RuntimeException('Route not found, looks like your route cache is stale.'); } - - return null; + return $this->routes[$identifier]; } /** - * Get named routes - * @return \ArrayIterator + * Build the path for a named route excluding the base path + * + * @param string $name Route name + * @param array $data Named argument replacement data + * @param array $queryParams Optional query string parameters + * + * @return string + * + * @throws RuntimeException If named route does not exist + * @throws InvalidArgumentException If required data not provided */ - public function getNamedRoutes() + public function relativePathFor($name, array $data = [], array $queryParams = []) { - if (is_null($this->namedRoutes)) { - $this->namedRoutes = array(); - foreach ($this->routes as $route) { - if ($route->getName() !== null) { - $this->addNamedRoute($route->getName(), $route); + $route = $this->getNamedRoute($name); + $pattern = $route->getPattern(); + + $routeDatas = $this->routeParser->parse($pattern); + // $routeDatas is an array of all possible routes that can be made. There is + // one routedata for each optional parameter plus one for no optional parameters. + // + // The most specific is last, so we look for that first. + $routeDatas = array_reverse($routeDatas); + + $segments = []; + foreach ($routeDatas as $routeData) { + foreach ($routeData as $item) { + if (is_string($item)) { + // this segment is a static string + $segments[] = $item; + continue; } + + // This segment has a parameter: first element is the name + if (!array_key_exists($item[0], $data)) { + // we don't have a data element for this segment: cancel + // testing this routeData item, so that we can try a less + // specific routeData item. + $segments = []; + $segmentName = $item[0]; + break; + } + $segments[] = $data[$item[0]]; + } + if (!empty($segments)) { + // we found all the parameters for this route data, no need to check + // less specific ones + break; } } - return new \ArrayIterator($this->namedRoutes); + if (empty($segments)) { + throw new InvalidArgumentException('Missing data for URL segment: ' . $segmentName); + } + $url = implode('', $segments); + + if ($queryParams) { + $url .= '?' . http_build_query($queryParams); + } + + return $url; + } + + + /** + * Build the path for a named route including the base path + * + * @param string $name Route name + * @param array $data Named argument replacement data + * @param array $queryParams Optional query string parameters + * + * @return string + * + * @throws RuntimeException If named route does not exist + * @throws InvalidArgumentException If required data not provided + */ + public function pathFor($name, array $data = [], array $queryParams = []) + { + $url = $this->relativePathFor($name, $data, $queryParams); + + if ($this->basePath) { + $url = $this->basePath . $url; + } + + return $url; + } + + /** + * Build the path for a named route. + * + * This method is deprecated. Use pathFor() from now on. + * + * @param string $name Route name + * @param array $data Named argument replacement data + * @param array $queryParams Optional query string parameters + * + * @return string + * + * @throws RuntimeException If named route does not exist + * @throws InvalidArgumentException If required data not provided + */ + public function urlFor($name, array $data = [], array $queryParams = []) + { + trigger_error('urlFor() is deprecated. Use pathFor() instead.', E_USER_DEPRECATED); + return $this->pathFor($name, $data, $queryParams); } } diff --git a/vendor/slim/slim/Slim/Slim.php b/vendor/slim/slim/Slim/Slim.php deleted file mode 100644 index 4a83595..0000000 --- a/vendor/slim/slim/Slim/Slim.php +++ /dev/null @@ -1,1444 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -namespace Slim; - -// Ensure mcrypt constants are defined even if mcrypt extension is not loaded -if (!extension_loaded('mcrypt')) { - define('MCRYPT_MODE_CBC', 0); - define('MCRYPT_RIJNDAEL_256', 0); -} - -/** - * Slim - * @package Slim - * @author Josh Lockhart - * @since 1.0.0 - * - * @property \Slim\Environment $environment - * @property \Slim\Http\Response $response - * @property \Slim\Http\Request $request - * @property \Slim\Router $router - */ -class Slim -{ - /** - * @const string - */ - const VERSION = '2.6.1'; - - /** - * @var \Slim\Helper\Set - */ - public $container; - - /** - * @var array[\Slim] - */ - protected static $apps = array(); - - /** - * @var string - */ - protected $name; - - /** - * @var array - */ - protected $middleware; - - /** - * @var mixed Callable to be invoked if application error - */ - protected $error; - - /** - * @var mixed Callable to be invoked if no matching routes are found - */ - protected $notFound; - - /** - * @var array - */ - protected $hooks = array( - 'slim.before' => array(array()), - 'slim.before.router' => array(array()), - 'slim.before.dispatch' => array(array()), - 'slim.after.dispatch' => array(array()), - 'slim.after.router' => array(array()), - 'slim.after' => array(array()) - ); - - /******************************************************************************** - * PSR-0 Autoloader - * - * Do not use if you are using Composer to autoload dependencies. - *******************************************************************************/ - - /** - * Slim PSR-0 autoloader - */ - public static function autoload($className) - { - $thisClass = str_replace(__NAMESPACE__.'\\', '', __CLASS__); - - $baseDir = __DIR__; - - if (substr($baseDir, -strlen($thisClass)) === $thisClass) { - $baseDir = substr($baseDir, 0, -strlen($thisClass)); - } - - $className = ltrim($className, '\\'); - $fileName = $baseDir; - $namespace = ''; - if ($lastNsPos = strripos($className, '\\')) { - $namespace = substr($className, 0, $lastNsPos); - $className = substr($className, $lastNsPos + 1); - $fileName .= str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; - } - $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; - - if (file_exists($fileName)) { - require $fileName; - } - } - - /** - * Register Slim's PSR-0 autoloader - */ - public static function registerAutoloader() - { - spl_autoload_register(__NAMESPACE__ . "\\Slim::autoload"); - } - - /******************************************************************************** - * Instantiation and Configuration - *******************************************************************************/ - - /** - * 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']); - $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'); - } - } - - public function __get($name) - { - return $this->container->get($name); - } - - public function __set($name, $value) - { - $this->container->set($name, $value); - } - - public function __isset($name) - { - return $this->container->has($name); - } - - public function __unset($name) - { - $this->container->remove($name); - } - - /** - * Get application instance by name - * @param string $name The name of the Slim application - * @return \Slim\Slim|null - */ - public static function getInstance($name = 'default') - { - return isset(static::$apps[$name]) ? static::$apps[$name] : null; - } - - /** - * Set Slim application name - * @param string $name The name of this Slim application - */ - public function setName($name) - { - $this->name = $name; - static::$apps[$name] = $this; - } - - /** - * Get Slim application name - * @return string|null - */ - public function getName() - { - return $this->name; - } - - /** - * Get default application settings - * @return array - */ - public static function getDefaultSettings() - { - return array( - // Application - 'mode' => 'development', - // Debugging - 'debug' => true, - // Logging - 'log.writer' => null, - 'log.level' => \Slim\Log::DEBUG, - 'log.enabled' => true, - // View - 'templates.path' => './templates', - 'view' => '\Slim\View', - // Cookies - 'cookies.encrypt' => false, - 'cookies.lifetime' => '20 minutes', - 'cookies.path' => '/', - 'cookies.domain' => null, - 'cookies.secure' => false, - 'cookies.httponly' => false, - // Encryption - 'cookies.secret_key' => 'CHANGE_ME', - 'cookies.cipher' => MCRYPT_RIJNDAEL_256, - 'cookies.cipher_mode' => MCRYPT_MODE_CBC, - // HTTP - 'http.version' => '1.1', - // Routing - 'routes.case_sensitive' => true - ); - } - - /** - * Configure Slim Settings - * - * This method defines application settings and acts as a setter and a getter. - * - * If only one argument is specified and that argument is a string, the value - * of the setting identified by the first argument will be returned, or NULL if - * that setting does not exist. - * - * If only one argument is specified and that argument is an associative array, - * the array will be merged into the existing application settings. - * - * If two arguments are provided, the first argument is the name of the setting - * to be created or updated, and the second argument is the setting value. - * - * @param string|array $name If a string, the name of the setting to set or retrieve. Else an associated array of setting names and values - * @param mixed $value If name is a string, the value of the setting identified by $name - * @return mixed The value of a setting if only one argument is a string - */ - public function config($name, $value = null) - { - $c = $this->container; - - if (is_array($name)) { - if (true === $value) { - $c['settings'] = array_merge_recursive($c['settings'], $name); - } else { - $c['settings'] = array_merge($c['settings'], $name); - } - } elseif (func_num_args() === 1) { - return isset($c['settings'][$name]) ? $c['settings'][$name] : null; - } else { - $settings = $c['settings']; - $settings[$name] = $value; - $c['settings'] = $settings; - } - } - - /******************************************************************************** - * Application Modes - *******************************************************************************/ - - /** - * Get application mode - * - * This method determines the application mode. It first inspects the $_ENV - * superglobal for key `SLIM_MODE`. If that is not found, it queries - * the `getenv` function. Else, it uses the application `mode` setting. - * - * @return string - */ - public function getMode() - { - return $this->mode; - } - - /** - * Configure Slim for a given mode - * - * This method will immediately invoke the callable if - * the specified mode matches the current application mode. - * Otherwise, the callable is ignored. This should be called - * only _after_ you initialize your Slim app. - * - * @param string $mode - * @param mixed $callable - * @return void - */ - public function configureMode($mode, $callable) - { - if ($mode === $this->getMode() && is_callable($callable)) { - call_user_func($callable); - } - } - - /******************************************************************************** - * Logging - *******************************************************************************/ - - /** - * Get application log - * @return \Slim\Log - */ - public function getLog() - { - return $this->log; - } - - /******************************************************************************** - * Routing - *******************************************************************************/ - - /** - * Add GET|POST|PUT|PATCH|DELETE route - * - * Adds a new route to the router with associated callable. This - * route will only be invoked when the HTTP request's method matches - * this route's method. - * - * ARGUMENTS: - * - * First: string The URL pattern (REQUIRED) - * In-Between: mixed Anything that returns TRUE for `is_callable` (OPTIONAL) - * Last: mixed Anything that returns TRUE for `is_callable` (REQUIRED) - * - * The first argument is required and must always be the - * route pattern (ie. '/books/:id'). - * - * The last argument is required and must always be the callable object - * to be invoked when the route matches an HTTP request. - * - * You may also provide an unlimited number of in-between arguments; - * each interior argument must be callable and will be invoked in the - * order specified before the route's callable is invoked. - * - * USAGE: - * - * Slim::get('/foo'[, middleware, middleware, ...], callable); - * - * @param array (See notes above) - * @return \Slim\Route - */ - protected function mapRoute($args) - { - $pattern = array_shift($args); - $callable = array_pop($args); - $route = new \Slim\Route($pattern, $callable, $this->settings['routes.case_sensitive']); - $this->router->map($route); - if (count($args) > 0) { - $route->setMiddleware($args); - } - - return $route; - } - - /** - * Add generic route without associated HTTP method - * @see mapRoute() - * @return \Slim\Route - */ - public function map() - { - $args = func_get_args(); - - return $this->mapRoute($args); - } - - /** - * Add GET route - * @see mapRoute() - * @return \Slim\Route - */ - public function get() - { - $args = func_get_args(); - - return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_GET, \Slim\Http\Request::METHOD_HEAD); - } - - /** - * Add POST route - * @see mapRoute() - * @return \Slim\Route - */ - public function post() - { - $args = func_get_args(); - - return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_POST); - } - - /** - * Add PUT route - * @see mapRoute() - * @return \Slim\Route - */ - public function put() - { - $args = func_get_args(); - - return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_PUT); - } - - /** - * Add PATCH route - * @see mapRoute() - * @return \Slim\Route - */ - public function patch() - { - $args = func_get_args(); - - return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_PATCH); - } - - /** - * Add DELETE route - * @see mapRoute() - * @return \Slim\Route - */ - public function delete() - { - $args = func_get_args(); - - return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_DELETE); - } - - /** - * Add OPTIONS route - * @see mapRoute() - * @return \Slim\Route - */ - public function options() - { - $args = func_get_args(); - - return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_OPTIONS); - } - - /** - * Route Groups - * - * This method accepts a route pattern and a callback all Route - * declarations in the callback will be prepended by the group(s) - * that it is in - * - * Accepts the same parameters as a standard route so: - * (pattern, middleware1, middleware2, ..., $callback) - */ - public function group() - { - $args = func_get_args(); - $pattern = array_shift($args); - $callable = array_pop($args); - $this->router->pushGroup($pattern, $args); - if (is_callable($callable)) { - call_user_func($callable); - } - $this->router->popGroup(); - } - - /* - * Add route for any HTTP method - * @see mapRoute() - * @return \Slim\Route - */ - public function any() - { - $args = func_get_args(); - - return $this->mapRoute($args)->via("ANY"); - } - - /** - * Not Found Handler - * - * This method defines or invokes the application-wide Not Found handler. - * There are two contexts in which this method may be invoked: - * - * 1. When declaring the handler: - * - * If the $callable parameter is not null and is callable, this - * method will register the callable to be invoked when no - * routes match the current HTTP request. It WILL NOT invoke the callable. - * - * 2. When invoking the handler: - * - * If the $callable parameter is null, Slim assumes you want - * to invoke an already-registered handler. If the handler has been - * registered and is callable, it is invoked and sends a 404 HTTP Response - * whose body is the output of the Not Found handler. - * - * @param mixed $callable Anything that returns true for is_callable() - */ - public function notFound ($callable = null) - { - if (is_callable($callable)) { - $this->notFound = $callable; - } else { - ob_start(); - if (is_callable($this->notFound)) { - call_user_func($this->notFound); - } else { - call_user_func(array($this, 'defaultNotFound')); - } - $this->halt(404, ob_get_clean()); - } - } - - /** - * Error Handler - * - * This method defines or invokes the application-wide Error handler. - * There are two contexts in which this method may be invoked: - * - * 1. When declaring the handler: - * - * If the $argument parameter is callable, this - * method will register the callable to be invoked when an uncaught - * Exception is detected, or when otherwise explicitly invoked. - * The handler WILL NOT be invoked in this context. - * - * 2. When invoking the handler: - * - * If the $argument parameter is not callable, Slim assumes you want - * to invoke an already-registered handler. If the handler has been - * registered and is callable, it is invoked and passed the caught Exception - * as its one and only argument. The error handler's output is captured - * into an output buffer and sent as the body of a 500 HTTP Response. - * - * @param mixed $argument Callable|\Exception - */ - public function error($argument = null) - { - if (is_callable($argument)) { - //Register error handler - $this->error = $argument; - } else { - //Invoke error handler - $this->response->status(500); - $this->response->body(''); - $this->response->write($this->callErrorHandler($argument)); - $this->stop(); - } - } - - /** - * Call error handler - * - * This will invoke the custom or default error handler - * and RETURN its output. - * - * @param \Exception|null $argument - * @return string - */ - protected function callErrorHandler($argument = null) - { - ob_start(); - if (is_callable($this->error)) { - call_user_func_array($this->error, array($argument)); - } else { - call_user_func_array(array($this, 'defaultError'), array($argument)); - } - - return ob_get_clean(); - } - - /******************************************************************************** - * Application Accessors - *******************************************************************************/ - - /** - * Get a reference to the Environment object - * @return \Slim\Environment - */ - public function environment() - { - return $this->environment; - } - - /** - * Get the Request object - * @return \Slim\Http\Request - */ - public function request() - { - return $this->request; - } - - /** - * Get the Response object - * @return \Slim\Http\Response - */ - public function response() - { - return $this->response; - } - - /** - * Get the Router object - * @return \Slim\Router - */ - public function router() - { - return $this->router; - } - - /** - * Get and/or set the View - * - * This method declares the View to be used by the Slim application. - * If the argument is a string, Slim will instantiate a new object - * of the same class. If the argument is an instance of View or a subclass - * of View, Slim will use the argument as the View. - * - * If a View already exists and this method is called to create a - * new View, data already set in the existing View will be - * transferred to the new View. - * - * @param string|\Slim\View $viewClass The name or instance of a \Slim\View subclass - * @return \Slim\View - */ - public function view($viewClass = null) - { - if (!is_null($viewClass)) { - $existingData = is_null($this->view) ? array() : $this->view->getData(); - if ($viewClass instanceOf \Slim\View) { - $this->view = $viewClass; - } else { - $this->view = new $viewClass(); - } - $this->view->appendData($existingData); - $this->view->setTemplatesDirectory($this->config('templates.path')); - } - - return $this->view; - } - - /******************************************************************************** - * Rendering - *******************************************************************************/ - - /** - * Render a template - * - * Call this method within a GET, POST, PUT, PATCH, DELETE, NOT FOUND, or ERROR - * callable to render a template whose output is appended to the - * current HTTP response body. How the template is rendered is - * delegated to the current View. - * - * @param string $template The name of the template passed into the view's render() method - * @param array $data Associative array of data made available to the view - * @param int $status The HTTP response status code to use (optional) - */ - public function render($template, $data = array(), $status = null) - { - if (!is_null($status)) { - $this->response->status($status); - } - $this->view->appendData($data); - $this->view->display($template); - } - - /******************************************************************************** - * HTTP Caching - *******************************************************************************/ - - /** - * Set Last-Modified HTTP Response Header - * - * Set the HTTP 'Last-Modified' header and stop if a conditional - * GET request's `If-Modified-Since` header matches the last modified time - * of the resource. The `time` argument is a UNIX timestamp integer value. - * When the current request includes an 'If-Modified-Since' header that - * matches the specified last modified time, the application will stop - * and send a '304 Not Modified' response to the client. - * - * @param int $time The last modified UNIX timestamp - * @throws \InvalidArgumentException If provided timestamp is not an integer - */ - public function lastModified($time) - { - if (is_integer($time)) { - $this->response->headers->set('Last-Modified', gmdate('D, d M Y H:i:s T', $time)); - if ($time === strtotime($this->request->headers->get('IF_MODIFIED_SINCE'))) { - $this->halt(304); - } - } else { - throw new \InvalidArgumentException('Slim::lastModified only accepts an integer UNIX timestamp value.'); - } - } - - /** - * Set ETag HTTP Response Header - * - * Set the etag header and stop if the conditional GET request matches. - * The `value` argument is a unique identifier for the current resource. - * The `type` argument indicates whether the etag should be used as a strong or - * weak cache validator. - * - * When the current request includes an 'If-None-Match' header with - * a matching etag, execution is immediately stopped. If the request - * method is GET or HEAD, a '304 Not Modified' response is sent. - * - * @param string $value The etag value - * @param string $type The type of etag to create; either "strong" or "weak" - * @throws \InvalidArgumentException If provided type is invalid - */ - public function etag($value, $type = 'strong') - { - //Ensure type is correct - if (!in_array($type, array('strong', 'weak'))) { - throw new \InvalidArgumentException('Invalid Slim::etag type. Expected "strong" or "weak".'); - } - - //Set etag value - $value = '"' . $value . '"'; - if ($type === 'weak') { - $value = 'W/'.$value; - } - $this->response['ETag'] = $value; - - //Check conditional GET - if ($etagsHeader = $this->request->headers->get('IF_NONE_MATCH')) { - $etags = preg_split('@\s*,\s*@', $etagsHeader); - if (in_array($value, $etags) || in_array('*', $etags)) { - $this->halt(304); - } - } - } - - /** - * Set Expires HTTP response header - * - * The `Expires` header tells the HTTP client the time at which - * the current resource should be considered stale. At that time the HTTP - * client will send a conditional GET request to the server; the server - * may return a 200 OK if the resource has changed, else a 304 Not Modified - * if the resource has not changed. The `Expires` header should be used in - * conjunction with the `etag()` or `lastModified()` methods above. - * - * @param string|int $time If string, a time to be parsed by `strtotime()`; - * If int, a UNIX timestamp; - */ - public function expires($time) - { - if (is_string($time)) { - $time = strtotime($time); - } - $this->response->headers->set('Expires', gmdate('D, d M Y H:i:s T', $time)); - } - - /******************************************************************************** - * HTTP Cookies - *******************************************************************************/ - - /** - * Set HTTP cookie to be sent with the HTTP response - * - * @param string $name The cookie name - * @param string $value The cookie value - * @param int|string $time The duration of the cookie; - * If integer, should be UNIX timestamp; - * If string, converted to UNIX timestamp with `strtotime`; - * @param string $path The path on the server in which the cookie will be available on - * @param string $domain The domain that the cookie is available to - * @param bool $secure Indicates that the cookie should only be transmitted over a secure - * HTTPS connection to/from the client - * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol - */ - public function setCookie($name, $value, $time = null, $path = null, $domain = null, $secure = null, $httponly = null) - { - $settings = array( - 'value' => $value, - 'expires' => is_null($time) ? $this->config('cookies.lifetime') : $time, - 'path' => is_null($path) ? $this->config('cookies.path') : $path, - 'domain' => is_null($domain) ? $this->config('cookies.domain') : $domain, - 'secure' => is_null($secure) ? $this->config('cookies.secure') : $secure, - 'httponly' => is_null($httponly) ? $this->config('cookies.httponly') : $httponly - ); - $this->response->cookies->set($name, $settings); - } - - /** - * Get value of HTTP cookie from the current HTTP request - * - * Return the value of a cookie from the current HTTP request, - * or return NULL if cookie does not exist. Cookies created during - * the current request will not be available until the next request. - * - * @param string $name - * @param bool $deleteIfInvalid - * @return string|null - */ - public function getCookie($name, $deleteIfInvalid = true) - { - // Get cookie value - $value = $this->request->cookies->get($name); - - // Decode if encrypted - if ($this->config('cookies.encrypt')) { - $value = \Slim\Http\Util::decodeSecureCookie( - $value, - $this->config('cookies.secret_key'), - $this->config('cookies.cipher'), - $this->config('cookies.cipher_mode') - ); - if ($value === false && $deleteIfInvalid) { - $this->deleteCookie($name); - } - } - - /* - * transform $value to @return doc requirement. - * \Slim\Http\Util::decodeSecureCookie - is able - * to return false and we have to cast it to null. - */ - return $value === false ? null : $value; - } - - /** - * DEPRECATION WARNING! Use `setCookie` with the `cookies.encrypt` app setting set to `true`. - * - * Set encrypted HTTP cookie - * - * @param string $name The cookie name - * @param mixed $value The cookie value - * @param mixed $expires The duration of the cookie; - * If integer, should be UNIX timestamp; - * If string, converted to UNIX timestamp with `strtotime`; - * @param string $path The path on the server in which the cookie will be available on - * @param string $domain The domain that the cookie is available to - * @param bool $secure Indicates that the cookie should only be transmitted over a secure - * HTTPS connection from the client - * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol - */ - public function setEncryptedCookie($name, $value, $expires = null, $path = null, $domain = null, $secure = false, $httponly = false) - { - $this->setCookie($name, $value, $expires, $path, $domain, $secure, $httponly); - } - - /** - * DEPRECATION WARNING! Use `getCookie` with the `cookies.encrypt` app setting set to `true`. - * - * Get value of encrypted HTTP cookie - * - * Return the value of an encrypted cookie from the current HTTP request, - * or return NULL if cookie does not exist. Encrypted cookies created during - * the current request will not be available until the next request. - * - * @param string $name - * @param bool $deleteIfInvalid - * @return string|bool - */ - public function getEncryptedCookie($name, $deleteIfInvalid = true) - { - return $this->getCookie($name, $deleteIfInvalid); - } - - /** - * Delete HTTP cookie (encrypted or unencrypted) - * - * Remove a Cookie from the client. This method will overwrite an existing Cookie - * with a new, empty, auto-expiring Cookie. This method's arguments must match - * the original Cookie's respective arguments for the original Cookie to be - * removed. If any of this method's arguments are omitted or set to NULL, the - * default Cookie setting values (set during Slim::init) will be used instead. - * - * @param string $name The cookie name - * @param string $path The path on the server in which the cookie will be available on - * @param string $domain The domain that the cookie is available to - * @param bool $secure Indicates that the cookie should only be transmitted over a secure - * HTTPS connection from the client - * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol - */ - public function deleteCookie($name, $path = null, $domain = null, $secure = null, $httponly = null) - { - $settings = array( - 'domain' => is_null($domain) ? $this->config('cookies.domain') : $domain, - 'path' => is_null($path) ? $this->config('cookies.path') : $path, - 'secure' => is_null($secure) ? $this->config('cookies.secure') : $secure, - 'httponly' => is_null($httponly) ? $this->config('cookies.httponly') : $httponly - ); - $this->response->cookies->remove($name, $settings); - } - - /******************************************************************************** - * Helper Methods - *******************************************************************************/ - - /** - * Get the absolute path to this Slim application's root directory - * - * This method returns the absolute path to the Slim application's - * directory. If the Slim application is installed in a public-accessible - * sub-directory, the sub-directory path will be included. This method - * will always return an absolute path WITH a trailing slash. - * - * @return string - */ - public function root() - { - return rtrim($_SERVER['DOCUMENT_ROOT'], '/') . rtrim($this->request->getRootUri(), '/') . '/'; - } - - /** - * Clean current output buffer - */ - protected function cleanBuffer() - { - if (ob_get_level() !== 0) { - ob_clean(); - } - } - - /** - * Stop - * - * The thrown exception will be caught in application's `call()` method - * and the response will be sent as is to the HTTP client. - * - * @throws \Slim\Exception\Stop - */ - public function stop() - { - throw new \Slim\Exception\Stop(); - } - - /** - * Halt - * - * Stop the application and immediately send the response with a - * specific status and body to the HTTP client. This may send any - * type of response: info, success, redirect, client error, or server error. - * If you need to render a template AND customize the response status, - * use the application's `render()` method instead. - * - * @param int $status The HTTP response status - * @param string $message The HTTP response body - */ - public function halt($status, $message = '') - { - $this->cleanBuffer(); - $this->response->status($status); - $this->response->body($message); - $this->stop(); - } - - /** - * Pass - * - * The thrown exception is caught in the application's `call()` method causing - * the router's current iteration to stop and continue to the subsequent route if available. - * If no subsequent matching routes are found, a 404 response will be sent to the client. - * - * @throws \Slim\Exception\Pass - */ - public function pass() - { - $this->cleanBuffer(); - throw new \Slim\Exception\Pass(); - } - - /** - * Set the HTTP response Content-Type - * @param string $type The Content-Type for the Response (ie. text/html) - */ - public function contentType($type) - { - $this->response->headers->set('Content-Type', $type); - } - - /** - * Set the HTTP response status code - * @param int $code The HTTP response status code - */ - public function status($code) - { - $this->response->setStatus($code); - } - - /** - * Get the URL for a named route - * @param string $name The route name - * @param array $params Associative array of URL parameters and replacement values - * @throws \RuntimeException If named route does not exist - * @return string - */ - public function urlFor($name, $params = array()) - { - return $this->request->getRootUri() . $this->router->urlFor($name, $params); - } - - /** - * Redirect - * - * This method immediately redirects to a new URL. By default, - * this issues a 302 Found response; this is considered the default - * generic redirect response. You may also specify another valid - * 3xx status code if you want. This method will automatically set the - * HTTP Location header for you using the URL parameter. - * - * @param string $url The destination URL - * @param int $status The HTTP redirect status code (optional) - */ - public function redirect($url, $status = 302) - { - $this->response->redirect($url, $status); - $this->halt($status); - } - - /** - * RedirectTo - * - * Redirects to a specific named route - * - * @param string $route The route name - * @param array $params Associative array of URL parameters and replacement values - */ - public function redirectTo($route, $params = array(), $status = 302){ - $this->redirect($this->urlFor($route, $params), $status); - } - - /******************************************************************************** - * Flash Messages - *******************************************************************************/ - - /** - * Set flash message for subsequent request - * @param string $key - * @param mixed $value - */ - public function flash($key, $value) - { - if (isset($this->environment['slim.flash'])) { - $this->environment['slim.flash']->set($key, $value); - } - } - - /** - * Set flash message for current request - * @param string $key - * @param mixed $value - */ - public function flashNow($key, $value) - { - if (isset($this->environment['slim.flash'])) { - $this->environment['slim.flash']->now($key, $value); - } - } - - /** - * Keep flash messages from previous request for subsequent request - */ - public function flashKeep() - { - if (isset($this->environment['slim.flash'])) { - $this->environment['slim.flash']->keep(); - } - } - - /** - * Get all flash messages - */ - public function flashData() - { - if (isset($this->environment['slim.flash'])) { - return $this->environment['slim.flash']->getMessages(); - } - } - - /******************************************************************************** - * Hooks - *******************************************************************************/ - - /** - * Assign hook - * @param string $name The hook name - * @param mixed $callable A callable object - * @param int $priority The hook priority; 0 = high, 10 = low - */ - public function hook($name, $callable, $priority = 10) - { - if (!isset($this->hooks[$name])) { - $this->hooks[$name] = array(array()); - } - if (is_callable($callable)) { - $this->hooks[$name][(int) $priority][] = $callable; - } - } - - /** - * Invoke hook - * @param string $name The hook name - * @param mixed ... (Optional) Argument(s) for hooked functions, can specify multiple arguments - */ - public function applyHook($name) - { - if (!isset($this->hooks[$name])) { - $this->hooks[$name] = array(array()); - } - if (!empty($this->hooks[$name])) { - // Sort by priority, low to high, if there's more than one priority - if (count($this->hooks[$name]) > 1) { - ksort($this->hooks[$name]); - } - - $args = func_get_args(); - array_shift($args); - - foreach ($this->hooks[$name] as $priority) { - if (!empty($priority)) { - foreach ($priority as $callable) { - call_user_func_array($callable, $args); - } - } - } - } - } - - /** - * Get hook listeners - * - * Return an array of registered hooks. If `$name` is a valid - * hook name, only the listeners attached to that hook are returned. - * Else, all listeners are returned as an associative array whose - * keys are hook names and whose values are arrays of listeners. - * - * @param string $name A hook name (Optional) - * @return array|null - */ - public function getHooks($name = null) - { - if (!is_null($name)) { - return isset($this->hooks[(string) $name]) ? $this->hooks[(string) $name] : null; - } else { - return $this->hooks; - } - } - - /** - * Clear hook listeners - * - * Clear all listeners for all hooks. If `$name` is - * a valid hook name, only the listeners attached - * to that hook will be cleared. - * - * @param string $name A hook name (Optional) - */ - public function clearHooks($name = null) - { - if (!is_null($name) && isset($this->hooks[(string) $name])) { - $this->hooks[(string) $name] = array(array()); - } else { - foreach ($this->hooks as $key => $value) { - $this->hooks[$key] = array(array()); - } - } - } - - /******************************************************************************** - * Middleware - *******************************************************************************/ - - /** - * Add middleware - * - * This method prepends new middleware to the application middleware stack. - * The argument must be an instance that subclasses Slim_Middleware. - * - * @param \Slim\Middleware - */ - public function add(\Slim\Middleware $newMiddleware) - { - if(in_array($newMiddleware, $this->middleware)) { - $middleware_class = get_class($newMiddleware); - throw new \RuntimeException("Circular Middleware setup detected. Tried to queue the same Middleware instance ({$middleware_class}) twice."); - } - $newMiddleware->setApplication($this); - $newMiddleware->setNextMiddleware($this->middleware[0]); - array_unshift($this->middleware, $newMiddleware); - } - - /******************************************************************************** - * Runner - *******************************************************************************/ - - /** - * Run - * - * This method invokes the middleware stack, including the core Slim application; - * the result is an array of HTTP status, header, and body. These three items - * are returned to the HTTP client. - */ - public function run() - { - set_error_handler(array('\Slim\Slim', 'handleErrors')); - - //Apply final outer middleware layers - if ($this->config('debug')) { - //Apply pretty exceptions only in debug to avoid accidental information leakage in production - $this->add(new \Slim\Middleware\PrettyExceptions()); - } - - //Invoke middleware and application stack - $this->middleware[0]->call(); - - //Fetch status, header, and body - list($status, $headers, $body) = $this->response->finalize(); - - // Serialize cookies (with optional encryption) - \Slim\Http\Util::serializeCookies($headers, $this->response->cookies, $this->settings); - - //Send headers - if (headers_sent() === false) { - //Send status - if (strpos(PHP_SAPI, 'cgi') === 0) { - header(sprintf('Status: %s', \Slim\Http\Response::getMessageForCode($status))); - } else { - header(sprintf('HTTP/%s %s', $this->config('http.version'), \Slim\Http\Response::getMessageForCode($status))); - } - - //Send headers - foreach ($headers as $name => $value) { - $hValues = explode("\n", $value); - foreach ($hValues as $hVal) { - header("$name: $hVal", false); - } - } - } - - //Send body, but only if it isn't a HEAD request - if (!$this->request->isHead()) { - echo $body; - } - - $this->applyHook('slim.after'); - - restore_error_handler(); - } - - /** - * Call - * - * This method finds and iterates all route objects that match the current request URI. - */ - public function call() - { - try { - if (isset($this->environment['slim.flash'])) { - $this->view()->setData('flash', $this->environment['slim.flash']); - } - $this->applyHook('slim.before'); - ob_start(); - $this->applyHook('slim.before.router'); - $dispatched = false; - $matchedRoutes = $this->router->getMatchedRoutes($this->request->getMethod(), $this->request->getResourceUri()); - foreach ($matchedRoutes as $route) { - try { - $this->applyHook('slim.before.dispatch'); - $dispatched = $route->dispatch(); - $this->applyHook('slim.after.dispatch'); - if ($dispatched) { - break; - } - } catch (\Slim\Exception\Pass $e) { - continue; - } - } - if (!$dispatched) { - $this->notFound(); - } - $this->applyHook('slim.after.router'); - $this->stop(); - } catch (\Slim\Exception\Stop $e) { - $this->response()->write(ob_get_clean()); - } catch (\Exception $e) { - if ($this->config('debug')) { - throw $e; - } else { - try { - $this->response()->write(ob_get_clean()); - $this->error($e); - } catch (\Slim\Exception\Stop $e) { - // Do nothing - } - } - } - } - - /******************************************************************************** - * Error Handling and Debugging - *******************************************************************************/ - - /** - * Convert errors into ErrorException objects - * - * This method catches PHP errors and converts them into \ErrorException objects; - * these \ErrorException objects are then thrown and caught by Slim's - * built-in or custom error handlers. - * - * @param int $errno The numeric type of the Error - * @param string $errstr The error message - * @param string $errfile The absolute path to the affected file - * @param int $errline The line number of the error in the affected file - * @return bool - * @throws \ErrorException - */ - public static function handleErrors($errno, $errstr = '', $errfile = '', $errline = '') - { - if (!($errno & error_reporting())) { - return; - } - - throw new \ErrorException($errstr, $errno, 0, $errfile, $errline); - } - - /** - * Generate diagnostic template markup - * - * This method accepts a title and body content to generate an HTML document layout. - * - * @param string $title The title of the HTML template - * @param string $body The body content of the HTML template - * @return string - */ - protected static function generateTemplateMarkup($title, $body) - { - return sprintf("%s

%s

%s", $title, $title, $body); - } - - /** - * Default Not Found handler - */ - protected function defaultNotFound() - { - echo static::generateTemplateMarkup('404 Page Not Found', '

The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.

Visit the Home Page'); - } - - /** - * Default Error handler - */ - protected function defaultError($e) - { - $this->getLog()->error($e); - echo self::generateTemplateMarkup('Error', '

A website error has occurred. The website administrator has been notified of the issue. Sorry for the temporary inconvenience.

'); - } -} diff --git a/vendor/slim/slim/Slim/View.php b/vendor/slim/slim/Slim/View.php deleted file mode 100644 index 4059c80..0000000 --- a/vendor/slim/slim/Slim/View.php +++ /dev/null @@ -1,282 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * @package Slim - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -namespace Slim; - -/** - * View - * - * The view is responsible for rendering a template. The view - * should subclass \Slim\View and implement this interface: - * - * public render(string $template); - * - * This method should render the specified template and return - * the resultant string. - * - * @package Slim - * @author Josh Lockhart - * @since 1.0.0 - */ -class View -{ - /** - * Data available to the view templates - * @var \Slim\Helper\Set - */ - protected $data; - - /** - * Path to templates base directory (without trailing slash) - * @var string - */ - protected $templatesDirectory; - - /** - * Constructor - */ - public function __construct() - { - $this->data = new \Slim\Helper\Set(); - } - - /******************************************************************************** - * Data methods - *******************************************************************************/ - - /** - * Does view data have value with key? - * @param string $key - * @return boolean - */ - public function has($key) - { - return $this->data->has($key); - } - - /** - * Return view data value with key - * @param string $key - * @return mixed - */ - public function get($key) - { - return $this->data->get($key); - } - - /** - * Set view data value with key - * @param string $key - * @param mixed $value - */ - public function set($key, $value) - { - $this->data->set($key, $value); - } - - /** - * Set view data value as Closure with key - * @param string $key - * @param mixed $value - */ - public function keep($key, \Closure $value) - { - $this->data->keep($key, $value); - } - - /** - * Return view data - * @return array - */ - public function all() - { - return $this->data->all(); - } - - /** - * Replace view data - * @param array $data - */ - public function replace(array $data) - { - $this->data->replace($data); - } - - /** - * Clear view data - */ - public function clear() - { - $this->data->clear(); - } - - /******************************************************************************** - * Legacy data methods - *******************************************************************************/ - - /** - * DEPRECATION WARNING! This method will be removed in the next major point release - * - * Get data from view - */ - public function getData($key = null) - { - if (!is_null($key)) { - return isset($this->data[$key]) ? $this->data[$key] : null; - } - - return $this->data->all(); - } - - /** - * DEPRECATION WARNING! This method will be removed in the next major point release - * - * Set data for view - */ - public function setData() - { - $args = func_get_args(); - if (count($args) === 1 && is_array($args[0])) { - $this->data->replace($args[0]); - } elseif (count($args) === 2) { - // Ensure original behavior is maintained. DO NOT invoke stored Closures. - if (is_object($args[1]) && method_exists($args[1], '__invoke')) { - $this->data->set($args[0], $this->data->protect($args[1])); - } else { - $this->data->set($args[0], $args[1]); - } - } else { - throw new \InvalidArgumentException('Cannot set View data with provided arguments. Usage: `View::setData( $key, $value );` or `View::setData([ key => value, ... ]);`'); - } - } - - /** - * DEPRECATION WARNING! This method will be removed in the next major point release - * - * Append data to view - * @param array $data - */ - public function appendData($data) - { - if (!is_array($data)) { - throw new \InvalidArgumentException('Cannot append view data. Expected array argument.'); - } - $this->data->replace($data); - } - - /******************************************************************************** - * Resolve template paths - *******************************************************************************/ - - /** - * Set the base directory that contains view templates - * @param string $directory - * @throws \InvalidArgumentException If directory is not a directory - */ - public function setTemplatesDirectory($directory) - { - $this->templatesDirectory = rtrim($directory, DIRECTORY_SEPARATOR); - } - - /** - * Get templates base directory - * @return string - */ - public function getTemplatesDirectory() - { - return $this->templatesDirectory; - } - - /** - * Get fully qualified path to template file using templates base directory - * @param string $file The template file pathname relative to templates base directory - * @return string - */ - public function getTemplatePathname($file) - { - return $this->templatesDirectory . DIRECTORY_SEPARATOR . ltrim($file, DIRECTORY_SEPARATOR); - } - - /******************************************************************************** - * Rendering - *******************************************************************************/ - - /** - * Display template - * - * This method echoes the rendered template to the current output buffer - * - * @param string $template Pathname of template file relative to templates directory - * @param array $data Any additonal data to be passed to the template. - */ - public function display($template, $data = null) - { - echo $this->fetch($template, $data); - } - - /** - * Return the contents of a rendered template file - * - * @param string $template The template pathname, relative to the template base directory - * @param array $data Any additonal data to be passed to the template. - * @return string The rendered template - */ - public function fetch($template, $data = null) - { - return $this->render($template, $data); - } - - /** - * Render a template file - * - * NOTE: This method should be overridden by custom view subclasses - * - * @param string $template The template pathname, relative to the template base directory - * @param array $data Any additonal data to be passed to the template. - * @return string The rendered template - * @throws \RuntimeException If resolved template pathname is not a valid file - */ - protected function render($template, $data = null) - { - $templatePathname = $this->getTemplatePathname($template); - if (!is_file($templatePathname)) { - throw new \RuntimeException("View cannot render `$template` because the template does not exist"); - } - - $data = array_merge($this->data->all(), (array) $data); - extract($data); - ob_start(); - require $templatePathname; - - return ob_get_clean(); - } -} diff --git a/vendor/slim/slim/composer.json b/vendor/slim/slim/composer.json index 0becfe6..554a838 100644 --- a/vendor/slim/slim/composer.json +++ b/vendor/slim/slim/composer.json @@ -1,24 +1,58 @@ { "name": "slim/slim", "type": "library", - "description": "Slim Framework, a PHP micro framework", - "keywords": ["microframework","rest","router"], - "homepage": "http://github.com/codeguy/Slim", + "description": "Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs", + "keywords": ["framework","micro","api","router"], + "homepage": "https://slimframework.com", "license": "MIT", "authors": [ { "name": "Josh Lockhart", - "email": "info@joshlockhart.com", - "homepage": "http://www.joshlockhart.com/" + "email": "hello@joshlockhart.com", + "homepage": "https://joshlockhart.com" + }, + { + "name": "Andrew Smith", + "email": "a.smith@silentworks.co.uk", + "homepage": "http://silentworks.co.uk" + }, + { + "name": "Rob Allen", + "email": "rob@akrabat.com", + "homepage": "http://akrabat.com" + }, + { + "name": "Gabriel Manricks", + "email": "gmanricks@me.com", + "homepage": "http://gabrielmanricks.com" } ], "require": { - "php": ">=5.3.0" + "php": ">=5.5.0", + "pimple/pimple": "^3.0", + "psr/http-message": "^1.0", + "nikic/fast-route": "^1.0", + "container-interop/container-interop": "^1.2", + "psr/container": "^1.0" }, - "suggest": { - "ext-mcrypt": "Required for HTTP cookie encryption" + "require-dev": { + "squizlabs/php_codesniffer": "^2.5", + "phpunit/phpunit": "^4.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" }, "autoload": { - "psr-0": { "Slim": "." } + "psr-4": { + "Slim\\": "Slim" + } + }, + "scripts": { + "test": [ + "@phpunit", + "@phpcs" + ], + "phpunit": "php vendor/bin/phpunit", + "phpcs": "php vendor/bin/phpcs" } } diff --git a/vendor/slim/slim/index.php b/vendor/slim/slim/index.php deleted file mode 100644 index 355a8f5..0000000 --- a/vendor/slim/slim/index.php +++ /dev/null @@ -1,169 +0,0 @@ -get( - '/', - function () { - $template = << - - - - Slim Framework for PHP 5 - - - -
- Slim -
-

Welcome to Slim!

-

- Congratulations! Your Slim application is running. If this is - your first time using Slim, start with this "Hello World" Tutorial. -

-
-

Get Started

-
    -
  1. The application code is in index.php
  2. -
  3. Read the online documentation
  4. -
  5. Follow @slimphp on Twitter
  6. -
-
-
-

Slim Framework Community

- -

Support Forum and Knowledge Base

-

- Visit the Slim support forum and knowledge base - to read announcements, chat with fellow Slim users, ask questions, help others, or show off your cool - Slim Framework apps. -

- -

Twitter

-

- Follow @slimphp on Twitter to receive the very latest news - and updates about the framework. -

-
-
-

Slim Framework Extras

-

- Custom View classes for Smarty, Twig, Mustache, and other template - frameworks are available online in a separate repository. -

-

Browse the Extras Repository

-
- - -EOT; - echo $template; - } -); - -// POST route -$app->post( - '/post', - function () { - echo 'This is a POST route'; - } -); - -// PUT route -$app->put( - '/put', - function () { - echo 'This is a PUT route'; - } -); - -// PATCH route -$app->patch('/patch', function () { - echo 'This is a PATCH route'; -}); - -// DELETE route -$app->delete( - '/delete', - function () { - echo 'This is a DELETE route'; - } -); - -/** - * Step 4: Run the Slim application - * - * This method should be called last. This executes the Slim application - * and returns the HTTP response to the HTTP client. - */ -$app->run(); diff --git a/vendor/slim/slim/phpunit.xml.dist b/vendor/slim/slim/phpunit.xml.dist deleted file mode 100644 index c4da172..0000000 --- a/vendor/slim/slim/phpunit.xml.dist +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - ./tests/ - - - - - - ./Slim/ - - - diff --git a/vendor/slim/slim/tests/EnvironmentTest.php b/vendor/slim/slim/tests/EnvironmentTest.php deleted file mode 100644 index db54a51..0000000 --- a/vendor/slim/slim/tests/EnvironmentTest.php +++ /dev/null @@ -1,376 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -class EnvironmentTest extends PHPUnit_Framework_TestCase -{ - /** - * Default server settings assume the Slim app is installed - * in a subdirectory `foo/` directly beneath the public document - * root directory; URL rewrite is disabled; requested app - * resource is GET `/bar/xyz` with three query params. - * - * These only provide a common baseline for the following - * tests; tests are free to override these values. - */ - public function setUp() - { - $_SERVER['DOCUMENT_ROOT'] = '/var/www'; - $_SERVER['SCRIPT_FILENAME'] = '/var/www/foo/index.php'; - $_SERVER['SERVER_NAME'] = 'slim'; - $_SERVER['SERVER_PORT'] = '80'; - $_SERVER['SCRIPT_NAME'] = '/foo/index.php'; - $_SERVER['REQUEST_URI'] = '/foo/index.php/bar/xyz'; - $_SERVER['PATH_INFO'] = '/bar/xyz'; - $_SERVER['REQUEST_METHOD'] = 'GET'; - $_SERVER['QUERY_STRING'] = 'one=1&two=2&three=3'; - $_SERVER['HTTPS'] = ''; - $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; - unset($_SERVER['CONTENT_TYPE'], $_SERVER['CONTENT_LENGTH']); - } - - /** - * Test mock environment - * - * This should return the custom values where specified - * and the default values otherwise. - */ - public function testMockEnvironment() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'PUT' - )); - $env2 = \Slim\Environment::getInstance(); - $this->assertSame($env, $env2); - $this->assertInstanceOf('\Slim\Environment', $env); - $this->assertEquals('PUT', $env['REQUEST_METHOD']); - $this->assertEquals(80, $env['SERVER_PORT']); - $this->assertNull($env['foo']); - } - - /** - * Test sets HTTP method - */ - public function testSetsHttpMethod() - { - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('GET', $env['REQUEST_METHOD']); - } - - /** - * Test parses script name and path info - * - * Pre-conditions: - * URL Rewrite is disabled; - * App installed in subdirectory; - */ - public function testParsesPathsWithoutUrlRewriteInSubdirectory() - { - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('/bar/xyz', $env['PATH_INFO']); - $this->assertEquals('/foo/index.php', $env['SCRIPT_NAME']); - } - - /** - * Test parses script name and path info - * - * Pre-conditions: - * URL Rewrite is disabled; - * App installed in root directory; - */ - public function testParsesPathsWithoutUrlRewriteInRootDirectory() - { - $_SERVER['SCRIPT_FILENAME'] = '/var/www/index.php'; - $_SERVER['REQUEST_URI'] = '/index.php/bar/xyz'; - $_SERVER['SCRIPT_NAME'] = '/index.php'; - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('/bar/xyz', $env['PATH_INFO']); - $this->assertEquals('/index.php', $env['SCRIPT_NAME']); - } - - /** - * Test parses script name and path info - * - * Pre-conditions: - * URL Rewrite disabled; - * App installed in root directory; - * Requested resource is "/"; - */ - public function testParsesPathsWithoutUrlRewriteInRootDirectoryForAppRootUri() - { - $_SERVER['SCRIPT_FILENAME'] = '/var/www/index.php'; - $_SERVER['REQUEST_URI'] = '/index.php'; - $_SERVER['SCRIPT_NAME'] = '/index.php'; - unset($_SERVER['PATH_INFO']); - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('/', $env['PATH_INFO']); - $this->assertEquals('/index.php', $env['SCRIPT_NAME']); - } - - /** - * Test parses script name and path info - * - * Pre-conditions: - * URL Rewrite enabled; - * App installed in subdirectory; - */ - public function testParsesPathsWithUrlRewriteInSubdirectory() - { - $_SERVER['SCRIPT_NAME'] = '/foo/index.php'; - $_SERVER['REQUEST_URI'] = '/foo/bar/xyz'; - unset($_SERVER['PATH_INFO']); - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('/bar/xyz', $env['PATH_INFO']); - $this->assertEquals('/foo', $env['SCRIPT_NAME']); - } - - /** - * Test parses script name and path info - * - * Pre-conditions: - * URL Rewrite enabled; - * App installed in root directory; - */ - public function testParsesPathsWithUrlRewriteInRootDirectory() - { - $_SERVER['SCRIPT_FILENAME'] = '/var/www/index.php'; - $_SERVER['SCRIPT_NAME'] = '/index.php'; - $_SERVER['REQUEST_URI'] = '/bar/xyz'; - unset($_SERVER['PATH_INFO']); - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('/bar/xyz', $env['PATH_INFO']); - $this->assertEquals('', $env['SCRIPT_NAME']); - } - - /** - * Test parses script name and path info - * - * Pre-conditions: - * URL Rewrite enabled; - * App installed in root directory; - * Requested resource is "/" - */ - public function testParsesPathsWithUrlRewriteInRootDirectoryForAppRootUri() - { - $_SERVER['SCRIPT_FILENAME'] = '/var/www/index.php'; - $_SERVER['REQUEST_URI'] = '/'; - $_SERVER['SCRIPT_NAME'] = '/index.php'; - unset($_SERVER['PATH_INFO']); - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('/', $env['PATH_INFO']); - $this->assertEquals('', $env['SCRIPT_NAME']); - } - - /** - * Test parses query string - * - * Pre-conditions: - * $_SERVER['QUERY_STRING'] exists and is not empty; - */ - public function testParsesQueryString() - { - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('one=1&two=2&three=3', $env['QUERY_STRING']); - } - - /** - * Test removes query string from PATH_INFO when using URL Rewrite - * - * Pre-conditions: - * $_SERVER['QUERY_STRING'] exists and is not empty; - * URL Rewrite enabled; - */ - public function testRemovesQueryStringFromPathInfo() - { - $_SERVER['SCRIPT_NAME'] = '/foo/index.php'; - $_SERVER['REQUEST_URI'] = '/foo/bar/xyz?one=1&two=2&three=3'; - unset($_SERVER['PATH_INFO']); - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('/bar/xyz', $env['PATH_INFO']); - } - - /** - * Test environment's PATH_INFO retains URL encoded characters (e.g. #) - * - * In earlier version, \Slim\Environment would use PATH_INFO instead - * of REQUEST_URI to determine the root URI and resource URI. - * Unfortunately, the server would URL decode the PATH_INFO string - * before it was handed to PHP. This prevented certain URL-encoded - * characters like the octothorpe from being delivered correctly to - * the Slim application environment. This test ensures the - * REQUEST_URI is used instead and parsed as expected. - */ - public function testPathInfoRetainsUrlEncodedCharacters() - { - $_SERVER['SCRIPT_FILENAME'] = '/var/www/index.php'; - $_SERVER['SCRIPT_NAME'] = '/index.php'; - $_SERVER['REQUEST_URI'] = '/foo/%23bar'; //<-- URL-encoded "#bar" - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('/foo/%23bar', $env['PATH_INFO']); - } - - /** - * Test parses query string - * - * Pre-conditions: - * $_SERVER['QUERY_STRING'] does not exist; - */ - public function testParsesQueryStringThatDoesNotExist() - { - unset($_SERVER['QUERY_STRING']); - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('', $env['QUERY_STRING']); - } - - /** - * Test SERVER_NAME is not empty - */ - public function testServerNameIsNotEmpty() - { - $env = \Slim\Environment::getInstance(true); - $this->assertFalse(empty($env['SERVER_NAME'])); - } - - /** - * Test SERVER_PORT is not empty - */ - public function testServerPortIsNotEmpty() - { - $env = \Slim\Environment::getInstance(true); - $this->assertFalse(empty($env['SERVER_PORT'])); - } - - /** - * Test unsets HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH - * - * Pre-conditions: - * HTTP_CONTENT_TYPE is sent with HTTP request; - * HTTP_CONTENT_LENGTH is sent with HTTP request; - */ - public function testUnsetsContentTypeAndContentLength() - { - $_SERVER['HTTP_CONTENT_LENGTH'] = 150; - $env = \Slim\Environment::getInstance(true); - $this->assertFalse(isset($env['HTTP_CONTENT_LENGTH'])); - } - - /** - * Test sets special request headers if not empty - * - * Pre-conditions: - * CONTENT_TYPE, CONTENT_LENGTH, X_REQUESTED_WITH are sent in client HTTP request; - * CONTENT_TYPE, CONTENT_LENGTH, X_REQUESTED_WITH are not empty; - */ - public function testSetsSpecialHeaders() - { - $_SERVER['CONTENT_TYPE'] = 'text/csv'; - $_SERVER['CONTENT_LENGTH'] = '100'; - $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XmlHttpRequest'; - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('text/csv', $env['CONTENT_TYPE']); - $this->assertEquals('100', $env['CONTENT_LENGTH']); - $this->assertEquals('XmlHttpRequest', $env['HTTP_X_REQUESTED_WITH']); - } - - /** - * Tests X-HTTP-Method-Override is allowed through unmolested. - * - * Pre-conditions: - * X_HTTP_METHOD_OVERRIDE is sent in client HTTP request; - * X_HTTP_METHOD_OVERRIDE is not empty; - */ - public function testSetsHttpMethodOverrideHeader() { - $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'DELETE'; - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('DELETE', $env['HTTP_X_HTTP_METHOD_OVERRIDE']); - } - - /** - * Test detects HTTPS - * - * Pre-conditions: - * $_SERVER['HTTPS'] is set to a non-empty value; - */ - public function testHttps() - { - $_SERVER['HTTPS'] = 1; - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('https', $env['slim.url_scheme']); - } - - /** - * Test detects not HTTPS - * - * Pre-conditions: - * $_SERVER['HTTPS'] is set to an empty value; - */ - public function testNotHttps() - { - $_SERVER['HTTPS'] = ''; - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('http', $env['slim.url_scheme']); - } - - /** - * Test detects not HTTPS on IIS - * - * Pre-conditions: - * $_SERVER['HTTPS'] is set to "off"; - */ - public function testNotHttpsIIS() - { - $_SERVER['HTTPS'] = 'off'; - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('http', $env['slim.url_scheme']); - } - - /** - * Test input is an empty string (and not false) - * - * Pre-conditions: - * Input at php://input may only be read once; subsequent attempts - * will return `false`; in which case, use an empty string. - */ - public function testInputIsEmptyString() - { - $env = \Slim\Environment::getInstance(true); - $this->assertEquals('', $env['slim.input']); - } - - /** - * Test valid resource handle to php://stdErr - */ - public function testErrorResource() - { - $env = \Slim\Environment::getInstance(true); - $this->assertTrue(is_resource($env['slim.errors'])); - } -} diff --git a/vendor/slim/slim/tests/Foo.php b/vendor/slim/slim/tests/Foo.php deleted file mode 100644 index d772d02..0000000 --- a/vendor/slim/slim/tests/Foo.php +++ /dev/null @@ -1,7 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -class SetTest extends PHPUnit_Framework_TestCase -{ - protected $bag; - protected $property; - - public function setUp() - { - $this->bag = new \Slim\Helper\Set(); - $this->property = new \ReflectionProperty($this->bag, 'data'); - $this->property->setAccessible(true); - } - - public function testSet() - { - $this->bag->set('foo', 'bar'); - $this->assertArrayHasKey('foo', $this->property->getValue($this->bag)); - $bag = $this->property->getValue($this->bag); - $this->assertEquals('bar', $bag['foo']); - } - - public function testGet() - { - $this->property->setValue($this->bag, array('foo' => 'bar')); - $this->assertEquals('bar', $this->bag->get('foo')); - } - - public function testGetNotExists() - { - $this->property->setValue($this->bag, array('foo' => 'bar')); - $this->assertEquals('default', $this->bag->get('abc', 'default')); - } - - public function testAdd() - { - $this->bag->replace(array( - 'abc' => '123', - 'foo' => 'bar' - )); - $this->assertArrayHasKey('abc', $this->property->getValue($this->bag)); - $this->assertArrayHasKey('foo', $this->property->getValue($this->bag)); - $bag = $this->property->getValue($this->bag); - $this->assertEquals('123', $bag['abc']); - $this->assertEquals('bar', $bag['foo']); - } - - public function testAll() - { - $data = array( - 'abc' => '123', - 'foo' => 'bar' - ); - $this->property->setValue($this->bag, $data); - $this->assertEquals($data, $this->bag->all()); - } - - public function testKeys() - { - $data = array( - 'abc' => '123', - 'foo' => 'bar' - ); - $this->property->setValue($this->bag, $data); - $this->assertEquals(array('abc', 'foo'), $this->bag->keys()); - } - - public function testRemove() - { - $data = array( - 'abc' => '123', - 'foo' => 'bar' - ); - $this->property->setValue($this->bag, $data); - $this->bag->remove('foo'); - $this->assertEquals(array('abc' => '123'), $this->property->getValue($this->bag)); - } - - public function testClear() - { - $data = array( - 'abc' => '123', - 'foo' => 'bar' - ); - $this->property->setValue($this->bag, $data); - $this->bag->clear(); - $this->assertEquals(array(), $this->property->getValue($this->bag)); - } - - public function testArrayAccessGet() - { - $data = array( - 'abc' => '123', - 'foo' => 'bar' - ); - $this->property->setValue($this->bag, $data); - $this->assertEquals('bar', $this->bag['foo']); - } - - public function testArrayAccessSet() - { - $data = array( - 'abc' => '123', - 'foo' => 'bar' - ); - $this->property->setValue($this->bag, $data); - $this->bag['foo'] = 'changed'; - $bag = $this->property->getValue($this->bag); - $this->assertEquals('changed', $bag['foo']); - } - - public function testArrayAccessExists() - { - $data = array( - 'abc' => '123', - 'foo' => 'bar' - ); - $this->property->setValue($this->bag, $data); - $this->assertTrue(isset($this->bag['foo'])); - $this->assertFalse(isset($this->bag['bar'])); - } - - public function testArrayAccessUnset() - { - $data = array( - 'abc' => '123', - 'foo' => 'bar' - ); - $this->property->setValue($this->bag, $data); - unset($this->bag['foo']); - $this->assertEquals(array('abc' => '123'), $this->property->getValue($this->bag)); - } - - public function testCount() - { - $data = array( - 'abc' => '123', - 'foo' => 'bar' - ); - $this->property->setValue($this->bag, $data); - $this->assertEquals(2, count($this->bag)); - } - - public function testGetIterator() - { - $data = array( - 'abc' => '123', - 'foo' => 'bar' - ); - $this->property->setValue($this->bag, $data); - $this->assertInstanceOf('\ArrayIterator', $this->bag->getIterator()); - } - - public function testPropertyOverloadGet() - { - $data = array( - 'abc' => '123', - 'foo' => 'bar' - ); - $this->property->setValue($this->bag, $data); - - $this->assertEquals('123', $this->bag->abc); - $this->assertEquals('bar', $this->bag->foo); - } - - public function testPropertyOverloadSet() - { - $this->bag->foo = 'bar'; - $this->assertArrayHasKey('foo', $this->property->getValue($this->bag)); - $this->assertEquals('bar', $this->bag->foo); - } - - public function testPropertyOverloadingIsset() - { - $data = array( - 'abc' => '123', - 'foo' => 'bar' - ); - $this->property->setValue($this->bag, $data); - - $this->assertTrue(isset($this->bag->abc)); - $this->assertTrue(isset($this->bag->foo)); - $this->assertFalse(isset($this->bag->foobar)); - } - - public function testPropertyOverloadingUnset() - { - $data = array( - 'abc' => '123', - 'foo' => 'bar' - ); - $this->property->setValue($this->bag, $data); - - $this->assertTrue(isset($this->bag->abc)); - unset($this->bag->abc); - $this->assertFalse(isset($this->bag->abc)); - $this->assertArrayNotHasKey('abc', $this->property->getValue($this->bag)); - $this->assertArrayHasKey('foo', $this->property->getValue($this->bag)); - } - - public function testProtect() - { - $callable = function () { - return 'foo'; - }; - $result = $this->bag->protect($callable); - - $this->assertInstanceOf('\Closure', $result); - $this->assertSame($callable, $result()); - } -} diff --git a/vendor/slim/slim/tests/Http/CookiesTest.php b/vendor/slim/slim/tests/Http/CookiesTest.php deleted file mode 100644 index 5ad1854..0000000 --- a/vendor/slim/slim/tests/Http/CookiesTest.php +++ /dev/null @@ -1,92 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -class CookiesTest extends PHPUnit_Framework_TestCase -{ - public function testSetWithStringValue() - { - $c = new \Slim\Http\Cookies(); - $c->set('foo', 'bar'); - $this->assertAttributeEquals( - array( - 'foo' => array( - 'value' => 'bar', - 'expires' => null, - 'domain' => null, - 'path' => null, - 'secure' => false, - 'httponly' => false - ) - ), - 'data', - $c - ); - } - - public function testSetWithArrayValue() - { - $now = time(); - $c = new \Slim\Http\Cookies(); - $c->set('foo', array( - 'value' => 'bar', - 'expires' => $now + 86400, - 'domain' => '.example.com', - 'path' => '/', - 'secure' => true, - 'httponly' => true - )); - $this->assertAttributeEquals( - array( - 'foo' => array( - 'value' => 'bar', - 'expires' => $now + 86400, - 'domain' => '.example.com', - 'path' => '/', - 'secure' => true, - 'httponly' => true - ) - ), - 'data', - $c - ); - } - - public function testRemove() - { - $c = new \Slim\Http\Cookies(); - $c->remove('foo'); - $prop = new \ReflectionProperty($c, 'data'); - $prop->setAccessible(true); - $cValue = $prop->getValue($c); - $this->assertEquals('', $cValue['foo']['value']); - $this->assertLessThan(time(), $cValue['foo']['expires']); - } -} diff --git a/vendor/slim/slim/tests/Http/HeadersTest.php b/vendor/slim/slim/tests/Http/HeadersTest.php deleted file mode 100644 index c0466ef..0000000 --- a/vendor/slim/slim/tests/Http/HeadersTest.php +++ /dev/null @@ -1,59 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -class HeadersTest extends PHPUnit_Framework_TestCase -{ - public function testNormalizesKey() - { - $h = new \Slim\Http\Headers(); - $h->set('Http_Content_Type', 'text/html'); - $prop = new \ReflectionProperty($h, 'data'); - $prop->setAccessible(true); - $this->assertArrayHasKey('Content-Type', $prop->getValue($h)); - } - - public function testExtractHeaders() - { - $test = array( - 'HTTP_HOST' => 'foo.com', - 'SERVER_NAME' => 'foo', - 'CONTENT_TYPE' => 'text/html', - 'X_FORWARDED_FOR' => '127.0.0.1' - ); - $results = \Slim\Http\Headers::extract($test); - $this->assertEquals(array( - 'HTTP_HOST' => 'foo.com', - 'CONTENT_TYPE' => 'text/html', - 'X_FORWARDED_FOR' => '127.0.0.1' - ), $results); - } -} diff --git a/vendor/slim/slim/tests/Http/RequestTest.php b/vendor/slim/slim/tests/Http/RequestTest.php deleted file mode 100644 index 117b72c..0000000 --- a/vendor/slim/slim/tests/Http/RequestTest.php +++ /dev/null @@ -1,949 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -class RequestTest extends PHPUnit_Framework_TestCase -{ - /** - * Test sets HTTP method - */ - public function testGetMethod() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'GET' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('GET', $req->getMethod()); - } - - /** - * Test HTTP GET method detection - */ - public function testIsGet() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'GET' - )); - $req = new \Slim\Http\Request($env); - $this->assertTrue($req->isGet()); - } - - /** - * Test HTTP POST method detection - */ - public function testIsPost() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'POST', - )); - $req = new \Slim\Http\Request($env); - $this->assertTrue($req->isPost()); - } - - /** - * Test HTTP PUT method detection - */ - public function testIsPut() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'PUT', - )); - $req = new \Slim\Http\Request($env); - $this->assertTrue($req->isPut()); - } - - /** - * Test HTTP DELETE method detection - */ - public function testIsDelete() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'DELETE', - )); - $req = new \Slim\Http\Request($env); - $this->assertTrue($req->isDelete()); - } - - /** - * Test HTTP OPTIONS method detection - */ - public function testIsOptions() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'OPTIONS', - )); - $req = new \Slim\Http\Request($env); - $this->assertTrue($req->isOptions()); - } - - /** - * Test HTTP HEAD method detection - */ - public function testIsHead() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'HEAD', - )); - $req = new \Slim\Http\Request($env); - $this->assertTrue($req->isHead()); - } - - /** - * Test HTTP PATCH method detection - */ - public function testIsPatch() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'PATCH', - )); - $req = new \Slim\Http\Request($env); - $this->assertTrue($req->isPatch()); - } - - /** - * Test AJAX method detection w/ header - */ - public function testIsAjaxWithHeader() - { - $env = \Slim\Environment::mock(array( - 'X_REQUESTED_WITH' => 'XMLHttpRequest' - )); - $req = new \Slim\Http\Request($env); - $this->assertTrue($req->isAjax()); - $this->assertTrue($req->isXhr()); - } - - /** - * Test AJAX method detection w/ query parameter - */ - public function testIsAjaxWithQueryParameter() - { - $env = \Slim\Environment::mock(array( - 'QUERY_STRING' => 'isajax=1', - )); - $req = new \Slim\Http\Request($env); - $this->assertTrue($req->isAjax()); - $this->assertTrue($req->isXhr()); - } - - /** - * Test AJAX method detection without header or query parameter - */ - public function testIsAjaxWithoutHeaderOrQueryParameter() - { - $env = \Slim\Environment::mock(); - $req = new \Slim\Http\Request($env); - $this->assertFalse($req->isAjax()); - $this->assertFalse($req->isXhr()); - } - - /** - * Test AJAX method detection with misspelled header - */ - public function testIsAjaxWithMisspelledHeader() - { - $env = \Slim\Environment::mock(array( - 'X_REQUESTED_WITH' => 'foo' - )); - $req = new \Slim\Http\Request($env); - $this->assertFalse($req->isAjax()); - $this->assertFalse($req->isXhr()); - } - - /** - * Test params from query string - */ - public function testParamsFromQueryString() - { - $env = \Slim\Environment::mock(array( - 'QUERY_STRING' => 'one=1&two=2&three=3' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals(3, count($req->params())); - $this->assertEquals('1', $req->params('one')); - $this->assertNull($req->params('foo')); - $this->assertEquals(1, $req->params('foo', 1)); - } - - /** - * Test params from request body - */ - public function testParamsFromRequestBody() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'POST', - 'QUERY_STRING' => 'one=1&two=2&three=3', - 'slim.input' => 'foo=bar&abc=123', - 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', - 'CONTENT_LENGTH' => 15 - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals(5, count($req->params())); //Union of GET and POST - $this->assertEquals('bar', $req->params('foo')); - } - - /** - * Test fetch GET params - */ - public function testGet() - { - $env = \Slim\Environment::mock(array( - 'QUERY_STRING' => 'one=1&two=2&three=3' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals(3, count($req->get())); - $this->assertEquals('1', $req->get('one')); - $this->assertNull($req->get('foo')); - $this->assertFalse($req->get('foo', false)); - } - - /** - * Test fetch GET params without multibyte - */ - public function testGetWithoutMultibyte() - { - $env = \Slim\Environment::mock(array( - 'QUERY_STRING' => 'one=1&two=2&three=3', - 'slim.tests.ignore_multibyte' => true - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals(3, count($req->get())); - $this->assertEquals('1', $req->get('one')); - $this->assertNull($req->get('foo')); - $this->assertFalse($req->get('foo', false)); - } - - /** - * Test fetch POST params - */ - public function testPost() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'POST', - 'slim.input' => 'foo=bar&abc=123', - 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', - 'CONTENT_LENGTH' => 15 - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals(2, count($req->post())); - $this->assertEquals('bar', $req->post('foo')); - $this->assertNull($req->post('xyz')); - $this->assertFalse($req->post('xyz', false)); - } - - /** - * Test fetch POST params without multibyte - */ - public function testPostWithoutMultibyte() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'POST', - 'slim.input' => 'foo=bar&abc=123', - 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', - 'CONTENT_LENGTH' => 15, - 'slim.tests.ignore_multibyte' => true - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals(2, count($req->post())); - $this->assertEquals('bar', $req->post('foo')); - $this->assertNull($req->post('xyz')); - $this->assertFalse($req->post('xyz', false)); - } - - /** - * Test fetch POST without slim.input - */ - public function testPostWithoutInput() - { - $this->setExpectedException('RuntimeException'); - $env = \Slim\Environment::mock(); - unset($env['slim.input']); - $req = new \Slim\Http\Request($env); - $req->post('foo'); - } - - /** - * Test fetch POST params even if multipart/form-data request - */ - public function testPostWithMultipartRequest() - { - $_POST = array('foo' => 'bar'); //<-- Set by PHP - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'POST', - 'slim.input' => '', //<-- "php://input" is empty for multipart/form-data requests - 'CONTENT_TYPE' => 'multipart/form-data', - 'CONTENT_LENGTH' => 0 - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals(1, count($req->post())); - $this->assertEquals('bar', $req->post('foo')); - $this->assertNull($req->post('xyz')); - } - - /** - * Test fetch PUT params - */ - public function testPut() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'PUT', - 'slim.input' => 'foo=bar&abc=123', - 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', - 'CONTENT_LENGTH' => 15 - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals(2, count($req->put())); - $this->assertEquals('bar', $req->put('foo')); - $this->assertEquals('bar', $req->params('foo')); - $this->assertNull($req->put('xyz')); - $this->assertFalse($req->put('xyz', false)); - } - - /** - * Test fetch PATCH params - */ - public function testPatch() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'PATCH', - 'slim.input' => 'foo=bar&abc=123', - 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', - 'CONTENT_LENGTH' => 15 - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals(2, count($req->patch())); - $this->assertEquals('bar', $req->patch('foo')); - $this->assertEquals('bar', $req->params('foo')); - $this->assertNull($req->patch('xyz')); - $this->assertFalse($req->patch('xyz', false)); - } - - /** - * Test fetch DELETE params - */ - public function testDelete() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'DELETE', - 'slim.input' => 'foo=bar&abc=123', - 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', - 'CONTENT_LENGTH' => 15 - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals(2, count($req->delete())); - $this->assertEquals('bar', $req->delete('foo')); - $this->assertEquals('bar', $req->params('foo')); - $this->assertNull($req->delete('xyz')); - $this->assertFalse($req->delete('xyz', false)); - } - - /** - * Test fetch COOKIE params - */ - public function testCookies() - { - $env = \Slim\Environment::mock(array( - 'HTTP_COOKIE' => 'foo=bar; abc=123' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals(2, count($req->cookies())); - $this->assertEquals('bar', $req->cookies('foo')); - $this->assertNull($req->cookies('xyz')); - } - - /** - * Test is form data - */ - public function testIsFormDataContentFormUrlencoded() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'PUT', - 'slim.input' => '', - 'CONTENT_TYPE' => 'application/x-www-form-urlencoded' - )); - $req = new \Slim\Http\Request($env); - $this->assertTrue($req->isFormData()); - } - - /** - * Test is form data - */ - public function testIsFormDataPostContentUnknown() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'POST', - 'slim.input' => '', - )); - $req = new \Slim\Http\Request($env); - $this->assertTrue($req->isFormData()); - } - - /** - * Test is form data - */ - public function testIsFormDataPostContentUnknownWithMethodOverride() - { - $env = \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'PUT', - )); - $env['slim.method_override.original_method'] = 'POST'; - $req = new \Slim\Http\Request($env); - $this->assertTrue($req->isPut()); - $this->assertTrue($req->isFormData()); - } - - /** - * Test is not form data - */ - public function testIsNotFormData() - { - $env = \Slim\Environment::mock(array( - 'slim.input' => '', - 'CONTENT_TYPE' => 'application/json' - )); - $req = new \Slim\Http\Request($env); - $this->assertFalse($req->isFormData()); - } - - /** - * Test headers - */ - public function testHeaders() - { - $env = \Slim\Environment::mock(array( - 'HTTP_ACCEPT_ENCODING' => 'gzip' - )); - $req = new \Slim\Http\Request($env); - $headers = $req->headers(); - $this->assertInstanceOf('\Slim\Http\Headers', $headers); - $this->assertEquals('gzip', $req->headers('HTTP_ACCEPT_ENCODING')); - $this->assertEquals('gzip', $req->headers('HTTP-ACCEPT-ENCODING')); - $this->assertEquals('gzip', $req->headers('http_accept_encoding')); - $this->assertEquals('gzip', $req->headers('http-accept-encoding')); - $this->assertEquals('gzip', $req->headers('ACCEPT_ENCODING')); - $this->assertEquals('gzip', $req->headers('ACCEPT-ENCODING')); - $this->assertEquals('gzip', $req->headers('accept_encoding')); - $this->assertEquals('gzip', $req->headers('accept-encoding')); - $this->assertNull($req->headers('foo')); - } - - /** - * Test accurately removes HTTP_ prefix from input header name - */ - public function testHeaderRemovesHttpPrefix() - { - $env = \Slim\Environment::mock(array( - 'X_HTTP_METHOD_OVERRIDE' => 'PUT', - 'CONTENT_TYPE' => 'application/json' - )); - //fwrite(fopen('php://stdout', 'w'), print_r($env, true)); - $req = new \Slim\Http\Request($env); - $this->assertEquals('PUT', $req->headers('X_HTTP_METHOD_OVERRIDE')); - $this->assertNull($req->headers('X_METHOD_OVERRIDE')); //<-- Ensures `HTTP_` is not removed if not prefix - $this->assertEquals('application/json', $req->headers('HTTP_CONTENT_TYPE')); //<-- Ensures `HTTP_` is removed if prefix - } - - /** - * Test get body - */ - public function testGetBodyWhenExists() - { - $env = \Slim\Environment::mock(array( - 'slim.input' => 'foo=bar&abc=123', - 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', - 'CONTENT_LENGTH' => 15 - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('foo=bar&abc=123', $req->getBody()); - } - - /** - * Test get body - */ - public function testGetBodyWhenNotExists() - { - $env = \Slim\Environment::mock(); - $req = new \Slim\Http\Request($env); - $this->assertEquals('', $req->getBody()); - } - - /** - * Test get content type - */ - public function testGetContentTypeWhenExists() - { - $env = \Slim\Environment::mock(array( - 'slim.input' => '', - 'CONTENT_TYPE' => 'application/json; charset=ISO-8859-4' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('application/json; charset=ISO-8859-4', $req->getContentType()); - } - - /** - * Test get content type for built-in PHP server - */ - public function testGetContentTypeForBuiltInServer() - { - $env = \Slim\Environment::mock(array( - 'slim.input' => '', - 'HTTP_CONTENT_TYPE' => 'application/json; charset=ISO-8859-4' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('application/json; charset=ISO-8859-4', $req->getContentType()); - } - - /** - * Test get content type - */ - public function testGetContentTypeWhenNotExists() - { - $env = \Slim\Environment::mock(); - $req = new \Slim\Http\Request($env); - $this->assertNull($req->getContentType()); - } - - /** - * Test get content type with built-in server - */ - public function testGetContentTypeWithBuiltInServer() - { - $env = \Slim\Environment::mock(array( - 'slim.input' => '', - 'HTTP_CONTENT_TYPE' => 'application/json; charset=ISO-8859-4' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('application/json; charset=ISO-8859-4', $req->getContentType()); - } - - /** - * Test get media type - */ - public function testGetMediaTypeWhenExists() - { - $env = \Slim\Environment::mock(array( - 'CONTENT_TYPE' => 'application/json;charset=utf-8' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('application/json', $req->getMediaType()); - } - - /** - * Test get media type - */ - public function testGetMediaTypeWhenNotExists() - { - $env = \Slim\Environment::mock(); - $req = new \Slim\Http\Request($env); - $this->assertNull($req->getMediaType()); - } - - /** - * Test get media type - */ - public function testGetMediaTypeWhenNoParamsExist() - { - $env = \Slim\Environment::mock(array( - 'slim.input' => '', - 'CONTENT_TYPE' => 'application/json' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('application/json', $req->getMediaType()); - } - - /** - * Test get media type params - */ - public function testGetMediaTypeParams() - { - $env = \Slim\Environment::mock(array( - 'CONTENT_TYPE' => 'application/json; charset=ISO-8859-4' - )); - $req = new \Slim\Http\Request($env); - $params = $req->getMediaTypeParams(); - $this->assertEquals(1, count($params)); - $this->assertArrayHasKey('charset', $params); - $this->assertEquals('ISO-8859-4', $params['charset']); - } - - /** - * Test get media type params - */ - public function testGetMediaTypeParamsWhenNotExists() - { - $env = \Slim\Environment::mock(); - $req = new \Slim\Http\Request($env); - $params = $req->getMediaTypeParams(); - $this->assertTrue(is_array($params)); - $this->assertEquals(0, count($params)); - } - - /** - * Test get content charset - */ - public function testGetContentCharset() - { - $env = \Slim\Environment::mock(array( - 'slim.input' => '', - 'CONTENT_TYPE' => 'application/json; charset=ISO-8859-4' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('ISO-8859-4', $req->getContentCharset()); - } - - /** - * Test get content charset - */ - public function testGetContentCharsetWhenNotExists() - { - $env = \Slim\Environment::mock(array( - 'slim.input' => '', - 'CONTENT_TYPE' => 'application/json' - )); - $req = new \Slim\Http\Request($env); - $this->assertNull($req->getContentCharset()); - } - - /** - * Test get content length - */ - public function testGetContentLength() - { - $env = \Slim\Environment::mock(array( - 'slim.input' => 'foo=bar&abc=123', - 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', - 'CONTENT_LENGTH' => 15 - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals(15, $req->getContentLength()); - } - - /** - * Test get content length - */ - public function testGetContentLengthWhenNotExists() - { - $env = \Slim\Environment::mock(array( - 'slim.input' => '', - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals(0, $req->getContentLength()); - } - - /** - * Test get host - */ - public function testGetHost() - { - $env = \Slim\Environment::mock(array( - 'SERVER_NAME' => 'slim', - 'HTTP_HOST' => 'slimframework.com' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('slimframework.com', $req->getHost()); //Uses HTTP_HOST if available - } - - /** - * Test get host when it has a port number - */ - public function testGetHostAndStripPort() - { - $env = \Slim\Environment::mock(array( - 'SERVER_NAME' => 'slim', - 'HTTP_HOST' => 'slimframework.com:80' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('slimframework.com', $req->getHost()); //Uses HTTP_HOST if available - } - - /** - * Test get host - */ - public function testGetHostWhenNotExists() - { - $env = \Slim\Environment::mock(array( - 'SERVER_NAME' => 'slim', - 'HTTP_HOST' => 'slimframework.com' - )); - unset($env['HTTP_HOST']); - $req = new \Slim\Http\Request($env); - $this->assertEquals('slim', $req->getHost()); //Uses SERVER_NAME as backup - } - - /** - * Test get host with port - */ - public function testGetHostWithPort() - { - $env = \Slim\Environment::mock(array( - 'HTTP_HOST' => 'slimframework.com', - 'SERVER_NAME' => 'slim', - 'SERVER_PORT' => 80, - 'slim.url_scheme' => 'http' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('slimframework.com:80', $req->getHostWithPort()); - } - - /** - * Test get host with port doesn't duplicate port numbers - */ - public function testGetHostDoesntDuplicatePort() - { - $env = \Slim\Environment::mock(array( - 'HTTP_HOST' => 'slimframework.com:80', - 'SERVER_NAME' => 'slim', - 'SERVER_PORT' => 80, - 'slim.url_scheme' => 'http' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('slimframework.com:80', $req->getHostWithPort()); - } - - /** - * Test get port - */ - public function testGetPort() - { - $env = \Slim\Environment::mock(array( - 'SERVER_PORT' => 80 - )); - $req = new \Slim\Http\Request($env); - $this->assertTrue(is_integer($req->getPort())); - $this->assertEquals(80, $req->getPort()); - } - - /** - * Test get scheme - */ - public function testGetSchemeIfHttp() - { - $env = \Slim\Environment::mock(array( - 'slim.url_scheme' => 'http' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('http', $req->getScheme()); - } - - /** - * Test get scheme - */ - public function testGetSchemeIfHttps() - { - $env = \Slim\Environment::mock(array( - 'slim.url_scheme' => 'https', - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('https', $req->getScheme()); - } - - /** - * Test get [script name, root uri, path, path info, resource uri] in subdirectory without htaccess - */ - public function testAppPathsInSubdirectoryWithoutHtaccess() - { - $env = \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo/index.php', //<-- Physical - 'PATH_INFO' => '/bar/xyz', //<-- Virtual - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('/foo/index.php', $req->getScriptName()); - $this->assertEquals('/foo/index.php', $req->getRootUri()); - $this->assertEquals('/foo/index.php/bar/xyz', $req->getPath()); - $this->assertEquals('/bar/xyz', $req->getPathInfo()); - $this->assertEquals('/bar/xyz', $req->getResourceUri()); - } - - /** - * Test get [script name, root uri, path, path info, resource uri] in subdirectory with htaccess - */ - public function testAppPathsInSubdirectoryWithHtaccess() - { - $env = \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar/xyz', //<-- Virtual - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('/foo', $req->getScriptName()); - $this->assertEquals('/foo', $req->getRootUri()); - $this->assertEquals('/foo/bar/xyz', $req->getPath()); - $this->assertEquals('/bar/xyz', $req->getPathInfo()); - $this->assertEquals('/bar/xyz', $req->getResourceUri()); - } - - /** - * Test get [script name, root uri, path, path info, resource uri] in root directory without htaccess - */ - public function testAppPathsInRootDirectoryWithoutHtaccess() - { - $env = \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/index.php', //<-- Physical - 'PATH_INFO' => '/bar/xyz', //<-- Virtual - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('/index.php', $req->getScriptName()); - $this->assertEquals('/index.php', $req->getRootUri()); - $this->assertEquals('/index.php/bar/xyz', $req->getPath()); - $this->assertEquals('/bar/xyz', $req->getPathInfo()); - $this->assertEquals('/bar/xyz', $req->getResourceUri()); - } - - /** - * Test get [script name, root uri, path, path info, resource uri] in root directory with htaccess - */ - public function testAppPathsInRootDirectoryWithHtaccess() - { - $env = \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '', //<-- Physical - 'PATH_INFO' => '/bar/xyz', //<-- Virtual - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('', $req->getScriptName()); - $this->assertEquals('', $req->getRootUri()); - $this->assertEquals('/bar/xyz', $req->getPath()); - $this->assertEquals('/bar/xyz', $req->getPathInfo()); - $this->assertEquals('/bar/xyz', $req->getResourceUri()); - } - - /** - * Test get URL - */ - public function testGetUrl() - { - $env = \Slim\Environment::mock(array( - 'HTTP_HOST' => 'slimframework.com', - 'SERVER_NAME' => 'slim', - 'SERVER_PORT' => 80, - 'slim.url_scheme' => 'http' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('http://slimframework.com', $req->getUrl()); - } - - /** - * Test get URL - */ - public function testGetUrlWithCustomPort() - { - $env = \Slim\Environment::mock(array( - 'HTTP_HOST' => 'slimframework.com', - 'SERVER_NAME' => 'slim', - 'SERVER_PORT' => 8080, - 'slim.url_scheme' => 'http' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('http://slimframework.com:8080', $req->getUrl()); - } - - /** - * Test get URL - */ - public function testGetUrlWithHttps() - { - $env = \Slim\Environment::mock(array( - 'HTTP_HOST' => 'slimframework.com', - 'SERVER_NAME' => 'slim', - 'SERVER_PORT' => 443, - 'slim.url_scheme' => 'https' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('https://slimframework.com', $req->getUrl()); - } - - /** - * Test get IP - * @dataProvider dataTestIp - */ - public function testGetIp(array $server, $expected) - { - $env = \Slim\Environment::mock($server); - $req = new \Slim\Http\Request($env); - $this->assertEquals($expected, $req->getIp()); - } - - public function dataTestIp() - { - return array( - array(array('REMOTE_ADDR' => '127.0.0.1'), '127.0.0.1'), - array(array('REMOTE_ADDR' => '127.0.0.1', 'CLIENT_IP' => '127.0.0.2'), '127.0.0.2'), - array(array('REMOTE_ADDR' => '127.0.0.1', 'CLIENT_IP' => '127.0.0.2', 'X_FORWARDED_FOR' => '127.0.0.3'), '127.0.0.3'), - array(array('REMOTE_ADDR' => '127.0.0.1', 'CLIENT_IP' => '127.0.0.2', 'HTTP_X_FORWARDED_FOR' => '127.0.0.4'), '127.0.0.4'), - array(array('REMOTE_ADDR' => '127.0.0.1', 'CLIENT_IP' => '127.0.0.2', 'X_FORWARDED_FOR' => '127.0.0.3', 'HTTP_X_FORWARDED_FOR' => '127.0.0.4'), '127.0.0.3'), - ); - } - - /** - * Test get referer - */ - public function testGetReferrer() - { - $env = \Slim\Environment::mock(array( - 'HTTP_REFERER' => 'http://foo.com' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('http://foo.com', $req->getReferrer()); - $this->assertEquals('http://foo.com', $req->getReferer()); - } - - /** - * Test get referer - */ - public function testGetReferrerWhenNotExists() - { - $env = \Slim\Environment::mock(); - $req = new \Slim\Http\Request($env); - $this->assertNull($req->getReferrer()); - $this->assertNull($req->getReferer()); - } - - /** - * Test get user agent string - */ - public function testGetUserAgent() - { - $env = \Slim\Environment::mock(array( - 'HTTP_USER_AGENT' => 'user-agent-string' - )); - $req = new \Slim\Http\Request($env); - $this->assertEquals('user-agent-string', $req->getUserAgent()); - } - - /** - * Test get user agent string when not set - */ - public function testGetUserAgentWhenNotExists() - { - $env = \Slim\Environment::mock(); - unset($env['HTTP_USER_AGENT']); - $req = new \Slim\Http\Request($env); - $this->assertNull($req->getUserAgent()); - } -} diff --git a/vendor/slim/slim/tests/Http/ResponseTest.php b/vendor/slim/slim/tests/Http/ResponseTest.php deleted file mode 100644 index c251fa1..0000000 --- a/vendor/slim/slim/tests/Http/ResponseTest.php +++ /dev/null @@ -1,271 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -class ResponseTest extends PHPUnit_Framework_TestCase -{ - public function testConstructWithoutArgs() - { - $res = new \Slim\Http\Response(); - - $this->assertAttributeEquals(200, 'status', $res); - $this->assertAttributeEquals('', 'body', $res); - } - - public function testConstructWithArgs() - { - $res = new \Slim\Http\Response('Foo', 201); - - $this->assertAttributeEquals(201, 'status', $res); - $this->assertAttributeEquals('Foo', 'body', $res); - } - - public function testGetStatus() - { - $res = new \Slim\Http\Response(); - - $this->assertEquals(200, $res->getStatus()); - } - - public function testSetStatus() - { - $res = new \Slim\Http\Response(); - $res->setStatus(301); - - $this->assertAttributeEquals(301, 'status', $res); - } - - /** - * DEPRECATION WARNING! - */ - public function testStatusGetOld() - { - $res = new \Slim\Http\Response('', 201); - $this->assertEquals(201, $res->status()); - } - - /** - * DEPRECATION WARNING! - */ - public function testStatusSetOld() - { - $res = new \Slim\Http\Response(); - $prop = new \ReflectionProperty($res, 'status'); - $prop->setAccessible(true); - $res->status(301); - - $this->assertEquals(301, $prop->getValue($res)); - } - - public function testGetBody() - { - $res = new \Slim\Http\Response(); - $property = new \ReflectionProperty($res, 'body'); - $property->setAccessible(true); - $property->setValue($res, 'foo'); - - $this->assertEquals('foo', $res->getBody()); - } - - public function testSetBody() - { - $res = new \Slim\Http\Response('bar'); - $res->setBody('foo'); // <-- Should replace body - - $this->assertAttributeEquals('foo', 'body', $res); - } - - public function testWrite() - { - $res = new \Slim\Http\Response(); - $property = new \ReflectionProperty($res, 'body'); - $property->setAccessible(true); - $property->setValue($res, 'foo'); - $res->write('bar'); // <-- Should append to body - - $this->assertAttributeEquals('foobar', 'body', $res); - } - - public function testLength() - { - $res = new \Slim\Http\Response('foo'); // <-- Sets body and length - - $this->assertEquals(3, $res->getLength()); - } - - public function testFinalize() - { - $res = new \Slim\Http\Response(); - $resFinal = $res->finalize(); - - $this->assertTrue(is_array($resFinal)); - $this->assertEquals(3, count($resFinal)); - $this->assertEquals(200, $resFinal[0]); - $this->assertInstanceOf('\Slim\Http\Headers', $resFinal[1]); - $this->assertEquals('', $resFinal[2]); - } - - public function testFinalizeWithEmptyBody() - { - $res = new \Slim\Http\Response('Foo', 304); - $resFinal = $res->finalize(); - - $this->assertEquals('', $resFinal[2]); - } - - public function testRedirect() - { - $res = new \Slim\Http\Response(); - $res->redirect('/foo'); - - $pStatus = new \ReflectionProperty($res, 'status'); - $pStatus->setAccessible(true); - - $this->assertEquals(302, $pStatus->getValue($res)); - $this->assertEquals('/foo', $res->headers['Location']); - } - - public function testIsEmpty() - { - $r1 = new \Slim\Http\Response(); - $r2 = new \Slim\Http\Response(); - $r1->setStatus(404); - $r2->setStatus(201); - $this->assertFalse($r1->isEmpty()); - $this->assertTrue($r2->isEmpty()); - } - - public function testIsClientError() - { - $r1 = new \Slim\Http\Response(); - $r2 = new \Slim\Http\Response(); - $r1->setStatus(404); - $r2->setStatus(500); - $this->assertTrue($r1->isClientError()); - $this->assertFalse($r2->isClientError()); - } - - public function testIsForbidden() - { - $r1 = new \Slim\Http\Response(); - $r2 = new \Slim\Http\Response(); - $r1->setStatus(403); - $r2->setStatus(500); - $this->assertTrue($r1->isForbidden()); - $this->assertFalse($r2->isForbidden()); - } - - public function testIsInformational() - { - $r1 = new \Slim\Http\Response(); - $r2 = new \Slim\Http\Response(); - $r1->setStatus(100); - $r2->setStatus(200); - $this->assertTrue($r1->isInformational()); - $this->assertFalse($r2->isInformational()); - } - - public function testIsNotFound() - { - $r1 = new \Slim\Http\Response(); - $r2 = new \Slim\Http\Response(); - $r1->setStatus(404); - $r2->setStatus(200); - $this->assertTrue($r1->isNotFound()); - $this->assertFalse($r2->isNotFound()); - } - - public function testIsOk() - { - $r1 = new \Slim\Http\Response(); - $r2 = new \Slim\Http\Response(); - $r1->setStatus(200); - $r2->setStatus(201); - $this->assertTrue($r1->isOk()); - $this->assertFalse($r2->isOk()); - } - - public function testIsSuccessful() - { - $r1 = new \Slim\Http\Response(); - $r2 = new \Slim\Http\Response(); - $r3 = new \Slim\Http\Response(); - $r1->setStatus(200); - $r2->setStatus(201); - $r3->setStatus(302); - $this->assertTrue($r1->isSuccessful()); - $this->assertTrue($r2->isSuccessful()); - $this->assertFalse($r3->isSuccessful()); - } - - public function testIsRedirect() - { - $r1 = new \Slim\Http\Response(); - $r2 = new \Slim\Http\Response(); - $r1->setStatus(307); - $r2->setStatus(304); - $this->assertTrue($r1->isRedirect()); - $this->assertFalse($r2->isRedirect()); - } - - public function testIsRedirection() - { - $r1 = new \Slim\Http\Response(); - $r2 = new \Slim\Http\Response(); - $r3 = new \Slim\Http\Response(); - $r1->setStatus(307); - $r2->setStatus(304); - $r3->setStatus(200); - $this->assertTrue($r1->isRedirection()); - $this->assertTrue($r2->isRedirection()); - $this->assertFalse($r3->isRedirection()); - } - - public function testIsServerError() - { - $r1 = new \Slim\Http\Response(); - $r2 = new \Slim\Http\Response(); - $r1->setStatus(500); - $r2->setStatus(400); - $this->assertTrue($r1->isServerError()); - $this->assertFalse($r2->isServerError()); - } - - public function testMessageForCode() - { - $this->assertEquals('200 OK', \Slim\Http\Response::getMessageForCode(200)); - } - - public function testMessageForCodeWithInvalidCode() - { - $this->assertNull(\Slim\Http\Response::getMessageForCode(600)); - } -} diff --git a/vendor/slim/slim/tests/Http/UtilTest.php b/vendor/slim/slim/tests/Http/UtilTest.php deleted file mode 100644 index 9abcfab..0000000 --- a/vendor/slim/slim/tests/Http/UtilTest.php +++ /dev/null @@ -1,445 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -class SlimHttpUtilTest extends PHPUnit_Framework_TestCase -{ - /** - * Test strip slashes when magic quotes disabled - */ - public function testStripSlashesWithoutMagicQuotes() - { - $data = "This should have \"quotes\" in it"; - $stripped = \Slim\Http\Util::stripSlashesIfMagicQuotes($data, false); - $this->assertEquals($data, $stripped); - } - - /** - * Test strip slashes from array when magic quotes disabled - */ - public function testStripSlashesFromArrayWithoutMagicQuotes() - { - $data = array("This should have \"quotes\" in it", "And this \"too\" has quotes"); - $stripped = \Slim\Http\Util::stripSlashesIfMagicQuotes($data, false); - $this->assertEquals($data, $stripped); - } - - /** - * Test strip slashes when magic quotes enabled - */ - public function testStripSlashesWithMagicQuotes() - { - $data = "This should have \"quotes\" in it"; - $stripped = \Slim\Http\Util::stripSlashesIfMagicQuotes($data, true); - $this->assertEquals('This should have "quotes" in it', $stripped); - } - - /** - * Test strip slashes from array when magic quotes enabled - */ - public function testStripSlashesFromArrayWithMagicQuotes() - { - $data = array("This should have \"quotes\" in it", "And this \"too\" has quotes"); - $stripped = \Slim\Http\Util::stripSlashesIfMagicQuotes($data, true); - $this->assertEquals($data = array('This should have "quotes" in it', 'And this "too" has quotes'), $stripped); - } - - /** - * Test encrypt and decrypt with valid data - */ - public function testEncryptAndDecryptWithValidData() - { - $data = 'foo'; - $key = 'secret'; - $iv = md5('initializationVector'); - $encrypted = \Slim\Http\Util::encrypt($data, $key, $iv); - $decrypted = \Slim\Http\Util::decrypt($encrypted, $key, $iv); - $this->assertEquals($data, $decrypted); - $this->assertTrue($data !== $encrypted); - } - - /** - * Test encrypt when data is empty string - */ - public function testEncryptWhenDataIsEmptyString() - { - $data = ''; - $key = 'secret'; - $iv = md5('initializationVector'); - $encrypted = \Slim\Http\Util::encrypt($data, $key, $iv); - $this->assertEquals('', $encrypted); - } - - /** - * Test decrypt when data is empty string - */ - public function testDecryptWhenDataIsEmptyString() - { - $data = ''; - $key = 'secret'; - $iv = md5('initializationVector'); - $decrypted = \Slim\Http\Util::decrypt($data, $key, $iv); - $this->assertEquals('', $decrypted); - } - - /** - * Test encrypt when IV and key sizes are too long - */ - public function testEncryptAndDecryptWhenKeyAndIvAreTooLong() - { - $data = 'foo'; - $key = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'; - $iv = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'; - $encrypted = \Slim\Http\Util::encrypt($data, $key, $iv); - $decrypted = \Slim\Http\Util::decrypt($encrypted, $key, $iv); - $this->assertEquals($data, $decrypted); - $this->assertTrue($data !== $encrypted); - } - - public function testEncodeAndDecodeSecureCookieWithValidData() - { - //Prepare cookie value - $value = 'foo'; - $expires = time() + 86400; - $secret = 'password'; - $algorithm = MCRYPT_RIJNDAEL_256; - $mode = MCRYPT_MODE_CBC; - $encodedValue = \Slim\Http\Util::encodeSecureCookie($value, $expires, $secret, $algorithm, $mode); - $decodedValue = \Slim\Http\Util::decodeSecureCookie($encodedValue, $secret, $algorithm, $mode); - - //Test secure cookie value - $parts = explode('|', $encodedValue); - $this->assertEquals(3, count($parts)); - $this->assertEquals($expires, $parts[0]); - $this->assertEquals($value, $decodedValue); - } - - /** - * Test encode/decode secure cookie with old expiration - * - * In this test, the expiration date is purposefully set to a time before now. - * When decoding the encoded cookie value, FALSE is returned since the cookie - * will have expired before it is decoded. - */ - public function testEncodeAndDecodeSecureCookieWithOldExpiration() - { - $value = 'foo'; - $expires = time() - 100; - $secret = 'password'; - $algorithm = MCRYPT_RIJNDAEL_256; - $mode = MCRYPT_MODE_CBC; - $encodedValue = \Slim\Http\Util::encodeSecureCookie($value, $expires, $secret, $algorithm, $mode); - $decodedValue = \Slim\Http\Util::decodeSecureCookie($encodedValue, $secret, $algorithm, $mode); - $this->assertFalse($decodedValue); - } - - /** - * Test encode/decode secure cookie with tampered data - * - * In this test, the encoded data is purposefully changed to simulate someone - * tampering with the client-side cookie data. When decoding the encoded cookie value, - * FALSE is returned since the verification key will not match. - */ - public function testEncodeAndDecodeSecureCookieWithTamperedData() - { - $value = 'foo'; - $expires = time() + 86400; - $secret = 'password'; - $algorithm = MCRYPT_RIJNDAEL_256; - $mode = MCRYPT_MODE_CBC; - $encodedValue = \Slim\Http\Util::encodeSecureCookie($value, $expires, $secret, $algorithm, $mode); - $encodedValueParts = explode('|', $encodedValue); - $encodedValueParts[1] = $encodedValueParts[1] . 'changed'; - $encodedValue = implode('|', $encodedValueParts); - $decodedValue = \Slim\Http\Util::decodeSecureCookie($encodedValue, $secret, $algorithm, $mode); - $this->assertFalse($decodedValue); - } - - public function testSetCookieHeaderWithNameAndValue() - { - $name = 'foo'; - $value = 'bar'; - $header = array(); - \Slim\Http\Util::setCookieHeader($header, $name, $value); - $this->assertEquals('foo=bar', $header['Set-Cookie']); - } - - public function testSetCookieHeaderWithNameAndValueWhenCookieAlreadySet() - { - $name = 'foo'; - $value = 'bar'; - $header = array('Set-Cookie' => 'one=two'); - \Slim\Http\Util::setCookieHeader($header, $name, $value); - $this->assertEquals("one=two\nfoo=bar", $header['Set-Cookie']); - } - - public function testSetCookieHeaderWithNameAndValueAndDomain() - { - $name = 'foo'; - $value = 'bar'; - $domain = 'foo.com'; - $header = array(); - \Slim\Http\Util::setCookieHeader($header, $name, array( - 'value' => $value, - 'domain' => $domain - )); - $this->assertEquals('foo=bar; domain=foo.com', $header['Set-Cookie']); - } - - public function testSetCookieHeaderWithNameAndValueAndDomainAndPath() - { - $name = 'foo'; - $value = 'bar'; - $domain = 'foo.com'; - $path = '/foo'; - $header = array(); - \Slim\Http\Util::setCookieHeader($header, $name, array( - 'value' => $value, - 'domain' => $domain, - 'path' => $path - )); - $this->assertEquals('foo=bar; domain=foo.com; path=/foo', $header['Set-Cookie']); - } - - public function testSetCookieHeaderWithNameAndValueAndDomainAndPathAndExpiresAsString() - { - $name = 'foo'; - $value = 'bar'; - $domain = 'foo.com'; - $path = '/foo'; - $expires = '2 days'; - $expiresFormat = gmdate('D, d-M-Y H:i:s e', strtotime($expires)); - $header = array(); - \Slim\Http\Util::setCookieHeader($header, $name, array( - 'value' => $value, - 'domain' => $domain, - 'path' => '/foo', - 'expires' => $expires - )); - $this->assertEquals('foo=bar; domain=foo.com; path=/foo; expires=' . $expiresFormat, $header['Set-Cookie']); - } - - public function testSetCookieHeaderWithNameAndValueAndDomainAndPathAndExpiresAsInteger() - { - $name = 'foo'; - $value = 'bar'; - $domain = 'foo.com'; - $path = '/foo'; - $expires = strtotime('2 days'); - $expiresFormat = gmdate('D, d-M-Y H:i:s e', $expires); - $header = array(); - \Slim\Http\Util::setCookieHeader($header, $name, array( - 'value' => $value, - 'domain' => $domain, - 'path' => '/foo', - 'expires' => $expires - )); - $this->assertEquals('foo=bar; domain=foo.com; path=/foo; expires=' . $expiresFormat, $header['Set-Cookie']); - } - - public function testSetCookieHeaderWithNameAndValueAndDomainAndPathAndExpiresAsZero() - { - $name = 'foo'; - $value = 'bar'; - $domain = 'foo.com'; - $path = '/foo'; - $expires = 0; - $header = array(); - \Slim\Http\Util::setCookieHeader($header, $name, array( - 'value' => $value, - 'domain' => $domain, - 'path' => '/foo', - 'expires' => $expires - )); - $this->assertEquals('foo=bar; domain=foo.com; path=/foo', $header['Set-Cookie']); - } - - public function testSetCookieHeaderWithNameAndValueAndDomainAndPathAndExpiresAndSecure() - { - $name = 'foo'; - $value = 'bar'; - $domain = 'foo.com'; - $path = '/foo'; - $expires = strtotime('2 days'); - $expiresFormat = gmdate('D, d-M-Y H:i:s e', $expires); - $secure = true; - $header = array(); - \Slim\Http\Util::setCookieHeader($header, $name, array( - 'value' => $value, - 'domain' => $domain, - 'path' => '/foo', - 'expires' => $expires, - 'secure' => $secure - )); - $this->assertEquals('foo=bar; domain=foo.com; path=/foo; expires=' . $expiresFormat . '; secure', $header['Set-Cookie']); - } - - public function testSetCookieHeaderWithNameAndValueAndDomainAndPathAndExpiresAndSecureAndHttpOnly() - { - $name = 'foo'; - $value = 'bar'; - $domain = 'foo.com'; - $path = '/foo'; - $expires = strtotime('2 days'); - $expiresFormat = gmdate('D, d-M-Y H:i:s e', $expires); - $secure = true; - $httpOnly = true; - $header = array(); - \Slim\Http\Util::setCookieHeader($header, $name, array( - 'value' => $value, - 'domain' => $domain, - 'path' => '/foo', - 'expires' => $expires, - 'secure' => $secure, - 'httponly' => $httpOnly - )); - $this->assertEquals('foo=bar; domain=foo.com; path=/foo; expires=' . $expiresFormat . '; secure; HttpOnly', $header['Set-Cookie']); - } - - /** - * Test serializeCookies and decrypt with string expires - * - * In this test a cookie with a string typed value for 'expires' is set, - * which should be parsed by `strtotime` to a timestamp when it's added to - * the headers; this timestamp should then be correctly parsed, and the - * value correctly decrypted, by `decodeSecureCookie`. - */ - public function testSerializeCookiesAndDecryptWithStringExpires() - { - $value = 'bar'; - - $headers = new \Slim\Http\Headers(); - - $settings = array( - 'cookies.encrypt' => true, - 'cookies.secret_key' => 'secret', - 'cookies.cipher' => MCRYPT_RIJNDAEL_256, - 'cookies.cipher_mode' => MCRYPT_MODE_CBC - ); - - $cookies = new \Slim\Http\Cookies(); - $cookies->set('foo', array( - 'value' => $value, - 'expires' => '1 hour' - )); - - \Slim\Http\Util::serializeCookies($headers, $cookies, $settings); - - $encrypted = $headers->get('Set-Cookie'); - $encrypted = strstr($encrypted, ';', true); - $encrypted = urldecode(substr(strstr($encrypted, '='), 1)); - - $decrypted = \Slim\Http\Util::decodeSecureCookie( - $encrypted, - $settings['cookies.secret_key'], - $settings['cookies.cipher'], - $settings['cookies.cipher_mode'] - ); - - $this->assertEquals($value, $decrypted); - $this->assertTrue($value !== $encrypted); - } - - public function testDeleteCookieHeaderWithSurvivingCookie() - { - $header = array('Set-Cookie' => "foo=bar\none=two"); - \Slim\Http\Util::deleteCookieHeader($header, 'foo'); - $this->assertEquals(1, preg_match("@^one=two\nfoo=; expires=@", $header['Set-Cookie'])); - } - - public function testDeleteCookieHeaderWithoutSurvivingCookie() - { - $header = array('Set-Cookie' => "foo=bar"); - \Slim\Http\Util::deleteCookieHeader($header, 'foo'); - $this->assertEquals(1, preg_match("@foo=; expires=@", $header['Set-Cookie'])); - } - - public function testDeleteCookieHeaderWithMatchingDomain() - { - $header = array('Set-Cookie' => "foo=bar; domain=foo.com"); - \Slim\Http\Util::deleteCookieHeader($header, 'foo', array( - 'domain' => 'foo.com' - )); - $this->assertEquals(1, preg_match("@foo=; domain=foo.com; expires=@", $header['Set-Cookie'])); - } - - public function testDeleteCookieHeaderWithoutMatchingDomain() - { - $header = array('Set-Cookie' => "foo=bar; domain=foo.com"); - \Slim\Http\Util::deleteCookieHeader($header, 'foo', array( - 'domain' => 'bar.com' - )); - $this->assertEquals(1, preg_match("@foo=bar; domain=foo\.com\nfoo=; domain=bar\.com@", $header['Set-Cookie'])); - } - - /** - * Test parses Cookie: HTTP header - */ - public function testParsesCookieHeader() - { - $header = 'foo=bar; one=two; colors=blue'; - $result = \Slim\Http\Util::parseCookieHeader($header); - $this->assertEquals(3, count($result)); - $this->assertEquals('bar', $result['foo']); - $this->assertEquals('two', $result['one']); - $this->assertEquals('blue', $result['colors']); - } - - /** - * Test parses Cookie: HTTP header with `=` in the cookie value - */ - public function testParsesCookieHeaderWithEqualSignInValue() - { - $header = 'foo=bar; one=two=; colors=blue'; - $result = \Slim\Http\Util::parseCookieHeader($header); - $this->assertEquals(3, count($result)); - $this->assertEquals('bar', $result['foo']); - $this->assertEquals('two=', $result['one']); - $this->assertEquals('blue', $result['colors']); - } - - public function testParsesCookieHeaderWithCommaSeparator() - { - $header = 'foo=bar, one=two, colors=blue'; - $result = \Slim\Http\Util::parseCookieHeader($header); - $this->assertEquals(3, count($result)); - $this->assertEquals('bar', $result['foo']); - $this->assertEquals('two', $result['one']); - $this->assertEquals('blue', $result['colors']); - } - - public function testPrefersLeftmostCookieWhenManyCookiesWithSameName() - { - $header = 'foo=bar; foo=beer'; - $result = \Slim\Http\Util::parseCookieHeader($header); - $this->assertEquals('bar', $result['foo']); - } -} diff --git a/vendor/slim/slim/tests/LogTest.php b/vendor/slim/slim/tests/LogTest.php deleted file mode 100644 index 28f99e8..0000000 --- a/vendor/slim/slim/tests/LogTest.php +++ /dev/null @@ -1,208 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -class MyWriter -{ - public function write( $object, $level ) - { - echo (string) $object; - - return true; - } -} - -class LogTest extends PHPUnit_Framework_TestCase -{ - public function testEnabled() - { - $log = new \Slim\Log(new MyWriter()); - $this->assertTrue($log->isEnabled()); //<-- Default case - $log->setEnabled(true); - $this->assertTrue($log->isEnabled()); - $log->setEnabled(false); - $this->assertFalse($log->isEnabled()); - } - - public function testGetLevel() - { - $log = new \Slim\Log(new MyWriter()); - $this->assertEquals(\Slim\Log::DEBUG, $log->getLevel()); - } - - public function testSetLevel() - { - $log = new \Slim\Log(new MyWriter()); - $log->setLevel(\Slim\Log::WARN); - $this->assertEquals(\Slim\Log::WARN, $log->getLevel()); - } - - public function testSetInvalidLevel() - { - $this->setExpectedException('InvalidArgumentException'); - $log = new \Slim\Log(new MyWriter()); - $log->setLevel(\Slim\Log::DEBUG + 1); - } - - public function testLogDebug() - { - $this->expectOutputString('Debug'); - $log = new \Slim\Log(new MyWriter()); - $result = $log->debug('Debug'); - $this->assertTrue($result); - } - - public function testLogDebugExcludedByLevel() - { - $log = new \Slim\Log(new MyWriter()); - $log->setLevel(\Slim\Log::INFO); - $this->assertFalse($log->debug('Debug')); - } - - public function testLogInfo() - { - $this->expectOutputString('Info'); - $log = new \Slim\Log(new MyWriter()); - $result = $log->info('Info'); - $this->assertTrue($result); - } - - public function testLogInfoExcludedByLevel() - { - $log = new \Slim\Log(new MyWriter()); - $log->setLevel(\Slim\Log::NOTICE); - $this->assertFalse($log->info('Info')); - } - - public function testLogNotice() - { - $this->expectOutputString('Notice'); - $log = new \Slim\Log(new MyWriter()); - $result = $log->notice('Notice'); - $this->assertTrue($result); - } - - public function testLogNoticeExcludedByLevel() - { - $log = new \Slim\Log(new MyWriter()); - $log->setLevel(\Slim\Log::WARN); - $this->assertFalse($log->info('Info')); - } - - public function testLogWarn() - { - $this->expectOutputString('Warn'); - $log = new \Slim\Log(new MyWriter()); - $result = $log->warning('Warn'); - $this->assertTrue($result); - } - - public function testLogWarnExcludedByLevel() - { - $log = new \Slim\Log(new MyWriter()); - $log->setLevel(\Slim\Log::ERROR); - $this->assertFalse($log->warning('Warn')); - } - - public function testLogError() - { - $this->expectOutputString('Error'); - $log = new \Slim\Log(new MyWriter()); - $result = $log->error('Error'); - $this->assertTrue($result); - } - - public function testLogErrorExcludedByLevel() - { - $log = new \Slim\Log(new MyWriter()); - $log->setLevel(\Slim\Log::CRITICAL); - $this->assertFalse($log->error('Error')); - } - - public function testLogCritical() - { - $this->expectOutputString('Critical'); - $log = new \Slim\Log(new MyWriter()); - $result = $log->critical('Critical'); - $this->assertTrue($result); - } - - public function testLogCriticalExcludedByLevel() - { - $log = new \Slim\Log(new MyWriter()); - $log->setLevel(\Slim\Log::ALERT); - $this->assertFalse($log->critical('Critical')); - } - - public function testLogAlert() - { - $this->expectOutputString('Alert'); - $log = new \Slim\Log(new MyWriter()); - $result = $log->alert('Alert'); - $this->assertTrue($result); - } - - public function testLogAlertExcludedByLevel() - { - $log = new \Slim\Log(new MyWriter()); - $log->setLevel(\Slim\Log::EMERGENCY); - $this->assertFalse($log->alert('Alert')); - } - - public function testLogEmergency() - { - $this->expectOutputString('Emergency'); - $log = new \Slim\Log(new MyWriter()); - $result = $log->emergency('Emergency'); - $this->assertTrue($result); - } - - public function testInterpolateMessage() - { - $this->expectOutputString('Hello Slim !'); - $log = new \Slim\Log(new MyWriter()); - $result = $log->debug( - 'Hello {framework} !', - array('framework' => "Slim") - ); - $this->assertTrue($result); - } - - public function testGetAndSetWriter() - { - $writer1 = new MyWriter(); - $writer2 = new MyWriter(); - $log = new \Slim\Log($writer1); - $this->assertSame($writer1, $log->getWriter()); - $log->setWriter($writer2); - $this->assertSame($writer2, $log->getWriter()); - } -} diff --git a/vendor/slim/slim/tests/LogWriterTest.php b/vendor/slim/slim/tests/LogWriterTest.php deleted file mode 100644 index f36009d..0000000 --- a/vendor/slim/slim/tests/LogWriterTest.php +++ /dev/null @@ -1,48 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -class LogWriterTest extends PHPUnit_Framework_TestCase -{ - public function testInstantiation() - { - $this->expectOutputString('Hello!' . PHP_EOL); - $handle = fopen('php://output', 'w'); - $fw = new \Slim\LogWriter($handle); - $this->assertTrue($fw->write('Hello!') > 0); //<-- Returns number of bytes written if successful - } - - public function testInstantiationWithNonResource() - { - $this->setExpectedException('InvalidArgumentException'); - $fw = new \Slim\LogWriter(@fopen('/foo/bar.txt', 'w')); - } -} diff --git a/vendor/slim/slim/tests/Middleware/ContentTypesTest.php b/vendor/slim/slim/tests/Middleware/ContentTypesTest.php deleted file mode 100644 index 4729a41..0000000 --- a/vendor/slim/slim/tests/Middleware/ContentTypesTest.php +++ /dev/null @@ -1,162 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -class ContentTypesTest extends PHPUnit_Framework_TestCase -{ - public function setUp() - { - ob_start(); - } - - public function tearDown() - { - ob_end_clean(); - } - - /** - * Test parses JSON - */ - public function testParsesJson() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'POST', - 'CONTENT_TYPE' => 'application/json', - 'CONENT_LENGTH' => 13, - 'slim.input' => '{"foo":"bar"}' - )); - $s = new \Slim\Slim(); - $s->add(new \Slim\Middleware\ContentTypes()); - $s->run(); - $body = $s->request()->getBody(); - $this->assertTrue(is_array($body)); - $this->assertEquals('bar', $body['foo']); - } - - /** - * Test ignores JSON with errors - */ - public function testParsesJsonWithError() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'POST', - 'CONTENT_TYPE' => 'application/json', - 'CONENT_LENGTH' => 12, - 'slim.input' => '{"foo":"bar"' //<-- This should be incorrect! - )); - $s = new \Slim\Slim(); - $s->add(new \Slim\Middleware\ContentTypes()); - $s->run(); - $body = $s->request()->getBody(); - $this->assertTrue(is_string($body)); - $this->assertEquals('{"foo":"bar"', $body); - } - - /** - * Test parses XML - */ - public function testParsesXml() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'POST', - 'CONTENT_TYPE' => 'application/xml', - 'CONENT_LENGTH' => 68, - 'slim.input' => '1Clive Cussler' - )); - $s = new \Slim\Slim(); - $s->add(new \Slim\Middleware\ContentTypes()); - $s->run(); - $body = $s->request()->getBody(); - $this->assertInstanceOf('SimpleXMLElement', $body); - $this->assertEquals('Clive Cussler', (string) $body->book->author); - } - - /** - * Test ignores XML with errors - */ - public function testParsesXmlWithError() - { - libxml_use_internal_errors(true); - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'POST', - 'CONTENT_TYPE' => 'application/xml', - 'CONTENT_LENGTH' => 68, - 'slim.input' => '1Clive Cussler' //<-- This should be incorrect! - )); - $s = new \Slim\Slim(); - $s->add(new \Slim\Middleware\ContentTypes()); - $s->run(); - $body = $s->request()->getBody(); - $this->assertTrue(is_string($body)); - $this->assertEquals('1Clive Cussler', $body); - } - - /** - * Test parses CSV - */ - public function testParsesCsv() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'POST', - 'CONTENT_TYPE' => 'text/csv', - 'CONTENT_LENGTH' => 44, - 'slim.input' => "John,Doe,000-111-2222\nJane,Doe,111-222-3333" - )); - $s = new \Slim\Slim(); - $s->add(new \Slim\Middleware\ContentTypes()); - $s->run(); - $body = $s->request()->getBody(); - $this->assertTrue(is_array($body)); - $this->assertEquals(2, count($body)); - $this->assertEquals('000-111-2222', $body[0][2]); - $this->assertEquals('Doe', $body[1][1]); - } - - /** - * Test parses request body based on media-type only, disregarding - * any extra content-type header parameters - */ - public function testParsesRequestBodyWithMediaType() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'POST', - 'CONTENT_TYPE' => 'application/json; charset=ISO-8859-4', - 'CONTENT_LENGTH' => 13, - 'slim.input' => '{"foo":"bar"}' - )); - $s = new \Slim\Slim(); - $s->add(new \Slim\Middleware\ContentTypes()); - $s->run(); - $body = $s->request()->getBody(); - $this->assertTrue(is_array($body)); - $this->assertEquals('bar', $body['foo']); - } -} diff --git a/vendor/slim/slim/tests/Middleware/FlashTest.php b/vendor/slim/slim/tests/Middleware/FlashTest.php deleted file mode 100644 index 2faf2c1..0000000 --- a/vendor/slim/slim/tests/Middleware/FlashTest.php +++ /dev/null @@ -1,141 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -class SlimFlashTest extends PHPUnit_Framework_TestCase -{ - /** - * Setup - */ - public function setUp() - { - $_SESSION = array(); - } - - /** - * Test set flash message for next request - */ - public function testSetFlashForNextRequest() - { - $f = new \Slim\Middleware\Flash(); - $f->set('foo', 'bar'); - $f->save(); - $this->assertEquals('bar', $_SESSION['slim.flash']['foo']); - } - - /** - * Test set flash message for current request - */ - public function testSetFlashForCurrentRequest() - { - $f = new \Slim\Middleware\Flash(); - $f->now('foo', 'bar'); - $this->assertEquals('bar', $f['foo']); - } - - /** - * Test loads flash from previous request - */ - public function testLoadsFlashFromPreviousRequest() - { - $_SESSION['slim.flash'] = array('info' => 'foo'); - $f = new \Slim\Middleware\Flash(); - $f->loadMessages(); - $this->assertEquals('foo', $f['info']); - } - - /** - * Test keep flash message for next request - */ - public function testKeepFlashFromPreviousRequest() - { - $_SESSION['slim.flash'] = array('info' => 'foo'); - $f = new \Slim\Middleware\Flash(); - $f->loadMessages(); - $f->keep(); - $f->save(); - $this->assertEquals('foo', $_SESSION['slim.flash']['info']); - } - - /** - * Test flash messages from previous request do not persist to next request - */ - public function testFlashMessagesFromPreviousRequestDoNotPersist() - { - $_SESSION['slim.flash'] = array('info' => 'foo'); - $f = new \Slim\Middleware\Flash(); - $f->save(); - $this->assertEmpty($_SESSION['slim.flash']); - } - - /** - * Test set Flash using array access - */ - public function testFlashArrayAccess() - { - $_SESSION['slim.flash'] = array('info' => 'foo'); - $f = new \Slim\Middleware\Flash(); - $f['info'] = 'bar'; - $f->save(); - $this->assertTrue(isset($f['info'])); - $this->assertEquals('bar', $f['info']); - unset($f['info']); - $this->assertFalse(isset($f['info'])); - } - - /** - * Test iteration - */ - public function testIteration() - { - $_SESSION['slim.flash'] = array('info' => 'foo', 'error' => 'bar'); - $f = new \Slim\Middleware\Flash(); - $f->loadMessages(); - $output = ''; - foreach ($f as $key => $value) { - $output .= $key . $value; - } - $this->assertEquals('infofooerrorbar', $output); - } - - /** - * Test countable - */ - public function testCountable() - { - $_SESSION['slim.flash'] = array('info' => 'foo', 'error' => 'bar'); - $f = new \Slim\MiddleWare\Flash(); - $f->loadMessages(); - $this->assertEquals(2, count($f)); - } - - -} diff --git a/vendor/slim/slim/tests/Middleware/MethodOverrideTest.php b/vendor/slim/slim/tests/Middleware/MethodOverrideTest.php deleted file mode 100644 index c07e397..0000000 --- a/vendor/slim/slim/tests/Middleware/MethodOverrideTest.php +++ /dev/null @@ -1,149 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -/** - * We use a mock application, instead of a Slim application. - * so that we may easily test the Method Override middleware - * in isolation. - */ -class CustomAppMethod -{ - protected $environment; - - public function __construct() - { - $this->environment = \Slim\Environment::getInstance(); - } - - public function &environment() { - return $this->environment; - } - - public function call() - { - //Do nothing - } -} - -class MethodOverrideTest extends PHPUnit_Framework_TestCase -{ - /** - * Test overrides method as POST - */ - public function testOverrideMethodAsPost() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'POST', - 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', - 'CONTENT_LENGTH' => 11, - 'slim.input' => '_METHOD=PUT' - )); - $app = new CustomAppMethod(); - $mw = new \Slim\Middleware\MethodOverride(); - $mw->setApplication($app); - $mw->setNextMiddleware($app); - $mw->call(); - $env =& $app->environment(); - $this->assertEquals('PUT', $env['REQUEST_METHOD']); - $this->assertTrue(isset($env['slim.method_override.original_method'])); - $this->assertEquals('POST', $env['slim.method_override.original_method']); - } - - /** - * Test does not override method if not POST - */ - public function testDoesNotOverrideMethodIfNotPost() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'GET', - 'slim.input' => '' - )); - $app = new CustomAppMethod(); - $mw = new \Slim\Middleware\MethodOverride(); - $mw->setApplication($app); - $mw->setNextMiddleware($app); - $mw->call(); - $env =& $app->environment(); - $this->assertEquals('GET', $env['REQUEST_METHOD']); - $this->assertFalse(isset($env['slim.method_override.original_method'])); - } - - /** - * Test does not override method if no method override parameter - */ - public function testDoesNotOverrideMethodAsPostWithoutParameter() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'POST', - 'REMOTE_ADDR' => '127.0.0.1', - 'SCRIPT_NAME' => '/foo/index.php', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - 'QUERY_STRING' => 'foo=bar', - 'SERVER_NAME' => 'slim', - 'SERVER_PORT' => 80, - 'slim.url_scheme' => 'http', - 'slim.input' => '', - 'slim.errors' => fopen('php://stderr', 'w') - )); - $app = new CustomAppMethod(); - $mw = new \Slim\Middleware\MethodOverride(); - $mw->setApplication($app); - $mw->setNextMiddleware($app); - $mw->call(); - $env =& $app->environment(); - $this->assertEquals('POST', $env['REQUEST_METHOD']); - $this->assertFalse(isset($env['slim.method_override.original_method'])); - } - - /** - * Test overrides method with X-Http-Method-Override header - */ - public function testOverrideMethodAsHeader() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'POST', - 'CONTENT_TYPE' => 'application/json', - 'CONTENT_LENGTH' => 0, - 'slim.input' => '', - 'HTTP_X_HTTP_METHOD_OVERRIDE' => 'DELETE' - )); - $app = new CustomAppMethod(); - $mw = new \Slim\Middleware\MethodOverride(); - $mw->setApplication($app); - $mw->setNextMiddleware($app); - $mw->call(); - $env =& $app->environment(); - $this->assertEquals('DELETE', $env['REQUEST_METHOD']); - $this->assertTrue(isset($env['slim.method_override.original_method'])); - $this->assertEquals('POST', $env['slim.method_override.original_method']); - } -} diff --git a/vendor/slim/slim/tests/Middleware/PrettyExceptionsTest.php b/vendor/slim/slim/tests/Middleware/PrettyExceptionsTest.php deleted file mode 100644 index 0ba8883..0000000 --- a/vendor/slim/slim/tests/Middleware/PrettyExceptionsTest.php +++ /dev/null @@ -1,153 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -class PrettyExceptionsTest extends PHPUnit_Framework_TestCase -{ - /** - * Test middleware returns successful response unchanged - */ - public function testReturnsUnchangedSuccessResponse() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/index.php', - 'PATH_INFO' => '/foo' - )); - $app = new \Slim\Slim(); - $app->get('/foo', function () { - echo "Success"; - }); - $mw = new \Slim\Middleware\PrettyExceptions(); - $mw->setApplication($app); - $mw->setNextMiddleware($app); - $mw->call(); - $this->assertEquals(200, $app->response()->status()); - $this->assertEquals('Success', $app->response()->body()); - } - - /** - * Test middleware returns diagnostic screen for error response - */ - public function testReturnsDiagnosticsForErrorResponse() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/index.php', - 'PATH_INFO' => '/foo' - )); - $app = new \Slim\Slim(array( - 'log.enabled' => false - )); - $app->get('/foo', function () { - throw new \Exception('Test Message', 100); - }); - $mw = new \Slim\Middleware\PrettyExceptions(); - $mw->setApplication($app); - $mw->setNextMiddleware($app); - $mw->call(); - $this->assertEquals(1, preg_match('@Slim Application Error@', $app->response()->body())); - $this->assertEquals(500, $app->response()->status()); - } - - /** - * Test middleware overrides response content type to html - */ - public function testResponseContentTypeIsOverriddenToHtml() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/index.php', - 'PATH_INFO' => '/foo' - )); - $app = new \Slim\Slim(array( - 'log.enabled' => false - )); - $app->get('/foo', function () use ($app) { - $app->contentType('application/json;charset=utf-8'); //<-- set content type to something else - throw new \Exception('Test Message', 100); - }); - $mw = new \Slim\Middleware\PrettyExceptions(); - $mw->setApplication($app); - $mw->setNextMiddleware($app); - $mw->call(); - $response = $app->response(); - $this->assertEquals('text/html', $response['Content-Type']); - } - - /** - * Test exception type is in response body - */ - public function testExceptionTypeIsInResponseBody() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/index.php', - 'PATH_INFO' => '/foo' - )); - $app = new \Slim\Slim(array( - 'log.enabled' => false - )); - $app->get('/foo', function () use ($app) { - throw new \LogicException('Test Message', 100); - }); - $mw = new \Slim\Middleware\PrettyExceptions(); - $mw->setApplication($app); - $mw->setNextMiddleware($app); - $mw->call(); - - $this->assertContains('LogicException', $app->response()->body()); - } - - /** - * Test with custom log - */ - public function testWithCustomLogWriter() - { - $this->setExpectedException('\LogicException'); - - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/index.php', - 'PATH_INFO' => '/foo' - )); - $app = new \Slim\Slim(array( - 'log.enabled' => false - )); - $app->container->singleton('log', function () use ($app) { - return new \Slim\Log(new \Slim\LogWriter('php://temp')); - }); - $app->get('/foo', function () use ($app) { - throw new \LogicException('Test Message', 100); - }); - $mw = new \Slim\Middleware\PrettyExceptions(); - $mw->setApplication($app); - $mw->setNextMiddleware($app); - $mw->call(); - - $this->assertContains('LogicException', $app->response()->body()); - } -} diff --git a/vendor/slim/slim/tests/Middleware/SessionCookieTest.php b/vendor/slim/slim/tests/Middleware/SessionCookieTest.php deleted file mode 100644 index 39de500..0000000 --- a/vendor/slim/slim/tests/Middleware/SessionCookieTest.php +++ /dev/null @@ -1,463 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -class SessionCookieTest extends PHPUnit_Framework_TestCase -{ - public function setUp() - { - $_SESSION = array(); - } - - /** - * Test session cookie is set and constructed correctly - * - * We test for two things: - * - * 1) That the HTTP cookie exists with the correct name; - * 2) That the HTTP cookie's value is the expected value; - */ - public function testSessionCookieIsCreated() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/index.php', - 'PATH_INFO' => '/foo' - )); - $app = new \Slim\Slim(); - $app->get('/foo', function () { - $_SESSION['foo'] = 'bar'; - echo "Success"; - }); - $mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years')); - $mw->setApplication($app); - $mw->setNextMiddleware($app); - $mw->call(); - list($status, $header, $body) = $app->response()->finalize(); - $this->assertTrue($app->response->cookies->has('slim_session')); - $cookie = $app->response->cookies->get('slim_session'); - $this->assertEquals('{"foo":"bar"}', $cookie['value']); - } - - /** - * Test $_SESSION is populated from an encrypted HTTP cookie - * - * The encrypted cookie contains the serialized array ['foo' => 'bar']. The - * global secret, cipher, and cipher mode are assumed to be the default - * values. - */ - // public function testSessionIsPopulatedFromEncryptedCookie() - // { - // \Slim\Environment::mock(array( - // 'SCRIPT_NAME' => '/index.php', - // 'PATH_INFO' => '/foo', - // 'HTTP_COOKIE' => 'slim_session=1644004961%7CLKkYPwqKIMvBK7MWl6D%2BxeuhLuMaW4quN%2F512ZAaVIY%3D%7Ce0f007fa852c7101e8224bb529e26be4d0dfbd63', - // )); - // $app = new \Slim\Slim(); - // // The cookie value in the test is encrypted, so cookies.encrypt must - // // be set to true - // $app->config('cookies.encrypt', true); - // $app->get('/foo', function () { - // echo "Success"; - // }); - // $mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years')); - // $mw->setApplication($app); - // $mw->setNextMiddleware($app); - // $mw->call(); - // $this->assertEquals(array('foo' => 'bar'), $_SESSION); - // } - - /** - * Test $_SESSION is populated from an unencrypted HTTP cookie - * - * The unencrypted cookie contains the serialized array ['foo' => 'bar']. - * The global cookies.encrypt setting is set to false - */ - public function testSessionIsPopulatedFromUnencryptedCookie() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/index.php', - 'PATH_INFO' => '/foo', - 'HTTP_COOKIE' => 'slim_session={"foo":"bar"}', - )); - $app = new \Slim\Slim(); - // The cookie value in the test is unencrypted, so cookies.encrypt must - // be set to false - $app->config('cookies.encrypt', false); - $app->get('/foo', function () { - echo "Success"; - }); - $mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years')); - $mw->setApplication($app); - $mw->setNextMiddleware($app); - $mw->call(); - $this->assertEquals(array('foo' => 'bar'), $_SESSION); - } - - /** - * Test $_SESSION is populated from an unencrypted HTTP cookie - * - * The unencrypted cookie contains the serialized array ['foo' => 'bar']. - * The global cookies.encrypt setting is set to false - */ - public function testSessionIsPopulatedFromMalformedCookieData() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/index.php', - 'PATH_INFO' => '/foo', - 'HTTP_COOKIE' => 'slim_session={"foo":"bar"sdkhguy5y}', - )); - $app = new \Slim\Slim(); - // The cookie value in the test is unencrypted, so cookies.encrypt must - // be set to false - $app->config('cookies.encrypt', false); - $app->get('/foo', function () { - echo "Success"; - }); - $mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years')); - $mw->setApplication($app); - $mw->setNextMiddleware($app); - $mw->call(); - $this->assertEquals(array(), $_SESSION); - } - - /** - * Test $_SESSION is populated as empty array if no HTTP cookie - */ - public function testSessionIsPopulatedAsEmptyIfNoCookie() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/index.php', - 'PATH_INFO' => '/foo' - )); - $app = new \Slim\Slim(); - $app->get('/foo', function () { - echo "Success"; - }); - $mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years')); - $mw->setApplication($app); - $mw->setNextMiddleware($app); - $mw->call(); - $this->assertEquals(array(), $_SESSION); - } - - public function testSerializingTooLongValueWritesLogAndDoesntCreateCookie() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/index.php', - 'PATH_INFO' => '/foo' - )); - - $logWriter = $this->getMockBuilder('Slim\LogWriter') - ->disableOriginalConstructor() - ->getMock(); - - $logWriter->expects($this->once()) - ->method('write') - ->with('WARNING! Slim\Middleware\SessionCookie data size is larger than 4KB. Content save failed.', \Slim\Log::ERROR); - - $app = new \Slim\Slim(array( - 'log.writer' => $logWriter - )); - - $tooLongValue = $this->getTooLongValue(); - - $app->get('/foo', function () use ($tooLongValue) { - $_SESSION['test'] = $tooLongValue; - echo "Success"; - }); - - $mw = new \Slim\Middleware\SessionCookie(array('expires' => '10 years')); - $mw->setApplication($app); - $mw->setNextMiddleware($app); - $mw->call(); - list($status, $header, $body) = $app->response()->finalize(); - $this->assertFalse($app->response->cookies->has('slim_session')); - } - - /** - * Generated by http://www.random.org/strings/ - */ - protected function getTooLongValue() - { - return << - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -class MyMiddleware extends \Slim\Middleware -{ - public function call() {} -} - -class MiddlewareTest extends PHPUnit_Framework_TestCase -{ - public function testSetApplication() - { - $app = new stdClass(); - $mw = new MyMiddleware(); - $mw->setApplication($app); - - $this->assertAttributeSame($app, 'app', $mw); - } - - public function testGetApplication() - { - $app = new stdClass(); - $mw = new MyMiddleware(); - $property = new \ReflectionProperty($mw, 'app'); - $property->setAccessible(true); - $property->setValue($mw, $app); - - $this->assertSame($app, $mw->getApplication()); - } - - public function testSetNextMiddleware() - { - $mw1 = new MyMiddleware(); - $mw2 = new MyMiddleware(); - $mw1->setNextMiddleware($mw2); - - $this->assertAttributeSame($mw2, 'next', $mw1); - } - - public function testGetNextMiddleware() - { - $mw1 = new MyMiddleware(); - $mw2 = new MyMiddleware(); - $property = new \ReflectionProperty($mw1, 'next'); - $property->setAccessible(true); - $property->setValue($mw1, $mw2); - - $this->assertSame($mw2, $mw1->getNextMiddleware()); - } -} diff --git a/vendor/slim/slim/tests/README b/vendor/slim/slim/tests/README deleted file mode 100644 index 7bc611c..0000000 --- a/vendor/slim/slim/tests/README +++ /dev/null @@ -1,18 +0,0 @@ -Slim Framework Unit Tests - -Follow the directions below to run the Slim Framework unit tests. You'll need the latest version of PHPUnit. To save development time, these unit tests require PHP >= 5.3. However, the Slim Framework itself requires only PHP >= 5.2. - -1. Install the latest version of PHPUnit -Visit http://www.phpunit.de/ for installation instructions. - -2. Run PHPUnit -From the filesystem directory that contains the `tests` directory, you may run all unit tests or specific unit tests. Here are several examples. The '$>' in the examples below is your command prompt. - -To run all tests: -$> phpunit tests - -To run all HTTP-related tests: -$> phpunit tests/Http - -To run only the HTTP Request tests: -$> phpunit tests/Http/RequestTest \ No newline at end of file diff --git a/vendor/slim/slim/tests/RouteTest.php b/vendor/slim/slim/tests/RouteTest.php deleted file mode 100644 index 6817641..0000000 --- a/vendor/slim/slim/tests/RouteTest.php +++ /dev/null @@ -1,617 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -class LazyInitializeTestClass { - public static $initialized = false; - - public function __construct() { - self::$initialized = true; - } - - public function foo() { - } -} - -class FooTestClass { - public static $foo_invoked = false; - public static $foo_invoked_args = array(); - - public function foo() { - self::$foo_invoked = true; - self::$foo_invoked_args = func_get_args(); - } -} - -class RouteTest extends PHPUnit_Framework_TestCase -{ - public function testGetPattern() - { - $route = new \Slim\Route('/foo', function () {}); - - $this->assertEquals('/foo', $route->getPattern()); - } - - public function testGetName() - { - $route = new \Slim\Route('/foo', function () {}); - - $property = new \ReflectionProperty($route, 'name'); - $property->setAccessible(true); - $property->setValue($route, 'foo'); - - $this->assertEquals('foo', $route->getName()); - } - - public function testSetName() - { - $route = new \Slim\Route('/foo', function () {}); - $route->name('foo'); // <-- Alias for `setName()` - - $this->assertAttributeEquals('foo', 'name', $route); - } - - public function testGetCallable() - { - $callable = function () { - echo 'Foo'; - }; - $route = new \Slim\Route('/foo', $callable); - - $this->assertSame($callable, $route->getCallable()); - } - - public function testGetCallableAsClass() - { - FooTestClass::$foo_invoked = false; - FooTestClass::$foo_invoked_args = array(); - $route = new \Slim\Route('/foo', '\FooTestClass:foo'); - $route->setParams(array('bar' => '1234')); - - $this->assertFalse(FooTestClass::$foo_invoked); - $this->assertTrue($route->dispatch()); - $this->assertTrue(FooTestClass::$foo_invoked); - $this->assertEquals(array('1234'), FooTestClass::$foo_invoked_args); - } - - public function testGetCallableAsClassLazyInitialize() - { - LazyInitializeTestClass::$initialized = false; - - $route = new \Slim\Route('/foo', '\LazyInitializeTestClass:foo'); - $this->assertFalse(LazyInitializeTestClass::$initialized); - - $route->dispatch(); - $this->assertTrue(LazyInitializeTestClass::$initialized); - } - - public function testGetCallableAsStaticMethod() - { - $route = new \Slim\Route('/bar', '\Slim\Slim::getInstance'); - - $callable = $route->getCallable(); - $this->assertEquals('\Slim\Slim::getInstance', $callable); - } - - public function example_càllâble_wïth_wéird_chars() - { - return 'test'; - } - - public function testGetCallableWithOddCharsAsClass() - { - $route = new \Slim\Route('/foo', '\RouteTest:example_càllâble_wïth_wéird_chars'); - $callable = $route->getCallable(); - - $this->assertEquals('test', $callable()); - } - - public function testSetCallable() - { - $callable = function () { - echo 'Foo'; - }; - $route = new \Slim\Route('/foo', $callable); // <-- Called inside __construct() - - $this->assertAttributeSame($callable, 'callable', $route); - } - - public function testSetCallableWithInvalidArgument() - { - $this->setExpectedException('\InvalidArgumentException'); - $route = new \Slim\Route('/foo', 'doesNotExist'); // <-- Called inside __construct() - } - - public function testGetParams() - { - $route = new \Slim\Route('/hello/:first/:last', function () {}); - $route->matches('/hello/mr/anderson'); // <-- Parses params from argument - - $this->assertEquals(array( - 'first' => 'mr', - 'last' => 'anderson' - ), $route->getParams()); - } - - public function testSetParams() - { - $route = new \Slim\Route('/hello/:first/:last', function () {}); - $route->matches('/hello/mr/anderson'); // <-- Parses params from argument - $route->setParams(array( - 'first' => 'agent', - 'last' => 'smith' - )); - - $this->assertAttributeEquals(array( - 'first' => 'agent', - 'last' => 'smith' - ), 'params', $route); - } - - public function testGetParam() - { - $route = new \Slim\Route('/hello/:first/:last', function () {}); - - $property = new \ReflectionProperty($route, 'params'); - $property->setAccessible(true); - $property->setValue($route, array( - 'first' => 'foo', - 'last' => 'bar' - )); - - $this->assertEquals('foo', $route->getParam('first')); - } - - public function testGetParamThatDoesNotExist() - { - $this->setExpectedException('InvalidArgumentException'); - - $route = new \Slim\Route('/hello/:first/:last', function () {}); - - $property = new \ReflectionProperty($route, 'params'); - $property->setAccessible(true); - $property->setValue($route, array( - 'first' => 'foo', - 'last' => 'bar' - )); - - $route->getParam('middle'); - } - - public function testSetParam() - { - $route = new \Slim\Route('/hello/:first/:last', function () {}); - $route->matches('/hello/mr/anderson'); // <-- Parses params from argument - $route->setParam('last', 'smith'); - - $this->assertAttributeEquals(array( - 'first' => 'mr', - 'last' => 'smith' - ), 'params', $route); - } - - public function testSetParamThatDoesNotExist() - { - $this->setExpectedException('InvalidArgumentException'); - - $route = new \Slim\Route('/hello/:first/:last', function () {}); - $route->matches('/hello/mr/anderson'); // <-- Parses params from argument - $route->setParam('middle', 'smith'); // <-- Should trigger InvalidArgumentException - } - - public function testMatches() - { - $route = new \Slim\Route('/hello/:name', function () {}); - - $this->assertTrue($route->matches('/hello/josh')); - } - - public function testMatchesIsFalse() - { - $route = new \Slim\Route('/foo', function () {}); - - $this->assertFalse($route->matches('/bar')); - } - - public function testMatchesPatternWithTrailingSlash() - { - $route = new \Slim\Route('/foo/', function () {}); - - $this->assertTrue($route->matches('/foo/')); - $this->assertTrue($route->matches('/foo')); - } - - public function testMatchesPatternWithoutTrailingSlash() - { - $route = new \Slim\Route('/foo', function () {}); - - $this->assertFalse($route->matches('/foo/')); - $this->assertTrue($route->matches('/foo')); - } - - public function testMatchesWithConditions() - { - $route = new \Slim\Route('/hello/:first/and/:second', function () {}); - $route->conditions(array( - 'first' => '[a-zA-Z]{3,}' - )); - - $this->assertTrue($route->matches('/hello/Josh/and/John')); - } - - public function testMatchesWithConditionsIsFalse() - { - $route = new \Slim\Route('/hello/:first/and/:second', function () {}); - $route->conditions(array( - 'first' => '[a-z]{3,}' - )); - - $this->assertFalse($route->matches('/hello/Josh/and/John')); - } - - /* - * Route should match URI with valid path component according to rfc2396 - * - * "Uniform Resource Identifiers (URI): Generic Syntax" http://www.ietf.org/rfc/rfc2396.txt - * - * Excludes "+" which is valid but decodes into a space character - */ - public function testMatchesWithValidRfc2396PathComponent() - { - $symbols = ':@&=$,'; - $route = new \Slim\Route('/rfc2386/:symbols', function () {}); - - $this->assertTrue($route->matches('/rfc2386/' . $symbols)); - } - - /* - * Route should match URI including unreserved punctuation marks from rfc2396 - * - * "Uniform Resource Identifiers (URI): Generic Syntax" http://www.ietf.org/rfc/rfc2396.txt - */ - public function testMatchesWithUnreservedMarks() - { - $marks = "-_.!~*'()"; - $route = new \Slim\Route('/marks/:marks', function () {}); - - $this->assertTrue($route->matches('/marks/' . $marks)); - } - - public function testMatchesOptionalParameters() - { - $pattern = '/archive/:year(/:month(/:day))'; - - $route1 = new \Slim\Route($pattern, function () {}); - $this->assertTrue($route1->matches('/archive/2010')); - $this->assertEquals(array('year' => '2010'), $route1->getParams()); - - $route2 = new \Slim\Route($pattern, function () {}); - $this->assertTrue($route2->matches('/archive/2010/05')); - $this->assertEquals(array('year' => '2010', 'month' => '05'), $route2->getParams()); - - $route3 = new \Slim\Route($pattern, function () {}); - $this->assertTrue($route3->matches('/archive/2010/05/13')); - $this->assertEquals(array('year' => '2010', 'month' => '05', 'day' => '13'), $route3->getParams()); - } - - public function testMatchesIsCaseSensitiveByDefault() - { - $route = new \Slim\Route('/case/sensitive', function () {}); - $this->assertTrue($route->matches('/case/sensitive')); - $this->assertFalse($route->matches('/CaSe/SensItiVe')); - } - - public function testMatchesCanBeCaseInsensitive() - { - $route = new \Slim\Route('/Case/Insensitive', function () {}, false); - $this->assertTrue($route->matches('/Case/Insensitive')); - $this->assertTrue($route->matches('/CaSe/iNSensItiVe')); - } - - public function testGetConditions() - { - $route = new \Slim\Route('/foo', function () {}); - - $property = new \ReflectionProperty($route, 'conditions'); - $property->setAccessible(true); - $property->setValue($route, array('foo' => '\d{3}')); - - $this->assertEquals(array('foo' => '\d{3}'), $route->getConditions()); - } - - public function testSetDefaultConditions() - { - \Slim\Route::setDefaultConditions(array( - 'id' => '\d+' - )); - - $property = new \ReflectionProperty('\Slim\Route', 'defaultConditions'); - $property->setAccessible(true); - - $this->assertEquals(array( - 'id' => '\d+' - ), $property->getValue()); - } - - public function testGetDefaultConditions() - { - $property = new \ReflectionProperty('\Slim\Route', 'defaultConditions'); - $property->setAccessible(true); - $property->setValue(array( - 'id' => '\d+' - )); - - $this->assertEquals(array( - 'id' => '\d+' - ), \Slim\Route::getDefaultConditions()); - } - - public function testDefaultConditionsAssignedToInstance() - { - $staticProperty = new \ReflectionProperty('\Slim\Route', 'defaultConditions'); - $staticProperty->setAccessible(true); - $staticProperty->setValue(array( - 'id' => '\d+' - )); - $route = new \Slim\Route('/foo', function () {}); - - $this->assertAttributeEquals(array( - 'id' => '\d+' - ), 'conditions', $route); - } - - public function testMatchesWildcard() - { - $route = new \Slim\Route('/hello/:path+/world', function () {}); - - $this->assertTrue($route->matches('/hello/foo/bar/world')); - $this->assertAttributeEquals(array( - 'path' => array('foo', 'bar') - ), 'params', $route); - } - - public function testMatchesMultipleWildcards() - { - $route = new \Slim\Route('/hello/:path+/world/:date+', function () {}); - - $this->assertTrue($route->matches('/hello/foo/bar/world/2012/03/10')); - $this->assertAttributeEquals(array( - 'path' => array('foo', 'bar'), - 'date' => array('2012', '03', '10') - ), 'params', $route); - } - - public function testMatchesParamsAndWildcards() - { - $route = new \Slim\Route('/hello/:path+/world/:year/:month/:day/:path2+', function () {}); - - $this->assertTrue($route->matches('/hello/foo/bar/world/2012/03/10/first/second')); - $this->assertAttributeEquals(array( - 'path' => array('foo', 'bar'), - 'year' => '2012', - 'month' => '03', - 'day' => '10', - 'path2' => array('first', 'second') - ), 'params', $route); - } - - public function testMatchesParamsWithOptionalWildcard() - { - $route = new \Slim\Route('/hello(/:foo(/:bar+))', function () {}); - - $this->assertTrue($route->matches('/hello')); - $this->assertTrue($route->matches('/hello/world')); - $this->assertTrue($route->matches('/hello/world/foo')); - $this->assertTrue($route->matches('/hello/world/foo/bar')); - } - - public function testSetMiddleware() - { - $route = new \Slim\Route('/foo', function () {}); - $mw = function () { - echo 'Foo'; - }; - $route->setMiddleware($mw); - - $this->assertAttributeContains($mw, 'middleware', $route); - } - - public function testSetMiddlewareMultipleTimes() - { - $route = new \Slim\Route('/foo', function () {}); - $mw1 = function () { - echo 'Foo'; - }; - $mw2 = function () { - echo 'Bar'; - }; - $route->setMiddleware($mw1); - $route->setMiddleware($mw2); - - $this->assertAttributeContains($mw1, 'middleware', $route); - $this->assertAttributeContains($mw2, 'middleware', $route); - } - - public function testSetMiddlewareWithArray() - { - $route = new \Slim\Route('/foo', function () {}); - $mw1 = function () { - echo 'Foo'; - }; - $mw2 = function () { - echo 'Bar'; - }; - $route->setMiddleware(array($mw1, $mw2)); - - $this->assertAttributeContains($mw1, 'middleware', $route); - $this->assertAttributeContains($mw2, 'middleware', $route); - } - - public function testSetMiddlewareWithInvalidArgument() - { - $this->setExpectedException('InvalidArgumentException'); - - $route = new \Slim\Route('/foo', function () {}); - $route->setMiddleware('doesNotExist'); // <-- Should throw InvalidArgumentException - } - - public function testSetMiddlewareWithArrayWithInvalidArgument() - { - $this->setExpectedException('InvalidArgumentException'); - - $route = new \Slim\Route('/foo', function () {}); - $route->setMiddleware(array('doesNotExist')); - } - - public function testGetMiddleware() - { - $route = new \Slim\Route('/foo', function () {}); - - $property = new \ReflectionProperty($route, 'middleware'); - $property->setAccessible(true); - $property->setValue($route, array('foo' => 'bar')); - - $this->assertEquals(array('foo' => 'bar'), $route->getMiddleware()); - } - - public function testSetHttpMethods() - { - $route = new \Slim\Route('/foo', function () {}); - $route->setHttpMethods('GET', 'POST'); - - $this->assertAttributeEquals(array('GET', 'POST'), 'methods', $route); - } - - public function testGetHttpMethods() - { - $route = new \Slim\Route('/foo', function () {}); - - $property = new \ReflectionProperty($route, 'methods'); - $property->setAccessible(true); - $property->setValue($route, array('GET', 'POST')); - - $this->assertEquals(array('GET', 'POST'), $route->getHttpMethods()); - } - - public function testAppendHttpMethods() - { - $route = new \Slim\Route('/foo', function () {}); - - $property = new \ReflectionProperty($route, 'methods'); - $property->setAccessible(true); - $property->setValue($route, array('GET', 'POST')); - - $route->appendHttpMethods('PUT'); - - $this->assertAttributeEquals(array('GET', 'POST', 'PUT'), 'methods', $route); - } - - public function testAppendArrayOfHttpMethods() - { - $arrayOfMethods = array('GET','POST','PUT'); - $route = new \Slim\Route('/foo', function () {}); - $route->appendHttpMethods($arrayOfMethods); - - $this->assertAttributeEquals($arrayOfMethods,'methods',$route); - } - - public function testAppendHttpMethodsWithVia() - { - $route = new \Slim\Route('/foo', function () {}); - $route->via('PUT'); - - $this->assertAttributeContains('PUT', 'methods', $route); - } - - public function testAppendArrayOfHttpMethodsWithVia() - { - $arrayOfMethods = array('GET','POST','PUT'); - $route = new \Slim\Route('/foo', function () {}); - $route->via($arrayOfMethods); - - $this->assertAttributeEquals($arrayOfMethods,'methods',$route); - } - - public function testSupportsHttpMethod() - { - $route = new \Slim\Route('/foo', function () {}); - - $property = new \ReflectionProperty($route, 'methods'); - $property->setAccessible(true); - $property->setValue($route, array('POST')); - - $this->assertTrue($route->supportsHttpMethod('POST')); - $this->assertFalse($route->supportsHttpMethod('PUT')); - } - - /** - * Test dispatch with params - */ - public function testDispatch() - { - $this->expectOutputString('Hello josh'); - $route = new \Slim\Route('/hello/:name', function ($name) { echo "Hello $name"; }); - $route->matches('/hello/josh'); //<-- Extracts params from resource URI - $route->dispatch(); - } - - /** - * Test dispatch with middleware - */ - public function testDispatchWithMiddleware() - { - $this->expectOutputString('First! Second! Hello josh'); - $route = new \Slim\Route('/hello/:name', function ($name) { echo "Hello $name"; }); - $route->setMiddleware(function () { - echo "First! "; - }); - $route->setMiddleware(function () { - echo "Second! "; - }); - $route->matches('/hello/josh'); //<-- Extracts params from resource URI - $route->dispatch(); - } - - /** - * Test middleware with arguments - */ - public function testRouteMiddlwareArguments() - { - $this->expectOutputString('foobar'); - $route = new \Slim\Route('/foo', function () { echo "bar"; }); - $route->setName('foo'); - $route->setMiddleware(function ($route) { - echo $route->getName(); - }); - $route->matches('/foo'); //<-- Extracts params from resource URI - $route->dispatch(); - } -} diff --git a/vendor/slim/slim/tests/RouterTest.php b/vendor/slim/slim/tests/RouterTest.php deleted file mode 100644 index edbb6d4..0000000 --- a/vendor/slim/slim/tests/RouterTest.php +++ /dev/null @@ -1,250 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -class RouterTest extends PHPUnit_Framework_TestCase -{ - /** - * Constructor should initialize routes as empty array - */ - public function testConstruct() - { - $router = new \Slim\Router(); - - $this->assertAttributeEquals(array(), 'routes', $router); - } - - /** - * Map should set and return instance of \Slim\Route - */ - public function testMap() - { - $router = new \Slim\Router(); - $route = new \Slim\Route('/foo', function() {}); - $router->map($route); - - $this->assertAttributeContains($route, 'routes', $router); - } - - /** - * Named route should be added and indexed by name - */ - public function testAddNamedRoute() - { - $router = new \Slim\Router(); - $route = new \Slim\Route('/foo', function () {}); - $router->addNamedRoute('foo', $route); - - $property = new \ReflectionProperty($router, 'namedRoutes'); - $property->setAccessible(true); - - $rV = $property->getValue($router); - $this->assertSame($route, $rV['foo']); - } - - /** - * Named route should have unique name - */ - public function testAddNamedRouteWithDuplicateKey() - { - $this->setExpectedException('RuntimeException'); - - $router = new \Slim\Router(); - $route = new \Slim\Route('/foo', function () {}); - $router->addNamedRoute('foo', $route); - $router->addNamedRoute('foo', $route); - } - - /** - * Router should return named route by name, or null if not found - */ - public function testGetNamedRoute() - { - $router = new \Slim\Router(); - $route = new \Slim\Route('/foo', function () {}); - - $property = new \ReflectionProperty($router, 'namedRoutes'); - $property->setAccessible(true); - $property->setValue($router, array('foo' => $route)); - - $this->assertSame($route, $router->getNamedRoute('foo')); - $this->assertNull($router->getNamedRoute('bar')); - } - - /** - * Router should determine named routes and cache results - */ - public function testGetNamedRoutes() - { - $router = new \Slim\Router(); - $route1 = new \Slim\Route('/foo', function () {}); - $route2 = new \Slim\Route('/bar', function () {}); - - // Init router routes to array - $propertyRouterRoutes = new \ReflectionProperty($router, 'routes'); - $propertyRouterRoutes->setAccessible(true); - $propertyRouterRoutes->setValue($router, array($route1, $route2)); - - // Init router named routes to null - $propertyRouterNamedRoutes = new \ReflectionProperty($router, 'namedRoutes'); - $propertyRouterNamedRoutes->setAccessible(true); - $propertyRouterNamedRoutes->setValue($router, null); - - // Init route name - $propertyRouteName = new \ReflectionProperty($route2, 'name'); - $propertyRouteName->setAccessible(true); - $propertyRouteName->setValue($route2, 'bar'); - - $namedRoutes = $router->getNamedRoutes(); - $this->assertCount(1, $namedRoutes); - $this->assertSame($route2, $namedRoutes['bar']); - } - - /** - * Router should detect presence of a named route by name - */ - public function testHasNamedRoute() - { - $router = new \Slim\Router(); - $route = new \Slim\Route('/foo', function () {}); - - $property = new \ReflectionProperty($router, 'namedRoutes'); - $property->setAccessible(true); - $property->setValue($router, array('foo' => $route)); - - $this->assertTrue($router->hasNamedRoute('foo')); - $this->assertFalse($router->hasNamedRoute('bar')); - } - - /** - * Router should return current route if set during iteration - */ - public function testGetCurrentRoute() - { - $router = new \Slim\Router(); - $route = new \Slim\Route('/foo', function () {}); - - $property = new \ReflectionProperty($router, 'currentRoute'); - $property->setAccessible(true); - $property->setValue($router, $route); - - $this->assertSame($route, $router->getCurrentRoute()); - } - - /** - * Router should return first matching route if current route not set yet by iteration - */ - public function testGetCurrentRouteIfMatchedRoutes() - { - $router = new \Slim\Router(); - $route = new \Slim\Route('/foo', function () {}); - - $propertyMatchedRoutes = new \ReflectionProperty($router, 'matchedRoutes'); - $propertyMatchedRoutes->setAccessible(true); - $propertyMatchedRoutes->setValue($router, array($route)); - - $propertyCurrentRoute = new \ReflectionProperty($router, 'currentRoute'); - $propertyCurrentRoute->setAccessible(true); - $propertyCurrentRoute->setValue($router, null); - - $this->assertSame($route, $router->getCurrentRoute()); - } - - /** - * Router should return `null` if current route not set yet and there are no matching routes - */ - public function testGetCurrentRouteIfNoMatchedRoutes() - { - $router = new \Slim\Router(); - - $propertyMatchedRoutes = new \ReflectionProperty($router, 'matchedRoutes'); - $propertyMatchedRoutes->setAccessible(true); - $propertyMatchedRoutes->setValue($router, array()); - - $propertyCurrentRoute = new \ReflectionProperty($router, 'currentRoute'); - $propertyCurrentRoute->setAccessible(true); - $propertyCurrentRoute->setValue($router, null); - - $this->assertNull($router->getCurrentRoute()); - } - - public function testGetMatchedRoutes() - { - $router = new \Slim\Router(); - - $route1 = new \Slim\Route('/foo', function () {}); - $route1 = $route1->via('GET'); - - $route2 = new \Slim\Route('/foo', function () {}); - $route2 = $route2->via('POST'); - - $route3 = new \Slim\Route('/bar', function () {}); - $route3 = $route3->via('PUT'); - - $routes = new \ReflectionProperty($router, 'routes'); - $routes->setAccessible(true); - $routes->setValue($router, array($route1, $route2, $route3)); - - $matchedRoutes = $router->getMatchedRoutes('GET', '/foo'); - $this->assertSame($route1, $matchedRoutes[0]); - } - - // Test url for named route - - public function testUrlFor() - { - $router = new \Slim\Router(); - - $route1 = new \Slim\Route('/hello/:first/:last', function () {}); - $route1 = $route1->via('GET')->name('hello'); - - $route2 = new \Slim\Route('/path/(:foo\.:bar)', function () {}); - $route2 = $route2->via('GET')->name('regexRoute'); - - $routes = new \ReflectionProperty($router, 'namedRoutes'); - $routes->setAccessible(true); - $routes->setValue($router, array( - 'hello' => $route1, - 'regexRoute' => $route2 - )); - - $this->assertEquals('/hello/Josh/Lockhart', $router->urlFor('hello', array('first' => 'Josh', 'last' => 'Lockhart'))); - $this->assertEquals('/path/Hello.Josh', $router->urlFor('regexRoute', array('foo' => 'Hello', 'bar' => 'Josh'))); - } - - public function testUrlForIfNoSuchRoute() - { - $this->setExpectedException('RuntimeException'); - - $router = new \Slim\Router(); - $router->urlFor('foo', array('abc' => '123')); - } -} diff --git a/vendor/slim/slim/tests/SlimTest.php b/vendor/slim/slim/tests/SlimTest.php deleted file mode 100644 index d661b4d..0000000 --- a/vendor/slim/slim/tests/SlimTest.php +++ /dev/null @@ -1,1657 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -//Mock custom view -class CustomView extends \Slim\View -{ - public function render($template, $data = null) { echo "Custom view"; } -} - -//Echo Logger -class EchoErrorLogger -{ - public function error($object) { echo get_class($object) .':'.$object->getMessage(); } -} - -//Mock extending class -class Derived extends \Slim\Slim -{ - public static function getDefaultSettings() - { - return array_merge( - array("late-static-binding" => true) - , parent::getDefaultSettings()); - } -} - -//Mock middleware -class CustomMiddleware extends \Slim\Middleware -{ - public function call() - { - $env = $this->app->environment(); - $res = $this->app->response(); - $env['slim.test'] = 'Hello'; - $this->next->call(); - $res->header('X-Slim-Test', 'Hello'); - $res->write('Hello'); - } -} - -class SlimTest extends PHPUnit_Framework_TestCase -{ - public function setUp() - { - //Remove environment mode if set - unset($_ENV['SLIM_MODE']); - - //Reset session - $_SESSION = array(); - - //Prepare default environment variables - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - 'QUERY_STRING' => 'one=foo&two=bar', - 'SERVER_NAME' => 'slimframework.com', - )); - } - - /************************************************ - * INSTANTIATION - ************************************************/ - - /** - * Test version constant is string - */ - public function testHasVersionConstant() - { - $this->assertTrue(is_string(\Slim\Slim::VERSION)); - } - - /** - * Test default instance properties - */ - public function testDefaultInstanceProperties() - { - $s = new \Slim\Slim(); - $this->assertInstanceOf('\Slim\Http\Request', $s->request()); - $this->assertInstanceOf('\Slim\Http\Response', $s->response()); - $this->assertInstanceOf('\Slim\Router', $s->router()); - $this->assertInstanceOf('\Slim\View', $s->view()); - $this->assertInstanceOf('\Slim\Log', $s->getLog()); - $this->assertEquals(\Slim\Log::DEBUG, $s->getLog()->getLevel()); - $this->assertTrue($s->getLog()->getEnabled()); - $this->assertInstanceOf('\Slim\Environment', $s->environment()); - } - - /** - * Test get default instance - */ - public function testGetDefaultInstance() - { - $s = new \Slim\Slim(); - $s->setName('default'); //We must do this manually since a default app is already set in prev tests - $this->assertEquals('default', $s->getName()); - $this->assertInstanceOf('\Slim\Slim', \Slim\Slim::getInstance()); - $this->assertSame($s, \Slim\Slim::getInstance()); - } - - /** - * Test get named instance - */ - public function testGetNamedInstance() - { - $s = new \Slim\Slim(); - $s->setName('foo'); - $this->assertSame($s, \Slim\Slim::getInstance('foo')); - } - - /** - * Test Slim autoloader ignores non-Slim classes - * - * Pre-conditions: - * Instantiate a non-Slim class; - * - * Post-conditions: - * Slim autoloader returns without requiring a class file; - */ - public function testSlimAutoloaderIgnoresNonSlimClass() - { - $foo = new Foo(); - } - - /************************************************ - * SETTINGS - ************************************************/ - - /** - * Test get setting that exists - */ - public function testGetSettingThatExists() - { - $s = new \Slim\Slim(); - $this->assertEquals('./templates', $s->config('templates.path')); - } - - /** - * Test get setting that does not exist - */ - public function testGetSettingThatDoesNotExist() - { - $s = new \Slim\Slim(); - $this->assertNull($s->config('foo')); - } - - /** - * Test set setting - */ - public function testSetSetting() - { - $s = new \Slim\Slim(); - $this->assertEquals('./templates', $s->config('templates.path')); - $s->config('templates.path', './tmpl'); - $this->assertEquals('./tmpl', $s->config('templates.path')); - } - - /** - * Test batch set settings - */ - public function testBatchSetSettings() - { - $s = new \Slim\Slim(); - $this->assertEquals('./templates', $s->config('templates.path')); - $this->assertTrue($s->config('debug')); - $s->config(array( - 'templates.path' => './tmpl', - 'debug' => false - )); - $this->assertEquals('./tmpl', $s->config('templates.path')); - $this->assertFalse($s->config('debug')); - } - - /** - * Test set settings recursively - */ - public function testSetSettingsRecursively() - { - $config = array( - 'my_module' => array( - 'paths' => array( - './my_module/path/1', - ), - ) - ); - - $s = new \Slim\Slim($config); - - $override = array( - 'my_module' => array( - 'paths' => array( - './my_module/path/2', - './my_module/path/3', - ), - ) - ); - - // Test recursive batch behaviour - $s->config($override, true); - - $expected = array( - 'paths' => array( - './my_module/path/1', - './my_module/path/2', - './my_module/path/3', - ), - ); - - $this->assertEquals($expected, $s->config('my_module')); - - // Test default batch behaviour - $s = new \Slim\Slim($config); - $s->config($override); - - $this->assertNotEquals($expected, $s->config('my_module')); - } - - /************************************************ - * MODES - ************************************************/ - - /** - * Test default mode - */ - public function testGetDefaultMode() - { - $s = new \Slim\Slim(); - $this->assertEquals('development', $s->getMode()); - } - - /** - * Test custom mode from environment - */ - public function testGetModeFromEnvironment() - { - $_ENV['SLIM_MODE'] = 'production'; - $s = new \Slim\Slim(); - $this->assertEquals('production', $s->getMode()); - } - - /** - * Test custom mode from app settings - */ - public function testGetModeFromSettings() - { - $s = new \Slim\Slim(array( - 'mode' => 'test' - )); - $this->assertEquals('test', $s->getMode()); - } - - /** - * Test mode configuration - */ - public function testModeConfiguration() - { - $flag = 0; - $configureTest = function () use (&$flag) { - $flag = 'test'; - }; - $configureProduction = function () use (&$flag) { - $flag = 'production'; - }; - $s = new \Slim\Slim(array('mode' => 'test')); - $s->configureMode('test', $configureTest); - $s->configureMode('production', $configureProduction); - $this->assertEquals('test', $flag); - } - - /** - * Test mode configuration when mode does not match - */ - public function testModeConfigurationWhenModeDoesNotMatch() - { - $flag = 0; - $configureTest = function () use (&$flag) { - $flag = 'test'; - }; - $s = new \Slim\Slim(array('mode' => 'production')); - $s->configureMode('test', $configureTest); - $this->assertEquals(0, $flag); - } - - /** - * Test mode configuration when not callable - */ - public function testModeConfigurationWhenNotCallable() - { - $flag = 0; - $s = new \Slim\Slim(array('mode' => 'production')); - $s->configureMode('production', 'foo'); - $this->assertEquals(0, $flag); - } - - /** - * Test custom mode from getenv() - */ - public function testGetModeFromGetEnv() - { - putenv('SLIM_MODE=production'); - $s = new \Slim\Slim(); - $this->assertEquals('production', $s->getMode()); - } - - /************************************************ - * ROUTING - ************************************************/ - - /** - * Test GENERIC route - */ - public function testGenericRoute() - { - $s = new \Slim\Slim(); - $callable = function () { echo "foo"; }; - $route = $s->map('/bar', $callable); - $this->assertInstanceOf('\Slim\Route', $route); - $this->assertEmpty($route->getHttpMethods()); - } - - /** - * Test GET routes also get mapped as a HEAD route - */ - public function testGetRouteIsAlsoMappedAsHead() - { - $s = new \Slim\Slim(); - $route = $s->get('/foo', function () {}); - $this->assertTrue($route->supportsHttpMethod(\Slim\Http\Request::METHOD_GET)); - $this->assertTrue($route->supportsHttpMethod(\Slim\Http\Request::METHOD_HEAD)); - } - - /** - * Test GET route - */ - public function testGetRoute() - { - $s = new \Slim\Slim(); - $mw1 = function () { echo "foo"; }; - $mw2 = function () { echo "bar"; }; - $callable = function () { echo "xyz"; }; - $route = $s->get('/bar', $mw1, $mw2, $callable); - $s->call(); - $this->assertEquals('foobarxyz', $s->response()->body()); - $this->assertEquals('/bar', $route->getPattern()); - $this->assertSame($callable, $route->getCallable()); - } - - /** - * Test POST route - */ - public function testPostRoute() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'POST', - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - )); - $s = new \Slim\Slim(); - $mw1 = function () { echo "foo"; }; - $mw2 = function () { echo "bar"; }; - $callable = function () { echo "xyz"; }; - $route = $s->post('/bar', $mw1, $mw2, $callable); - $s->call(); - $this->assertEquals('foobarxyz', $s->response()->body()); - $this->assertEquals('/bar', $route->getPattern()); - $this->assertSame($callable, $route->getCallable()); - } - - /** - * Test PUT route - */ - public function testPutRoute() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'PUT', - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - )); - $s = new \Slim\Slim(); - $mw1 = function () { echo "foo"; }; - $mw2 = function () { echo "bar"; }; - $callable = function () { echo "xyz"; }; - $route = $s->put('/bar', $mw1, $mw2, $callable); - $s->call(); - $this->assertEquals('foobarxyz', $s->response()->body()); - $this->assertEquals('/bar', $route->getPattern()); - $this->assertSame($callable, $route->getCallable()); - } - - /** - * Test PATCH route - */ - public function testPatchRoute() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'PATCH', - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - )); - $s = new \Slim\Slim(); - $mw1 = function () { echo "foo"; }; - $mw2 = function () { echo "bar"; }; - $callable = function () { echo "xyz"; }; - $route = $s->patch('/bar', $mw1, $mw2, $callable); - $s->call(); - $this->assertEquals('foobarxyz', $s->response()->body()); - $this->assertEquals('/bar', $route->getPattern()); - $this->assertSame($callable, $route->getCallable()); - } - - /** - * Test DELETE route - */ - public function testDeleteRoute() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'DELETE', - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - )); - $s = new \Slim\Slim(); - $mw1 = function () { echo "foo"; }; - $mw2 = function () { echo "bar"; }; - $callable = function () { echo "xyz"; }; - $route = $s->delete('/bar', $mw1, $mw2, $callable); - $s->call(); - $this->assertEquals('foobarxyz', $s->response()->body()); - $this->assertEquals('/bar', $route->getPattern()); - $this->assertSame($callable, $route->getCallable()); - } - - /** - * Test OPTIONS route - */ - public function testOptionsRoute() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'OPTIONS', - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - )); - $s = new \Slim\Slim(); - $mw1 = function () { echo "foo"; }; - $mw2 = function () { echo "bar"; }; - $callable = function () { echo "xyz"; }; - $route = $s->options('/bar', $mw1, $mw2, $callable); - $s->call(); - $this->assertEquals('foobarxyz', $s->response()->body()); - $this->assertEquals('/bar', $route->getPattern()); - $this->assertSame($callable, $route->getCallable()); - } - - /** - * Test route groups - */ - public function testRouteGroups() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'GET', - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar/baz', //<-- Virtual' - )); - $s = new \Slim\Slim(); - $mw1 = function () { echo "foo"; }; - $mw2 = function () { echo "bar"; }; - $callable = function () { echo "xyz"; }; - $s->group('/bar', $mw1, function () use ($s, $mw2, $callable) { - $s->get('/baz', $mw2, $callable); - }); - $s->call(); - $this->assertEquals('foobarxyz', $s->response()->body()); - } - - /* - * Test ANY route - */ - public function testAnyRoute() - { - $mw1 = function () { echo "foo"; }; - $mw2 = function () { echo "bar"; }; - $callable = function () { echo "xyz"; }; - $methods = array('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'); - foreach ($methods as $i => $method) { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => $method, - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - )); - $s = new \Slim\Slim(); - $route = $s->any('/bar', $mw1, $mw2, $callable); - $s->call(); - $this->assertEquals('foobarxyz', $s->response()->body()); - $this->assertEquals('/bar', $route->getPattern()); - $this->assertSame($callable, $route->getCallable()); - } - } - - /** - * Test if route does NOT expect trailing slash and URL has one - */ - public function testRouteWithoutSlashAndUrlWithOne() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar/', //<-- Virtual - )); - $s = new \Slim\Slim(); - $s->get('/bar', function () { echo "xyz"; }); - $s->call(); - $this->assertEquals(404, $s->response()->status()); - } - - /** - * Tests if route will match in case-insensitive manner if configured to do so - */ - public function testRouteMatchesInCaseInsensitiveMannerIfConfigured() - { - \Slim\Environment::mock(array( - 'PATH_INFO' => '/BaR', // Does not match route case - )); - $s = new \Slim\Slim(array('routes.case_sensitive' => false)); - $route = $s->get('/bar', function () { echo "xyz"; }); - $s->call(); - $this->assertEquals(200, $s->response()->status()); - $this->assertEquals('xyz', $s->response()->body()); - $this->assertEquals('/bar', $route->getPattern()); - } - - /** - * Test if route contains URL encoded characters - */ - public function testRouteWithUrlEncodedCharacters() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar/jo%20hn/smi%20th', //<-- Virtual - )); - $s = new \Slim\Slim(); - $s->get('/bar/:one/:two', function ($one, $two) { echo $one . $two; }); - $s->call(); - $this->assertEquals('jo hnsmi th', $s->response()->body()); - } - - /************************************************ - * VIEW - ************************************************/ - - /** - * Test set view with string class name - */ - public function testSetSlimViewFromString() - { - $s = new \Slim\Slim(); - $this->assertInstanceOf('\Slim\View', $s->view()); - $s->view('CustomView'); - $this->assertInstanceOf('CustomView', $s->view()); - } - - /** - * Test set view with object instance - */ - public function testSetSlimViewFromInstance() - { - $s = new \Slim\Slim(); - $this->assertInstanceOf('\Slim\View', $s->view()); - $s->view(new CustomView()); - $this->assertInstanceOf('CustomView', $s->view()); - } - - /** - * Test view data is transferred to newer view - */ - public function testViewDataTransfer() - { - $data = array('foo' => 'bar'); - $s = new \Slim\Slim(); - $s->view()->setData($data); - $s->view('CustomView'); - $this->assertSame($data, $s->view()->getData()); - } - - /************************************************ - * RENDERING - ************************************************/ - - /** - * Test template path is passed to view - */ - public function testViewGetsTemplatesPath() - { - $path = dirname(__FILE__) . '/templates'; - $s = new \Slim\Slim(array('templates.path' => $path)); - $this->assertEquals($s->view->getTemplatesDirectory(), $path); - } - - /** - * Test render with template and data - */ - public function testRenderTemplateWithData() - { - $s = new \Slim\Slim(array('templates.path' => dirname(__FILE__) . '/templates')); - $s->get('/bar', function () use ($s) { - $s->render('test.php', array('foo' => 'bar')); - }); - $s->call(); - list($status, $header, $body) = $s->response()->finalize(); - $this->assertEquals(200, $status); - $this->assertEquals('test output bar', $body); - } - - /** - * Test render with template and data and status - */ - public function testRenderTemplateWithDataAndStatus() - { - $s = new \Slim\Slim(array('templates.path' => dirname(__FILE__) . '/templates')); - $s->get('/bar', function () use ($s) { - $s->render('test.php', array('foo' => 'bar'), 500); - }); - $s->call(); - list($status, $header, $body) = $s->response()->finalize(); - $this->assertEquals(500, $status); - $this->assertEquals('test output bar', $body); - } - - /************************************************ - * LOG - ************************************************/ - - /** - * Test get log - * - * This asserts that a Slim app has a default Log - * upon instantiation. The Log itself is tested - * separately in another file. - */ - public function testGetLog() - { - $s = new \Slim\Slim(); - $this->assertInstanceOf('\Slim\Log', $s->getLog()); - } - - /************************************************ - * HTTP CACHING - ************************************************/ - - /** - * Test Last-Modified match - */ - public function testLastModifiedMatch() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'GET', - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - 'HTTP_IF_MODIFIED_SINCE' => 'Sun, 03 Oct 2010 21:00:52 GMT', - )); - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->lastModified(1286139652); - }); - $s->call(); - $this->assertEquals(304, $s->response()->status()); - } - - /** - * Test Last-Modified match - */ - public function testLastModifiedDoesNotMatch() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - 'IF_MODIFIED_SINCE' => 'Sun, 03 Oct 2010 21:00:52 GMT', - )); - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->lastModified(1286139250); - }); - $s->call(); - $this->assertEquals(200, $s->response()->status()); - } - - public function testLastModifiedOnlyAcceptsIntegers() - { - $this->setExpectedException('\InvalidArgumentException'); - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - )); - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->lastModified('Test'); - }); - $s->call(); - } - - /** - * Test Last Modified header format - */ - public function testLastModifiedHeaderFormat() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - )); - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->lastModified(1286139652); - }); - $s->call(); - list($status, $header, $body) = $s->response()->finalize(); - $this->assertTrue(isset($header['Last-Modified'])); - $this->assertEquals('Sun, 03 Oct 2010 21:00:52 GMT', $header['Last-Modified']); - } - - /** - * Test ETag matches - */ - public function testEtagMatches() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - 'HTTP_IF_NONE_MATCH' => '"abc123"', - )); - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->etag('abc123'); - }); - $s->call(); - $this->assertEquals(304, $s->response()->status()); - } - - /** - * Test ETag does not match - */ - public function testEtagDoesNotMatch() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - 'IF_NONE_MATCH' => '"abc1234"', - )); - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->etag('abc123'); - }); - $s->call(); - $this->assertEquals(200, $s->response()->status()); - } - - /** - * Test ETag with invalid type - */ - public function testETagWithInvalidType() - { - $this->setExpectedException('\InvalidArgumentException'); - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - 'IF_NONE_MATCH' => '"abc1234"', - )); - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->etag('123','foo'); - }); - $s->call(); - } - - /** - * Test Expires - */ - public function testExpiresAsString() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - )); - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->expires('5 days'); - }); - $s->call(); - list($status, $header, $body) = $s->response()->finalize(); - $this->assertTrue(isset($header['Expires'])); - - $this->assertEquals( - strtotime('5 days'), - strtotime($header['Expires']), - 1 // delta - ); - } - - /** - * Test Expires - */ - public function testExpiresAsInteger() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - )); - $fiveDaysFromNow = time() + (60 * 60 * 24 * 5); - $expectedDate = gmdate('D, d M Y H:i:s T', $fiveDaysFromNow); - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s, $fiveDaysFromNow) { - $s->expires($fiveDaysFromNow); - }); - $s->call(); - list($status, $header, $body) = $s->response()->finalize(); - $this->assertTrue(isset($header['Expires'])); - $this->assertEquals($header['Expires'], $expectedDate); - } - - /************************************************ - * COOKIES - ************************************************/ - - /** - * Set cookie - * - * This tests that the Slim application instance sets - * a cookie in the HTTP response header. This does NOT - * test the implementation of setting the cookie; that is - * tested in a separate file. - */ - public function testSetCookie() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - )); - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->setCookie('foo', 'bar', '2 days'); - $s->setCookie('foo1', 'bar1', '2 days'); - }); - $s->call(); - $cookie1 = $s->response->cookies->get('foo'); - $cookie2 = $s->response->cookies->get('foo1'); - $this->assertEquals(2, count($s->response->cookies)); - $this->assertEquals('bar', $cookie1['value']); - $this->assertEquals('bar1', $cookie2['value']); - } - - /** - * Test get cookie - * - * This method ensures that the `Cookie:` HTTP request - * header is parsed if present, and made accessible via the - * Request object. - */ - public function testGetCookie() - { - \Slim\Environment::mock(array( - 'REQUEST_METHOD' => 'GET', - 'REMOTE_ADDR' => '127.0.0.1', - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - 'QUERY_STRING' => 'one=foo&two=bar', - 'SERVER_NAME' => 'slimframework.com', - 'SERVER_PORT' => 80, - 'HTTP_COOKIE' => 'foo=bar; foo2=bar2', - 'slim.url_scheme' => 'http', - 'slim.input' => '', - 'slim.errors' => @fopen('php://stderr', 'w') - )); - $s = new \Slim\Slim(); - $this->assertEquals('bar', $s->getCookie('foo')); - $this->assertEquals('bar2', $s->getCookie('foo2')); - } - - /** - * Test get cookie when cookie does not exist - */ - public function testGetCookieThatDoesNotExist() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - )); - $s = new \Slim\Slim(); - $this->assertNull($s->getCookie('foo')); - } - - /** - * Test delete cookie - * - * This method ensures that the `Set-Cookie:` HTTP response - * header is set. The implementation of setting the response - * cookie is tested separately in another file. - */ - public function testDeleteCookie() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - 'COOKIE' => 'foo=bar; foo2=bar2', - )); - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->setCookie('foo', 'bar'); - $s->deleteCookie('foo'); - }); - $s->call(); - $cookie = $s->response->cookies->get('foo'); - $this->assertEquals(1, count($s->response->cookies)); - $this->assertEquals('', $cookie['value']); - $this->assertLessThan(time(), $cookie['expires']); - } - - /************************************************ - * HELPERS - ************************************************/ - - /** - * Test get filesystem path to Slim app root directory - */ - public function testGetRoot() - { - $_SERVER['DOCUMENT_ROOT'] = dirname(__FILE__); //<-- No trailing slash - $s = new \Slim\Slim(); - $this->assertEquals($_SERVER['DOCUMENT_ROOT'] . '/foo/', $s->root()); //<-- Appends physical app path with trailing slash - } - - /** - * Test stop - */ - public function testStop() - { - $this->setExpectedException('\Slim\Exception\Stop'); - $s = new \Slim\Slim(); - $s->stop(); - } - - /** - * Test stop with subsequent output - */ - public function testStopWithSubsequentOutput() - { - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - echo "Foo"; //<-- Should be in response body! - $s->stop(); - echo "Bar"; //<-- Should not be in response body! - }); - $s->call(); - $this->assertEquals('Foo', $s->response()->body()); - } - - /** - * Test stop with output buffer on and pre content - */ - public function testStopOutputWithOutputBufferingOnAndPreContent() - { - $this->expectOutputString('1.2.Foo.3'); //<-- PHP unit uses OB here - echo "1."; - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - echo "Foo"; - $s->stop(); - }); - echo "2."; - $s->run(); //<-- Needs to be run to actually echo body - echo ".3"; - } - - /** - * Test stop does not leave output buffers open - */ - public function testStopDoesNotLeaveOutputBuffersOpen() - { - $level_start = ob_get_level(); - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->stop(); - }); - $s->run(); - $this->assertEquals($level_start, ob_get_level()); - } - - /** - * Test halt - */ - public function testHalt() - { - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - echo "Foo!"; //<-- Should not be in response body! - $s->halt(500, 'Something broke'); - }); - $s->call(); - list($status, $header, $body) = $s->response()->finalize(); - $this->assertEquals(500, $status); - $this->assertEquals('Something broke', $body); - } - - /** - * Test halt with output buffering and pre content - */ - public function testHaltOutputWithOutputBufferingOnAndPreContent() - { - $this->expectOutputString('1.2.Something broke.3'); //<-- PHP unit uses OB here - echo "1."; - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - echo "Foo!"; //<-- Should not be in response body! - $s->halt(500, 'Something broke'); - }); - echo "2."; - $s->run(); - echo ".3"; - } - - /** - * Test halt does not leave output buffers open - */ - public function testHaltDoesNotLeaveOutputBuffersOpen() - { - $level_start = ob_get_level(); - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->halt(500, ''); - }); - $s->run(); - $this->assertEquals($level_start, ob_get_level()); - } - - /** - * Test pass cleans buffer and throws exception - */ - public function testPass() - { - ob_start(); - $s = new \Slim\Slim(); - echo "Foo"; - try { - $s->pass(); - $this->fail('Did not catch Slim_Exception_Pass'); - } catch ( \Slim\Exception\Pass $e ) {} - $output = ob_get_clean(); - $this->assertEquals('', $output); - } - - /** - * Test pass when there is a subsequent fallback route - */ - public function testPassWithSubsequentRoute() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/name/Frank', //<-- Virtual - )); - $s = new \Slim\Slim(); - $s->get('/name/Frank', function () use ($s) { - echo "Fail"; //<-- Should not be in response body! - $s->pass(); - }); - $s->get('/name/:name', function ($name) { - echo $name; //<-- Should be in response body! - }); - $s->call(); - $this->assertEquals('Frank', $s->response()->body()); - } - - /** - * Test pass when there is not a subsequent fallback route - */ - public function testPassWithoutSubsequentRoute() - { - \Slim\Environment::mock(array( - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/name/Frank', //<-- Virtual - )); - $s = new \Slim\Slim(); - $s->get('/name/Frank', function () use ($s) { - echo "Fail"; //<-- Should not be in response body! - $s->pass(); - }); - $s->call(); - $this->assertEquals(404, $s->response()->status()); - } - - /** - * Test content type - */ - public function testContentType() - { - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->contentType('application/json'); - }); - $s->call(); - list($status, $header, $body) = $s->response()->finalize(); - $this->assertEquals('application/json', $header['Content-Type']); - } - - /** - * Test status - */ - public function testStatus() - { - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->status(403); - }); - $s->call(); - $this->assertEquals(403, $s->response()->status()); - } - - /** - * Test URL for - */ - public function testSlimUrlFor() - { - $s = new \Slim\Slim(); - $s->get('/hello/:name', function () {})->name('hello'); - $this->assertEquals('/foo/hello/Josh', $s->urlFor('hello', array('name' => 'Josh'))); //<-- Prepends physical path! - } - - /** - * Test redirect sets status and header - */ - public function testRedirect() - { - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - echo "Foo"; //<-- Should not be in response body! - $s->redirect('/somewhere/else', 303); - }); - $s->call(); - list($status, $header, $body) = $s->response()->finalize(); - $this->assertEquals(303, $status); - $this->assertEquals('/somewhere/else', $header['Location']); - $this->assertEquals('', $body); - } - - /************************************************ - * RUNNER - ************************************************/ - - /** - * Test that runner sends headers and body - */ - public function testRun() - { - $this->expectOutputString('Foo'); - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - echo "Foo"; - }); - $s->run(); - } - - /** - * Test runner output with output buffering on and pre content - */ - public function testRunOutputWithOutputBufferingOnAndPreContent() - { - $this->expectOutputString('1.2.Foo.3'); //<-- PHP unit uses OB here - $s = new \Slim\Slim(); - echo "1."; - $s->get('/bar', function () use ($s) { - echo "Foo"; - }); - echo "2."; - $s->run(); - echo ".3"; - } - - /** - * Test that runner does not leave output buffers open - */ - public function testRunDoesNotLeaveAnyOutputBuffersOpen() - { - $level_start = ob_get_level(); - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) {}); - $s->run(); - $this->assertEquals($level_start, ob_get_level()); - } - - /************************************************ - * MIDDLEWARE - ************************************************/ - - /** - * Test add middleware - * - * This asserts that middleware are queued and called - * in sequence. This also asserts that the environment - * variables are passed by reference. - */ - public function testAddMiddleware() - { - $this->expectOutputString('FooHello'); - $s = new \Slim\Slim(); - $s->add(new CustomMiddleware()); //<-- See top of this file for class definition - $s->get('/bar', function () { - echo 'Foo'; - }); - $s->run(); - $this->assertEquals('Hello', $s->response()->header('X-Slim-Test')); - } - - /** - * Test exception when adding circular middleware queues - * - * This asserts that the same middleware can NOT be queued twice (usually by accident). - * Circular middleware stack causes a troublesome to debug PHP Fatal error: - * - * > Fatal error: Maximum function nesting level of '100' reached. aborting! - */ - public function testFailureWhenAddingCircularMiddleware() - { - $this->setExpectedException('\RuntimeException'); - $middleware = new CustomMiddleware; - $s = new \Slim\Slim; - $s->add($middleware); - $s->add(new CustomMiddleware); - $s->add($middleware); - $s->run(); - } - - /************************************************ - * FLASH MESSAGING - ************************************************/ - - public function testSetFlashForNextRequest() - { - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->flash('info', 'bar'); - }); - $this->assertFalse(isset($_SESSION['slim.flash'])); - $s->run(); - $this->assertEquals('bar', $_SESSION['slim.flash']['info']); - } - - public function testSetFlashForCurrentRequest() - { - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->flashNow('info', 'bar'); - }); - $s->run(); - $env = $s->environment(); - $this->assertEquals('bar', $env['slim.flash']['info']); - } - - public function testKeepFlashForNextRequest() - { - $_SESSION['slim.flash'] = array('info' => 'Foo'); - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->flashKeep(); - }); - $s->run(); - $this->assertEquals('Foo', $_SESSION['slim.flash']['info']); - } - - public function testFlashData() - { - $s = new \Slim\Slim(); - $s->get('/bar', function () use ($s) { - $s->flashNow('info', 'bar'); - }); - $s->run(); - $this->assertEquals(array('info' => 'bar'), $s->flashData()); - } - - /************************************************ - * NOT FOUND HANDLING - ************************************************/ - - /** - * Test custom Not Found handler - */ - public function testNotFound() - { - $s = new \Slim\Slim(); - $s->notFound(function () { - echo "Not Found"; - }); - $s->get('/foo', function () {}); - $s->call(); - list($status, $header, $body) = $s->response()->finalize(); - $this->assertEquals(404, $status); - $this->assertEquals('Not Found', $body); - } - - /************************************************ - * ERROR HANDLING - ************************************************/ - - /** - * Test default and custom error handlers - * - * Pre-conditions: - * Invoked app route calls default error handler; - * - * Post-conditions: - * Response status code is 500; - */ - public function testSlimError() - { - $s = new \Slim\Slim(array( - "log.enabled" => false - )); - $s->get('/bar', function () use ($s) { - $s->error(); - }); - $s->call(); - $this->assertEquals(500, $s->response()->status()); - } - - /** - * Test default error handler logs the error when debug is false. - * - * Pre-conditions: - * Invoked app route calls default error handler; - * - * Post-conditions: - * Error log is called - */ - public function testDefaultHandlerLogsTheErrorWhenDebugIsFalse() - { - $s = new \Slim\Slim(array('debug' => false)); - $s->container->singleton('log', function ($c) { - return new EchoErrorLogger(); - }); - $s->get('/bar', function () use ($s) { - throw new \InvalidArgumentException('my specific error message'); - }); - - ob_start(); - $s->run(); - $output = ob_get_clean(); - $this->assertTrue(strpos($output, 'InvalidArgumentException:my specific error message') !== false); - } - - /** - * Test triggered errors are converted to ErrorExceptions - * - * Pre-conditions: - * Custom error handler defined; - * Invoked app route triggers error; - * - * Post-conditions: - * Response status is 500; - * Response body is equal to triggered error message; - * Error handler's argument is ErrorException instance; - */ - public function DISABLEDtestTriggeredErrorsAreConvertedToErrorExceptions() - { - $s = new \Slim\Slim(array( - 'debug' => false - )); - $s->error(function ( $e ) { - if ($e instanceof \ErrorException) { - echo $e->getMessage(); - } - }); - $s->get('/bar', function () { - trigger_error('Foo I say!'); - }); - $s->call(); - list($status, $header, $body) = $s->response()->finalize(); - $this->assertEquals(500, $status); - $this->assertEquals('Foo I say!', $body); - } - - /** - * Test error triggered with multiple applications - * - * Pre-conditions: - * Multiple Slim apps are instantiated; - * Both apps are run; - * One app returns 200 OK; - * One app triggers an error; - * - * Post-conditions: - * One app returns 200 OK with no Exceptions; - * One app returns 500 Error; - * Error triggered does not affect other app; - */ - public function testErrorWithMultipleApps() - { - $s1 = new \Slim\Slim(array( - 'debug' => false, - 'log.enabled' => false - )); - $s2 = new \Slim\Slim(); - $s1->get('/bar', function () use ($s1) { - $s1->error(); - }); - $s2->get('/bar', function () { - echo 'success'; - }); - $s1->call(); - $s2->call(); - $this->assertEquals(500, $s1->response()->status()); - $this->assertEquals(200, $s2->response()->status()); - } - - /** - * Test custom error handler uses existing Response object - */ - public function testErrorHandlerUsesCurrentResponseObject() - { - $s = new \Slim\Slim(array( - 'debug' => false - )); - $s->error(function ( \Exception $e ) use ($s) { - $r = $s->response(); - $r->status(503); - $r->write('Foo'); - $r['X-Powered-By'] = 'Slim'; - echo 'Bar'; - }); - $s->get('/bar', function () { - throw new \Exception('Foo'); - }); - $s->call(); - list($status, $header, $body) = $s->response()->finalize(); - $this->assertEquals(503, $status); - $this->assertEquals('FooBar', $body); - $this->assertEquals('Slim', $header['X-Powered-By']); - } - - /** - * Test custom global error handler - */ - public function testHandleErrors() - { - $defaultErrorReporting = error_reporting(); - - // Test 1 - error_reporting(E_ALL ^ E_NOTICE); // <-- Report all errors EXCEPT notices - try { - \Slim\Slim::handleErrors(E_NOTICE, 'test error', 'Slim.php', 119); - } catch (\ErrorException $e) { - $this->fail('Slim::handleErrors reported a disabled error level.'); - } - - // Test 2 - error_reporting(E_ALL | E_STRICT); // <-- Report all errors, including E_STRICT - try { - \Slim\Slim::handleErrors(E_STRICT, 'test error', 'Slim.php', 119); - $this->fail('Slim::handleErrors didn\'t report a enabled error level'); - } catch (\ErrorException $e) {} - - error_reporting($defaultErrorReporting); - } - - /** - * Slim should keep reference to a callable error callback - */ - public function testErrorHandler() { - $s = new \Slim\Slim(); - $errCallback = function () { echo "404"; }; - $s->error($errCallback); - $this->assertSame($errCallback, PHPUnit_Framework_Assert::readAttribute($s, 'error')); - } - - /** - * Slim should throw a Slim_Exception_Stop if error callback is not callable - */ - public function testErrorHandlerIfNotCallable() { - $this->setExpectedException('\Slim\Exception\Stop'); - $s = new \Slim\Slim(array("log.enabled" => false)); - $errCallback = 'foo'; - $s->error($errCallback); - } - - /** - * Slim should keep reference to a callable NotFound callback - */ - public function testNotFoundHandler() { - $s = new \Slim\Slim(); - $notFoundCallback = function () { echo "404"; }; - $s->notFound($notFoundCallback); - $this->assertSame($notFoundCallback, PHPUnit_Framework_Assert::readAttribute($s, 'notFound')); - } - - /** - * Slim should throw a Slim_Exception_Stop if NotFound callback is not callable - */ - public function testNotFoundHandlerIfNotCallable() { - $this->setExpectedException('\Slim\Exception\Stop'); - $s = new \Slim\Slim(); - $notFoundCallback = 'foo'; - $s->notFound($notFoundCallback); - } - - /************************************************ - * HOOKS - ************************************************/ - - /** - * Test hook listener - * - * Pre-conditions: - * Slim app instantiated; - * Hook name does not exist; - * Listeners are callable objects; - * - * Post-conditions: - * Callables are invoked in expected order; - */ - public function testRegistersAndCallsHooksByPriority() - { - $this->expectOutputString('barfoo'); - $app = new \Slim\Slim(); - $callable1 = function () { echo "foo"; }; - $callable2 = function () { echo "bar"; }; - $app->hook('test.hook.one', $callable1); //default is 10 - $app->hook('test.hook.one', $callable2, 8); - $hooks = $app->getHooks(); - $this->assertEquals(7, count($hooks)); //6 default, 1 custom - $app->applyHook('test.hook.one'); - } - - /** - * Test hook listener if listener is not callable - * - * Pre-conditions: - * Slim app instantiated; - * Hook name does not exist; - * Listener is NOT a callable object; - * - * Post-conditions: - * Hook is created; - * Callable is NOT assigned to hook; - */ - public function testHookInvalidCallable() - { - $app = new \Slim\Slim(); - $callable = 'test'; //NOT callable - $app->hook('test.hook.one', $callable); - $this->assertEquals(array(array()), $app->getHooks('test.hook.one')); - } - - /** - * Test hook invocation if hook does not exist - * - * Pre-conditions: - * Slim app instantiated; - * Hook name does not exist; - * - * Post-conditions: - * Hook is created; - * Hook initialized with empty array; - */ - public function testHookInvocationIfNotExists() - { - $app = new \Slim\Slim(); - $app->applyHook('test.hook.one'); - $this->assertEquals(array(array()), $app->getHooks('test.hook.one')); - } - - /** - * Test clear hooks - * - * Pre-conditions: - * Slim app instantiated; - * Two hooks exist, each with one listener; - * - * Post-conditions: - * Case A: Listeners for 'test.hook.one' are cleared; - * Case B: Listeners for all hooks are cleared; - */ - public function testHookClear() - { - $app = new \Slim\Slim(); - $app->hook('test.hook.one', function () {}); - $app->hook('test.hook.two', function () {}); - $app->clearHooks('test.hook.two'); - $this->assertEquals(array(array()), $app->getHooks('test.hook.two')); - $hookOne = $app->getHooks('test.hook.one'); - $this->assertTrue(count($hookOne[10]) === 1); - $app->clearHooks(); - $this->assertEquals(array(array()), $app->getHooks('test.hook.one')); - } - - /** - * Test hooks accept multiple arguments - * - * Pre-conditions: - * Slim app instantiated; - * Hook name does not exist; - * Listener is a callable object; - * - * Post-conditions: - * Callable invoked with 2 arguments - */ - public function testHooksMultipleArguments() - { - $testArgA = 'argumentA'; - $testArgB = 'argumentB'; - - $this->expectOutputString($testArgA . $testArgB); - - $app = new \Slim\Slim(); - - $app->hook('test.hook.one', function ($argA, $argB) { - echo $argA . $argB; - }); - $app->applyHook('test.hook.one', $testArgA, $testArgB); - } - - /** - * Test late static binding - * - * Pre-conditions: - * Slim app is extended by Derived class and instantiated; - * Derived class overrides the 'getDefaultSettings' function and adds an extra default config value - * Test that the new config value exists - * - * Post-conditions: - * Config value exists and is equal to expected value - */ - public function testDerivedClassCanOverrideStaticFunction() - { - $app = new Derived(); - $this->assertEquals($app->config("late-static-binding"), true); - } -} diff --git a/vendor/slim/slim/tests/ViewTest.php b/vendor/slim/slim/tests/ViewTest.php deleted file mode 100644 index 5d84b8b..0000000 --- a/vendor/slim/slim/tests/ViewTest.php +++ /dev/null @@ -1,199 +0,0 @@ - - * @copyright 2011 Josh Lockhart - * @link http://www.slimframework.com - * @license http://www.slimframework.com/license - * @version 2.6.1 - * - * MIT LICENSE - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -class ViewTest extends PHPUnit_Framework_TestCase -{ - public function testGetDataAll() - { - $view = new \Slim\View(); - $prop = new \ReflectionProperty($view, 'data'); - $prop->setAccessible(true); - $prop->setValue($view, new \Slim\Helper\Set(array('foo' => 'bar'))); - - $this->assertSame(array('foo' => 'bar'), $view->getData()); - } - - public function testGetDataKeyExists() - { - $view = new \Slim\View(); - $prop = new \ReflectionProperty($view, 'data'); - $prop->setAccessible(true); - $prop->setValue($view, new \Slim\Helper\Set(array('foo' => 'bar'))); - - $this->assertEquals('bar', $view->getData('foo')); - } - - public function testGetDataKeyNotExists() - { - $view = new \Slim\View(); - $prop = new \ReflectionProperty($view, 'data'); - $prop->setAccessible(true); - $prop->setValue($view, new \Slim\Helper\Set(array('foo' => 'bar'))); - - $this->assertNull($view->getData('abc')); - } - - public function testSetDataKeyValue() - { - $view = new \Slim\View(); - $prop = new \ReflectionProperty($view, 'data'); - $prop->setAccessible(true); - $view->setData('foo', 'bar'); - - $this->assertEquals(array('foo' => 'bar'), $prop->getValue($view)->all()); - } - - public function testSetDataKeyValueAsClosure() - { - $view = new \Slim\View(); - $prop = new \ReflectionProperty($view, 'data'); - $prop->setAccessible(true); - - $view->setData('fooClosure', function () { - return 'foo'; - }); - - $value = $prop->getValue($view)->get('fooClosure'); - $this->assertInstanceOf('Closure', $value); - $this->assertEquals('foo', $value()); - } - - public function testSetDataArray() - { - $view = new \Slim\View(); - $prop = new \ReflectionProperty($view, 'data'); - $prop->setAccessible(true); - $view->setData(array('foo' => 'bar')); - - $this->assertEquals(array('foo' => 'bar'), $prop->getValue($view)->all()); - } - - public function testSetDataInvalidArgument() - { - $this->setExpectedException('InvalidArgumentException'); - - $view = new \Slim\View(); - $view->setData('foo'); - } - - public function testAppendData() - { - $view = new \Slim\View(); - $prop = new \ReflectionProperty($view, 'data'); - $prop->setAccessible(true); - $view->appendData(array('foo' => 'bar')); - - $this->assertEquals(array('foo' => 'bar'), $prop->getValue($view)->all()); - } - - public function testLocalData() - { - $view = new \Slim\View(); - $prop1 = new \ReflectionProperty($view, 'data'); - $prop1->setAccessible(true); - $prop1->setValue($view, new \Slim\Helper\Set(array('foo' => 'bar'))); - - $prop2 = new \ReflectionProperty($view, 'templatesDirectory'); - $prop2->setAccessible(true); - $prop2->setValue($view, dirname(__FILE__) . '/templates'); - - $output = $view->fetch('test.php', array('foo' => 'baz')); - $this->assertEquals('test output baz', $output); - } - - public function testAppendDataOverwrite() - { - $view = new \Slim\View(); - $prop = new \ReflectionProperty($view, 'data'); - $prop->setAccessible(true); - $prop->setValue($view, new \Slim\Helper\Set(array('foo' => 'bar'))); - $view->appendData(array('foo' => '123')); - - $this->assertEquals(array('foo' => '123'), $prop->getValue($view)->all()); - } - - public function testAppendDataInvalidArgument() - { - $this->setExpectedException('InvalidArgumentException'); - - $view = new \Slim\View(); - $view->appendData('foo'); - } - - public function testGetTemplatesDirectory() - { - $view = new \Slim\View(); - $property = new \ReflectionProperty($view, 'templatesDirectory'); - $property->setAccessible(true); - $property->setValue($view, 'templates'); - - $this->assertEquals('templates', $view->getTemplatesDirectory()); - } - - public function testSetTemplatesDirectory() - { - $view = new \Slim\View(); - $directory = 'templates' . DIRECTORY_SEPARATOR; - $view->setTemplatesDirectory($directory); // <-- Should strip trailing slash - - $this->assertAttributeEquals('templates', 'templatesDirectory', $view); - } - - public function testDisplay() - { - $this->expectOutputString('test output bar'); - - $view = new \Slim\View(); - $prop1 = new \ReflectionProperty($view, 'data'); - $prop1->setAccessible(true); - $prop1->setValue($view, new \Slim\Helper\Set(array('foo' => 'bar'))); - - $prop2 = new \ReflectionProperty($view, 'templatesDirectory'); - $prop2->setAccessible(true); - $prop2->setValue($view, dirname(__FILE__) . '/templates'); - - $view->display('test.php'); - } - - public function testDisplayTemplateThatDoesNotExist() - { - $this->setExpectedException('\RuntimeException'); - - $view = new \Slim\View(); - - $prop2 = new \ReflectionProperty($view, 'templatesDirectory'); - $prop2->setAccessible(true); - $prop2->setValue($view, dirname(__FILE__) . '/templates'); - - $view->display('foo.php'); - } -} diff --git a/vendor/slim/slim/tests/bootstrap.php b/vendor/slim/slim/tests/bootstrap.php deleted file mode 100644 index c253350..0000000 --- a/vendor/slim/slim/tests/bootstrap.php +++ /dev/null @@ -1,22 +0,0 @@ -