Added vendor/ directory for Composer's installed files

This commit is contained in:
Ascendings
2015-08-30 12:33:20 -04:00
parent 45df179c49
commit b66a773ed8
1162 changed files with 112457 additions and 0 deletions

20
vendor/slim/slim/CONTRIBUTING.md vendored Executable file
View File

@ -0,0 +1,20 @@
# 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/)

19
vendor/slim/slim/LICENSE vendored Executable file
View File

@ -0,0 +1,19 @@
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.

208
vendor/slim/slim/README.markdown vendored Executable file
View File

@ -0,0 +1,208 @@
# 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:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="slim" patternSyntax="Wildcard">
<match url="*" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="index.php" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
#### 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
<http://docs.slimframework.com/>
## 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 <http://help.slimframework.com> 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.
<http://www.slimframework.com/license>

228
vendor/slim/slim/Slim/Environment.php vendored Executable file
View File

@ -0,0 +1,228 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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);
}
}

49
vendor/slim/slim/Slim/Exception/Pass.php vendored Executable file
View File

@ -0,0 +1,49 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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
{
}

47
vendor/slim/slim/Slim/Exception/Stop.php vendored Executable file
View File

@ -0,0 +1,47 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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
{
}

246
vendor/slim/slim/Slim/Helper/Set.php vendored Executable file
View File

@ -0,0 +1,246 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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;
};
}
}

91
vendor/slim/slim/Slim/Http/Cookies.php vendored Executable file
View File

@ -0,0 +1,91 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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;
class Cookies extends \Slim\Helper\Set
{
/**
* Default cookie settings
* @var array
*/
protected $defaults = array(
'value' => '',
'domain' => null,
'path' => null,
'expires' => null,
'secure' => false,
'httponly' => false
);
/**
* Set cookie
*
* 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.
*
* 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 $key Cookie name
* @param mixed $value Cookie settings
*/
public function set($key, $value)
{
if (is_array($value)) {
$cookieSettings = array_replace($this->defaults, $value);
} else {
$cookieSettings = array_replace($this->defaults, array('value' => $value));
}
parent::set($key, $cookieSettings);
}
/**
* Remove cookie
*
* 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.
*
* @param string $key Cookie name
* @param array $settings Optional cookie settings
*/
public function remove($key, $settings = array())
{
$settings['value'] = '';
$settings['expires'] = time() - 86400;
$this->set($key, array_replace($this->defaults, $settings));
}
}

104
vendor/slim/slim/Slim/Http/Headers.php vendored Executable file
View File

@ -0,0 +1,104 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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;
/**
* HTTP Headers
*
* @package Slim
* @author Josh Lockhart
* @since 1.6.0
*/
class Headers extends \Slim\Helper\Set
{
/********************************************************************************
* Static interface
*******************************************************************************/
/**
* 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.
*
* @var array
*/
protected static $special = array(
'CONTENT_TYPE',
'CONTENT_LENGTH',
'PHP_AUTH_USER',
'PHP_AUTH_PW',
'PHP_AUTH_DIGEST',
'AUTH_TYPE'
);
/**
* Extract HTTP headers from an array of data (e.g. $_SERVER)
* @param array $data
* @return array
*/
public static function extract($data)
{
$results = array();
foreach ($data 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;
}
$results[$key] = $value;
}
}
return $results;
}
/********************************************************************************
* Instance interface
*******************************************************************************/
/**
* Transform header name into canonical form
* @param string $key
* @return string
*/
protected function normalizeKey($key)
{
$key = strtolower($key);
$key = str_replace(array('-', '_'), ' ', $key);
$key = preg_replace('#^http #', '', $key);
$key = ucwords($key);
$key = str_replace(' ', '-', $key);
return $key;
}
}

617
vendor/slim/slim/Slim/Http/Request.php vendored Executable file
View File

@ -0,0 +1,617 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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 Request
*
* This class provides a human-friendly interface to the Slim environment variables;
* environment variables are passed by reference and will be modified directly.
*
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*/
class Request
{
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';
/**
* @var array
*/
protected static $formDataMediaTypes = array('application/x-www-form-urlencoded');
/**
* Application Environment
* @var \Slim\Environment
*/
protected $env;
/**
* HTTP Headers
* @var \Slim\Http\Headers
*/
public $headers;
/**
* HTTP Cookies
* @var \Slim\Helper\Set
*/
public $cookies;
/**
* Constructor
* @param \Slim\Environment $env
*/
public function __construct(\Slim\Environment $env)
{
$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']));
}
/**
* Get HTTP method
* @return string
*/
public function getMethod()
{
return $this->env['REQUEST_METHOD'];
}
/**
* Is this a GET request?
* @return bool
*/
public function isGet()
{
return $this->getMethod() === self::METHOD_GET;
}
/**
* Is this a POST request?
* @return bool
*/
public function isPost()
{
return $this->getMethod() === self::METHOD_POST;
}
/**
* Is this a PUT request?
* @return bool
*/
public function isPut()
{
return $this->getMethod() === self::METHOD_PUT;
}
/**
* Is this a PATCH request?
* @return bool
*/
public function isPatch()
{
return $this->getMethod() === self::METHOD_PATCH;
}
/**
* Is this a DELETE request?
* @return bool
*/
public function isDelete()
{
return $this->getMethod() === self::METHOD_DELETE;
}
/**
* Is this a HEAD request?
* @return bool
*/
public function isHead()
{
return $this->getMethod() === self::METHOD_HEAD;
}
/**
* Is this a OPTIONS request?
* @return bool
*/
public function isOptions()
{
return $this->getMethod() === self::METHOD_OPTIONS;
}
/**
* Is this an AJAX request?
* @return bool
*/
public function isAjax()
{
if ($this->params('isajax')) {
return true;
} elseif (isset($this->headers['X_REQUESTED_WITH']) && $this->headers['X_REQUESTED_WITH'] === 'XMLHttpRequest') {
return true;
}
return false;
}
/**
* Is this an XHR request? (alias of Slim_Http_Request::isAjax)
* @return bool
*/
public function isXhr()
{
return $this->isAjax();
}
/**
* Fetch GET and POST data
*
* 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.
*
* @param string $key
* @param mixed $default
* @return array|mixed|null
*/
public function params($key = null, $default = null)
{
$union = array_merge($this->get(), $this->post());
if ($key) {
return isset($union[$key]) ? $union[$key] : $default;
}
return $union;
}
/**
* Fetch GET data
*
* 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.
*
* @param string $key
* @param mixed $default Default return value when key does not exist
* @return array|mixed|null
*/
public function get($key = null, $default = null)
{
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'];
}
}
/**
* Fetch POST data
*
* 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.
*
* @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
*/
public function post($key = null, $default = null)
{
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'];
}
}
/**
* 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
*/
public function put($key = null, $default = null)
{
return $this->post($key, $default);
}
/**
* 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
*/
public function patch($key = null, $default = null)
{
return $this->post($key, $default);
}
/**
* 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
*/
public function delete($key = null, $default = null)
{
return $this->post($key, $default);
}
/**
* Fetch COOKIE data
*
* 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.
*
* @param string $key
* @return array|string|null
*/
public function cookies($key = null)
{
if ($key) {
return $this->cookies->get($key);
}
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
*/
public function isFormData()
{
$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);
}
/**
* Get Headers
*
* 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.
*
* @param string $key
* @param mixed $default The default value returned if the requested header is not available
* @return mixed
*/
public function headers($key = null, $default = null)
{
if ($key) {
return $this->headers->get($key, $default);
}
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'];
}
/**
* Get Content Type
* @return string|null
*/
public function getContentType()
{
return $this->headers->get('CONTENT_TYPE');
}
/**
* Get Media Type (type/subtype within Content Type header)
* @return string|null
*/
public function getMediaType()
{
$contentType = $this->getContentType();
if ($contentType) {
$contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
return strtolower($contentTypeParts[0]);
}
return null;
}
/**
* Get Media Type Params
* @return array
*/
public function getMediaTypeParams()
{
$contentType = $this->getContentType();
$contentTypeParams = array();
if ($contentType) {
$contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
$contentTypePartsLength = count($contentTypeParts);
for ($i = 1; $i < $contentTypePartsLength; $i++) {
$paramParts = explode('=', $contentTypeParts[$i]);
$contentTypeParams[strtolower($paramParts[0])] = $paramParts[1];
}
}
return $contentTypeParams;
}
/**
* Get Content Charset
* @return string|null
*/
public function getContentCharset()
{
$mediaTypeParams = $this->getMediaTypeParams();
if (isset($mediaTypeParams['charset'])) {
return $mediaTypeParams['charset'];
}
return null;
}
/**
* Get Content-Length
* @return int
*/
public function getContentLength()
{
return $this->headers->get('CONTENT_LENGTH', 0);
}
/**
* Get Host
* @return string
*/
public function getHost()
{
if (isset($this->env['HTTP_HOST'])) {
if (strpos($this->env['HTTP_HOST'], ':') !== false) {
$hostParts = explode(':', $this->env['HTTP_HOST']);
return $hostParts[0];
}
return $this->env['HTTP_HOST'];
}
return $this->env['SERVER_NAME'];
}
/**
* Get Host with Port
* @return string
*/
public function getHostWithPort()
{
return sprintf('%s:%s', $this->getHost(), $this->getPort());
}
/**
* Get Port
* @return int
*/
public function getPort()
{
return (int)$this->env['SERVER_PORT'];
}
/**
* Get Scheme (https or http)
* @return string
*/
public function getScheme()
{
return $this->env['slim.url_scheme'];
}
/**
* Get Script Name (physical path)
* @return string
*/
public function getScriptName()
{
return $this->env['SCRIPT_NAME'];
}
/**
* LEGACY: Get Root URI (alias for Slim_Http_Request::getScriptName)
* @return string
*/
public function getRootUri()
{
return $this->getScriptName();
}
/**
* Get Path (physical path + virtual path)
* @return string
*/
public function getPath()
{
return $this->getScriptName() . $this->getPathInfo();
}
/**
* Get Path Info (virtual path)
* @return string
*/
public function getPathInfo()
{
return $this->env['PATH_INFO'];
}
/**
* LEGACY: Get Resource URI (alias for Slim_Http_Request::getPathInfo)
* @return string
*/
public function getResourceUri()
{
return $this->getPathInfo();
}
/**
* Get URL (scheme + host [ + port if non-standard ])
* @return string
*/
public function getUrl()
{
$url = $this->getScheme() . '://' . $this->getHost();
if (($this->getScheme() === 'https' && $this->getPort() !== 443) || ($this->getScheme() === 'http' && $this->getPort() !== 80)) {
$url .= sprintf(':%s', $this->getPort());
}
return $url;
}
/**
* Get IP
* @return string
*/
public function getIp()
{
$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];
}
}
return $this->env['REMOTE_ADDR'];
}
/**
* Get Referrer
* @return string|null
*/
public function getReferrer()
{
return $this->headers->get('HTTP_REFERER');
}
/**
* Get Referer (for those who can't spell)
* @return string|null
*/
public function getReferer()
{
return $this->getReferrer();
}
/**
* Get User Agent
* @return string|null
*/
public function getUserAgent()
{
return $this->headers->get('HTTP_USER_AGENT');
}
}

