Files
crypto/backend/api/common/Controller/Wallets.php
2021-06-28 23:15:13 -04:00

72 lines
2.6 KiB
PHP

<?php
namespace ProVM\Crypto\Common\Controller;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use ProVM\Common\Define\Controller\JSON;
use ProVM\Common\Factory\Model as ModelFactory;
use ProVM\Crypto\Wallet;
class Wallets {
use JSON;
public function __invoke(Request $request, Response $response, ModelFactory $factory): Response {
$wallets = $factory->find(Wallet::class)->array();
$output = compact('wallets');
return $this->withJson($response, $output);
}
public function show(Request $request, Response $response, ModelFactory $factory, $wallet_id): Response {
$wallet = $factory->find(Wallet::class)->one($wallet_id);
if (!$wallet) {
return $this->withJson($response, ['wallet' => null]);
}
$output = ['wallet' => $wallet->asArray()];
return $this->withJson($response, $output);
}
public function add(Request $request, Response $response, ModelFactory $factory): Response {
$post = json_decode($request->getBody()->getContents());
$fields = [
'name' => 'name',
'location' => 'location_id',
'address' => 'public_address'
];
$data = array_combine($fields, array_merge(array_intersect_key((array) $post, $fields), array_fill_keys(array_keys(array_diff_key($fields, (array) $post)), null)));
$wallet = $factory->find(Wallet::class)->where([
['name', $data['name']]
])->one();
$status = true;
if (!$wallet) {
$wallet = $factory->create(Wallet::class, $data);
$status = $wallet->save();
}
$output = [
'information_provided' => $post,
'used_data' => $data,
'wallet' => $wallet->asArray(),
'saved' => $status
];
return $this->withJson($response, $output);
}
public function edit(Request $request, Response $response, ModelFactory $factory, $wallet_id): Response {
$wallet = $factory->find(Wallet::class)->one($wallet_id);
if (!$wallet) {
return $this->withJson($response, ['wallet' => null]);
}
$post = json_decode($request->getBody()->getContents());
$output = compact('wallet');
return $this->withJson($response, $output);
}
public function delete(Request $request, Response $response, ModelFactory $factory, $wallet_id): Response {
$wallet = $factory->find(Wallet::class)->one($wallet_id);
if (!$wallet) {
return $this->withJson($response, ['wallet' => null, 'deleted' => false]);
}
$output = [
'wallet' => $wallet->asArray()
];
$status = $wallet->delete();
$output['deleted'] = $status;
return $this->withJson($response, $output);
}
}