Created
September 17, 2013 11:53
-
-
Save amezghal/6593327 to your computer and use it in GitHub Desktop.
ajax base
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by JetBrains PhpStorm. | |
* User: amezghal abdelilah | |
* Date: 17/09/13 | |
* Time: 11:08 | |
*/ | |
class AjaxBase { | |
public function executeAction($actionName, $arguments = []){ | |
try{ | |
$method = new ReflectionMethod($this, $actionName); | |
if(!$method->isFinal()){ | |
throw new Exception("method is not final"); | |
} | |
}catch(Exception $notFoundMethod){ | |
$errorMessage = "The action << $actionName >> does not exists"; | |
$this->error($errorMessage); | |
} | |
$methodArguments = $method->getParameters(); | |
$requiredArguments = $method->getNumberOfRequiredParameters(); | |
if(count($arguments) >= $requiredArguments){ | |
$params = array(); | |
if(count($methodArguments) > 0){ | |
foreach($methodArguments as $arg){ | |
if(isset($arguments[$arg->getName()])){ | |
//todo protect value; | |
$params[] = $arguments[$arg->getName()]; | |
}elseif(!isset($arguments[$arg->getName()]) && !$arg->isOptional()){ | |
$this->error("Function call, Missing argument << {$arg->getName()} >>, check the function arguments"); | |
} | |
} | |
//before invoking the method we have to order the arguments | |
$this->output($method, $params); | |
}else{ | |
$this->output($method); | |
} | |
}else{ | |
$this->error("The number of arguments needed to call this function is incorrect. check the function arguments"); | |
} | |
} | |
protected function output(ReflectionMethod $method, $params = []){ | |
$response = $method->invokeArgs($this, $params); | |
//output json if is php array, otherwise text/html | |
if(is_array($response)){ | |
$this->utfEncode($response); | |
header("Content-type: application/json"); | |
echo json_encode($response); | |
}else{ | |
header("Content-type: text/html"); | |
echo $response; | |
} | |
} | |
protected function error($message){ | |
exit($message); | |
} | |
protected function utfEncode(&$var) { | |
if (is_array($var) || is_object($var)) { | |
foreach ($var as &$token) { | |
$this->utfEncode($token); | |
} | |
} else { | |
if (is_string($var)) { | |
$currentEncoding = mb_detect_encoding($var); | |
if($currentEncoding != 'UTF-8') | |
$var = mb_convert_encoding($var, 'UTF-8', $currentEncoding); | |
} elseif (is_null($var)) { | |
$var = ''; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment