Json.php
84 lines
| 1 | <?php |
| 2 | |
| 3 | namespace AC\Response; |
| 4 | |
| 5 | use LogicException; |
| 6 | |
| 7 | class Json { |
| 8 | |
| 9 | const MESSAGE = 'message'; |
| 10 | |
| 11 | /** |
| 12 | * @var array |
| 13 | */ |
| 14 | protected $parameters = []; |
| 15 | |
| 16 | /** |
| 17 | * @var int |
| 18 | */ |
| 19 | protected $status_code; |
| 20 | |
| 21 | public function send() { |
| 22 | if ( empty( $this->parameters ) ) { |
| 23 | throw new LogicException( 'Missing response body.' ); |
| 24 | } |
| 25 | |
| 26 | wp_send_json( $this->parameters, $this->status_code ); |
| 27 | } |
| 28 | |
| 29 | public function error() { |
| 30 | wp_send_json_error( $this->parameters, $this->status_code ); |
| 31 | } |
| 32 | |
| 33 | public function success() { |
| 34 | wp_send_json_success( $this->parameters, $this->status_code ); |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * @param string $key |
| 39 | * @param mixed $value |
| 40 | * |
| 41 | * @return $this |
| 42 | */ |
| 43 | public function set_parameter( $key, $value ) { |
| 44 | $this->parameters[ $key ] = $value; |
| 45 | |
| 46 | return $this; |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * @param array $values |
| 51 | * |
| 52 | * @return $this |
| 53 | */ |
| 54 | public function set_parameters( array $values ) { |
| 55 | foreach ( $values as $key => $value ) { |
| 56 | $this->set_parameter( $key, $value ); |
| 57 | } |
| 58 | |
| 59 | return $this; |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * @param string $message |
| 64 | * |
| 65 | * @return $this |
| 66 | */ |
| 67 | public function set_message( $message ) { |
| 68 | $this->set_parameter( self::MESSAGE, $message ); |
| 69 | |
| 70 | return $this; |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * @param int $code |
| 75 | * |
| 76 | * @return $this |
| 77 | */ |
| 78 | public function set_status_code( $code ) { |
| 79 | $this->status_code = $code; |
| 80 | |
| 81 | return $this; |
| 82 | } |
| 83 | |
| 84 | } |