| 1 |
<?php |
| 2 |
|
| 3 |
namespace Calotes\Component; |
| 4 |
|
| 5 |
use Calotes\Base\Model; |
| 6 |
use Calotes\Helper\HTTP; |
| 7 |
|
| 8 |
/** |
| 9 |
* This will be passed to every defender_route, This will get data from _POST or _GET and sanitize it before |
| 10 |
* land to the actual process method |
| 11 |
* |
| 12 |
* Class Request |
| 13 |
* |
| 14 |
* @package Calotes\Component |
| 15 |
*/ |
| 16 |
class Request { |
| 17 |
/** |
| 18 |
* store the data from request |
| 19 |
* |
| 20 |
* @var array |
| 21 |
*/ |
| 22 |
protected $data = array(); |
| 23 |
|
| 24 |
public function __construct() { |
| 25 |
if ( 'POST' === $_SERVER['REQUEST_METHOD'] ) { |
| 26 |
$raw_data = HTTP::post( 'data', false ); |
| 27 |
} else { |
| 28 |
$raw_data = HTTP::get( 'data', false ); |
| 29 |
} |
| 30 |
if ( false !== $raw_data ) { |
| 31 |
$this->data = json_decode( $raw_data, true ); |
| 32 |
} |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* Retrieve the data that will be in use, it is recommend that a $filters should be provide for data validation and cast |
| 37 |
* |
| 38 |
* @param array $filters |
| 39 |
* |
| 40 |
* @return array |
| 41 |
*/ |
| 42 |
public function get_data( $filters = array() ) { |
| 43 |
if ( empty( $filters ) ) { |
| 44 |
return $this->data; |
| 45 |
} |
| 46 |
$data = array(); |
| 47 |
foreach ( $filters as $key => $rule ) { |
| 48 |
if ( ! isset( $this->data[ $key ] ) ) { |
| 49 |
continue; // moving on |
| 50 |
} |
| 51 |
// mandatory |
| 52 |
$type = $rule['type']; |
| 53 |
$sanitize = isset( $rule['sanitize'] ) ? $rule['sanitize'] : null; |
| 54 |
|
| 55 |
$value = $this->data[ $key ]; |
| 56 |
// cast |
| 57 |
settype( $value, $type ); |
| 58 |
if ( ! is_array( $sanitize ) ) { |
| 59 |
$sanitize = [ $sanitize ]; |
| 60 |
} |
| 61 |
foreach ( $sanitize as $function ) { |
| 62 |
if ( null !== $function && function_exists( $function ) ) { |
| 63 |
if ( is_array( $value ) ) { |
| 64 |
$value = $this->sanitize_array( $value, $function ); |
| 65 |
} else { |
| 66 |
$value = $function( $value ); |
| 67 |
} |
| 68 |
} |
| 69 |
} |
| 70 |
$data[ $key ] = $value; |
| 71 |
} |
| 72 |
|
| 73 |
return $data; |
| 74 |
} |
| 75 |
|
| 76 |
/** |
| 77 |
* @param $arr |
| 78 |
* @param $sanitize |
| 79 |
* |
| 80 |
* @return mixed |
| 81 |
*/ |
| 82 |
protected function sanitize_array( $arr, $sanitize ) { |
| 83 |
foreach ( $arr as &$value ) { |
| 84 |
if ( is_array( $value ) ) { |
| 85 |
$value = $this->sanitize_array( $value, $sanitize ); |
| 86 |
} else { |
| 87 |
$value = $sanitize( $value ); |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
return $arr; |
| 92 |
} |
| 93 |
|
| 94 |
/** |
| 95 |
* Get the data from _REQUEST |
| 96 |
* |
| 97 |
* @param Model $model |
| 98 |
* |
| 99 |
* @return array |
| 100 |
*/ |
| 101 |
public function get_data_by_model( Model $model ) { |
| 102 |
return $this->get_data( $model->annotations ); |
| 103 |
} |
| 104 |
} |
| 105 |
|