Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace app\controllers\api;
- use App;
- use app\controllers\api\compression\CompressionManager;
- use app\controllers\api\compression\DeflateCompressor;
- use app\controllers\api\compression\GzipCompressor;
- use app\controllers\api\compression\SdchCompressor;
- use app\controllers\api\formatter\FormatterManager;
- use app\controllers\api\formatter\JsonFormatter;
- use app\controllers\api\formatter\XmlFormatter;
- use app\controllers\api\formatter\YamlFormatter;
- use Input;
- use Config;
- use Symfony\Component\HttpKernel\Exception\HttpException;
- use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
- use UserLog;
- use Exception;
- use ApiClient;
- use Controller;
- use ReflectionClass;
- use Illuminate\Http\Request;
- use Illuminate\Http\Response;
- use Symfony\Component\Yaml\Yaml;
- use Doctrine\Common\Cache\FilesystemCache;
- use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
- /**
- * Class ApiController
- */
- class ApiController extends Controller
- {
- const VERSION = '1.3';
- /**
- * @var
- */
- protected $cache;
- /**
- * @var Request
- */
- protected $request;
- /**
- * @var ApiClient
- */
- protected $client;
- /**
- * @var string
- */
- protected $token;
- /**
- * @var string
- */
- protected $host;
- /**
- * @var \Illuminate\Routing\Route
- */
- protected $route;
- /**
- *
- */
- public function __construct(Request $request)
- {
- Config::set('laravel-debugbar::config.enabled', false);
- $this->route = \Route::current();
- $this->request = $request;
- $this->beforeFilter(function() {
- $this->onRequest($this->request);
- });
- $this->afterFilter(function($route, Request $request, Response $response) {
- $this->onResponse($response);
- });
- App::error(function(Exception $exception) {
- $response = new Response();
- if ($exception instanceof HttpExceptionInterface) {
- $response->setStatusCode($exception->getStatusCode());
- } else {
- $response->setStatusCode($exception->getCode() ?: 500);
- }
- $response->setContent(json_encode($this->onError($exception)));
- return $this->onResponse($response, 'error');
- });
- $this->cache = new FilesystemCache(storage_path('cache'));
- }
- /**
- * Authorize Client by X-Api-Token
- *
- * @param Request $request
- * @return Request
- */
- protected function onRequest(Request $request)
- {
- if (!$request->headers->has('x-api-token')) {
- throw new AccessDeniedHttpException('Request token not found');
- }
- $this->token = $request->headers->get('x-api-token');
- $client = ApiClient::getByToken($this->token);
- if (!$client) {
- throw new AccessDeniedHttpException(
- 'Mismatch credinals. Invalid access token: ' . print_r($this->token, 1)
- );
- }
- $ip = array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)
- ? trim($_SERVER['HTTP_X_FORWARDED_FOR'])
- : $request->getClientIps();
- if (!$client->check($ip)) {
- throw new AccessDeniedHttpException(
- 'Mismatch credinals. Invalid request host: ' . print_r($ip, 1) .
- ' ( ' . implode(', ', $request->getClientIps()) . ' )'
- );
- }
- return $request;
- }
- /**
- * @param Response $response
- * @param string $status
- * @return Response
- */
- protected function onResponse(Response $response, $status = 'success')
- {
- $responseContent = json_decode($response->getContent(), true);
- if (json_last_error() !== JSON_ERROR_NONE) {
- $responseContent = ['data' => $response->getContent()];
- }
- $data = $this->getContent($responseContent, $status);
- /**
- * Api Output format
- */
- $ext = $this->route->getParameter('extension', '.json');
- $manager = new FormatterManager([
- new JsonFormatter(),
- new YamlFormatter(),
- new XmlFormatter()
- ]);
- $manager->format($ext, $response, $data);
- /**
- * Api Output compression
- */
- $type = $this->request->headers->get('x-api-compression');
- $manager = new CompressionManager([
- new GzipCompressor(),
- new DeflateCompressor(),
- new SdchCompressor()
- ]);
- $manager->format($type, $response);
- return $response;
- }
- /**
- * @param Exception $e
- * @return Response
- */
- protected function onError(Exception $e)
- {
- $result = [
- 'code' => $e->getCode(),
- 'type' => (new ReflectionClass($e))->getShortName(),
- 'message' => get_class($e) . ': ' . $e->getMessage()
- ];
- if (App::environment('local')) {
- $result['file'] = $e->getFile() . ':' . $e->getLine();
- $result['trace'] = explode("\n", $e->getTraceAsString());
- }
- return $result;
- }
- /**
- * @param $responseData
- * @param string $responseStatus
- * @return array
- */
- protected function getContent($responseData, $responseStatus = 'success')
- {
- $data = [
- 'info' => [
- 'version' => self::VERSION,
- 'timeout' => number_format(microtime(true) - LARAVEL_START, 6)
- ],
- 'status' => $responseStatus,
- 'response' => $responseData,
- ];
- if (Input::get('debug')) {
- $data['debug'] = [
- 'queries' => \DB::getQueryLog(),
- 'request' => [
- 'arguments' => Input::all()
- ]
- ];
- }
- if (Input::get('id')) {
- $data['id'] = Input::get('id');
- }
- return $data;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement