Skip to content

Instantly share code, notes, and snippets.

@antoniodipinto
Created July 6, 2019 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antoniodipinto/4cd6b89b668f865afb70aa5a3ae35097 to your computer and use it in GitHub Desktop.
Save antoniodipinto/4cd6b89b668f865afb70aa5a3ae35097 to your computer and use it in GitHub Desktop.
A simple class fo CodeIgniter that helps to receive JSON format data
<?php
/**
* Author: Antonio Di Pinto
* Email: adp19911229@gmail.com
*
* @description: A simple class fo CodeIgniter that helps to receive JSON format data
*/
class Input_Json extends CI_Input
{
/**
* @var array
*/
protected $_validation_fields = [];
/**
* @var array
*/
protected $_errors = [];
/**
* @var string
*/
protected $_error_message = "Missing value: %s";
/**
* Input_Json constructor.
*/
public function __construct()
{
parent::__construct();
}
/**
* @param $field string Json key to retrieve
*/
public function add_required_field($field)
{
$this->_validation_fields[] = $field;
}
public function set_error_message($message){
$this->_error_message = $message;
}
/**
* @return bool
*/
public function has_required_fields()
{
foreach ($this->_validation_fields as $index) {
if (is_null_or_empty($this->key($index))) {
$this->_add_validation_error($index);
}
}
return empty($this->_errors);
}
/**
* @param null $index
* @return mixed|null
*/
public function key($index = null)
{
$input = parent::__get('raw_input_stream');
if (!is_null_or_empty($input) && is_json($input)) {
$json = json_decode($this->security->xss_clean($input), true);
if (!empty($json)) {
if (!is_null($index)) {
return isset($json[$index]) ? $json[$index] : null;
}
return $json;
}
}
return null;
}
/**
* @param $field
*/
private function _add_validation_error($field)
{
$this->_errors[] = sprintf($this->_error_message, $field);
}
/**
* @return array
*/
public function errors()
{
return $this->_errors;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment