<?php
/**
* Try it out
*/
$user = (new Api)->user(1);
echo "Got user ".$user->id;
function phpdoc_params(ReflectionMethod $method) : array
{
// Retrieve the full PhpDoc comment block
$doc = $method->getDocComment();
// Trim each line from space and star chars
$lines = array_map(function($line){
return trim($line, " *");
}, explode("\n", $doc));
// Retain lines that start with an @
$lines = array_filter($lines, function($line){
return strpos($line, "@") === 0;
});
$args = [];
// Push each value in the corresponding @param array
foreach($lines as $line){
list($param, $value) = explode(' ', $line, 2);
$args[$param][] = $value;
}
return $args;
}
class Api {
/**
* @param int $id
* @return User
* @throws ReflectionException
* @endpoint users
*/
public function user(int $id) : User {
return $this->request($this->endpoint(__METHOD__), $id);
}
/**
* @param string $method
* @return string
* @throws ReflectionException
*/
protected function endpoint(string $method) : string {
$reflection = new \ReflectionMethod($method);
$params = phpdoc_params($reflection);
return $params['@endpoint'][0] ?? null;
}
/**
* @param string $endpoint
* @param $param
* @return User
*/
protected function request(string $endpoint, $param)
{
switch($endpoint){
case 'users':
return new User($param);
default:
throw new InvalidArgumentException("Invalid endpoint");
}
}
}
/**
* Class User
*/
class User {
public $id;
public function __construct($id)
{
$this->id = $id;
}
}