520
vendor/slim/slim/Slim/Http/Response.php vendored Executable file
View File

@ -0,0 +1,520 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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;
/**
* 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.
*
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*/
class Response implements \ArrayAccess, \Countable, \IteratorAggregate
{
/**
* @var int HTTP status code
*/
protected $status;
/**
* @var \Slim\Http\Headers
*/
public $headers;
/**
* @var \Slim\Http\Cookies
*/
public $cookies;
/**
* @var string HTTP response body
*/
protected $body;
/**
* @var int Length of HTTP response body
*/
protected $length;
/**
* @var array HTTP response codes and messages
*/
protected static $messages = array(
//Informational 1xx
100 => '100 Continue',
101 => '101 Switching Protocols',
//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',
//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',
//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',
//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
*/
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;
}
/**
* DEPRECATION WARNING! Use `getStatus` or `setStatus` instead.
*
* Get and set status
* @param int|null $status
* @return int
*/
public function status($status = null)
{
if (!is_null($status)) {
$this->status = (int) $status;
}
return $this->status;
}
/**
* 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
*/
public function header($name, $value = null)
{
if (!is_null($value)) {
$this->headers->set($name, $value);
}
return $this->headers->get($name);
}
/**
* DEPRECATION WARNING! Access `headers` property directly.
*
* Get headers
* @return \Slim\Http\Headers
*/
public function headers()
{
return $this->headers;
}
public function getBody()
{
return $this->body;
}
public function setBody($content)
{
$this->write($content, true);
}
/**
* DEPRECATION WARNING! use `getBody` or `setBody` instead.
*
* Get and set body
* @param string|null $body Content of HTTP response body
* @return string
*/
public function body($body = null)
{
if (!is_null($body)) {
$this->write($body, true);
}
return $this->body;
}
/**
* 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;
}
$this->length = strlen($this->body);
return $this->body;
}
public function getLength()
{
return $this->length;
}
/**
* DEPRECATION WARNING! Use `getLength` or `write` or `body` instead.
*
* Get and set length
* @param int|null $length
* @return int
*/
public function length($length = null)
{
if (!is_null($length)) {
$this->length = (int) $length;
}
return $this->length;
}
/**
* Finalize
*
* 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.
*
* @return array[int status, array headers, string body]
*/
public function finalize()
{
// Prepare response
if (in_array($this->status, array(204, 304))) {
$this->headers->remove('Content-Type');
$this->headers->remove('Content-Length');
$this->setBody('');
}
return array($this->status, $this->headers, $this->body);
}
/**
* DEPRECATION WARNING! Access `cookies` property directly.
*
* Set cookie
*
* 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.
*
* @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
*/
public function setCookie($name, $value)
{
// Util::setCookieHeader($this->header, $name, $value);
$this->cookies->set($name, $value);
}
/**
* DEPRECATION WARNING! Access `cookies` property directly.
*
* Delete cookie
*
* 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 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
*/
public function deleteCookie($name, $settings = array())
{
$this->cookies->remove($name, $settings);
// Util::deleteCookieHeader($this->header, $name, $value);
}
/**
* Redirect
*
* This method prepares this response to return an HTTP Redirect response
* to the HTTP client.
*
* @param string $url The redirect destination
* @param int $status The redirect HTTP status code
*/
public function redirect ($url, $status = 302)
{
$this->setStatus($status);
$this->headers->set('Location', $url);
}
/**
* Helpers: Empty?
* @return bool
*/
public function isEmpty()
{
return in_array($this->status, array(201, 204, 304));
}
/**
* Helpers: Informational?
* @return bool
*/
public function isInformational()
{
return $this->status >= 100 && $this->status < 200;
}
/**
* Helpers: OK?
* @return bool
*/
public function isOk()
{
return $this->status === 200;
}
/**
* Helpers: Successful?
* @return bool
*/
public function isSuccessful()
{
return $this->status >= 200 && $this->status < 300;
}
/**
* Helpers: Redirect?
* @return bool
*/
public function isRedirect()
{
return in_array($this->status, array(301, 302, 303, 307));
}
/**
* Helpers: Redirection?
* @return bool
*/
public function isRedirection()
{
return $this->status >= 300 && $this->status < 400;
}
/**
* Helpers: Forbidden?
* @return bool
*/
public function isForbidden()
{
return $this->status === 403;
}
/**
* Helpers: Not Found?
* @return bool
*/
public function isNotFound()
{
return $this->status === 404;
}
/**
* Helpers: Client error?
* @return bool
*/
public function isClientError()
{
return $this->status >= 400 && $this->status < 500;
}
/**
* Helpers: Server Error?
* @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]);
}
/**
* 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
*
* This returns the contained `\Slim\Http\Headers` instance which
* is itself iterable.
*
* @return \Slim\Http\Headers
*/
public function getIterator()
{
return $this->headers->getIterator();
}
/**
* Get message for HTTP status code
* @param int $status
* @return string|null
*/
public static function getMessageForCode($status)
{
if (isset(self::$messages[$status])) {
return self::$messages[$status];
} else {
return null;
}
}
}

434
vendor/slim/slim/Slim/Http/Util.php vendored Executable file
View File

@ -0,0 +1,434 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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);
}
}

354
vendor/slim/slim/Slim/Log.php vendored Executable file
View File

@ -0,0 +1,354 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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);
}
}

75
vendor/slim/slim/Slim/LogWriter.php vendored Executable file
View File

@ -0,0 +1,75 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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);
}
}

114
vendor/slim/slim/Slim/Middleware.php vendored Executable file
View File

@ -0,0 +1,114 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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();
}

View File

@ -0,0 +1,174 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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;
}
}

212
vendor/slim/slim/Slim/Middleware/Flash.php vendored Executable file
View File

@ -0,0 +1,212 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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());
}
}

View File

@ -0,0 +1,94 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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();
}
}

View File

