Files
crypto/backend/api/common/Controller/Locations.php

71 lines
2.6 KiB
PHP
Raw Normal View History

2021-06-28 23:15:13 -04:00
<?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\Location;
class Locations {
use JSON;
public function __invoke(Request $request, Response $response, ModelFactory $factory): Response {
$locations = $factory->find(Location::class)->array();
$output = compact('locations');
return $this->withJson($response, $output);
}
public function show(Request $request, Response $response, ModelFactory $factory, $location_id): Response {
$location = $factory->find(Location::class)->one($location_id);
if (!$location) {
return $this->withJson($response, ['location' => null]);
}
$output = ['location' => $location->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',
'description' => 'description'
];
$data = array_combine($fields, array_merge(array_intersect_key((array) $post, $fields), array_fill_keys(array_keys(array_diff_key($fields, (array) $post)), null)));
$location = $factory->find(Location::class)->where([
['name', $data['name']]
])->one();
$status = true;
if (!$location) {
$location = $factory->create(Location::class, $data);
$status = $location->save();
}
$output = [
'information_provided' => $post,
'used_data' => $data,
'location' => $location->asArray(),
'saved' => $status
];
return $this->withJson($response, $output);
}
public function edit(Request $request, Response $response, ModelFactory $factory, $location_id): Response {
$location = $factory->find(Location::class)->one($location_id);
if (!$location) {
return $this->withJson($response, ['location' => null]);
}
$post = json_decode($request->getBody()->getContents());
$output = compact('location');
return $this->withJson($response, $output);
}
public function delete(Request $request, Response $response, ModelFactory $factory, $location_id): Response {
$location = $factory->find(Location::class)->one($location_id);
if (!$location) {
return $this->withJson($response, ['location' => null, 'deleted' => false]);
}
$output = [
'location' => $location->asArray()
];
$status = $location->delete();
$output['deleted'] = $status;
return $this->withJson($response, $output);
}
}