Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement field limiting and make class better extendable #5

Merged
merged 2 commits into from
Jun 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/test.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public function validate($intent = null)
}
}
session_start();
$db = new \atk4\data\Persistence_SQL('mysql:dbname=atk4;host=localhost', 'root', 'root');
$db = new \atk4\data\Persistence_SQL('mysql:dbname=atk4;host=localhost', 'root', '');

$api->get('/ping/', function () {
return 'Hello, World';
Expand Down
194 changes: 147 additions & 47 deletions src/Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,35 +117,124 @@ public function match($pattern)
* @param callable $callable
* @param array $vars
*/
public function call($callable, $vars = [])
public function exec($callable, $vars = [])
{
// try to call callable function
try {
$ret = call_user_func_array($callable, $vars);
} catch (\Exception $e) {
$this->caughtException($e);
}
$ret = $this->call($callable, $vars);

// if callable function returns agile data model, then export it
// this is important for REST API implementation
if ($ret instanceof \atk4\data\Model) {
if ($ret->only_fields) {
$ret = $ret->export($ret->only_fields); // use only_fields to not add system fields by default
} else {
$ret = $ret->export(); // all fields including allsystem fields
}
$ret = $this->exportModel($ret);
}

// no response, just step out
if ($ret === null) {
return;
}

// emit successful response
$this->successResponse($ret);
}

/**
* Call callable and return response.
*
* @param callable $callable
* @param array $vars
*
* @return mixed
*/
protected function call($callable, $vars = [])
{
// try to call callable function
try {
$ret = call_user_func_array($callable, $vars);
} catch (\Exception $e) {
$this->caughtException($e);
}

return $ret;
}

/**
* Exports data model.
*
* Extend this method to implement your own field restrictions.
*
* @param \atk4\data\Model $m
*
* @return array
*/
protected function exportModel(\atk4\data\Model $m)
{
return $m->export($this->getAllowedFields($m, 'read'));
}

/**
* Returns list of model field names which allow particular action - read or modify.
* Also takes model->only_fields into account if that's defined.
*
* It uses custom model property apiFields[$action] which should contain array of allowed field names.
*
* @param \atk4\data\Model $m
* @param string $action read|modify
*
* @return null|array of field names
*/
protected function getAllowedFields(\atk4\data\Model $m, $action = 'read')
{
$fields = null;

// take model only_fields into account
if ($m->only_fields) {
$fields = $m->only_fields;
}

// limit by apiFields
if (isset($m->apiFields[$action])) {
$allowed = $m->apiFields[$action];
$fields = $fields ? array_intersect($fields, $allowed) : $allowed;
}

return $fields;
}

/**
* Filters data array by only allowed fields.
*
* Extend this method to implement your own field restrictions.
*
* @param \atk4\data\Model $m
* @param array $data
*
* @return array
*/
/* not used and maybe will not be needed too
protected function filterData(\atk4\data\Model $m, array $data)
{
$allowed = $this->getAllowedFields($m, 'modify');

if ($allowed) {
$data = array_intersect_key($data, array_flip($allowed));
}

return $data;
}
*/

/**
* Emit successful response.
*
* @param mixed $response
*/
protected function successResponse($response)
{
// create response object
if (!$this->response) {
$this->response =
new \Zend\Diactoros\Response\JsonResponse(
$ret,
$response,
200,
[],
JSON_PRETTY_PRINT | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT
Expand All @@ -159,7 +248,7 @@ public function call($callable, $vars = [])
exit;
}

// @todo Should we also stop script execution if no response is received or just ignore that?
// @todo Should we also stop script execution if no emitter is defined or just ignore that?
//exit;
}

Expand All @@ -174,7 +263,7 @@ public function call($callable, $vars = [])
public function get($pattern, $callable = null)
{
if ($this->request->getMethod() === 'GET' && $this->match($pattern)) {
return $this->call($callable, $this->_vars);
return $this->exec($callable, $this->_vars);
}
}

Expand All @@ -189,7 +278,7 @@ public function get($pattern, $callable = null)
public function post($pattern, $callable = null)
{
if ($this->request->getMethod() === 'POST' && $this->match($pattern)) {
return $this->call($callable, $this->_vars);
return $this->exec($callable, $this->_vars);
}
}

Expand All @@ -204,7 +293,7 @@ public function post($pattern, $callable = null)
public function patch($pattern, $callable = null)
{
if ($this->request->getMethod() === 'PATCH' && $this->match($pattern)) {
return $this->call($callable, $this->_vars);
return $this->exec($callable, $this->_vars);
}
}

Expand All @@ -219,7 +308,7 @@ public function patch($pattern, $callable = null)
public function delete($pattern, $callable = null)
{
if ($this->request->getMethod() === 'DELETE' && $this->match($pattern)) {
return $this->call($callable, $this->_vars);
return $this->exec($callable, $this->_vars);
}
}

Expand All @@ -234,74 +323,85 @@ public function delete($pattern, $callable = null)
public function rest($pattern, $model = null)
{
// GET all records
$this->get($pattern, function () use ($model) {
$f = function () use ($model) {
$args = func_get_args();

if (is_callable($model)) {
$model = call_user_func_array($model, $args);
$model = $this->call($model, $args);
}

return $model;
});
};
$this->get($pattern, $f);

// GET :id - one record
$this->get($pattern.'/:id', function () use ($model) {
$f = function () use ($model) {
$args = func_get_args();
$id = array_pop($args); // pop last element of args array, it's :id

if (is_callable($model)) {
$model = call_user_func_array($model, $args);
$model = $this->call($model, $args);
}

// limit fields
$model->onlyFields($this->getAllowedFields($model, 'read'));

return $model->load($id)->get();
});
};
$this->get($pattern.'/:id', $f);

// POST :id - update one record
// PATCH :id - update one record (same as POST :id)
$this->patch($pattern.'/:id', function () use ($model) {
$f = function () use ($model) {
$args = func_get_args();
$id = array_pop($args); // pop last element of args array, it's :id

if (is_callable($model)) {
$model = call_user_func_array($model, $args);
$model = $this->call($model, $args);
}

return $model->load($id)->save($this->requestData)->get();
});
// limit fields
$model->onlyFields($this->getAllowedFields($model, 'modify'));
$model->load($id)->save($this->requestData);
$model->onlyFields($this->getAllowedFields($model, 'read'));

// POST :id - update one record
$this->post($pattern.'/:id', function () use ($model) {
return $model->get();
};
$this->patch($pattern.'/:id', $f);
$this->post($pattern.'/:id', $f);

// POST - insert new record
$f = function () use ($model) {
$args = func_get_args();
$id = array_pop($args); // pop last element of args array, it's :id

if (is_callable($model)) {
$model = call_user_func_array($model, $args);
$model = $this->call($model, $args);
}

return $model->load($id)->save($this->requestData)->get();
});
// limit fields
$model->onlyFields($this->getAllowedFields($model, 'modify'));
$model->unload()->save($this->requestData);
$model->onlyFields($this->getAllowedFields($model, 'read'));

return $model->get();
};
$this->post($pattern, $f);

// DELETE :id - delete one record
$this->delete($pattern.'/:id', function () use ($model) {
$f = function () use ($model) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unused $f ?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh its used below, n/p.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah it's to avoid code duplication for post/patch methods and for consistency i set $f for other methods too.

$args = func_get_args();
$id = array_pop($args); // pop last element of args array, it's :id

if (is_callable($model)) {
$model = call_user_func_array($model, $args);
$model = $this->call($model, $args);
}

return !$model->load($id)->delete()->loaded();
});

// POST - insert new record
$this->post($pattern, function () use ($model) {
$args = func_get_args();

if (is_callable($model)) {
$model = call_user_func_array($model, $args);
}
// limit fields (not necessary, but will limit field list for performance)
$model->onlyFields($this->getAllowedFields($model, 'read'));

return $model->unload()->save($this->requestData)->get();
});
return !$model->delete($id)->loaded();
};
$this->delete($pattern.'/:id', $f);
}

/**
Expand Down