@ -0,0 +1,116 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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('<div>#', '</div>'), $exception->getTraceAsString());
$html = sprintf('<h1>%s</h1>', $title);
$html .= '<p>The application could not run because of the following error:</p>';
$html .= '<h2>Details</h2>';
$html .= sprintf('<div><strong>Type:</strong> %s</div>', get_class($exception));
if ($code) {
$html .= sprintf('<div><strong>Code:</strong> %s</div>', $code);
}
if ($message) {
$html .= sprintf('<div><strong>Message:</strong> %s</div>', $message);
}
if ($file) {
$html .= sprintf('<div><strong>File:</strong> %s</div>', $file);
}
if ($line) {
$html .= sprintf('<div><strong>Line:</strong> %s</div>', $line);
}
if ($trace) {
$html .= '<h2>Trace</h2>';
$html .= sprintf('<pre>%s</pre>', $trace);
}
return sprintf("<html><head><title>%s</title><style>body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}</style></head><body>%s</body></html>", $title, $html);
}
}

View File

@ -0,0 +1,205 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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;
}
}

471
vendor/slim/slim/Slim/Route.php vendored Executable file
View File

@ -0,0 +1,471 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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;
/**
* Route
* @package Slim
* @author Josh Lockhart, Thomas Bley
* @since 1.0.0
*/
class Route
{
/**
* @var string The route pattern (e.g. "/books/:id")
*/
protected $pattern;
/**
* @var mixed The route callable
*/
protected $callable;
/**
* @var array Conditions for this route's URL parameters
*/
protected $conditions = array();
/**
* @var array Default conditions applied to all route instances
*/
protected static $defaultConditions = array();
/**
* @var string The name of this route (optional)
*/
protected $name;
/**
* @var array Key-value array of URL parameters
*/
protected $params = array();
/**
* @var array value array of URL parameter names
*/
protected $paramNames = array();
/**
* @var array key array of URL parameter names with + at the end
*/
protected $paramNamesPath = array();
/**
* @var array HTTP methods supported by this Route
*/
protected $methods = array();
/**
* @var array[Callable] Middleware to be run before only this route instance
*/
protected $middleware = array();
/**
* @var bool Whether or not this route should be matched in a case-sensitive manner
*/
protected $caseSensitive;
/**
* 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
*/
public function __construct($pattern, $callable, $caseSensitive = true)
{
$this->setPattern($pattern);
$this->setCallable($callable);
$this->setConditions(self::getDefaultConditions());
$this->caseSensitive = $caseSensitive;
}
/**
* Set default route conditions for all instances
* @param array $defaultConditions
*/
public static function setDefaultConditions(array $defaultConditions)
{
self::$defaultConditions = $defaultConditions;
}
/**
* Get default route conditions for all instances
* @return array
*/
public static function getDefaultConditions()
{
return self::$defaultConditions;
}
/**
* Get route pattern
* @return string
*/
public function getPattern()
{
return $this->pattern;
}
/**
* Set route pattern
* @param string $pattern
*/
public function setPattern($pattern)
{
$this->pattern = $pattern;
}
/**
* Get route callable
* @return mixed
*/
public function getCallable()
{
return $this->callable;
}
/**
* Set route callable
* @param mixed $callable
* @throws \InvalidArgumentException If argument is not 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
*/
public function getConditions()
{
return $this->conditions;
}
/**
* Set route conditions
* @param array $conditions
*/
public function setConditions(array $conditions)
{
$this->conditions = $conditions;
}
/**
* Get route name
* @return string|null
*/
public function getName()
{
return $this->name;
}
/**
* 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
* @return string
* @throws \InvalidArgumentException If route parameter does not exist at index
*/
public function getParam($index)
{
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;
}
/**
* Add supported HTTP method(s)
*/
public function setHttpMethods()
{
$args = func_get_args();
$this->methods = $args;
}
/**
* Get supported HTTP methods
* @return array
*/
public function getHttpMethods()
{
return $this->methods;
}
/**
* Append supported HTTP methods
*/
public function appendHttpMethods()
{
$args = func_get_args();
if(count($args) && is_array($args[0])){
$args = $args[0];
}
$this->methods = array_merge($this->methods, $args);
}
/**
* Append supported HTTP methods (alias for Route::appendHttpMethods)
* @return \Slim\Route
*/
public function via()
{
$args = func_get_args();
if(count($args) && is_array($args[0])){
$args = $args[0];
}
$this->methods = array_merge($this->methods, $args);
return $this;
}
/**
* Detect support for an HTTP method
* @param string $method
* @return bool
*/
public function supportsHttpMethod($method)
{
return in_array($method, $this->methods);
}
/**
* Get middleware
* @return array[Callable]
*/
public function getMiddleware()
{
return $this->middleware;
}
/**
* 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.
*/
public function setMiddleware($middleware)
{
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;
}
/**
* Matches URI?
*
* 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:
*
* http://blog.sosedoff.com/2009/09/20/rails-like-php-url-router/
*
* @param string $resourceUri A Request URI
* @return bool
*/
public function matches($resourceUri)
{
//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';
}
//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;
}
/**
* 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] . '>[^/]+)';
}
/**
* Set route name
* @param string $name The name of the route
* @return \Slim\Route
*/
public function name($name)
{
$this->setName($name);
return $this;
}
/**
* Merge route conditions
* @param array $conditions Key-value array of URL parameter conditions
* @return \Slim\Route
*/
public function conditions(array $conditions)
{
$this->conditions = array_merge($this->conditions, $conditions);
return $this;
}
/**
* Dispatch route
*
* 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
*/
public function dispatch()
{
foreach ($this->middleware as $mw) {
call_user_func_array($mw, array($this));
}
$return = call_user_func_array($this->getCallable(), array_values($this->getParams()));
return ($return === false) ? false : true;
}
}

257
vendor/slim/slim/Slim/Router.php vendored Executable file
View File

@ -0,0 +1,257 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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;
/**
* Router
*
* This class organizes, iterates, and dispatches \Slim\Route objects.
*
* @package Slim
* @author Josh Lockhart
* @since 1.0.0
*/
class Router
{
/**
* @var Route The current route (most recently dispatched)
*/
protected $currentRoute;
/**
* @var array Lookup hash of all route objects
*/
protected $routes;
/**
* @var array Lookup hash of named route objects, keyed by route name (lazy-loaded)
*/
protected $namedRoutes;
/**
* @var array Array of route objects that match the request URI (lazy-loaded)
*/
protected $matchedRoutes;
/**
* @var array Array containing all route groups
*/
protected $routeGroups;
/**
* Constructor
*/
public function __construct()
{
$this->routes = array();
$this->routeGroups = array();
}
/**
* Get Current Route object or the first matched one if matching has been performed
* @return \Slim\Route|null
*/
public function getCurrentRoute()
{
if ($this->currentRoute !== null) {
return $this->currentRoute;
}
if (is_array($this->matchedRoutes) && count($this->matchedRoutes) > 0) {
return $this->matchedRoutes[0];
}
return null;
}
/**
* 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]
*/
public function getMatchedRoutes($httpMethod, $resourceUri, $reload = false)
{
if ($reload || is_null($this->matchedRoutes)) {
$this->matchedRoutes = array();
foreach ($this->routes as $route) {
if (!$route->supportsHttpMethod($httpMethod) && !$route->supportsHttpMethod("ANY")) {
continue;
}
if ($route->matches($resourceUri)) {
$this->matchedRoutes[] = $route;
}
}
}
return $this->matchedRoutes;
}
/**
* Add a route object to the router
* @param \Slim\Route $route The Slim Route
*/
public function map(\Slim\Route $route)
{
list($groupPattern, $groupMiddleware) = $this->processGroups();
$route->setPattern($groupPattern . $route->getPattern());
$this->routes[] = $route;
foreach ($groupMiddleware as $middleware) {
$route->setMiddleware($middleware);
}
}
/**
* A helper function for processing the group's pattern and middleware
* @return array Returns an array with the elements: pattern, middlewareArr
*/
protected function processGroups()
{
$pattern = "";
$middleware = array();
foreach ($this->routeGroups as $group) {
$k = key($group);
$pattern .= $k;
if (is_array($group[$k])) {
$middleware = array_merge($middleware, $group[$k]);
}
}
return array($pattern, $middleware);
}
/**
* 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
*/
public function pushGroup($group, $middleware = array())
{
return array_push($this->routeGroups, array($group => $middleware));
}
/**
* Removes the last route group from the array
* @return bool True if successful, else False
*/
public function popGroup()
{
return (array_pop($this->routeGroups) !== null);
}
/**
* 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
*/
public function urlFor($name, $params = array())
{
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)#';
}
$pattern = preg_replace($search, $params, $this->getNamedRoute($name)->getPattern());
//Remove remnants of unpopulated, trailing optional pattern segments, escaped special characters
return preg_replace('#\(/?:.+\)|\(|\)|\\\\#', '', $pattern);
}
/**
* 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
*/
public function addNamedRoute($name, \Slim\Route $route)
{
if ($this->hasNamedRoute($name)) {
throw new \RuntimeException('Named route already exists with name: ' . $name);
}
$this->namedRoutes[(string) $name] = $route;
}
/**
* Has named route
* @param string $name The route name
* @return bool
*/
public function hasNamedRoute($name)
{
$this->getNamedRoutes();
return isset($this->namedRoutes[(string) $name]);
}
/**
* Get named route
* @param string $name
* @return \Slim\Route|null
*/
public function getNamedRoute($name)
{
$this->getNamedRoutes();
if ($this->hasNamedRoute($name)) {
return $this->namedRoutes[(string) $name];
}
return null;
}
/**
* Get named routes
* @return \ArrayIterator
*/
public function getNamedRoutes()
{
if (is_null($this->namedRoutes)) {
$this->namedRoutes = array();
foreach ($this->routes as $route) {
if ($route->getName() !== null) {
$this->addNamedRoute($route->getName(), $route);
}
}
}
return new \ArrayIterator($this->namedRoutes);
}
}

