prod-releaser.php/build/api/core/Documentation.php

125 lines
2.9 KiB
PHP
Raw Normal View History

<?php
namespace api\core;
use \error\core\Error;
use \error\core\Err;
use \api\core\Request;
use \api\core\Config;
class Documentation{
/* (1) Attributes
---------------------------------------------------------*/
/* (1) Static */
/* (2) Instance */
/* (2) Builds the documentation
*
---------------------------------------------------------*/
public static function generate(Request $rq=null){
/* (1) Get data from config
---------------------------------------------------------*/
/* (1) If no index for this path -> exit */
if( !isset(Config::get()->index[$rq->get('id')['path']]) )
return new Response(new Error(Err::WrongPathModule));
/* (2) Instance store: configuration for this path */
$cfg = Config::get()->index[$rq->get('id')['path']];
/* (2) For each method
---------------------------------------------------------*/
foreach($cfg as $method=>$spec){
/* (1) Build uri with args */
$cfg[$method]['uri_scheme'] = self::uri_with_parameters($rq->get('id')['path'], $spec);
}
$response = new Response();
// $response->append('uri', $built_uri);
$response->append('methods', $cfg);
return $response;
}
/* (3) Builds uri with GET parameter inside
*
* @uri<String> Base URI
*
---------------------------------------------------------*/
private static function uri_with_parameters($uri=null, $spec=null){
/* (1) If no param return nothing */
if( !isset($spec['par']) || !is_array($spec['par']) || count($spec['par']) <= 0 )
return;
/* (2) If uri is only '/', reset to nothing */
if( $uri == '/' )
$uri = '';
/* (1) Manage GET parameters
---------------------------------------------------------*/
/* (1) Get highest 'URL' parameter available in the spec */
$highest = 0;
foreach($spec['par'] as $pname=>$pspec){
$is_url = strlen($pname) > 3 && substr($pname, 0, 3) == 'URL' && is_numeric(substr($pname, 3));
if( $is_url && intval(substr($pname, 3)) > $highest )
$highest = intval(substr($pname, 3));
}
/* (2) Add each GET parameter (even if not in spec) */
for( $i = 0 ; $i <= $highest ; $i++ ){
/* (2.1) If not in the spec -> set default to empty */
if( !isset($spec['par']["URL$i"]) ){
$uri .= '/';
continue;
}
$pspec = $spec['par']["URL$i"];
/* (2.2) Define the 'optional' property */
$optional = ( isset($pspec['opt']) && $pspec['opt'] === true ) ? '?' : '';
/* (2.3) Define the 'default' property */
$optional .= ( $optional == '?' && isset($pspec['def']) ) ? json_encode($pspec['def']) : 'null';
/* (2.4) If 'rename' set the rename content */
if( isset($pspec['ren']) && is_string($pspec['ren']) ){
$uri .= '/@'.$pspec['ren']."$optional";
continue;
}
/* (2.5) If no rename set the default name */
$uri .= "/@url$i$optional";
}
return $uri;
}
}