Overview

Namespaces

  • Kotchasan
    • Cache
    • Database
    • Http
    • Log
    • Orm
  • None
  • PHP
  • Psr
    • Cache
    • Http
      • Message
    • Log

Classes

  • ArrayIterator
  • DateInterval
  • DOMNode
  • Kotchasan
  • Kotchasan\Accordion
  • Kotchasan\ApiController
  • Kotchasan\ArrayTool
  • Kotchasan\Cache\ApcCache
  • Kotchasan\Cache\Cache
  • Kotchasan\Cache\CacheItem
  • Kotchasan\Cache\FileCache
  • Kotchasan\CKEditor
  • Kotchasan\Collection
  • Kotchasan\Config
  • Kotchasan\Controller
  • Kotchasan\Country
  • Kotchasan\Csv
  • Kotchasan\Curl
  • Kotchasan\Currency
  • Kotchasan\Database
  • Kotchasan\Database\Db
  • Kotchasan\Database\DbCache
  • Kotchasan\Database\Driver
  • Kotchasan\Database\PdoMysqlDriver
  • Kotchasan\Database\Query
  • Kotchasan\Database\QueryBuilder
  • Kotchasan\Database\Schema
  • Kotchasan\Database\Sql
  • Kotchasan\DataTable
  • Kotchasan\Date
  • Kotchasan\DOMNode
  • Kotchasan\DOMParser
  • Kotchasan\Email
  • Kotchasan\File
  • Kotchasan\Files
  • Kotchasan\Form
  • Kotchasan\Grid
  • Kotchasan\Html
  • Kotchasan\Htmldoc
  • Kotchasan\HtmlTable
  • Kotchasan\Http\AbstractMessage
  • Kotchasan\Http\AbstractRequest
  • Kotchasan\Http\Message
  • Kotchasan\Http\NotFound
  • Kotchasan\Http\Request
  • Kotchasan\Http\Response
  • Kotchasan\Http\Stream
  • Kotchasan\Http\UploadedFile
  • Kotchasan\Http\Uri
  • Kotchasan\Image
  • Kotchasan\InputItem
  • Kotchasan\Inputs
  • Kotchasan\KBase
  • Kotchasan\Language
  • Kotchasan\ListItem
  • Kotchasan\Log\AbstractLogger
  • Kotchasan\Log\Logger
  • Kotchasan\Login
  • Kotchasan\Menu
  • Kotchasan\Mime
  • Kotchasan\Model
  • Kotchasan\Number
  • Kotchasan\ObjectTool
  • Kotchasan\Orm\Field
  • Kotchasan\Orm\Recordset
  • Kotchasan\Password
  • Kotchasan\Pdf
  • Kotchasan\Province
  • Kotchasan\Router
  • Kotchasan\Session
  • Kotchasan\Singleton
  • Kotchasan\Tab
  • Kotchasan\TableRow
  • Kotchasan\Template
  • Kotchasan\Text
  • Kotchasan\Validator
  • Kotchasan\View
  • PHPMailer
  • Psr\Log\AbstractLogger
  • Psr\Log\LogLevel
  • Psr\Log\NullLogger
  • SMTP

Interfaces

  • ArrayAccess
  • Countable
  • DateTimeInterface
  • Iterator
  • IteratorAggregate
  • Psr\Cache\CacheItemInterface
  • Psr\Cache\CacheItemPoolInterface
  • Psr\Http\Message\MessageInterface
  • Psr\Http\Message\RequestInterface
  • Psr\Http\Message\ResponseInterface
  • Psr\Http\Message\ServerRequestInterface
  • Psr\Http\Message\StreamInterface
  • Psr\Http\Message\UploadedFileInterface
  • Psr\Http\Message\UriInterface
  • Psr\Log\LoggerAwareInterface
  • Psr\Log\LoggerInterface
  • SeekableIterator
  • Serializable
  • Traversable

Traits

  • Psr\Log\LoggerTrait

Exceptions

  • Exception
  • InvalidArgumentException
  • Kotchasan\ApiException
  • Kotchasan\Cache\Exception
  • Kotchasan\Database\Exception
  • Kotchasan\InputItemException
  • LogicException
  • phpmailerException
  • RuntimeException

Functions

  • createClass
  • debug
  • getClassPath
  • Overview
  • Namespace
  • Class
  • Tree
  1: <?php
  2: /**
  3:  * @filesource Kotchasan/ApiController.php
  4:  *
  5:  * @copyright 2016 Goragod.com
  6:  * @license http://www.kotchasan.com/license/
  7:  *
  8:  * @see http://www.kotchasan.com/
  9:  */
 10: 
 11: namespace Kotchasan;
 12: 
 13: use Kotchasan\Http\Request;
 14: 
 15: /**
 16:  * API Controller base class
 17:  *
 18:  * @author Goragod Wiriya <admin@goragod.com>
 19:  *
 20:  * @since 1.0
 21:  */
 22: class ApiController extends KBase
 23: {
 24:     /**
 25:      * แม่แบบคอนโทรลเลอร์ สำหรับ API
 26:      *
 27:      * @param Request $request
 28:      *
 29:      * @return JSON
 30:      */
 31:     public function index(Request $request)
 32:     {
 33:         if (empty(self::$cfg->api_token) || empty(self::$cfg->api_ips)) {
 34:             // ยังไม่ได้สร้าง Token หรือ ยังไม่ได้อนุญาต IP
 35:             $result = array(
 36:                 'code' => 503,
 37:                 'message' => 'Unavailable API',
 38:             );
 39:         } elseif (in_array('0.0.0.0', self::$cfg->api_ips) || in_array($request->getClientIp(), self::$cfg->api_ips)) {
 40:             try {
 41:                 // รับค่าที่ส่งมาจาก Router
 42:                 $module = $request->get('module')->filter('a-z0-9');
 43:                 $method = $request->get('method')->filter('a-z');
 44:                 $action = $request->get('action')->filter('a-z');
 45:                 // แปลงเป็นชื่อคลาส สำหรับ Model เช่น
 46:                 // api.php/v1/user/create ได้เป็น V1\User\Model::create
 47:                 $className = ucfirst($module).'\\'.ucfirst($method).'\\Model';
 48:                 // ตรวจสอบ method
 49:                 if (method_exists($className, $action)) {
 50:                     // เรียกใช้งาน Class
 51:                     $result = createClass($className)->$action($request);
 52:                 } else {
 53:                     // error ไม่พบ class หรือ method
 54:                     $result = array(
 55:                         'code' => 404,
 56:                         'message' => 'Object Not Found',
 57:                     );
 58:                 }
 59:             } catch (ApiException $e) {
 60:                 // API Error
 61:                 $result = array(
 62:                     'code' => $e->getCode(),
 63:                     'message' => $e->getMessage(),
 64:                 );
 65:             }
 66:         } else {
 67:             // ไม่อนุญาต IP
 68:             $result = array(
 69:                 'code' => 403,
 70:                 'message' => 'Forbidden',
 71:             );
 72:         }
 73:         // Response คืนค่ากลับเป็น JSON ตาม $result
 74:         $response = new \Kotchasan\Http\Response();
 75:         $response->withHeaders(array(
 76:             'Content-type' => 'application/json; charset=UTF-8',
 77:         ))
 78:             ->withStatus(empty($result['code']) ? 200 : $result['code'])
 79:             ->withContent(json_encode($result))
 80:             ->send();
 81:     }
 82: 
 83:     /**
 84:      * ตรวจสอบ Token
 85:      * สำเร็จ คืนค่า true
 86:      * ไม่สำเร็จคืนค่าข้อผิดพลาด ApiException Invalid token
 87:      *
 88:      * @param string $token
 89:      *
 90:      * @return bool
 91:      */
 92:     public static function validateToken($token)
 93:     {
 94:         if (self::$cfg->api_token === $token) {
 95:             return true;
 96:         }
 97:         throw new ApiException('Invalid token', 401);
 98:     }
 99: 
100:     /**
101:      * ตรวจสอบ Token Bearer
102:      * สำเร็จ คืนค่า true
103:      * ไม่สำเร็จคืนค่าข้อผิดพลาด ApiException Invalid token
104:      *
105:      * @param Request $request
106:      *
107:      * @return bool
108:      */
109:     public static function validateTokenBearer(Request $request)
110:     {
111:         if (preg_match('/^Bearer\s'.self::$cfg->api_token.'$/', $request->getHeaderLine('Authorization'))) {
112:             return true;
113:         }
114:         throw new ApiException('Invalid token', 401);
115:     }
116: 
117:     /**
118:      * ตรวจสอบ sign
119:      * สำเร็จ คืนค่า true
120:      * ไม่สำเร็จคืนค่าข้อผิดพลาด ApiException Invalid sign
121:      *
122:      * @param $params
123:      *
124:      * @return bool
125:      */
126:     public static function validateSign($params)
127:     {
128:         if (count($params) > 1 && isset($params['sign'])) {
129:             $sign = $params['sign'];
130:             unset($params['sign']);
131:             if ($sign === \Kotchasan\Password::generateSign($params, self::$cfg->api_secret)) {
132:                 return true;
133:             }
134:         }
135:         throw new ApiException('Invalid sign', 403);
136: 
137:     }
138: 
139:     /**
140:      * ตรวจสอบ Method
141:      * สำเร็จ คืนค่า true
142:      * ไม่สำเร็จคืนค่าข้อผิดพลาด ApiException Method not allowed
143:      *
144:      * @param Request $request
145:      * @param string $method Method เช่น POST GET PUT DELETE OPTIONS
146:      *
147:      * @return bool
148:      */
149:     public static function validateMethod(Request $request, $method)
150:     {
151:         if ($request->getMethod() === $method) {
152:             return true;
153:         }
154:         throw new ApiException('Method not allowed', 405);
155:     }
156: }
157: 
Kotchasan API documentation generated by ApiGen