1444
vendor/slim/slim/Slim/Slim.php vendored Executable file

File diff suppressed because it is too large Load Diff

282
vendor/slim/slim/Slim/View.php vendored Executable file
View File

@ -0,0 +1,282 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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();
}
}

24
vendor/slim/slim/composer.json vendored Executable file
View File

@ -0,0 +1,24 @@
{
"name": "slim/slim",
"type": "library",
"description": "Slim Framework, a PHP micro framework",
"keywords": ["microframework","rest","router"],
"homepage": "http://github.com/codeguy/Slim",
"license": "MIT",
"authors": [
{
"name": "Josh Lockhart",
"email": "info@joshlockhart.com",
"homepage": "http://www.joshlockhart.com/"
}
],
"require": {
"php": ">=5.3.0"
},
"suggest": {
"ext-mcrypt": "Required for HTTP cookie encryption"
},
"autoload": {
"psr-0": { "Slim": "." }
}
}

169
vendor/slim/slim/index.php vendored Executable file
View File

@ -0,0 +1,169 @@
<?php
/**
* Step 1: Require the Slim Framework
*
* If you are not using Composer, you need to require the
* Slim Framework and register its PSR-0 autoloader.
*
* If you are using Composer, you can skip this step.
*/
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
/**
* Step 2: Instantiate a Slim application
*
* This example instantiates a Slim application using
* its default settings. However, you will usually configure
* your Slim application now by passing an associative array
* of setting names and values into the application constructor.
*/
$app = new \Slim\Slim();
/**
* Step 3: Define the Slim application routes
*
* Here we define several Slim application routes that respond
* to appropriate HTTP request methods. In this example, the second
* argument for `Slim::get`, `Slim::post`, `Slim::put`, `Slim::patch`, and `Slim::delete`
* is an anonymous function.
*/
// GET route
$app->get(
'/',
function () {
$template = <<<EOT
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Slim Framework for PHP 5</title>
<style>
html,body,div,span,object,iframe,
h1,h2,h3,h4,h5,h6,p,blockquote,pre,
abbr,address,cite,code,
del,dfn,em,img,ins,kbd,q,samp,
small,strong,sub,sup,var,
b,i,
dl,dt,dd,ol,ul,li,
fieldset,form,label,legend,
table,caption,tbody,tfoot,thead,tr,th,td,
article,aside,canvas,details,figcaption,figure,
footer,header,hgroup,menu,nav,section,summary,
time,mark,audio,video{margin:0;padding:0;border:0;outline:0;font-size:100%;vertical-align:baseline;background:transparent;}
body{line-height:1;}
article,aside,details,figcaption,figure,
footer,header,hgroup,menu,nav,section{display:block;}
nav ul{list-style:none;}
blockquote,q{quotes:none;}
blockquote:before,blockquote:after,
q:before,q:after{content:'';content:none;}
a{margin:0;padding:0;font-size:100%;vertical-align:baseline;background:transparent;}
ins{background-color:#ff9;color:#000;text-decoration:none;}
mark{background-color:#ff9;color:#000;font-style:italic;font-weight:bold;}
del{text-decoration:line-through;}
abbr[title],dfn[title]{border-bottom:1px dotted;cursor:help;}
table{border-collapse:collapse;border-spacing:0;}
hr{display:block;height:1px;border:0;border-top:1px solid #cccccc;margin:1em 0;padding:0;}
input,select{vertical-align:middle;}
html{ background: #EDEDED; height: 100%; }
body{background:#FFF;margin:0 auto;min-height:100%;padding:0 30px;width:440px;color:#666;font:14px/23px Arial,Verdana,sans-serif;}
h1,h2,h3,p,ul,ol,form,section{margin:0 0 20px 0;}
h1{color:#333;font-size:20px;}
h2,h3{color:#333;font-size:14px;}
h3{margin:0;font-size:12px;font-weight:bold;}
ul,ol{list-style-position:inside;color:#999;}
ul{list-style-type:square;}
code,kbd{background:#EEE;border:1px solid #DDD;border:1px solid #DDD;border-radius:4px;-moz-border-radius:4px;-webkit-border-radius:4px;padding:0 4px;color:#666;font-size:12px;}
pre{background:#EEE;border:1px solid #DDD;border-radius:4px;-moz-border-radius:4px;-webkit-border-radius:4px;padding:5px 10px;color:#666;font-size:12px;}
pre code{background:transparent;border:none;padding:0;}
a{color:#70a23e;}
header{padding: 30px 0;text-align:center;}
</style>
</head>
<body>
<header>
<a href="http://www.slimframework.com"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHIAAAA6CAYAAABs1g18AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABRhJREFUeNrsXY+VsjAMR98twAo6Ao4gI+gIOIKOgCPICDoCjCAjXFdgha+5C3dcv/QfFB5i8h5PD21Bfk3yS9L2VpGnlGW5kS9wJMTHNRxpmjYRy6SycgRvL18OeMQOTYQ8HvIoJKiiz43hgHkq1zvK/h6e/TyJQXeV/VyWBOSHA4C5RvtMAiCc4ZB9FPjgRI8+YuKcrySO515a1hoAY3nc4G2AH52BZsn+MjaAEwIJICKAIR889HljMCcyrR0QE4v/q/BVBQva7Q1tAczG18+x+PvIswHEAslLbfGrMZKiXEOMAMy6LwlisQCJLPFMfKdBtli5dIihRyH7A627Iaiq5sJ1ThP9xoIgSdWSNVIHYmrTQgOgRyRNqm/M5PnrFFopr3F6B41cd8whRUSufUBU5EL4U93AYRnIWimCIiSI1wAaAZpJ9bPnxx8eyI3Gt4QybwWa6T/BvbQECUMQFkhd3jSkPFgrxwcynuBaNT/u6eJIlbGOBWSNIUDFEIwPZFAtBfYrfeIOSRSXuUYCsprCXwUIZWYnmEhJFMIocMDWjn206c2EsGLCJd42aWSyBNMnHxLEq7niMrY2qyDbQUbqrrTbwUPtxN1ZZCitQV4ZSd6DyoxhmRD6OFjuRUS/KdLGRHYowJZaqYgjt9Lchmi3QYA/cXBsHK6VfWNR5jgA1DLhwfFe4HqfODBpINEECCLO47LT/+HSvSd/OCOgQ8qE0DbHQUBqpC4BkKMPYPkFY4iAJXhGAYr1qmaqQDbECCg5A2NMchzR567aA4xcRKclI405Bmt46vYD7/Gcjqfk6GP/kh1wovIDSHDfiAs/8bOCQ4cf4qMt7eH5Cucr3S0aWGFfjdLHD8EhCFvXQlSqRrY5UV2O9cfZtk77jUFMXeqzCEZqSK4ICkSin2tE12/3rbVcE41OBjBjBPSdJ1N5lfYQpIuhr8axnyIy5KvXmkYnw8VbcwtTNj7fDNCmT2kPQXA+bxpEXkB21HlnSQq0gD67jnfh5KavVJa/XQYEFSaagWwbgjNA+ywstLpEWTKgc5gwVpsyO1bTII+tA6B7BPS+0PiznuM9gPKsPVXbFdADMtwbJxSmkXWfRh6AZhyyzBjIHoDmnCGaMZAKjd5hyNJYCBGDOVcg28AXQ5atAVDO3c4dSALQnYblfa3M4kc/cyA7gMIUBQCTyl4kugIpy8yA7ACqK8Uwk30lIFGOEV3rPDAELwQkr/9YjkaCPDQhCcsrAYlF1v8W8jAEYeQDY7qn6tNGWudfq+YUEr6uq6FZzBpJMUfWFDatLHMCciw2mRC+k81qCCA1DzK4aUVfrJpxnloZWCPVnOgYy8L3GvKjE96HpweQoy7iwVQclVutLOEKJxA8gaRCjSzgNI2zhh3bQhzBCQQPIHGaHaUd96GJbZz3Smmjy16u6j3FuKyNxcBarxqWWfYFE0tVVO1Rl3t1Mb05V00MQCJ71YHpNaMcsjWAfkQvPPkaNC7LqTG7JAhGXTKYf+VDeXAX9IvURoAwtTFHvyYIxtnd5tPkywrPafcwbeSuGVwFau3b76NO7SHQrvqhfFE8kM0Wvpv8gVYiYBlxL+fW/34bgP6bIC7JR7YPDubcHCPzIp4+cum7U6NlhZgK7lua3KGLeFwE2m+HblDYWSHG2SAfINuwBBfxbJEIuWZbBH4fAExD7cvaGVyXyH0dhiAYc92z3ZDfUVv+jgb8HrHy7WVO/8BFcy9vuTz+nwADAGnOR39Yg/QkAAAAAElFTkSuQmCC" alt="Slim"/></a>
</header>
<h1>Welcome to Slim!</h1>
<p>
Congratulations! Your Slim application is running. If this is
your first time using Slim, start with this <a href="http://docs.slimframework.com/#Hello-World" target="_blank">"Hello World" Tutorial</a>.
</p>
<section>
<h2>Get Started</h2>
<ol>
<li>The application code is in <code>index.php</code></li>
<li>Read the <a href="http://docs.slimframework.com/" target="_blank">online documentation</a></li>
<li>Follow <a href="http://www.twitter.com/slimphp" target="_blank">@slimphp</a> on Twitter</li>
</ol>
</section>
<section>
<h2>Slim Framework Community</h2>
<h3>Support Forum and Knowledge Base</h3>
<p>
Visit the <a href="http://help.slimframework.com" target="_blank">Slim support forum and knowledge base</a>
to read announcements, chat with fellow Slim users, ask questions, help others, or show off your cool
Slim Framework apps.
</p>
<h3>Twitter</h3>
<p>
Follow <a href="http://www.twitter.com/slimphp" target="_blank">@slimphp</a> on Twitter to receive the very latest news
and updates about the framework.
</p>
</section>
<section style="padding-bottom: 20px">
<h2>Slim Framework Extras</h2>
<p>
Custom View classes for Smarty, Twig, Mustache, and other template
frameworks are available online in a separate repository.
</p>
<p><a href="https://github.com/codeguy/Slim-Extras" target="_blank">Browse the Extras Repository</a></p>
</section>
</body>
</html>
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();

25
vendor/slim/slim/phpunit.xml.dist vendored Executable file
View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="tests/bootstrap.php"
>
<testsuites>
<testsuite name="Slim Test Suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>./Slim/</directory>
</whitelist>
</filter>
</phpunit>

376
vendor/slim/slim/tests/EnvironmentTest.php vendored Executable file
View File

@ -0,0 +1,376 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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']));
}
}

7
vendor/slim/slim/tests/Foo.php vendored Executable file
View File

@ -0,0 +1,7 @@
<?php
class Foo
{
public function __construct()
{
}
}

241
vendor/slim/slim/tests/Helper/SetTest.php vendored Executable file
View File

@ -0,0 +1,241 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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());
}
}

92
vendor/slim/slim/tests/Http/CookiesTest.php vendored Executable file
View File

@ -0,0 +1,92 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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']);
}
}

59
vendor/slim/slim/tests/Http/HeadersTest.php vendored Executable file
View File

@ -0,0 +1,59 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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);
}
}

949
vendor/slim/slim/tests/Http/RequestTest.php vendored Executable file
View File

@ -0,0 +1,949 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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());
}
}

