Skip to content

Commit

Permalink
init all things
Browse files Browse the repository at this point in the history
  • Loading branch information
Alvaro Carneiro committed Dec 3, 2014
0 parents commit 3b7ee1b
Show file tree
Hide file tree
Showing 8 changed files with 911 additions and 0 deletions.
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
The 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.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
Routz
=======================

PHP simple routing using the powerful http-foundation component

## License

MIT License

## Installation

Install it through composer

## Documentation

The api is VERY similar to my previous router, *Routy*.

There is a **very** dirty example file to get the idea behind this router

It's 5am right now and I have to work so I'll document it later.

## Special

I would love to see some pull requests, so many months I didn't touch a single line of code and I would really love to come back doing what I love to do :)
22 changes: 22 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "routz/routz",
"description": "PHP simple routing using the powerful http-foundation component",
"keywords": ["php", "routz", "routing", "httpfoundation", "symfony"],
"license": "MIT",
"autorhs": [
{
"name": "Alvaro Carneiro",
"email": "[email protected]"
}
],
"require": {
"php": ">=5.4.0",
"symfony/http-foundation": "*"
},
"autoload": {
"psr-0": {
"Routz": "src/"
}
},
"minimum-stability": "dev"
}
54 changes: 54 additions & 0 deletions index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

require 'vendor/autoload.php';

use Routz\Router;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;

Request::enableHttpMethodParameterOverride();

$router = new Router();

$router->get('/, /home', function() {
// $this refers to the router
// through the router you can access the current request, session and other methods
$content = '';

if ($rem = $this->session->get('name')) {
$content .= 'Whoa, I remember you '.$rem.'<br />';
$this->session->remove('name');
}
else {
$this->session->set('name', 'Alvaro');
}

$content .= 'Hello there ' . $this->request->get('name', 'alvaro').'<br />';

$content .= $this->to('home').'<br />';

$content .= $this->to('testo').'<br />';

$content .= $this->to('profile', ['id' => 2]).'<br />';

return new Response($content);
})->named('home');

$router->get('/test', function() {
echo ':D';
})->named('testo');

$router->get('/user/{id}', function($id) {
echo 'Hi ' . $id;
})->before(function($id) {
if ($id == 2) {
return new RedirectResponse($this->to('home'));
}
})->named('profile');

$router->error(function() {
echo 'Whoa, an error';
});

$router->run()->send();
240 changes: 240 additions & 0 deletions src/Routz/Action.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
<?php

namespace Routz;

/**
* Class representing an action
*
* @author Alvaro Carneiro <[email protected]>
* @package Routz
* @license MIT License
*/
class Action {

/**
* Routes this callback with handle
*
* @var string|array
*/
protected $route;

/**
* The name used to identify this action
*
* @var string
*/
protected $name;

/**
* The callback to execute
*
* @var callable
*/
protected $callback;

/**
* Condition to execute the action
*
* @var callable
*/
protected $condition;

/**
* Set of callbacks to call after calling the current action
*
* @var callable
*/
protected $before = [];

/**
* Set of callbacks to be called after the current action
*
* @var callable
*/
protected $after = [];

/**
* The router used to generate this action, we need it in some methods
*
* @var Router
*/
private $router;

/**
* Constructs a new action
*
* @param string|array $route Routes this action with handle
* @param callable $callback The callback
* @param Router $router The router used to generate this action
*
* @throws InvalidArgumentException When the callback parameter isn't valid
*/
public function __construct($route, $callback, Router $router)
{
$this->router = $router;

// With this, we're able to register a callback to
// more routes like this: "/, home, index"
if (is_string($route)) $route = explode(', ', $route);

// make the $route variable an array so we can attach
// the callback to more than one route
$this->route = (array)$route;

$this->callback = \Closure::bind($callback, $router);
}

/**
* Get all the routes this action handles
*
* @return array List of routes
*/
public function route()
{
return $this->route;
}

/**
* Call the action and pass arguments to it
*
* @return mixed The returned value of the action
*/
public function call($arguments = [])
{
$arguments = (array)$arguments;

// for now we can call the action
$result = true;

// if we defined a condition using the "when" method
if ($this->condition)
{
$result = (bool)call_user_func_array($this->condition, $arguments);
}

// If the condition returns false
// throw http not found error
if ( ! $result)
{
throw new HttpException('Route not found', 404);
}

// if we defined a callback to execute
// before the action
if (count($this->before))
{
foreach ($this->before as $before) {
// call it passing the same arguments
// we're going to pass to the action
$contents = call_user_func_array($before, $arguments);

// if it returned something use it as the contents
// to send (it's like using route filters)
if ($contents)
{
return Router::ensureItsResponseObject($contents);
}
}
}

// Fetch the contents of the action callback
// so if we defined an "after" method we'll pass them to it
$contents = Router::ensureItsResponseObject(call_user_func_array($this->callback, $arguments));

if (count($this->after))
{
foreach ($this->after as $after) {
$aftercall = call_user_func($after, $contents);

if ($after) {
$contents = Router::ensureItsResponseObject($aftercall);
}
}
}

return $contents;
}

/**
* Sets an identifier to this route, so we make a url to it
*
* @param string $name The name of this action
*
* @return Action
*/
public function named($name)
{
$this->router->identify($this, $this->name = $name);

return $this;
}

/**
* Callback to execute before the action
*
* @param callable $callback The callback
*/
public function before($callback)
{
// If the callback is invalid
// throw an exception
if ( ! is_callable($callback))
{
throw new \InvalidArgumentException('The $callback parameter isn\'t valid.');
}

$this->before[] = \Closure::bind($callback, $this->router);

return $this;
}

/**
* Callback to execute after the action
*
* @param callable $callback The callback
*/
public function after($callback)
{
// If the callback is invalid
// throw an exception
if ( ! is_callable($callback))
{
throw new \InvalidArgumentException('The $callback parameter isn\'t valid.');
}

$this->after[] = \Closure::bind($callback, $this->router);

return $this;
}

/**
* Set a required condition to execute the action
*
* <code>
*
* $router->get('greet/:name', function($name)
* {
* echo "Hello {$name}";
* })->when(function($name)
* {
* return $name == 'Alvaro';
* });
* // the action will be called only when $name equals "Alvaro"
* </code>
*
* @param callable $callback The callback that will return true or false
*/
public function when($callback)
{
// If the callback is invalid
// throw an exception
if ( ! is_callable($callback))
{
throw new \InvalidArgumentException('The $callback parameter isn\'t valid.');
}

$this->condition = $callback;

return $this;
}
}
19 changes: 19 additions & 0 deletions src/Routz/HttpException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace Routz;

/**
* Represents an Http error to the Routz library
*
* @author Alvaro Carneiro <[email protected]>
* @package Routz
* @license MIT License
*/
class HttpException extends \Exception {

public function __construct($message = null, $code = 500)
{
parent::__construct($message, $code);
}

}
Loading

0 comments on commit 3b7ee1b

Please sign in to comment.