Skip to content

Commit

Permalink
add json api
Browse files Browse the repository at this point in the history
  • Loading branch information
afshinakhgar committed Feb 15, 2018
1 parent 8921bae commit da1a27d
Show file tree
Hide file tree
Showing 9 changed files with 94 additions and 23 deletions.
15 changes: 15 additions & 0 deletions app/Controller/Api/V1/Test/TestController.php
@@ -0,0 +1,15 @@
<?php

namespace App\Controller\Api\V1\Test;
use App\Controller\Controller;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

class TestController extends Controller
{

public function index(Request $request, Response $response, $args)
{
return $this->jsonApi->render($response,['username' => 'akhgar.net', 'realname' => 'Afsh', 'age' => 32]);
}
}
21 changes: 2 additions & 19 deletions app/Middleware/RouterMiddleware.php
@@ -1,14 +1,4 @@
<?php
/**
* Created by PhpStorm.
* User: afshin
* Date: 11/14/17
* Time: 12:22 AM
*/

namespace App\Middleware;


namespace App\Middleware;

use Core\Interfaces\_Middleware;
Expand All @@ -25,9 +15,7 @@ public function __invoke($request, $response, $next) {
if ($route) {

$route_name = $route->getName();

$uri_page_parameter = $request->getParam('page');

// We want to retrieve the whole url including all the get parameters to get the current url itself
// Excluding page (pagination) parameter.
if ($uri_page_parameter != '') {
Expand All @@ -37,13 +25,8 @@ public function __invoke($request, $response, $next) {
// We'll also check if the request has been sent using get method
$uri_request_sent = explode('?', $uri);

// Route Information
$this->container->view->getEnvironment()->addGlobal('uri', [
'link' => $uri,
'request_sent' => (isset($uri_request_sent[1])) ? true : false
]);
$this->container->view->getEnvironment()->addGlobal('current_route', $route_name);
$this->container->view->getEnvironment()->addGlobal('current_path', $current_path);

$GLOBALS['current_route_path'] = rtrim($current_path,'/');
}

$response = $next($request, $response);
Expand Down
2 changes: 2 additions & 0 deletions app/Routes/Api.php
@@ -0,0 +1,2 @@
<?php
$route->get('/api/v1/test', \App\Controller\Api\V1\Test\TestController::class.':index')->setName('api_test');
6 changes: 6 additions & 0 deletions bootstrap/dependencies.php
Expand Up @@ -175,6 +175,12 @@
return new \Core\Handlers\JsonHandler();
};

$container['jsonApi'] = function ($container) {
return new \Core\Renderers\JsonApiRenderer();
};



$app->getContainer()['view']->getRenderer()->getCompiler()->directive('helloWorld', function(){

return "<?php echo 'Hello Directive'; ?>";
Expand Down
3 changes: 2 additions & 1 deletion bootstrap/routes.php
Expand Up @@ -6,13 +6,14 @@
/** Route Partial Loadup =================================================== */
foreach ($files as $partial) {
$file = __APP_ROOT__.'app/Routes/'.$partial;

$filse[] = $file;
if ( ! file_exists($file))
{
$msg = "Route partial [{$partial}] not found.";
}
include $file;
}

$route->get('/', HomeController::class.':index')->setName('home');

$route->resource('/user/auth', '\App\Controller\User\AuthController', $args = []);
Expand Down
7 changes: 6 additions & 1 deletion composer.json
Expand Up @@ -16,7 +16,8 @@
"cli-tool",
"console",
"phpunit",
"Modular"
"Modular",
"Json APi"
],
"require": {
"php": ">= 7.0.0",
Expand Down Expand Up @@ -46,5 +47,9 @@
"App\\": "app/",
"Core\\": "core/"
}
},
"scripts": {
"start": "php -S localhost:7000 -t public/",
"test": "phpunit"
}
}
2 changes: 1 addition & 1 deletion config/view.php
@@ -1,4 +1,4 @@
<?php
<?php
return [
// Renderer settings
'view' => [
Expand Down
2 changes: 1 addition & 1 deletion core/Helpers/Env.php
Expand Up @@ -20,7 +20,6 @@ public function __invoke($filePath ,$key, $default = null)
}else {
return '';
}

$value = getenv($key);

if ($value === false) {
Expand All @@ -41,6 +40,7 @@ public function __invoke($filePath ,$key, $default = null)
return null;
}
$strLen = strlen($value);

if ($strLen > 1 && $value[0] === '"' && $value[$strLen - 1] === '"') {
return substr($value, 1, -1);
}
Expand Down
59 changes: 59 additions & 0 deletions core/Renderers/JsonApiRenderer.php
@@ -0,0 +1,59 @@
<?php
namespace Core\Renderers;

use Psr\Http\Message\ResponseInterface;
use Slim\Http\Body;

class JsonApiRenderer
{
/**
* Bitmask consisting of <b>JSON_HEX_QUOT</b>,
* <b>JSON_HEX_TAG</b>,
* <b>JSON_HEX_AMP</b>,
* <b>JSON_HEX_APOS</b>,
* <b>JSON_NUMERIC_CHECK</b>,
* <b>JSON_PRETTY_PRINT</b>,
* <b>JSON_UNESCAPED_SLASHES</b>,
* <b>JSON_FORCE_OBJECT</b>,
* <b>JSON_UNESCAPED_UNICODE</b>.
* The behaviour of these constants is described on
* the JSON constants page.
* @var int
*/
/**
* Output rendered template
*
* @param ResponseInterface $response
* @param array $data Associative array of data to be returned
* @param int $status HTTP status code
* @param array $addHeaders Associative array of header to be added
* @return ResponseInterface
*/
public function render(ResponseInterface $response, array $data = [], $status = 200, $addHeaders = [])
{
$status = intval($status);
$output = [
'meta' => ['error' => true, 'status' => $status],
'data' => $data,
];
$output['meta']['error'] = ($status < 400) ? false : true;
$json = json_encode($output, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
// Ensure that the json encoding passed successfully
if ($json === false) {
throw new \RuntimeException(json_last_error_msg(), json_last_error());
}
$body = new Body(fopen('php://temp', 'r+'));
$body->write($json);
$newResponse = $response->withBody($body);
$newResponse = $newResponse->withStatus($status)
->withHeader('Content-Type', 'application/json;charset=utf-8');
if (count($addHeaders)) {
foreach ($addHeaders as $headerKey => $headerValue) {
if (strtolower($headerKey) != 'content-type') {
$newResponse->withHeader($headerKey, $headerValue);
}
}
}
return $newResponse;
}
}

0 comments on commit da1a27d

Please sign in to comment.