271
vendor/slim/slim/tests/Http/ResponseTest.php vendored Executable file
View File

@ -0,0 +1,271 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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));
}
}

445
vendor/slim/slim/tests/Http/UtilTest.php vendored Executable file
View File

@ -0,0 +1,445 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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']);
}
}

208
vendor/slim/slim/tests/LogTest.php vendored Executable file
View File

@ -0,0 +1,208 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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());
}
}

48
vendor/slim/slim/tests/LogWriterTest.php vendored Executable file
View File

@ -0,0 +1,48 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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'));
}
}

View File

@ -0,0 +1,162 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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' => '<books><book><id>1</id><author>Clive Cussler</author></book></books>'
));
$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' => '<books><book><id>1</id><author>Clive Cussler</book></books>' //<-- 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('<books><book><id>1</id><author>Clive Cussler</book></books>', $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']);
}
}

View File

@ -0,0 +1,141 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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));
}
}

View File

@ -0,0 +1,149 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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']);
}
}

View File

@ -0,0 +1,153 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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());
}
}

View File

@ -0,0 +1,463 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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 <<<EOF
8Y7WpaR3Fiyv0wF0QhKn
hwgh0SYA5cNOh85lSY3E
POUv7tHdFAKK0rmJnNUT
dxVjXuDUlStKTiC6B2rE
BMnchGCK2IIC83agjZ8t
K5U9tmPok3z7n7qFJPp4
YfMPI07qRBgZnYW3vvrj
mY1082KeqiegFNwGiUSs
HYE16N7PChio33DZWjsD
urQLFxD1I0FsxPO7rora
Nmas8nhLl1SiwnlL8eZX
y2xe18BWfXcNHDGkfaih
zXT7MxHXmnq0s4lowjcc
5n8lrXmjYtIdHxl2QcMb
emFTXQpPX9bw8WjulQCB
Peq12lgmurt988RZiquy
lQ5Dw86wMIcIm3uULhr7
T8Obj45ubR8poc1l5sIs
EG6kvcDIHVeQjUdrJuiw
sBLmZnLll23QGK8hMFO1
Pii0BXpzL9wpUt3hQnfe
prkTuA8zuxU8vMOu5uSi
Zynrx9BniMwYGPTOJVSd
ygUsr1GQ1KGJu6ukLvgo
7zrkBV0QM9jNqqvkzZwm
ZnoKRJI1SbaSCqsAduCt
q5RPtNVpHmtizY3QwiJs
8tjGt9MG37zgKx8KhfYE
ByoILEa2ceHjdrP6yd1G
UMHeFx2kOCx2DVeVJIkt
aiFdKMTE9rIbpObSp1fy
Aei9bjwcWwHT2S22rYnj
QHG7FEHSPdkw8acO393N
Ip4rgim3NKanJXpfdthy
yMh4EnoYBBoqSScfW4g5
bVrXYt8JkyCuR5Og0JBN
npKpr7obY4ZYVOnIF9Pe
soEmhC8uCw73bXzMy4ui
2oi4eFSXOoNDXZiAkz3c
zshSls22jy5QBvEJDDtY
C50qtymWnisOM1TIochg
OOnMEtkUHJw21kuw6m91
aqxRK1thCfPGBGytOmzG
kyqvZE1oEzCONj7q4I3p
rvbnRzZhXv21UXRJnR51
QJyXbtzDGpSljtSt4Fxi
SGiklrhWQCdRrnXuBExW
mQFykwpVF07NRPet9LdT
zOaOhwMfCeYQr2xqkKq7
Ru2dsZdhHzhBDvV5nv1q
qB7kVD0YDKB6RJyPcpX9
MxvPmISfMJMFiAFD82Qf
0idAAQxmd6fK9TkJPihp
wp2mvp3yAHWKmdsgLcss
OUqFt0BJoM7Iz4jJpF2d
hiWTsF1jrgEhV07TInLp
u7htseWgTDRY9UYp9wy6
vnF0vsaFikqpjGkLy5oH
ncvaoRPa5MDBNvXZoiG9
gCMvsGG8eLW3u8UWvRrk
bKgFBuy4zLhBF4RBuTVt
Dz1QmbyQPqmmfjchF6u3
myRkxQtSnHQZr0kUqSJS
Ati7CBQq6LOPSVlAek5a
7EOVTREQ52qOjKAibvAr
etvEUy3CbsDiaeSPGlJH
XyFey6LugF2UZfHDFjgV
ByBaUrDz0yuvLOvECQuS
5CoA6FBz8D71FwwebEYl
5xQyEV5h7lNAsgbjBY6o
N92xlCGjyNGWp1Y9HoNL
mMhirp7mufNYVqIy8jBl
nYSK8Rk6KybpAPspHXPd
oemmqqxjF9g4ZjNk2pyL
dqetI1RYqszZPZeH7WNW
B1x1GSPdGXnefeNmxFxr
vFTVOHqgOgZR0xHHUl8P
RwFio0Cd8ZkaRIpcs7jh
Ps0tGJgPyo1gRdm9wtlB
j4hmInyIpAz1MjHYAQc1
YIjnSirWsrItgqidgS3W
LNT7DriU7wPyN6zV9G6d
YFD19x1DDBwz57DegTsy
rz72EblrUsP6wtN69GRo
irhM6N9eNu8Bq9Qo5Tlc
Cpb3Zl3FDttiW63KXQpL
4ZQ7VGbfVjwBwhcGoOe7
RgXxZ9OU0HJFQRpjvJDW
lk3PpNhcHT4vVkgF9Q3V
URiazjSe8G4zHrBBMaxM
Gh7Xp4hqf9GTnIYyMe5E
palqUjJhSGm7EZAR1b4i
HN8qrHznKAyhlywYBw3N
nV9Kla5KFWaRG4r3cCT1
qHT7nPIbVjxNYdujh5WK
CKg7BfQjwZtHk2oM1cyO
RBPMpZxNpM3ZhiXNz5D2
xZJM9ETPwABBqHirjTXA
faI4irlrshHra2hg6mHE
N0OLyZjmKpyzHRlAcC44
oEMe1Mq85Kynyla7S3Lo
Us9auTpKq33jAI51MUvC
Vbu2qKSsmCrXu1WMDFfL
WCCzzLqz2kfMy3IV0ngc
ya4k4AoSjb2nd43VGRvt
1FrWocIRfoyFj3igs8lF
dQlTXv3jttgGmHVJtuJK
zCHcfzABc5pNch7cEW4B
r8jB0mL9ESrMHhvqGxbf
qLUYdNrXNJNujy43WNLt
GaQ6adUTFHErjRYFj7ws
btv28UZlttBqlVAEpu7G
1Se9HT2tp45a5iwbAHpA
tXaOwMjaI3S1uxngaVVL
saFZXdx4kExE3Y3SEMTA
my9rhAEFcw4N1uBqa2Ts
IRupwTKFoRIpPSBwnPPw
qpxq4VIrOdESR4UZiOcw
1n12beyYTUN0zNzV0nRf
dkgrmnaeWbrxA2QQaHDq
o1f6VCap62NxJI2Wd0F7
eyYYL6mY0XUmuCdV2v9e
SPBqa552akcetnRViZD9
cqLrX89ouNlDcjC7hmYk
3vAcrwlseFDYDYzrCXXx
tkyJUeJjORVXoFKaoEmi
o1JoqBFpSPyRT6RwFTXC
IMW657539XCcn0Tvx3iJ
rW9ZUNBSHNHjR0wfbr1R
x7Ez1Br1T9VG4wEetwfY
Xj9s0ipdQDEeYG3eCkBG
xQCp4J0a7BEqEEVPJvYY
S46aXD70Ur3BiokRfeJK
kEQcqPCP9kmWxXboESOB
VjADYs7ZwJUvWNAk0Msc
5cSrhWsbizSwo31NsPKj
PHKG7ui9gU0F5fXKXtWz
8FxjchkHJ3jQQSWKfkSu
pN8e9d71IVYA1vLyQGqV
Hh3QE3o9tmNsJMEBoRK8
QBLTFWWfkGSOI3Vp3y6c
5gwll5qdcgnaF4tDvdRd
NDYpacWX4hnFsrO73OOo
GaenbdbDOUp0iClZKlTU
79UJvctLD86KC2mwxSqc
jbwmzM4oZZ7zuYo769YY
B7Ssx6qbITbIqaJJboMK
7tLwsE3FhBphBJBKP4Bk
aumHnttxOXpiX3b5ivlk
gsvWRKCd1KLYkucRdW1j
j0TSXNoMGXlIK9X6YjX1
4zvHH7QEPlgK4AaRWw6r
eXSVfE2X2nbn1wzA3bdw
exrWkKQ8v87kzzxpzdF7
wL9B42yeyA6SgfnZ0SnW
hyO53wkaJNQnK2rzndcA
8jSesmehxaHL39QUdlEo
oAQMANsGVewC4cYhdjpk
tBVMFz1LMIg8nj5acoKx
4IxsrP4UrdaHa2QlFZ38
OMg0erS6Mg2nVY9PBLGu
WLybJJlrNJ3ZKgftRyOb
s392j4FVZuxnLc8Euq2g
2AB9ceeOXHrw6dJeqImY
q8Gqy9rzsKyp9vEg13h3
UhWoiMQuE8i38vd5HZuO
CjLfC9MtQY7wou4YGl1f
bQGFeV3I1YVsyh1zjdYX
E4yS7PXLT2pTvq9aTuPc
41Vm8F6tc6mnYCc0gfCY
nmKOUzThbGpqnSkJzmr5
E5izT37qIM1PJ1IotRnw
X0rD7K2rUN47XeLXW3x2
3taWQ4GMNGQgjuD7MPwX
u7AyGdUWFG25ZaeZSyrt
mLPs4NU5ayAgrj9L089E
5mWnKfJ8OoAbhjb9XpY5
cBv75uTcpezbnWe5C7YC
DWikoIaaJQebFW2tddw2
qMyIzbkUJxyTheONxBjJ
WyWqJmTW5uniw9ofX84U
JaFGtu4y24UGSmPrIjVj
SDFz3iRvf2FG65m8brV9
0mpT6dWL4p59cdTs0n1c
jw7rIgu3VFnkuOp8mZR3
F1PPQYZfZkqbyiu7Tvl6
tXT8EPpH39oB9Qe3SI6C
DwL6cklHbnOyEOO5jNOo
vEORF3tEYRngOowzuOEY
6XY27pGEG9L9MvwvHinw
rEMyl7S9eFk554yHvCa3
pLToqRXBWIPK51roFlKs
AXfdbVdGkGqwlKn68k01
ecFbbnvrpmcLF2gL3GbC
aWJf90PECBF0qqZ1jVC3
WjMuah0gZjryj7zsZKMB
1J9koTowUYguyp4MBGmp
rnjhybC8RQSEvmYpqkGR
Qdj2QlGYXN1H8A1315QJ
amycQeWwXnrdI3duyqTa
H2YwgIStIGQlWNigfiIZ
btR0CdDnkwGt0hlCtQF0
O37vtIvVgCKVbcXbBexH
xhkbsShz4onN4CeGf7Ox
1vJfx422pUnxtjG5Laag
3IV5ib20qSYZW3Wr2LiH
zmvoTLblxTX3EpYPlHxC
U0Ceix4L3dMomXzn7OAC
JyzkRGfIi8j4EnKfoWPG
gMUXWXZZgJzLBfZ4y9FV
7ClYOAd9EoWspOWQ1MmO
1CIKB3Ei846C1rmXS8Zc
ARLDXFpaHp1VlbEMF8fk
KrQa28U3gbHs9B5oGhxS
WHc9LmQiINcUglo8cKPs
3WMYJ8TAtvlMswUPOd6t
s81Cy4B2oLrc4E5XSa5p
QA6pDUiKipuWFXZ4BMUF
E03CQbBiZ27GpJekftsF
pqGkJifdjVLuuIu0xBej
V27rk0vIwp1Q8p4DvJ1F
TPhvHNooyU6Rrmcx8GIK
81nRsYYsvVo3LCmuOnX5
uY6xGTes3UOMXkXwEfGj
T5LfaSyWP5y4L7vvLBjS
dHO7dVB1bmIA40fEgk3i
KHJxU6C0rUVtPtIR1slm
YdhTz1mwWi2z2GDzzRJB
TIzFqPkKrgCgkiv2RzCg
Z0qY4Wjpfug51zXzU51H
nWm3mJnVLAKv9RNkdThl
xk28IMKOGOPdQuXjGDB6
eEG3ndIRXnmmLilygHop
jE6u88nWi30Yos79canx
b0VuROFF04rZuOTo5Fue
yt4fSpHN7v4uZ7uNPMA9
0sENIYeLlIbBWhqTjXCp
m7qMMX3acdRtTTVNp7Qt
s8XKOJmCQr7YGk47jGMn
6o1kxMmoUgWCW8rEtnWA
kxXj1hKRFBJmX8ErM6Zp
FZBIPSbNt5hmXoC1M92l
UxeirI2PCJnQcAJVmNVJ
FaJ9L5K0u1J9JKGl2Aew
bHGX5QLvkGXSFY5OCezp
5cnbOjU1j8Fuvtuuk9d0
7Oz2IIi69WB5J14n9iWQ
XgCpDLURX3urpiYDFf3P
7xeWOS4yTMUQ0EbLkZOU
AzKM3Dp7nGr9SYPI4xmi
EOF;
}
}

