Commit 9fa69e08 authored by Taylor Otwell's avatar Taylor Otwell

refactoring routing and class comments.

parent cff90b52
...@@ -40,7 +40,7 @@ return array( ...@@ -40,7 +40,7 @@ return array(
| |
*/ */
'key' => 'some_secret_key', 'key' => '',
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
...@@ -137,7 +137,7 @@ return array( ...@@ -137,7 +137,7 @@ return array(
'Benchmark' => 'Laravel\\Benchmark', 'Benchmark' => 'Laravel\\Benchmark',
'Cache' => 'Laravel\\Cache', 'Cache' => 'Laravel\\Cache',
'Config' => 'Laravel\\Config', 'Config' => 'Laravel\\Config',
'Controller' => 'Laravel\\Controller', 'Controller' => 'Laravel\\Routing\\Controller',
'Cookie' => 'Laravel\\Cookie', 'Cookie' => 'Laravel\\Cookie',
'Crypter' => 'Laravel\\Security\\Crypter', 'Crypter' => 'Laravel\\Security\\Crypter',
'DB' => 'Laravel\\Database\\Manager', 'DB' => 'Laravel\\Database\\Manager',
......
...@@ -21,7 +21,11 @@ class Blade { ...@@ -21,7 +21,11 @@ class Blade {
*/ */
public static function parse_string($value) public static function parse_string($value)
{ {
return static::closings(static::openings(static::echos($value))); $value = static::echos($value);
$value = static::openings($value);
$value = static::closings($value);
return $value;
} }
/** /**
......
...@@ -39,9 +39,13 @@ class File extends Driver { ...@@ -39,9 +39,13 @@ class File extends Driver {
*/ */
protected function retrieve($key) protected function retrieve($key)
{ {
if ( ! \Laravel\File::exists($this->path.$key)) return null; if ( ! file_exists($this->path.$key)) return null;
if (time() >= substr($cache = \Laravel\File::get($this->path.$key), 0, 10)) // File based caches store have the expiration timestamp stored in
// UNIX format prepended to their contents. This timestamp is then
// extracted and removed when the cache is read to determine if
// the file is still valid.
if (time() >= substr($cache = file_get_contents($this->path.$key), 0, 10))
{ {
return $this->forget($key); return $this->forget($key);
} }
...@@ -64,7 +68,7 @@ class File extends Driver { ...@@ -64,7 +68,7 @@ class File extends Driver {
*/ */
public function put($key, $value, $minutes) public function put($key, $value, $minutes)
{ {
\Laravel\File::put($this->path.$key, (time() + ($minutes * 60)).serialize($value)); file_put_contents($this->path.$key, (time() + ($minutes * 60)).serialize($value), LOCK_EX);
} }
/** /**
...@@ -75,7 +79,10 @@ class File extends Driver { ...@@ -75,7 +79,10 @@ class File extends Driver {
*/ */
public function forget($key) public function forget($key)
{ {
\Laravel\File::delete($this->path.$key); if (file_exists($this->path.$key))
{
@unlink($this->path.$key);
}
} }
} }
\ No newline at end of file
...@@ -89,12 +89,24 @@ class Config { ...@@ -89,12 +89,24 @@ class Config {
static::load($file); static::load($file);
(is_null($key)) ? Arr::set(static::$items, $file, $value) : Arr::set(static::$items[$file], $key, $value); if (is_null($key))
{
Arr::set(static::$items, $file, $value);
}
else
{
Arr::set(static::$items[$file], $key, $value);
}
} }
/** /**
* Parse a configuration key and return its file and key segments. * Parse a configuration key and return its file and key segments.
* *
* The first segment of a configuration key represents the configuration
* file, while the remaining segments represent an item within that file.
* If no item segment is present, null will be returned for the item value
* indicating that the entire configuration array should be returned.
*
* @param string $key * @param string $key
* @return array * @return array
*/ */
...@@ -102,8 +114,6 @@ class Config { ...@@ -102,8 +114,6 @@ class Config {
{ {
$segments = explode('.', $key); $segments = explode('.', $key);
// If there is only one segment after exploding on dots, we will return NULL
// as the key value, causing the entire configuration array to be returned.
$key = (count($segments) > 1) ? implode('.', array_slice($segments, 1)) : null; $key = (count($segments) > 1) ? implode('.', array_slice($segments, 1)) : null;
return array($segments[0], $key); return array($segments[0], $key);
...@@ -121,9 +131,9 @@ class Config { ...@@ -121,9 +131,9 @@ class Config {
$config = array(); $config = array();
// Configuration files cascade. Typically, the system configuration array is loaded // Configuration files cascade. Typically, the system configuration array is
// first, followed by the application array, providing the convenient cascading // loaded first, followed by the application array, providing the convenient
// of configuration options from system to application. // cascading of configuration options from system to application.
foreach (static::$paths as $directory) foreach (static::$paths as $directory)
{ {
if (file_exists($path = $directory.$file.EXT)) if (file_exists($path = $directory.$file.EXT))
......
...@@ -157,7 +157,7 @@ class Form { ...@@ -157,7 +157,7 @@ class Form {
throw new \Exception("A session driver must be specified before using CSRF tokens."); throw new \Exception("A session driver must be specified before using CSRF tokens.");
} }
return Session\Manager::$payload->get('csrf_token'); return Session\Manager::get('csrf_token');
} }
/** /**
......
...@@ -12,7 +12,7 @@ class HTML { ...@@ -12,7 +12,7 @@ class HTML {
*/ */
public static function entities($value) public static function entities($value)
{ {
return htmlentities($value, ENT_QUOTES, Config::get('application.encoding'), false); return htmlentities($value, ENT_QUOTES, Config::$items['application']['encoding'], false);
} }
/** /**
...@@ -60,7 +60,10 @@ class HTML { ...@@ -60,7 +60,10 @@ class HTML {
foreach ($defaults as $attribute => $default) foreach ($defaults as $attribute => $default)
{ {
if ( ! array_key_exists($attribute, $attributes)) $attributes[$attribute] = $default; if ( ! array_key_exists($attribute, $attributes))
{
$attributes[$attribute] = $default;
}
} }
return '<link href="'.static::entities(URL::to_asset($url)).'"'.static::attributes($attributes).'>'.PHP_EOL; return '<link href="'.static::entities(URL::to_asset($url)).'"'.static::attributes($attributes).'>'.PHP_EOL;
......
...@@ -107,7 +107,7 @@ class Input { ...@@ -107,7 +107,7 @@ class Input {
throw new \Exception('A session driver must be specified in order to access old input.'); throw new \Exception('A session driver must be specified in order to access old input.');
} }
return Arr::get(Session\Manager::$payload->get(Input::old_input, array()), $key, $default); return Arr::get(Session\Manager::get(Input::old_input, array()), $key, $default);
} }
/** /**
......
...@@ -37,7 +37,7 @@ class Lang { ...@@ -37,7 +37,7 @@ class Lang {
* *
* @var array * @var array
*/ */
protected $paths; protected $paths = array(SYS_LANG_PATH, LANG_PATH);
/** /**
* Create a new Lang instance. * Create a new Lang instance.
...@@ -45,13 +45,11 @@ class Lang { ...@@ -45,13 +45,11 @@ class Lang {
* @param string $key * @param string $key
* @param array $replacements * @param array $replacements
* @param string $language * @param string $language
* @param array $paths
* @return void * @return void
*/ */
protected function __construct($key, $replacements = array(), $language = null, $paths = array()) protected function __construct($key, $replacements = array(), $language = null)
{ {
$this->key = $key; $this->key = $key;
$this->paths = $paths;
$this->language = $language; $this->language = $language;
$this->replacements = $replacements; $this->replacements = $replacements;
} }
...@@ -70,23 +68,20 @@ class Lang { ...@@ -70,23 +68,20 @@ class Lang {
* @param string $key * @param string $key
* @param array $replacements * @param array $replacements
* @param string $language * @param string $language
* @param array $paths
* @return Lang * @return Lang
*/ */
public static function line($key, $replacements = array(), $language = null, $paths = array()) public static function line($key, $replacements = array(), $language = null)
{ {
if (count($paths) == 0) $paths = array(SYS_LANG_PATH, LANG_PATH);
if (is_null($language)) $language = Config::get('application.language'); if (is_null($language)) $language = Config::get('application.language');
return new static($key, $replacements, $language, $paths); return new static($key, $replacements, $language);
} }
/** /**
* Get the language line as a string. * Get the language line as a string.
* *
* If a language is specified, it should correspond to a directory within * If a language is specified, it should correspond to a directory
* your application language directory. * within your application language directory.
* *
* <code> * <code>
* // Get a language line * // Get a language line
...@@ -105,7 +100,6 @@ class Lang { ...@@ -105,7 +100,6 @@ class Lang {
*/ */
public function get($language = null, $default = null) public function get($language = null, $default = null)
{ {
// If a language was passed to the method, we will let it override the default
if ( ! is_null($language)) $this->language = $language; if ( ! is_null($language)) $this->language = $language;
list($file, $line) = $this->parse($this->key); list($file, $line) = $this->parse($this->key);
...@@ -115,8 +109,21 @@ class Lang { ...@@ -115,8 +109,21 @@ class Lang {
return ($default instanceof Closure) ? call_user_func($default) : $default; return ($default instanceof Closure) ? call_user_func($default) : $default;
} }
$line = Arr::get(static::$lines[$this->language.$file], $line, $default); return $this->replace(Arr::get(static::$lines[$this->language.$file], $line, $default));
}
/**
* Make all necessary replacements on a language line.
*
* Replacements place-holder are prefixed with a colon, and are replaced
* with the appropriate value based on the replacement array set for the
* language line instance.
*
* @param string $line
* @return string
*/
protected function replace($line)
{
foreach ($this->replacements as $key => $value) foreach ($this->replacements as $key => $value)
{ {
$line = str_replace(':'.$key, $value, $line); $line = str_replace(':'.$key, $value, $line);
...@@ -128,6 +135,10 @@ class Lang { ...@@ -128,6 +135,10 @@ class Lang {
/** /**
* Parse a language key into its file and line segments. * Parse a language key into its file and line segments.
* *
* Language keys are formatted similarly to configuration keys. The first
* segment represents the language file, while the second segment
* represents a language line within that file.
*
* @param string $key * @param string $key
* @return array * @return array
*/ */
...@@ -153,9 +164,9 @@ class Lang { ...@@ -153,9 +164,9 @@ class Lang {
$language = array(); $language = array();
// Language files cascade. Typically, the system language array is loaded first, // Language files cascade. Typically, the system language array is
// followed by the application array. This allows the convenient overriding of the // loaded first, followed by the application array. This allows the
// system language files (like validation) by the application developer. // convenient overriding of the system language files.
foreach ($this->paths as $directory) foreach ($this->paths as $directory)
{ {
if (file_exists($path = $directory.$this->language.'/'.$file.EXT)) if (file_exists($path = $directory.$this->language.'/'.$file.EXT))
...@@ -164,9 +175,9 @@ class Lang { ...@@ -164,9 +175,9 @@ class Lang {
} }
} }
// If language lines were actually found, they will be loaded into the array // If language lines were actually found, they will be loaded into
// containing all of the lines for all languages and files. The array is // the array containing all of the lines for all languages and files.
// keyed by the language and the file name. // The array is keyed by the language and the file name.
if (count($language) > 0) static::$lines[$this->language.$file] = $language; if (count($language) > 0) static::$lines[$this->language.$file] = $language;
return isset(static::$lines[$this->language.$file]); return isset(static::$lines[$this->language.$file]);
...@@ -175,6 +186,9 @@ class Lang { ...@@ -175,6 +186,9 @@ class Lang {
/** /**
* Get the string content of the language line. * Get the string content of the language line.
*/ */
public function __toString() { return $this->get(); } public function __toString()
{
return $this->get();
}
} }
\ No newline at end of file
...@@ -41,7 +41,7 @@ require SYS_PATH.'request'.EXT; ...@@ -41,7 +41,7 @@ require SYS_PATH.'request'.EXT;
require SYS_PATH.'routing/route'.EXT; require SYS_PATH.'routing/route'.EXT;
require SYS_PATH.'routing/router'.EXT; require SYS_PATH.'routing/router'.EXT;
require SYS_PATH.'routing/loader'.EXT; require SYS_PATH.'routing/loader'.EXT;
require SYS_PATH.'routing/caller'.EXT; require SYS_PATH.'routing/filter'.EXT;
/** /**
* Gather the input to the application for the current request. * Gather the input to the application for the current request.
...@@ -72,6 +72,10 @@ switch (Request::method()) ...@@ -72,6 +72,10 @@ switch (Request::method())
} }
} }
/**
* The spoofed request method is removed from the input so it is
* not unexpectedly included in Input::all() or Input::get().s
*/
unset($input[Request::spoofer]); unset($input[Request::spoofer]);
Input::set($input); Input::set($input);
...@@ -82,19 +86,31 @@ Input::set($input); ...@@ -82,19 +86,31 @@ Input::set($input);
* instance. If no route is found, the 404 response will be returned * instance. If no route is found, the 404 response will be returned
* to the browser. * to the browser.
*/ */
Routing\Filter::register(require APP_PATH.'filters'.EXT);
list($method, $uri) = array(Request::method(), Request::uri()); list($method, $uri) = array(Request::method(), Request::uri());
$route = IoC::container()->core('routing.router')->route($method, $uri); $route = IoC::container()->core('routing.router')->route($method, $uri);
if ( ! is_null($route)) if ( ! is_null($route))
{ {
$response = IoC::container()->core('routing.caller')->call($route); $response = $route->call();
} }
else else
{ {
$response = Response::error('404'); $response = Response::error('404');
} }
if ($response instanceof Routing\Delegate)
{
$response = Routing\Controller::call($response, $route->parameters);
}
if ( ! $response instanceof Response)
{
$response = new Response($response);
}
/** /**
* Stringify the response. We need to force the response to be * Stringify the response. We need to force the response to be
* stringed before closing the session, since the developer may * stringed before closing the session, since the developer may
......
...@@ -280,7 +280,6 @@ class Paginator { ...@@ -280,7 +280,6 @@ class Paginator {
public function appends($values) public function appends($values)
{ {
$this->appends = $values; $this->appends = $values;
return $this; return $this;
} }
...@@ -295,7 +294,6 @@ class Paginator { ...@@ -295,7 +294,6 @@ class Paginator {
public function elements($elements) public function elements($elements)
{ {
$this->elements = $elements; $this->elements = $elements;
return $this; return $this;
} }
......
...@@ -61,7 +61,7 @@ class Redirect extends Response { ...@@ -61,7 +61,7 @@ class Redirect extends Response {
throw new \Exception('A session driver must be set before setting flash data.'); throw new \Exception('A session driver must be set before setting flash data.');
} }
Session\Manager::$payload->flash($key, $value); Session\Manager::flash($key, $value);
return $this; return $this;
} }
......
...@@ -197,6 +197,9 @@ class Request { ...@@ -197,6 +197,9 @@ class Request {
* *
* @return Route * @return Route
*/ */
public static function route() { return static::$route; } public static function route()
{
return static::$route;
}
} }
\ No newline at end of file
...@@ -235,7 +235,10 @@ class Response { ...@@ -235,7 +235,10 @@ class Response {
*/ */
public function send() public function send()
{ {
if ( ! isset($this->headers['Content-Type'])) $this->header('Content-Type', 'text/html; charset=utf-8'); if ( ! isset($this->headers['Content-Type']))
{
$this->header('Content-Type', 'text/html; charset=utf-8');
}
if ( ! headers_sent()) $this->send_headers(); if ( ! headers_sent()) $this->send_headers();
...@@ -274,7 +277,6 @@ class Response { ...@@ -274,7 +277,6 @@ class Response {
public function header($name, $value) public function header($name, $value)
{ {
$this->headers[$name] = $value; $this->headers[$name] = $value;
return $this; return $this;
} }
...@@ -287,7 +289,6 @@ class Response { ...@@ -287,7 +289,6 @@ class Response {
public function status($status) public function status($status)
{ {
$this->status = $status; $this->status = $status;
return $this; return $this;
} }
......
<?php namespace Laravel\Routing;
use Closure;
use Laravel\Response;
use Laravel\Container;
use Laravel\Controller;
class Caller {
/**
* The IoC container instance.
*
* @var Container
*/
protected $container;
/**
* The route filters defined for the application.
*
* @var array
*/
protected $filters;
/**
* The path to the application's controllers.
*
* @var string
*/
protected $path;
/**
* Create a new route caller instance.
*
* @param Container $container
* @param Delegator $delegator
* @param array $filters
* @return void
*/
public function __construct(Container $container, $filters, $path)
{
$this->path = $path;
$this->filters = $filters;
$this->container = $container;
}
/**
* Call a given route and return the route's response.
*
* @param Route $route
* @return Response
*/
public function call(Route $route)
{
// Since "before" filters can halt the request cycle, we will return any response
// from the before filters. Allowing the filters to halt the request cycle makes
// common tasks like authorization convenient to implement.
$before = array_merge(array('before'), $route->filters('before'));
if ( ! is_null($response = $this->filter($before, array(), true)))
{
return $this->finish($route, $response);
}
// If a route returns a Delegate, it means the route is delegating the handling
// of the request to a controller method. We will pass the Delegate instance
// to the "delegate" method which will call the controller.
if ($route->delegates())
{
return $this->delegate($route, $route->call());
}
// If no before filters returned a response and the route is not delegating
// execution to a controller, we will call the route like normal and return
// the response. If the no response is given by the route, we will return
// the 404 error view.
elseif ( ! is_null($response = $route->call()))
{
return $this->finish($route, $response);
}
else
{
return $this->finish($route, Response::error('404'));
}
}
/**
* Handle the delegation of a route to a controller method.
*
* @param Route $route
* @param Delegate $delegate
* @return mixed
*/
protected function delegate(Route $route, Delegate $delegate)
{
// Route delegates follow a {controller}@{method} naming convention. For example,
// to delegate to the "home" controller's "index" method, the delegate should be
// formatted like "home@index". Nested controllers may be delegated to using dot
// syntax, like so: "user.profile@show".
if (strpos($delegate->destination, '@') === false)
{
throw new \Exception("Route delegate [{$delegate->destination}] has an invalid format.");
}
list($controller, $method) = explode('@', $delegate->destination);
$controller = Controller::resolve($this->container, $controller, $this->path);
// If the controller doesn't exist or the request is to an invalid method, we will
// return the 404 error response. The "before" method and any method beginning with
// an underscore are not publicly available.
if (is_null($controller) or ! $this->callable($method))
{
return Response::error('404');
}
$controller->container = $this->container;
// Again, as was the case with route closures, if the controller "before" filters
// return a response, it will be considered the response to the request and the
// controller method will not be used to handle the request to the application.
$response = $this->filter($controller->filters('before'), array(), true);
if (is_null($response))
{
$response = call_user_func_array(array($controller, $method), $route->parameters);
}
return $this->finish($controller, $response);
}
/**
* Determine if a given controller method is callable.
*
* @param string $method
* @return bool
*/
protected function callable($method)
{
return $method !== 'before' and $method !== 'after' and strncmp($method, '_', 1) !== 0;
}
/**
* Finish the route handling for the request.
*
* The route response will be converted to a Response instance and the "after" filters will be run.
*
* @param Route|Controller $destination
* @param mixed $response
* @return Response
*/
protected function finish($destination, $response)
{
if ( ! $response instanceof Response) $response = new Response($response);
$this->filter(array_merge($destination->filters('after'), array('after')), array($response));
return $response;
}
/**
* Call a filter or set of filters.
*
* @param array|string $filters
* @param array $parameters
* @param bool $override
* @return mixed
*/
protected function filter($filters, $parameters = array(), $override = false)
{
if (is_string($filters)) $filters = explode('|', $filters);
foreach ((array) $filters as $filter)
{
// Parameters may be passed into routes by specifying the list of parameters after
// a colon. If parameters are present, we will merge them into the parameter array
// that was passed to the method and slice the parameters off of the filter string.
if (($colon = strpos($filter, ':')) !== false)
{
$parameters = array_merge($parameters, explode(',', substr($filter, $colon + 1)));
$filter = substr($filter, 0, $colon);
}
if ( ! isset($this->filters[$filter])) continue;
$response = call_user_func_array($this->filters[$filter], $parameters);
// "Before" filters may override the request cycle. For example, an authentication
// filter may redirect a user to a login view if they are not logged in. Because of
// this, we will return the first filter response if overriding is enabled.
if ( ! is_null($response) and $override) return $response;
}
}
}
\ No newline at end of file
<?php namespace Laravel; <?php namespace Laravel\Routing;
use Laravel\IoC;
use Laravel\Response;
abstract class Controller { abstract class Controller {
...@@ -17,14 +20,62 @@ abstract class Controller { ...@@ -17,14 +20,62 @@ abstract class Controller {
public $after = array(); public $after = array();
/** /**
* Get an array of filter names defined for the destination. * Handle the delegation of a route to a controller method.
* *
* @param string $name * The controller destination should follow a {controller}@{method} convention.
* @return array * Nested controllers may be delegated to using dot syntax.
*
* For example, a destination of "user.profile@show" would call the User_Profile
* controller's show method with the given parameters.
*
* @param string $destination
* @param array $parameters
* @return mixed
*/ */
public function filters($name) public static function call($destination, $parameters)
{ {
return (array) $this->$name; if (strpos($destination, '@') === false)
{
throw new \Exception("Route delegate [{$destination}] has an invalid format.");
}
list($controller, $method) = explode('@', $destination);
$controller = static::resolve($controller);
if (is_null($controller) or static::hidden($method))
{
return Response::error('404');
}
// Again, as was the case with route closures, if the controller
// "before" filters return a response, it will be considered the
// response to the request and the controller method will not be
// used to handle the request to the application.
$response = Filter::run($controller->filters('before'), array(), true);
if (is_null($response))
{
$response = call_user_func_array(array($controller, $method), $parameters);
}
$filters = array_merge($controller->filters('after'), array('after'));
Filter::run($filters, array($response));
return $response;
}
/**
* Determine if a given controller method is callable.
*
* @param string $method
* @return bool
*/
protected static function hidden($method)
{
return $method == 'before' or $method == 'after' or strncmp($method, '_', 1) == 0;
} }
/** /**
...@@ -32,19 +83,19 @@ abstract class Controller { ...@@ -32,19 +83,19 @@ abstract class Controller {
* *
* @param Container $container * @param Container $container
* @param string $controller * @param string $controller
* @param string $path
* @return Controller * @return Controller
*/ */
public static function resolve(Container $container, $controller, $path) public static function resolve($controller)
{ {
if ( ! static::load($controller, $path)) return; if ( ! static::load($controller)) return;
// If the controller is registered in the IoC container, we will resolve it out // If the controller is registered in the IoC container, we will
// of the container. Using constructor injection on controllers via the container // resolve it out of the container. Using constructor injection
// allows more flexible and testable development of applications. // on controllers via the container allows more flexible and
if ($container->registered('controllers.'.$controller)) // testable development of applications.
if (IoC::container()->registered('controllers.'.$controller))
{ {
return $container->resolve('controllers.'.$controller); return IoC::container()->resolve('controllers.'.$controller);
} }
$controller = str_replace(' ', '_', ucwords(str_replace('.', ' ', $controller))).'_Controller'; $controller = str_replace(' ', '_', ucwords(str_replace('.', ' ', $controller))).'_Controller';
...@@ -56,12 +107,13 @@ abstract class Controller { ...@@ -56,12 +107,13 @@ abstract class Controller {
* Load the file for a given controller. * Load the file for a given controller.
* *
* @param string $controller * @param string $controller
* @param string $path
* @return bool * @return bool
*/ */
protected static function load($controller, $path) protected static function load($controller)
{ {
if (file_exists($path = $path.strtolower(str_replace('.', '/', $controller)).EXT)) $controller = strtolower(str_replace('.', '/', $controller));
if (file_exists($path = CONTROLLER_PATH.$controller.EXT))
{ {
require $path; require $path;
...@@ -71,6 +123,17 @@ abstract class Controller { ...@@ -71,6 +123,17 @@ abstract class Controller {
return false; return false;
} }
/**
* Get an array of filter names defined for the destination.
*
* @param string $name
* @return array
*/
public function filters($name)
{
return (array) $this->$name;
}
/** /**
* Magic Method to handle calls to undefined functions on the controller. * Magic Method to handle calls to undefined functions on the controller.
* *
...@@ -96,7 +159,10 @@ abstract class Controller { ...@@ -96,7 +159,10 @@ abstract class Controller {
*/ */
public function __get($key) public function __get($key)
{ {
if (IoC::container()->registered($key)) return IoC::container()->resolve($key); if (IoC::container()->registered($key))
{
return IoC::container()->resolve($key);
}
throw new \Exception("Attempting to access undefined property [$key] on controller."); throw new \Exception("Attempting to access undefined property [$key] on controller.");
} }
......
<?php namespace Laravel\Routing;
class Filter {
/**
* The route filters for the application.
*
* @var array
*/
protected static $filters = array();
/**
* Register an array of route filters.
*
* @param array $filters
* @return void
*/
public static function register($filters)
{
static::$filters = array_merge(static::$filters, $filters);
}
/**
* Call a filter or set of filters.
*
* @param array|string $filters
* @param array $parameters
* @param bool $override
* @return mixed
*/
public static function run($filters, $parameters = array(), $override = false)
{
if (is_string($filters)) $filters = explode('|', $filters);
foreach ((array) $filters as $filter)
{
// Parameters may be passed into routes by specifying the list of
// parameters after a colon. If parameters are present, we will
// merge them into the parameter array that was passed to the
// method and slice the parameters off of the filter string.
if (($colon = strpos($filter, ':')) !== false)
{
$parameters = array_merge($parameters, explode(',', substr($filter, $colon + 1)));
$filter = substr($filter, 0, $colon);
}
if ( ! isset(static::$filters[$filter])) continue;
$response = call_user_func_array(static::$filters[$filter], $parameters);
// "Before" filters may override the request cycle. For example,
// an authentication filter may redirect a user to a login view
// if they are not logged in. Because of this, we will return
// the first filter response if overriding is enabled.
if ( ! is_null($response) and $override) return $response;
}
}
}
\ No newline at end of file
...@@ -90,15 +90,16 @@ class Loader { ...@@ -90,15 +90,16 @@ class Loader {
$routes = array_merge($routes, require $path); $routes = array_merge($routes, require $path);
} }
// Since route files can be nested deep within the route directory, we need to // Since route files can be nested deep within the route directory,
// recursively spin through each directory to find every file. // we need to recursively spin through each directory
$iterator = new Iterator(new DirectoryIterator($this->nest), Iterator::SELF_FIRST); $iterator = new Iterator(new DirectoryIterator($this->nest), Iterator::SELF_FIRST);
foreach ($iterator as $file) foreach ($iterator as $file)
{ {
// Since some Laravel developers may place HTML files in the route directories, we will // Since some Laravel developers may place HTML files in the route
// check for the PHP extension before merging the file. Typically, the HTML files are // directories, we will check for the PHP extension before merging
// present in installations that are not using mod_rewrite and the public directory. // the file. Typically, the HTML files are present in installations
// that are not using mod_rewrite and the public directory.
if (filetype($file) === 'file' and strpos($file, EXT) !== false) if (filetype($file) === 'file' and strpos($file, EXT) !== false)
{ {
$routes = array_merge(require $file, $routes); $routes = array_merge(require $file, $routes);
......
<?php namespace Laravel\Routing; use Closure, Laravel\Arr; <?php namespace Laravel\Routing;
use Closure;
use Laravel\Arr;
use Laravel\Response;
class Route { class Route {
...@@ -44,56 +48,96 @@ class Route { ...@@ -44,56 +48,96 @@ class Route {
$this->callback = $callback; $this->callback = $callback;
$this->parameters = $parameters; $this->parameters = $parameters;
// The extractor closure will retrieve the URI from a given route destination. // Extract each URI from the route key. Since the route key has the
// If the request is to the root of the application, a single forward slash // request method, we will extract that from the string. If the URI
// will be returned, otherwise the leading slash will be removed. // points to the root of the application, a single forward slash
$extractor = function($segment) // will be returned.
if (strpos($key, ', ') === false)
{
$this->uris = array($this->extract($this->key));
}
else
{
$this->uris = array_map(array($this, 'extract'), explode(', ', $key));
}
if ( ! $callback instanceof Closure and ! is_array($callback) and ! is_string($callback))
{
throw new \Exception('Invalid route defined for URI ['.$this->key.']');
}
}
/**
* Retrieve the URI from a given route destination.
*
* If the request is to the root of the application, a single slash
* will be returned, otherwise the leading slash will be removed.
*
* @param string $segment
* @return string
*/
protected function extract($segment)
{ {
$segment = substr($segment, strpos($segment, ' ') + 1); $segment = substr($segment, strpos($segment, ' ') + 1);
return ($segment !== '/') ? trim($segment, '/') : $segment; return ($segment !== '/') ? trim($segment, '/') : $segment;
}; }
// Extract each URI out of the route key. Since the route key has the request /**
// method, we will extract the method off of the string. If the URI points to * Call a given route and return the route's response.
// the root of the application, a single forward slash will be returned. *
// Otherwise, the leading slash will be removed. * @return Response
if (strpos($key, ', ') === false) */
public function call()
{
// Since "before" filters can halt the request cycle, we will return
// any response from the before filters. Allowing filters to halt the
// request cycle makes tasks like authorization convenient.
$before = array_merge(array('before'), $this->filters('before'));
if ( ! is_null($response = $this->filter($before, array(), true)))
{ {
$this->uris = array($extractor($this->key)); return $response;
} }
else
if ( ! is_null($response = $this->response()))
{
if ($response instanceof Delegate)
{ {
$this->uris = array_map(function($segment) use ($extractor) { return $extractor($segment); }, explode(', ', $key)); return $response;
} }
// The route callback must be either a Closure, an array, or a string. Closures $filters = array_merge($this->filters('after'), array('after'));
// obviously handle the requests to the route. An array can contain filters, as
// well as a Closure to handle requests to the route. A string, delegates control Filter::run($filters, array($response));
// of the request to a controller method.
if ( ! $this->callback instanceof Closure and ! is_array($this->callback) and ! is_string($this->callback)) return $response;
}
else
{ {
throw new \Exception('Invalid route defined for URI ['.$this->key.']'); return Response::error('404');
} }
} }
/** /**
* Call the closure defined for the route, or get the route delegator. * Call the closure defined for the route, or get the route delegator.
* *
* Note that this method differs from the "call" method in that it does
* not resolve the controller or prepare the response. Delegating to
* controller's is handled by the "call" method.
*
* @return mixed * @return mixed
*/ */
public function call() protected function response()
{ {
// If the value defined for a route is a Closure, we simply call the closure with the
// route's parameters and return the response.
if ($this->callback instanceof Closure) if ($this->callback instanceof Closure)
{ {
return call_user_func_array($this->callback, $this->parameters); return call_user_func_array($this->callback, $this->parameters);
} }
// If the route is an array we will return the first value with a
// Otherwise, we will assume the route is an array and will return the first value with // key of "delegate", or the first instance of a Closure. If the
// a key of "delegate", or the first instance of a Closure. If the value is a string, the // value is a string, the route is delegating the responsibility
// route is delegating the responsibility for handling the request to a controller. // for handling the request to a controller.
elseif (is_array($this->callback)) elseif (is_array($this->callback))
{ {
$callback = Arr::first($this->callback, function($key, $value) $callback = Arr::first($this->callback, function($key, $value)
...@@ -101,12 +145,15 @@ class Route { ...@@ -101,12 +145,15 @@ class Route {
return $key == 'delegate' or $value instanceof Closure; return $key == 'delegate' or $value instanceof Closure;
}); });
return ($callback instanceof Closure) ? call_user_func_array($callback, $this->parameters) : new Delegate($callback); if ($callback instanceof Closure)
{
return call_user_func_array($callback, $this->parameters);
}
else
{
return new Delegate($callback);
}
} }
// If a value defined for a route is a string, it means the route is delegating control
// of the request to a controller. If that is the case, we will simply return the string
// for the route caller to parse and delegate.
elseif (is_string($this->callback)) elseif (is_string($this->callback))
{ {
return new Delegate($this->callback); return new Delegate($this->callback);
...@@ -129,16 +176,6 @@ class Route { ...@@ -129,16 +176,6 @@ class Route {
return array(); return array();
} }
/**
* Deteremine if the route delegates to a controller.
*
* @return bool
*/
public function delegates()
{
return is_string($this->callback) or (is_array($this->callback) and isset($this->callback['delegate']));
}
/** /**
* Determine if the route has a given name. * Determine if the route has a given name.
* *
...@@ -147,7 +184,7 @@ class Route { ...@@ -147,7 +184,7 @@ class Route {
*/ */
public function is($name) public function is($name)
{ {
return (is_array($this->callback) and isset($this->callback['name'])) ? $this->callback['name'] === $name : false; return is_array($this->callback) and Arr::get($this->callback, 'name') === $name;
} }
/** /**
...@@ -166,7 +203,7 @@ class Route { ...@@ -166,7 +203,7 @@ class Route {
*/ */
public function __call($method, $parameters) public function __call($method, $parameters)
{ {
if (strpos($method, 'is_') === 0) { return $this->is(substr($method, 3)); } if (strpos($method, 'is_') === 0) return $this->is(substr($method, 3));
} }
} }
\ No newline at end of file
...@@ -100,13 +100,14 @@ class Auth { ...@@ -100,13 +100,14 @@ class Auth {
/** /**
* Attempt to log a user into the application. * Attempt to log a user into the application.
* *
* If the given credentials are valid, the user will be logged into the application * If the given credentials are valid, the user will be logged into
* and their user ID will be stored in the session via the "login" method. * the application and their user ID will be stored in the session
* via the "login" method.
* *
* The user may also be "remembered". When this option is set, the user will be * The user may also be "remembered". When this option is set, the user
* automatically logged into the application for one year via an encrypted cookie * will be automatically logged into the application for one year via
* containing their ID. Of course, if the user logs out of the application, * an encrypted cookie containing their ID. Of course, if the user logs
* they will no longer be remembered. * out of the application, they will no longer be remembered.
* *
* @param string $username * @param string $username
* @param string $password * @param string $password
...@@ -130,8 +131,6 @@ class Auth { ...@@ -130,8 +131,6 @@ class Auth {
/** /**
* Log a user into the application. * Log a user into the application.
* *
* The user ID will be stored in the session so it is available on subsequent requests.
*
* @param object $user * @param object $user
* @param bool $remember * @param bool $remember
* @return void * @return void
...@@ -156,9 +155,10 @@ class Auth { ...@@ -156,9 +155,10 @@ class Auth {
{ {
$cookie = Crypter::encrypt($id.'|'.$username.'|'.Str::random(40)); $cookie = Crypter::encrypt($id.'|'.$username.'|'.Str::random(40));
// This method assumes the "remember me" cookie should have the same configuration // This method assumes the "remember me" cookie should have the
// as the session cookie. Since this cookie, like the session cookie, should be // same configuration as the session cookie. Since this cookie,
// kept very secure, it's probably safe to assume the settings are the same. // like the session cookie, should be kept very secure, it's
// probably safe to assume the settings are the same.
$config = Config::get('session'); $config = Config::get('session');
Cookie::forever(Auth::remember_key, $cookie, $config['path'], $config['domain'], $config['secure']); Cookie::forever(Auth::remember_key, $cookie, $config['path'], $config['domain'], $config['secure']);
...@@ -167,9 +167,9 @@ class Auth { ...@@ -167,9 +167,9 @@ class Auth {
/** /**
* Log the current user out of the application. * Log the current user out of the application.
* *
* The "logout" closure in the authenciation configuration file will be called. * The "logout" closure in the authenciation configuration file
* All authentication cookies will be deleted and the user ID will be removed * will be called. All authentication cookies will be deleted
* from the session. * and the user ID will be removed from the session.
* *
* @return void * @return void
*/ */
......
...@@ -24,8 +24,9 @@ class Crypter { ...@@ -24,8 +24,9 @@ class Crypter {
/** /**
* Encrypt a string using Mcrypt. * Encrypt a string using Mcrypt.
* *
* The string will be encrypted using the cipher and mode specified when the crypter * The string will be encrypted using the cipher and mode specified
* instance was created, and the final result will be base64 encoded. * when the crypter instance was created, and the final result will
* be base64 encoded.
* *
* <code> * <code>
* // Encrypt a string using the Mcrypt PHP extension * // Encrypt a string using the Mcrypt PHP extension
...@@ -70,8 +71,9 @@ class Crypter { ...@@ -70,8 +71,9 @@ class Crypter {
*/ */
public static function decrypt($value) public static function decrypt($value)
{ {
// Since all encrypted strings generated by this class are base64 encoded, we will // Since all encrypted strings generated by this class are base64
// first attempt to base64 decode the string. If we can't do it, we'll bail out. // encoded, we will first attempt to base64 decode the string.
// If we can't do it, we'll bail out.
if ( ! is_string($value = base64_decode($value, true))) if ( ! is_string($value = base64_decode($value, true)))
{ {
throw new \Exception('Decryption error. Input value is not valid base64 data.'); throw new \Exception('Decryption error. Input value is not valid base64 data.');
......
...@@ -5,10 +5,10 @@ class Hasher { ...@@ -5,10 +5,10 @@ class Hasher {
/** /**
* Hash a password using the Bcrypt hashing scheme. * Hash a password using the Bcrypt hashing scheme.
* *
* Bcrypt provides a future-proof hashing algorithm by allowing the number of "rounds" * Bcrypt provides a future-proof hashing algorithm by allowing the number
* to be increased, thus increasing the time is takes to generate the hashed value. * of "rounds" to be increased, thus increasing the time is takes to generate
* The longer is takes to generate the hash, the more impractical a rainbow table * the hashed value. The longer is takes to generate the hash, the more
* attack against the hashes becomes. * impractical a rainbow table attack against the hashes becomes.
* *
* <code> * <code>
* // Create a Bcrypt hash of a value * // Create a Bcrypt hash of a value
...@@ -30,9 +30,6 @@ class Hasher { ...@@ -30,9 +30,6 @@ class Hasher {
/** /**
* Determine if an unhashed value matches a given Bcrypt hash. * Determine if an unhashed value matches a given Bcrypt hash.
* *
* Since the number of rounds is included in the Bcrypt hash, it is not
* necessary to specify the rounds when calling this method.
*
* @param string $value * @param string $value
* @param string $hash * @param string $hash
* @return bool * @return bool
......
...@@ -101,7 +101,7 @@ class Database implements Driver, Sweeper { ...@@ -101,7 +101,7 @@ class Database implements Driver, Sweeper {
*/ */
private function table() private function table()
{ {
return $this->connection->table(Config::get('session.table')); return $this->connection->table(Config::$items['session']['table']);
} }
} }
\ No newline at end of file
<?php namespace Laravel\Session\Drivers; <?php namespace Laravel\Session\Drivers;
use Laravel\File as F;
class File implements Driver, Sweeper { class File implements Driver, Sweeper {
/** /**
...@@ -32,7 +30,10 @@ class File implements Driver, Sweeper { ...@@ -32,7 +30,10 @@ class File implements Driver, Sweeper {
*/ */
public function load($id) public function load($id)
{ {
if (F::exists($path = $this->path.$id)) return unserialize(F::get($path)); if (file_exists($path = $this->path.$id))
{
return unserialize(file_get_contents($path));
}
} }
/** /**
...@@ -45,7 +46,7 @@ class File implements Driver, Sweeper { ...@@ -45,7 +46,7 @@ class File implements Driver, Sweeper {
*/ */
public function save($session, $config, $exists) public function save($session, $config, $exists)
{ {
F::put($this->path.$session['id'], serialize($session), LOCK_EX); file_put_contents($this->path.$session['id'], serialize($session), LOCK_EX);
} }
/** /**
...@@ -56,7 +57,7 @@ class File implements Driver, Sweeper { ...@@ -56,7 +57,7 @@ class File implements Driver, Sweeper {
*/ */
public function delete($id) public function delete($id)
{ {
F::delete($this->path.$id); if (file_exists($this->path.$id)) @unlink($this->path.$id);
} }
/** /**
...@@ -69,9 +70,9 @@ class File implements Driver, Sweeper { ...@@ -69,9 +70,9 @@ class File implements Driver, Sweeper {
{ {
foreach (glob($this->path.'*') as $file) foreach (glob($this->path.'*') as $file)
{ {
if (F::type($file) == 'file' and F::modified($file) < $expiration) if (filetype($file) == 'file' and filemtime($file) < $expiration)
{ {
F::delete($file); @unlink($file);
} }
} }
} }
......
...@@ -168,7 +168,10 @@ class Manager { ...@@ -168,7 +168,10 @@ class Manager {
*/ */
public static function keep($key) public static function keep($key)
{ {
if (is_array($key)) return array_map(array('Laravel\\Session\\Manager', 'keep'), $key); if (is_array($key))
{
return array_map(array('Laravel\\Session\\Manager', 'keep'), $key);
}
static::flash($key, static::get($key)); static::flash($key, static::get($key));
...@@ -242,7 +245,9 @@ class Manager { ...@@ -242,7 +245,9 @@ class Manager {
*/ */
protected static function replace($search, $replace, $keys) protected static function replace($search, $replace, $keys)
{ {
static::$session['data'] = array_combine(str_replace($search, $replace, $keys), array_values(static::$session['data'])); $keys = str_replace($search, $replace, $keys);
static::$session['data'] = array_combine($keys, array_values(static::$session['data']));
} }
/** /**
......
...@@ -29,9 +29,9 @@ class Cookie implements Transporter { ...@@ -29,9 +29,9 @@ class Cookie implements Transporter {
*/ */
public function put($id, $config) public function put($id, $config)
{ {
// Session cookies may be set to expire on close, which means we // Session cookies may be set to expire on close, which means we will
// will need to pass "0" into the cookie manager. This will cause // need to pass "0" into the cookie manager. This will cause the
// the cookie to not be deleted until the user closes their browser. // cookie to not be deleted until the user closes their browser.
$minutes = ( ! $config['expire_on_close']) ? $config['lifetime'] : 0; $minutes = ( ! $config['expire_on_close']) ? $config['lifetime'] : 0;
\Laravel\Cookie::put(Cookie::key, $id, $minutes, $config['path'], $config['domain'], $config['secure']); \Laravel\Cookie::put(Cookie::key, $id, $minutes, $config['path'], $config['domain'], $config['secure']);
......
...@@ -252,7 +252,6 @@ class View { ...@@ -252,7 +252,6 @@ class View {
public function with($key, $value) public function with($key, $value)
{ {
$this->data[$key] = $value; $this->data[$key] = $value;
return $this; return $this;
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment