| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentSupport\Framework\Http; |
| 4 |
|
| 5 |
use WP_REST_Response; |
| 6 |
use ReflectionException; |
| 7 |
use FluentSupport\Framework\Foundation\App; |
| 8 |
use FluentSupport\Framework\Validator\ValidationException; |
| 9 |
|
| 10 |
abstract class Controller |
| 11 |
{ |
| 12 |
protected $app = null; |
| 13 |
protected $request = null; |
| 14 |
protected $response = null; |
| 15 |
|
| 16 |
public function __construct() |
| 17 |
{ |
| 18 |
$this->app = App::getInstance(); |
| 19 |
$this->request = $this->app['request']; |
| 20 |
$this->response = $this->app['response']; |
| 21 |
} |
| 22 |
|
| 23 |
public function validate($data, $rules, $messages = []) |
| 24 |
{ |
| 25 |
try { |
| 26 |
$validator = $this->app->validator->make($data, $rules, $messages); |
| 27 |
|
| 28 |
if ($validator->validate()->fails()) { |
| 29 |
throw new ValidationException( |
| 30 |
'Unprocessable Entity!', 422, null, $validator->errors() |
| 31 |
); |
| 32 |
} |
| 33 |
|
| 34 |
return $data; |
| 35 |
|
| 36 |
} catch (ValidationException $e) { |
| 37 |
|
| 38 |
if (defined('REST_REQUEST') && REST_REQUEST) { |
| 39 |
throw $e; |
| 40 |
}; |
| 41 |
|
| 42 |
$this->app->doCustomAction('handle_exception', $e); |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
public function json($data = null, $code = 200) |
| 47 |
{ |
| 48 |
return $this->response->json($data, $code); |
| 49 |
} |
| 50 |
|
| 51 |
public function send($data = null, $code = 200) |
| 52 |
{ |
| 53 |
return $this->response->send($data, $code); |
| 54 |
} |
| 55 |
|
| 56 |
public function sendSuccess($data = null, $code = 200) |
| 57 |
{ |
| 58 |
return $this->response->sendSuccess($data, $code); |
| 59 |
} |
| 60 |
|
| 61 |
public function sendError($data = null, $code = 423) |
| 62 |
{ |
| 63 |
return $this->response->sendError($data, $code); |
| 64 |
} |
| 65 |
|
| 66 |
public function __get($key) |
| 67 |
{ |
| 68 |
try { |
| 69 |
return App::getInstance($key); |
| 70 |
} catch(ReflectionException $e) { |
| 71 |
$class = get_class($this); |
| 72 |
wp_die("Undefined property {$key} in $class"); |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
public function response($data, $code = 200) |
| 77 |
{ |
| 78 |
return new WP_REST_Response($data, $code); |
| 79 |
} |
| 80 |
} |
| 81 |
|