79
vendor/slim/slim/tests/MiddlewareTest.php vendored Executable file
View File

@ -0,0 +1,79 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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());
}
}

18
vendor/slim/slim/tests/README vendored Executable file
View File

@ -0,0 +1,18 @@
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

617
vendor/slim/slim/tests/RouteTest.php vendored Executable file
View File

@ -0,0 +1,617 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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();
}
}

250
vendor/slim/slim/tests/RouterTest.php vendored Executable file
View File

@ -0,0 +1,250 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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'));
}
}

1657
vendor/slim/slim/tests/SlimTest.php vendored Executable file

File diff suppressed because it is too large Load Diff

199
vendor/slim/slim/tests/ViewTest.php vendored Executable file
View File

@ -0,0 +1,199 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart <info@slimframework.com>
* @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');
}
}

22
vendor/slim/slim/tests/bootstrap.php vendored Executable file
View File

@ -0,0 +1,22 @@
<?php
set_include_path(dirname(__FILE__) . '/../' . PATH_SEPARATOR . get_include_path());
// Set default timezone
date_default_timezone_set('America/New_York');
require_once 'Slim/Slim.php';
// Register Slim's autoloader
\Slim\Slim::registerAutoloader();
//Register non-Slim autoloader
function customAutoLoader( $class )
{
$file = rtrim(dirname(__FILE__), '/') . '/' . $class . '.php';
if ( file_exists($file) ) {
require $file;
} else {
return;
}
}
spl_autoload_register('customAutoLoader');

