Advertisement
Guest User

Untitled

a guest
Aug 21st, 2015
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.07 KB | None | 0 0
  1. <?php
  2. namespace app\controllers\api;
  3.  
  4. use App;
  5. use app\controllers\api\compression\CompressionManager;
  6. use app\controllers\api\compression\DeflateCompressor;
  7. use app\controllers\api\compression\GzipCompressor;
  8. use app\controllers\api\compression\SdchCompressor;
  9. use app\controllers\api\formatter\FormatterManager;
  10. use app\controllers\api\formatter\JsonFormatter;
  11. use app\controllers\api\formatter\XmlFormatter;
  12. use app\controllers\api\formatter\YamlFormatter;
  13. use Input;
  14. use Config;
  15. use Symfony\Component\HttpKernel\Exception\HttpException;
  16. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  17. use UserLog;
  18. use Exception;
  19. use ApiClient;
  20. use Controller;
  21. use ReflectionClass;
  22. use Illuminate\Http\Request;
  23. use Illuminate\Http\Response;
  24. use  Symfony\Component\Yaml\Yaml;
  25. use Doctrine\Common\Cache\FilesystemCache;
  26. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  27.  
  28. /**
  29.  * Class ApiController
  30.  */
  31. class ApiController extends Controller
  32. {
  33.     const VERSION = '1.3';
  34.  
  35.     /**
  36.      * @var
  37.      */
  38.     protected $cache;
  39.  
  40.     /**
  41.      * @var Request
  42.      */
  43.     protected $request;
  44.  
  45.     /**
  46.      * @var ApiClient
  47.      */
  48.     protected $client;
  49.  
  50.     /**
  51.      * @var string
  52.      */
  53.     protected $token;
  54.  
  55.     /**
  56.      * @var string
  57.      */
  58.     protected $host;
  59.  
  60.     /**
  61.      * @var \Illuminate\Routing\Route
  62.      */
  63.     protected $route;
  64.  
  65.     /**
  66.      *
  67.      */
  68.     public function __construct(Request $request)
  69.     {
  70.         Config::set('laravel-debugbar::config.enabled', false);
  71.  
  72.         $this->route    = \Route::current();
  73.         $this->request  = $request;
  74.  
  75.  
  76.         $this->beforeFilter(function() {
  77.             $this->onRequest($this->request);
  78.         });
  79.  
  80.  
  81.         $this->afterFilter(function($route, Request $request, Response $response) {
  82.             $this->onResponse($response);
  83.         });
  84.  
  85.  
  86.         App::error(function(Exception $exception) {
  87.             $response = new Response();
  88.  
  89.             if ($exception instanceof HttpExceptionInterface) {
  90.                 $response->setStatusCode($exception->getStatusCode());
  91.             } else {
  92.                 $response->setStatusCode($exception->getCode() ?: 500);
  93.             }
  94.  
  95.             $response->setContent(json_encode($this->onError($exception)));
  96.  
  97.             return $this->onResponse($response, 'error');
  98.         });
  99.  
  100.         $this->cache = new FilesystemCache(storage_path('cache'));
  101.     }
  102.  
  103.     /**
  104.      * Authorize Client by X-Api-Token
  105.      *
  106.      * @param Request $request
  107.      * @return Request
  108.      */
  109.     protected function onRequest(Request $request)
  110.     {
  111.         if (!$request->headers->has('x-api-token')) {
  112.             throw new AccessDeniedHttpException('Request token not found');
  113.         }
  114.  
  115.         $this->token = $request->headers->get('x-api-token');
  116.  
  117.         $client = ApiClient::getByToken($this->token);
  118.         if (!$client) {
  119.             throw new AccessDeniedHttpException(
  120.                 'Mismatch credinals. Invalid access token: ' . print_r($this->token, 1)
  121.             );
  122.         }
  123.  
  124.         $ip = array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)
  125.             ? trim($_SERVER['HTTP_X_FORWARDED_FOR'])
  126.             : $request->getClientIps();
  127.  
  128.         if (!$client->check($ip)) {
  129.             throw new AccessDeniedHttpException(
  130.                 'Mismatch credinals. Invalid request host: ' . print_r($ip, 1) .
  131.                     ' ( ' . implode(', ', $request->getClientIps()) . ' )'
  132.             );
  133.         }
  134.  
  135.         return $request;
  136.     }
  137.  
  138.  
  139.     /**
  140.      * @param Response $response
  141.      * @param string $status
  142.      * @return Response
  143.      */
  144.     protected function onResponse(Response $response, $status = 'success')
  145.     {
  146.         $responseContent = json_decode($response->getContent(), true);
  147.         if (json_last_error() !== JSON_ERROR_NONE) {
  148.             $responseContent = ['data' => $response->getContent()];
  149.         }
  150.  
  151.         $data = $this->getContent($responseContent, $status);
  152.  
  153.         /**
  154.          * Api Output format
  155.          */
  156.         $ext = $this->route->getParameter('extension', '.json');
  157.         $manager = new FormatterManager([
  158.             new JsonFormatter(),
  159.             new YamlFormatter(),
  160.             new XmlFormatter()
  161.         ]);
  162.         $manager->format($ext, $response, $data);
  163.  
  164.  
  165.         /**
  166.          * Api Output compression
  167.          */
  168.         $type = $this->request->headers->get('x-api-compression');
  169.         $manager = new CompressionManager([
  170.             new GzipCompressor(),
  171.             new DeflateCompressor(),
  172.             new SdchCompressor()
  173.         ]);
  174.         $manager->format($type, $response);
  175.  
  176.  
  177.         return $response;
  178.     }
  179.  
  180.     /**
  181.      * @param Exception $e
  182.      * @return Response
  183.      */
  184.     protected function onError(Exception $e)
  185.     {
  186.         $result = [
  187.             'code'      => $e->getCode(),
  188.             'type'      => (new ReflectionClass($e))->getShortName(),
  189.             'message'   => get_class($e) . ': ' . $e->getMessage()
  190.         ];
  191.  
  192.         if (App::environment('local')) {
  193.             $result['file']     = $e->getFile() . ':' . $e->getLine();
  194.             $result['trace']    = explode("\n", $e->getTraceAsString());
  195.         }
  196.  
  197.         return $result;
  198.     }
  199.  
  200.  
  201.     /**
  202.      * @param $responseData
  203.      * @param string $responseStatus
  204.      * @return array
  205.      */
  206.     protected function getContent($responseData, $responseStatus = 'success')
  207.     {
  208.         $data = [
  209.             'info'      => [
  210.                 'version' => self::VERSION,
  211.                 'timeout' => number_format(microtime(true) - LARAVEL_START, 6)
  212.             ],
  213.             'status'    => $responseStatus,
  214.             'response'  => $responseData,
  215.         ];
  216.  
  217.         if (Input::get('debug')) {
  218.             $data['debug'] = [
  219.                 'queries' => \DB::getQueryLog(),
  220.                 'request' => [
  221.                     'arguments' => Input::all()
  222.                 ]
  223.             ];
  224.         }
  225.  
  226.         if (Input::get('id')) {
  227.             $data['id'] = Input::get('id');
  228.         }
  229.  
  230.  
  231.         return $data;
  232.     }
  233. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement