Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.89 KB | None | 0 0
  1. //GenericApi.php
  2. <?php
  3.  
  4. class GenericApi {
  5.    
  6.     private $class;
  7.     private $validApiColumns;
  8.     private $booleanColumns;
  9.    
  10.     public function __construct() {
  11.        
  12.         $auth = $GLOBALS['authentication'];
  13.        
  14.         if(!$auth->loggedIn()){
  15.             header('HTTP/1.1 401 Api requires login');
  16.             die();
  17.         }
  18.        
  19.         $class = ucfirst(strtolower(fGrammar::singularize($_GET['class'])));
  20.         $this->class = $class;
  21.        
  22.         if(!DriveApi::hasApi($class)){
  23.             throw new fProgrammerException('the class %s has not been configured for DriveApi', $class);
  24.         }
  25.        
  26.         $this->validApiColumns = $class::getApiSetting('validApiColumns');
  27.         $this->booleanColumns = $class::getApiSetting('booleanColumns');   
  28.     }
  29.    
  30.     public function notFound(){
  31.         PageData::generate404();
  32.     }
  33.    
  34.     public function getObject(){
  35.         $id = $_GET['id'];
  36.        
  37.         try{
  38.             $obj = new $this->class($id);
  39.             $output = $this->getObjectApiData($obj);
  40.             fJSON::sendHeader();
  41.             echo fJSON::encode($output);
  42.         }
  43.         catch(fExpectedException $e){
  44.             header('HTTP/1.1 404 Not Found');
  45.             echo 'The ' . $this->class . ' requested could not be found';
  46.         }
  47.     }
  48.    
  49.     public function listObjects(){
  50.         try{
  51.             $objects = fRecordSet::build($this->class);
  52.             // TODO sort hook params
  53.             $objects = $objects->sort('getLevel', 'asc');
  54.             $output = array();
  55.            
  56.             foreach($objects as $obj){
  57.                 $output[] = $this->getObjectApiData($obj);
  58.             }
  59.             fJSON::sendHeader();
  60.             echo fJSON::encode($output);
  61.         }
  62.         catch(Exception $e){
  63.             expose($e);
  64.         }
  65.    
  66.     }
  67.     private function getObjectApiData($obj){
  68.        
  69.         $values = $obj->getValuesAsArray();
  70.  
  71.         // filter validvalues
  72.         $validApiColumns = array_flip($this->validApiColumns);
  73.         $apiData = array_intersect_key($values, $validApiColumns);
  74.        
  75.         // TODO add hook
  76.         $apiData['level'] = $obj->getLevel();
  77.        
  78.         if($this->booleanColumns != null){
  79.             foreach($this->booleanColumns as $column){
  80.                 //echo $column . ' : ' . $apiData[$column] . PHP_EOL;
  81.                 $apiData[$column] = (bool)($apiData[$column] == 'true');
  82.             }
  83.         }
  84.            
  85.        
  86.         // TODO: create api data value post hook for stuff like url_rewrite_override ?
  87.         if($obj->getUrlRewrite() == 'home'){
  88.             $apiData['url_rewrite_override'] = '/';
  89.         }
  90.        
  91.         return $apiData;
  92.     }
  93.     public function create(){
  94.        
  95.         $put = file_get_contents('php://input');  
  96.        
  97.         $data = (array)json_decode($put);  
  98.        
  99.         try {
  100.             $page = $this->createFromArray($data); 
  101.  
  102.             $page->validate(TRUE);
  103.             $page->store();
  104.             $output = $this->getObjectApiData($page);
  105.  
  106.             header('HTTP/1.1 201 ' . $this->class . ' Created');
  107.             fJSON::sendHeader();
  108.             // all values are new don't check for changed
  109.             echo fJSON::encode($output);
  110.         }
  111.         catch (fValidationException $e) {
  112.             header('HTTP/1.1 400 Validation Error');   
  113.             echo $e->getMessage();
  114.  
  115.         }
  116.     }
  117.     private function createFromArray(Array $data){
  118.         $page = new Page();
  119.         self::populateFromArray($data);
  120.         $page->validate(TRUE);
  121.         $page->store();
  122.         return $page;
  123.     }
  124.    
  125.     private function updateFromArray(Array $data){
  126.        
  127.         $page = new Page($data['id']); 
  128.         self::populateFromArray($data);
  129.         $page->validate(TRUE);
  130.         $changedValues = $page->getChanged();
  131.         $page->store();
  132.         $newValues = $page->getValuesAsArray();
  133.         $changedValues = $page->getChanged();
  134.         return $changedValues; 
  135.     }
  136.    
  137.     private static function populateFromArray(Array $data){
  138.         $schema = fORMSchema::retrieve($this->class);
  139.         $table  = fORM::tablize($this->class);
  140.  
  141.         $column_info = $schema->getColumnInfo($table);
  142.         foreach ($column_info as $column => $info) {
  143.             if(array_key_exists($column, $data)){
  144.                 $method = 'set' . fGrammar::camelize($column, TRUE);
  145.                 $page->$method($data[$column]);
  146.             }
  147.         }
  148.     }
  149.    
  150.    
  151.     public function batchUpdate(){
  152.         try {
  153.            
  154.             $put = file_get_contents('php://input');  
  155.             $data = (array)json_decode($put);
  156.            
  157.             $changed = array();
  158.             foreach($data as $page){
  159.                 $changedPageValues = $this->updateFromArray((array)$page);
  160.                 // add id that will not be present because it was not changed
  161.                 $changedPageValues['id'] = $page->id;
  162.                 $changed[] = $changedPageValues;
  163.             }
  164.            
  165.             header('HTTP/1.1 200 ' . fGrammar::pluralize('zxc') . ' Updated');
  166.             fJSON::sendHeader();
  167.             echo fJSON::encode($changed);
  168.         }
  169.         catch (fValidationException $e) {
  170.             header('HTTP/1.1 400 Validation Error');   
  171.             echo $e->getMessage();
  172.         }
  173.  
  174.     }
  175.    
  176.     public function update(){
  177.        
  178.         try {
  179.             $put = file_get_contents('php://input');  
  180.        
  181.             $data = (array)json_decode($put);
  182.             $output = $this->updateFromArray((array)$data);
  183.            
  184.             header('HTTP/1.1 200 ' . $this->class . ' Updated');
  185.             fJSON::sendHeader();
  186.             echo fJSON::encode($output);
  187.         }
  188.         catch (fValidationException $e) {
  189.             header('HTTP/1.1 400 Validation Error');   
  190.             echo $e->getMessage();
  191.         }
  192.  
  193.     }
  194.    
  195.     public function delete(){
  196.    
  197.         try {
  198.             $id = fRequest::get('id', 'int');
  199.            
  200.             $item = new $this->class($id);
  201.             $item->validate(true);
  202.             $item->delete();
  203.            
  204.             header('HTTP/1.1 200 ' . $this->class . ' Deleted');
  205.             echo  $this->class . ' was deleted';
  206.         }
  207.         catch (fValidationException $e) {
  208.             header('HTTP/1.1 400 Validation Error');   
  209.             echo $e->getMessage();
  210.         }
  211.  
  212.     }
  213. }
  214.  
  215.  
  216. // DriveApi.php (drive is application name not sure what to call this)
  217. <?php
  218.  
  219. class DriveApi {
  220.    
  221.     static private $module_classes = array();
  222.    
  223.     static public function configure($class,Array $validApiColumns,Array $booleanColumns = null){
  224.         $class = fORM::getClass($class);
  225.        
  226.         self::$module_classes[$class] = array();
  227.         self::$module_classes[$class]['validApiColumns'] = $validApiColumns;
  228.         self::$module_classes[$class]['booleanColumns'] = $booleanColumns;
  229.        
  230.        
  231.         fORM::registerActiveRecordStaticMethod($class, 'getApiSetting', 'DriveApi::getApiSetting');
  232.        
  233.         // list all
  234.         Anchor::add('get json /api/v1/:class', 'GenericApi::listObjects');
  235.  
  236.         // get obj with id
  237.         Anchor::add('get json /api/v1/:class/:id', 'GenericApi::getObject');
  238.  
  239.         // create new obj
  240.         Anchor::add('post json /api/v1/:class', 'GenericApi::create');
  241.  
  242.         // update obj
  243.         Anchor::add('put json /api/v1/:class/:id', 'GenericApi::update');
  244.         // batch update objects
  245.         Anchor::add('put json /api/v1/:class/batch/update', 'GenericApi::batchUpdate');
  246.  
  247.         // delete obj
  248.         Anchor::add('delete json /api/v1/:class/:id', 'GenericApi::delete');
  249.     }
  250.    
  251.     static public function getApiSetting($class, $method_name, $parameters){
  252.         $class = fORM::getClass($class);
  253.         if(isset(self::$module_classes[$class])){
  254.             return self::$module_classes[$class][$parameters[0]];
  255.         }
  256.     }
  257.    
  258.     static public function hasApi($class){
  259.         return isset(self::$module_classes[$class]);
  260.     }
  261.    
  262. }
  263.  
  264. // example useage
  265. class Foo extends fActiveRecord
  266. {
  267.    
  268.     protected function configure(){
  269.  
  270.         DriveApi::configure(
  271.             $this,
  272.             array(
  273.                 'id',
  274.                 'parent_id',
  275.                 'name',
  276.                 'url_rewrite',
  277.                 'order',
  278.                 'locked',
  279.                 'target',
  280.                 'status',
  281.                 'external_url',
  282.                 'primary_nav_visible'
  283.             ),
  284.             array('locked', 'primary_nav_visible')
  285.         );
  286. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement