Last active
June 6, 2017 16:16
-
-
Save sutandang/de70bfe464cb2508b2542a48e7824e61 to your computer and use it in GitHub Desktop.
Basic PSR 4 autoloader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // Inside MyApp/ create composer.json with the below contents | |
| { | |
| "require": { | |
| }, | |
| "autoload": { | |
| "psr-4": { | |
| "MyApp\\": ["src/", "tests/"] | |
| } | |
| } | |
| } | |
| namespace MyApp\Http; | |
| class Request | |
| { | |
| private $query; | |
| private $request; | |
| public function __construct(array $query = array(), array $request = array()) | |
| { | |
| $this->query = $query; | |
| $this->request = $request; | |
| } | |
| public static function init() | |
| { | |
| return new self( | |
| $_GET, | |
| $_POST | |
| ); | |
| } | |
| public function get($param, $default = null) | |
| { | |
| // order being called: GET, POST | |
| return $this->getQuery($param, $this->getPost($param, $default)); | |
| } | |
| public function getPost($param, $default = null) | |
| { | |
| if (!isset($this->request[$param])) { | |
| return $default; | |
| } | |
| return $this->request[$param]; | |
| } | |
| public function getQuery($param, $default = null) | |
| { | |
| if (!isset($this->query[$param])) { | |
| return $default; | |
| } | |
| return $this->query[$param]; | |
| } | |
| } | |
| namespace MyApp\Http; | |
| class RequestTest extends \PHPUnit_Framework_TestCase | |
| { | |
| protected $request; | |
| public function setUp() | |
| { | |
| $this->request = new Request(); | |
| } | |
| public function testGet() | |
| { | |
| $request = new Request(array('q1' => 'query1')); | |
| $this->assertEquals('query1', $request->get('q1', false)); | |
| } | |
| public function testGetKeyNotFoundReturnsDefaultNull() | |
| { | |
| $request = new Request(array('q1' => 'query1')); | |
| $this->assertNull($request->get('q3')); | |
| } | |
| public function testGetKeyNotFoundReturnsCustomEmptyArray() | |
| { | |
| $request = new Request(array('q1' => 'query1')); | |
| $this->assertEquals(array(), $request->get('q3', array())); | |
| } | |
| public function testGetPost() | |
| { | |
| $request = new Request(array(), array('p1' => 'post1')); | |
| $this->assertEquals('post1', $request->getPost('p1', false)); | |
| } | |
| public function testGetQuery() | |
| { | |
| $request = new Request(array('q1' => 'query1')); | |
| $this->assertEquals('query1', $request->getQuery('q1', false)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment