Skip to content

Commit

Permalink
Add ability to set custom header values in response
Browse files Browse the repository at this point in the history
 ---
 * Ability to use `->header()` method to set custom header data on response
 * Refactor code structure to use /src for project files
 * Update phpunit dependency version
  • Loading branch information
gigili committed Apr 26, 2022
1 parent d53994b commit e476dba
Show file tree
Hide file tree
Showing 10 changed files with 184 additions and 146 deletions.
5 changes: 1 addition & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,7 @@ application file is.
Sample code to allow you to quickly start with your development.

```php
use Gac\Routing\Exceptions\CallbackNotFound;
use Gac\Routing\Exceptions\RouteNotFoundException;
use Gac\Routing\Request;
use Gac\Routing\Routes;
use Gac\Routing\Exceptions\CallbackNotFound;use Gac\Routing\Exceptions\RouteNotFoundException;use Gac\Routing\Request;use Gac\Routing\Routes;

include_once "vendor/autoload.php"; # IF YOU'RE USING composer

Expand Down
6 changes: 3 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "gac/routing",
"type": "library",
"description": "Custom routing library especially useful for API development",
"description": "Custom routing library especially useful for fast API development",
"homepage": "https://github.com/gigili/PHP-routing",
"license": "GPL-3.0-only",
"keywords": [
Expand Down Expand Up @@ -39,8 +39,8 @@
},
"autoload": {
"psr-4": {
"Gac\\Routing\\": "./",
"Gac\\Routing\\Exceptions\\": "./Exceptions"
"Gac\\Routing\\": "./src",
"Gac\\Routing\\Exceptions\\": "./src/Exceptions"
}
},
"require-dev": {
Expand Down
258 changes: 133 additions & 125 deletions composer.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
backupGlobals="false" backupStaticAttributes="false" beStrictAboutTestsThatDoNotTestAnything="true"
beStrictAboutChangesToGlobalState="true"
beStrictAboutOutputDuringTests="true" colors="true" convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertNoticesToExceptions="true" cacheResult="false"
convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false"
bootstrap="vendor/autoload.php" executionOrder="random">
<coverage processUncoveredFiles="true">
Expand Down
16 changes: 13 additions & 3 deletions sample/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,12 +137,22 @@
//This $otherRoutes variable could be defined in a different file and included here only via require or include
$otherRoutes = new Routes();
$otherRoutes->prefix("/sample")
->get("/", function (Request $request){})
->get("/sample1", function (Request $request){})
->get("/sample2", function (Request $request){})
->get("/", function (Request $request) { })
->get("/sample1", function (Request $request) { })
->get("/sample2", function (Request $request) { })
->save();

$routes->append($otherRoutes->get_routes());


$routes->add("/headers", function (Request $request) {
$request->header("Content-type", "text/plain")
->header([ "foo" => "bar", "best" => "test" ])
->header((object) [ "X-Auth" => "Token {token-123}" ])
->status(201)
->send([ "message" => "hello" ]);
}, Routes::GET);

$routes->handle();
} catch ( RouteNotFoundException $ex ) {
$routes->request->status(404, 'Route not found')->send([ 'error' => [ 'message' => $ex->getMessage() ] ]);
Expand Down
File renamed without changes.
File renamed without changes.
39 changes: 31 additions & 8 deletions Request.php → src/Request.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?php

declare( strict_types=1 );

namespace Gac\Routing;

Expand Down Expand Up @@ -58,7 +58,7 @@ public function headers(string $key = '') : array|string|null {
* Sets the header status code for the response
*
* @param int $statusCode Status code to be set for the response
* @param string $message Message to be returned in the header alongside the status code
* @param string $message Message to be sent int the header alongside the status code
*
* @return Request Returns an instance of the Request class so that it can be chained on
*/
Expand All @@ -67,12 +67,36 @@ public function status(int $statusCode = 200, string $message = '') : self {
return $this;
}

/**
* Method used for setting custom header properties
*
* @param string|array|object $key Header key value
* @param mixed $value Header value
*
* @return Request Returns an instance of the Request class so that it can be chained on
*/
public function header(string|array|object $key, mixed $value = NULL) : self {
if ( is_string($key) ) {
header("$key: $value");
} elseif ( is_array($key) || is_object($key) ) {
$keys = $key;
foreach ( $keys as $key => $value ) {
header("$key: $value");
}
}
return $this;
}

/**
* Send response back
*
* @param string|array|object $output Value to be outputted as part of the response
* @param array|object|null $headers Optional list of custom header properties to be sent with the response
*/
public function send(string|array|object $output) {
public function send(string|array|object $output, array|object|null $headers = null) {
if(!is_null($headers)){
$this->header($headers);
}
echo json_encode($output);
}

Expand All @@ -84,16 +108,16 @@ public function send(string|array|object $output) {
private function parse_patch_and_put_request_data() : array {

/* PUT data comes in on the stdin stream */
$putdata = fopen('php://input', 'r');
$putData = fopen('php://input', 'r');

$raw_data = '';

/* Read the data 1 KB at a time and write to the file */
while ( $chunk = fread($putdata, 1024) )
while ( $chunk = fread($putData, 1024) )
$raw_data .= $chunk;

/* Close the streams */
fclose($putdata);
fclose($putData);

// Fetch content and determine boundary
$boundary = substr($raw_data, 0, strpos($raw_data, "\r\n"));
Expand Down Expand Up @@ -126,7 +150,6 @@ private function parse_patch_and_put_request_data() : array {
// Parse the Content-Disposition to get the field name, etc.
if ( isset($headers['content-disposition']) ) {
$filename = NULL;
$tmp_name = NULL;
preg_match(
'/^(.+); *name="([^"]+)"(; *filename="([^"]+)")?/',
$headers['content-disposition'],
Expand Down Expand Up @@ -154,7 +177,7 @@ private function parse_patch_and_put_request_data() : array {
'name' => $filename,
'tmp_name' => $tmp_name,
'size' => strlen($body),
'type' => $value,
'type' => $type,
];

//place in temporary directory
Expand Down
File renamed without changes.
4 changes: 2 additions & 2 deletions tests/RoutesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ public function testCanAddMultipleRequestMethodRoutes() {
"Unable to add new route");
}

public function testCannAddMiddleware() {
public function testCanAddMiddleware() {
$this->routes->middleware([ "test" ])->add("/middleware", []);
$this->assertTrue($this->routes->get_routes()["GET"]["/middleware"]["middlewares"][0] == "test",
"Unable to add middleware");
}

public function testCannAddPrefix() {
public function testCanAddPrefix() {
$this->routes->prefix("/testing")->add("/test", []);
$routes = $this->routes->get_routes();

Expand Down

0 comments on commit e476dba

Please sign in to comment.