1
vendor/slim/slim/tests/templates/test.php vendored Executable file
View File

@ -0,0 +1 @@
test output <?php echo $foo; ?>

181
vendor/slim/views/README.md vendored Executable file
View File

@ -0,0 +1,181 @@
# Slim Views
This repository contains custom View classes for the template frameworks listed below.
You can use any of these custom View classes by either requiring the appropriate class in your
Slim Framework bootstrap file and initialize your Slim application using an instance of
the selected View class or using Composer (the recommended way).
Slim Views only officially support the following views listed below.
- Smarty
- Twig
## How to Install
#### using [Composer](http://getcomposer.org/)
Install in your project by running the following composer command:
```bash
$ php composer require slim/views
```
## Smarty
### How to use
```php
<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim(array(
'view' => new \Slim\Views\Smarty()
));
```
To use Smarty options do the following:
```php
$view = $app->view();
$view->parserDirectory = dirname(__FILE__) . 'smarty';
$view->parserCompileDirectory = dirname(__FILE__) . '/compiled';
$view->parserCacheDirectory = dirname(__FILE__) . '/cache';
```
## Twig
### How to use
```php
<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim(array(
'view' => new \Slim\Views\Twig()
));
```
To use Twig options do the following:
```php
$view = $app->view();
$view->parserOptions = array(
'debug' => true,
'cache' => dirname(__FILE__) . '/cache'
);
```
In addition to all of this we also have a few helper functions which are included for both view parsers.
In order to start using these you can add them to their respective view parser as stated below:
#### Twig
```php
$view->parserExtensions = array(
new \Slim\Views\TwigExtension(),
);
```
#### Smarty
```php
$view->parserExtensions = array(
dirname(__FILE__) . '/vendor/slim/views/Slim/Views/SmartyPlugins',
);
```
These helpers are listed below.
- urlFor
- siteUrl
- baseUrl
- currentUrl
#### urlFor
__Twig__
Inside your Twig template you would write:
{{ urlFor('hello', {"name": "Josh", "age": "19"}) }}
You can easily pass variables that are objects or arrays by doing:
<a href="{{ urlFor('hello', {"name": person.name, "age": person.age}) }}">Hello {{ name }}</a>
If you need to specify the appname for the getInstance method in the urlFor functions, set it as the third parameter of the function
in your template:
<a href="{{ urlFor('hello', {"name": person.name, "age": person.age}, 'admin') }}">Hello {{ name }}</a>
__Smarty__
Inside your Smarty template you would write:
{urlFor name="hello" options="name.Josh|age.26"}
or with the new array syntax:
{urlFor name="hello" options=["name" => "Josh", "age" => "26"]}
You can easily pass variables that are arrays as normal or using the (.):
<a href="{urlFor name="hello" options="name.{$person.name}|age.{$person.age}"}">Hello {$name}</a>
If you need to specify the appname for the getInstance method in the urlFor functions, set the appname parameter in your function:
<a href="{urlFor name="hello" appname="admin" options="name.{$person.name}|age.{$person.age}"}">Hello {$name}</a>
#### siteUrl
__Twig__
Inside your Twig template you would write:
{{ siteUrl('/about/me') }}
__Smarty__
Inside your Smarty template you would write:
{siteUrl url='/about/me'}
#### baseUrl
__Twig__
Inside your Twig template you would write:
{{ baseUrl() }}
__Smarty__
Inside your Smarty template you would write:
{baseUrl}
#### currentUrl
__Twig__
Inside your Twig template you would write:
{{ currentUrl() }}
__Smarty__
Inside your Smarty template you would write:
{currentUrl}
## Authors
[Josh Lockhart](https://github.com/codeguy)
[Andrew Smith](https://github.com/silentworks)
## License
MIT Public License

124
vendor/slim/views/Smarty.php vendored Executable file
View File

@ -0,0 +1,124 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart
* @author Andrew Smith
* @link http://www.slimframework.com
* @copyright 2013 Josh Lockhart
* @version 0.1.3
* @package SlimViews
*
* 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\Views;
/**
* SmartyView
*
* The SmartyView is a custom View class that renders templates using the Smarty
* template language (http://www.smarty.net).
*
* Two fields that you, the developer, will need to change are:
* - parserDirectory
* - parserCompileDirectory
* - parserCacheDirectory
*
* @package Slim
* @author Jose da Silva <http://josedasilva.net>
*/
class Smarty extends \Slim\View
{
/**
* @var string The path to the Smarty code directory WITHOUT the trailing slash
*/
public $parserDirectory = null;
/**
* @var string The path to the Smarty compiled templates folder WITHOUT the trailing slash
*/
public $parserCompileDirectory = null;
/**
* @var string The path to the Smarty cache folder WITHOUT the trailing slash
*/
public $parserCacheDirectory = null;
/**
* @var SmartyExtensions The Smarty extensions directory you want to load plugins from
*/
public $parserExtensions = array();
/**
* @var parserInstance persistent instance of the Parser object.
*/
private $parserInstance = null;
/**
* Render Template
*
* This method will output the rendered template content
*
* @param string $template The path to the template, relative to the templates directory.
* @param null $data
* @return string
*/
public function render($template, $data = null)
{
$parser = $this->getInstance();
$parser->assign($this->all());
return $parser->fetch($template, $data);
}
/**
* Creates new Smarty object instance if it doesn't already exist, and returns it.
*
* @throws \RuntimeException If Smarty lib directory does not exist
* @return \Smarty Instance
*/
public function getInstance()
{
if (!($this->parserInstance instanceof \Smarty)) {
if (!class_exists('\Smarty')) {
if (!is_dir($this->parserDirectory)) {
throw new \RuntimeException('Cannot set the Smarty lib directory : ' . $this->parserDirectory . '. Directory does not exist.');
}
require_once $this->parserDirectory . '/Smarty.class.php';
}
$this->parserInstance = new \Smarty();
$this->parserInstance->template_dir = $this->getTemplatesDirectory();
if ($this->parserExtensions) {
$this->parserInstance->addPluginsDir($this->parserExtensions);
}
if ($this->parserCompileDirectory) {
$this->parserInstance->compile_dir = $this->parserCompileDirectory;
}
if ($this->parserCacheDirectory) {
$this->parserInstance->cache_dir = $this->parserCacheDirectory;
}
}
return $this->parserInstance;
}
}

View File

@ -0,0 +1,26 @@
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File: function.baseUrl.php
* Type: function
* Name: baseUrl
* Purpose: outputs url for a function with the defined name method
* version 0.1.3
* package SlimViews
* -------------------------------------------------------------
*/
function smarty_function_baseUrl($params, $template)
{
$withUri = isset($params['withUri']) ? $params['withUri'] : true;
$appName = isset($params['appname']) ? $params['appname'] : 'default';
$req = \Slim\Slim::getInstance($appName)->request();
$uri = $req->getUrl();
if ($withUri) {
$uri .= $req->getRootUri();
}
return $uri;
}

View File

@ -0,0 +1,31 @@
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File: function.currentUrl.php
* Type: function
* Name: currentUrl
* Purpose: outputs url for a function with the defined name method
* version 0.1.3
* package SlimViews
* -------------------------------------------------------------
*/
function smarty_function_currentUrl($params, $template)
{
$appName = isset($params['appname']) ? $params['appname'] : 'default';
$withQueryString = isset($params['queryString']) ? $params['queryString'] : true;
$app = \Slim\Slim::getInstance($appName);
$req = $app->request();
$uri = $req->getUrl() . $req->getPath();
if ($withQueryString) {
$env = $app->environment();
if ($env['QUERY_STRING']) {
$uri .= '?' . $env['QUERY_STRING'];
}
}
return $uri;
}

View File

@ -0,0 +1,27 @@
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* File: function.siteUrl.php
* Type: function
* Name: siteUrl
* Purpose: outputs url for a function with the defined name method
* version 0.1.3
* package SlimViews
* -------------------------------------------------------------
*/
function smarty_function_siteUrl($params, $template)
{
$withUri = isset($params['withUri']) ? $params['withUri'] : true;
$appName = isset($params['appname']) ? $params['appname'] : 'default';
$url = isset($params['url']) ? $params['url'] : '';
$req = \Slim\Slim::getInstance($appName)->request();
$uri = $req->getUrl();
if ($withUri) {
$uri .= $req->getRootUri();
}
return $uri . '/' . ltrim($url, '/');
}

View File

@ -0,0 +1,42 @@
<?php
/**
* Smarty plugin
* -------------------------------------------------------------
* File: function.urlFor.php
* Type: function
* Name: urlFor
* Purpose: outputs url for a function with the defined name method
* @version 0.1.3
* @package SlimViews
* -------------------------------------------------------------
*/
function smarty_function_urlFor($params, $template)
{
$name = isset($params['name']) ? $params['name'] : '';
$appName = isset($params['appname']) ? $params['appname'] : 'default';
$url = \Slim\Slim::getInstance($appName)->urlFor($name);
if (isset($params['options'])) {
switch (gettype($params['options'])) {
case 'array':
$opts = $params['options'];
break;
case 'string':
$options = explode('|', $params['options']);
foreach ($options as $option) {
list($key, $value) = explode('.', $option);
$opts[$key] = $value;
}
break;
default:
throw new \Exception('Options parameter is of unknown type, provide either string or array');
}
$url = \Slim\Slim::getInstance($appName)->urlFor($name, $opts);
}
return $url;
}

153
vendor/slim/views/Twig.php vendored Executable file
View File

@ -0,0 +1,153 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart
* @author Andrew Smith
* @link http://www.slimframework.com
* @copyright 2013 Josh Lockhart
* @version 0.1.3
* @package SlimViews
*
* 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\Views;
/**
* Twig view
*
* The Twig view is a custom View class that renders templates using the Twig
* template language (http://www.twig-project.org/).
*
* Two fields that you, the developer, will need to change are:
* - parserDirectory
* - parserOptions
*/
class Twig extends \Slim\View
{
/**
* @var string The path to the Twig code directory WITHOUT the trailing slash
*/
public $parserDirectory = null;
/**
* DEPRECATION WARNING! This method will be removed in the next major point release
*
* @var array Paths to directories to attempt to load Twig template from
*/
public $twigTemplateDirs = array();
/**
* @var array The options for the Twig environment, see
* http://www.twig-project.org/book/03-Twig-for-Developers
*/
public $parserOptions = array();
/**
* @var TwigExtension The Twig extensions you want to load
*/
public $parserExtensions = array();
/**
* @var TwigEnvironment The Twig environment for rendering templates.
*/
private $parserInstance = null;
/**
* Render Twig Template
*
* This method will output the rendered template content
*
* @param string $template The path to the Twig template, relative to the Twig templates directory.
* @param null $data
* @return string
*/
public function render($template, $data = null)
{
$env = $this->getInstance();
$parser = $env->loadTemplate($template);
$data = array_merge($this->all(), (array) $data);
return $parser->render($data);
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release
*
* Use getInstance method instead
*/
public function getEnvironment()
{
return $this->getInstance();
}
/**
* Creates new TwigEnvironment if it doesn't already exist, and returns it.
*
* @return \Twig_Environment
*/
public function getInstance()
{
if (!$this->parserInstance) {
/**
* Check if Twig_Autoloader class exists
* otherwise include it.
*/
if (!class_exists('\Twig_Autoloader')) {
require_once $this->parserDirectory . '/Autoloader.php';
}
\Twig_Autoloader::register();
$loader = new \Twig_Loader_Filesystem($this->getTemplateDirs());
$this->parserInstance = new \Twig_Environment(
$loader,
$this->parserOptions
);
foreach ($this->parserExtensions as $ext) {
$extension = is_object($ext) ? $ext : new $ext;
$this->parserInstance->addExtension($extension);
}
}
return $this->parserInstance;
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release
*
* Get a list of template directories
*
* Returns an array of templates defined by self::$twigTemplateDirs, falls
* back to Slim\View's built-in getTemplatesDirectory method.
*
* @return array
**/
private function getTemplateDirs()
{
if (empty($this->twigTemplateDirs)) {
return array($this->getTemplatesDirectory());
}
return $this->twigTemplateDirs;
}
}

91
vendor/slim/views/TwigExtension.php vendored Executable file
View File

@ -0,0 +1,91 @@
<?php
/**
* Slim - a micro PHP 5 framework
*
* @author Josh Lockhart
* @author Andrew Smith
* @link http://www.slimframework.com
* @copyright 2013 Josh Lockhart
* @version 0.1.3
* @package SlimViews
*
* 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\Views;
use Slim\Slim;
class TwigExtension extends \Twig_Extension
{
public function getName()
{
return 'slim';
}
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('urlFor', array($this, 'urlFor')),
new \Twig_SimpleFunction('baseUrl', array($this, 'base')),
new \Twig_SimpleFunction('siteUrl', array($this, 'site')),
new \Twig_SimpleFunction('currentUrl', array($this, 'currentUrl')),
);
}
public function urlFor($name, $params = array(), $appName = 'default')
{
return Slim::getInstance($appName)->urlFor($name, $params);
}
public function site($url, $withUri = true, $appName = 'default')
{
return $this->base($withUri, $appName) . '/' . ltrim($url, '/');
}
public function base($withUri = true, $appName = 'default')
{
$req = Slim::getInstance($appName)->request();
$uri = $req->getUrl();
if ($withUri) {
$uri .= $req->getRootUri();
}
return $uri;
}
public function currentUrl($withQueryString = true, $appName = 'default')
{
$app = Slim::getInstance($appName);
$req = $app->request();
$uri = $req->getUrl() . $req->getPath();
if ($withQueryString) {
$env = $app->environment();
if ($env['QUERY_STRING']) {
$uri .= '?' . $env['QUERY_STRING'];
}
}
return $uri;
}
}

33
vendor/slim/views/composer.json vendored Executable file
View File

@ -0,0 +1,33 @@
{
"name": "slim/views",
"type": "library",
"description": "Smarty and Twig View Parser package for the Slim Framework",
"keywords": ["templating", "extensions", "slimphp"],
"homepage": "http://github.com/codeguy/Slim-Views",
"license": "MIT",
"authors": [
{
"name": "Josh Lockhart",
"email": "info@joshlockhart.com",
"homepage": "http://www.joshlockhart.com/"
},
{
"name": "Andrew Smith",
"email": "a.smith@silentworks.co.uk",
"homepage": "http://thoughts.silentworks.co.uk/"
}
],
"require": {
"slim/slim": ">=2.4.0",
"php": ">=5.3.0"
},
"suggest": {
"smarty/smarty": "Smarty templating system",
"twig/twig": "Twig templating system"
},
"autoload": {
"psr-4": {
"Slim\\Views\\": "./"
}
}
}