Files
money/app/common/Controller/Currencies.php
2021-03-15 17:42:56 -03:00

81 lines
2.7 KiB
PHP

<?php
namespace ProVM\Money\Common\Controller;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use ProVM\Common\Factory\Model as ModelFactory;
use ProVM\Common\Define\Controller\Json;
use ProVM\Money\Currency;
class Currencies {
use Json;
public function __invoke(Request $request, Response $response, ModelFactory $factory): Response {
$currencies = $factory->find(Currency::class)->order('name')->array();
$output = compact('currencies');
return $this->withJson($response, $output);
}
public function show(Request $request, Response $response, ModelFactory $factory, $currency_id): Response {
$currency = $factory->find(Currency::class)->one($currency_id);
$output = [
'currency' => $currency->asArray()
];
return $this->withJson($response, $output);
}
public function add(Request $request, Response $response, ModelFactory $factory): Response {
$fields = [
'code',
'name'
];
$post = json_decode($request->getBody()->getContents());
$data = array_intersect_key((array) $post, array_combine($fields, $fields));
$currency = $factory->find(Currency::class)->where([['code', $data['code']]])->one();
if (!$currency) {
$currency = $factory->create(Currency::class, $data);
$currency->save();
}
$output = [
'post_data' => $post,
'input' => $data,
'currency' => $currency->asArray()
];
return $this->withJson($response, $output);
}
public function edit(Request $request, Response $response, ModelFactory $factory, $currency_id): Response {
$currency = $factory->find(Currency::class)->one($currency_id);
$fields = [
'code',
'name'
];
$post = json_decode($request->getBody()->getContents());
$data = array_intersect_key((array) $post, array_combine($fields, $fields));
$edited = false;
foreach ($data as $field => $value) {
if ($currency->{$field} != $value) {
$currency->{$field} = $value;
$edited = true;
}
}
if ($edited) {
$currency->save();
}
$output = [
'get_data' => compact('currency_id'),
'post_data' => $post,
'input' => $data,
'currency' => $currency->asArray()
];
return $this->withJson($response, $output);
}
public function delete(Request $request, Response $response, ModelFactory $factory, $currency_id): Response {
$currency = $factory->find(Currency::class)->one($currency_id);
$output = [
'get_data' => compact('currency_id'),
'currency' => $currency->asArray()
];
$status = $currency->delete();
$output['deleted'] = $status;
return $this->withJson($response, $output);
}
}