Files
This commit is contained in:
120
common/Alias/Model.php
Normal file
120
common/Alias/Model.php
Normal file
@ -0,0 +1,120 @@
|
||||
<?php
|
||||
namespace Incoviba\API\Common\Alias;
|
||||
|
||||
use http\Exception\InvalidArgumentException;
|
||||
use \Model as BaseModel;
|
||||
use Incoviba\API\Common\Define\Model as ModelInterface;
|
||||
use Incoviba\API\Common\Factory\Model as ModelFactory;
|
||||
|
||||
abstract class Model extends BaseModel implements ModelInterface {
|
||||
const SELF_KEY = 'self_key';
|
||||
const CHILD_KEY = 'child_key';
|
||||
const PARENT_KEY = 'parent_key';
|
||||
const SIBLING_KEY = 'sibling_key';
|
||||
const SELF_THROUGH_KEY = 'self_through_key';
|
||||
const SIBLING_THROUGH_KEY = 'sibling_through_key';
|
||||
|
||||
public function getTable(): string {
|
||||
return static::$_table;
|
||||
}
|
||||
|
||||
protected ModelFactory $factory;
|
||||
public function setFactory(ModelFactory $factory): ModelInterface {
|
||||
$this->factory = $factory;
|
||||
return $this;
|
||||
}
|
||||
|
||||
protected function validateDefinitions(array $definitions, array $minimum_requirements, array $default_values): array {
|
||||
foreach ($default_values as $key => $val) {
|
||||
if (!isset($definitions[$key])) {
|
||||
$definitions[$key] = $val;
|
||||
}
|
||||
}
|
||||
foreach ($minimum_requirements as $key) {
|
||||
if (!isset($definitions[$key])) {
|
||||
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
|
||||
$class = get_called_class();
|
||||
throw new InvalidArgumentException("Missing {$key} in {$trace[1]['function']} called in {$class}.");
|
||||
}
|
||||
}
|
||||
return $definitions;
|
||||
}
|
||||
public function parentOf(string $child_class, array $definitions): ?array {
|
||||
$definitions = $this->validateDefinitions(
|
||||
$definitions,
|
||||
[Model::CHILD_KEY, Model::SELF_KEY],
|
||||
[Model::SELF_KEY => 'id']
|
||||
);
|
||||
$where = [[$definitions[Model::CHILD_KEY], $this->{$definitions[Model::SELF_KEY]}]];
|
||||
return $this->factory->find($child_class)->where($where)->many();
|
||||
}
|
||||
public function childOf(string $parent_class, array $definitions): ?ModelInterface {
|
||||
$definitions = $this->validateDefinitions(
|
||||
$definitions,
|
||||
[Model::PARENT_KEY, Model::SELF_KEY],
|
||||
[Model::PARENT_KEY => 'id']
|
||||
);
|
||||
$where = [[$definitions[Model::PARENT_KEY], $this->{$definitions[Model::SELF_KEY]}]];
|
||||
return $this->factory->find($parent_class)->where($where)->one();
|
||||
}
|
||||
public function siblingOf(string $sibling_class, string $connecting_table, array $definitions): ?array {
|
||||
$definitions = $this->validateDefinitions(
|
||||
$definitions,
|
||||
[Model::SIBLING_KEY, Model::SIBLING_THROUGH_KEY, Model::SELF_THROUGH_KEY, Model::SELF_KEY],
|
||||
[Model::SIBLING_KEY => 'id', Model::SELF_KEY => 'id']
|
||||
);
|
||||
$sibling_table = (new $sibling_class())->getTable();
|
||||
$joins = [
|
||||
[
|
||||
$connecting_table,
|
||||
"{$connecting_table}.{$definitions[Model::SIBLING_THROUGH_KEY]}",
|
||||
"{$sibling_table}.{$definitions[Model::SIBLING_KEY]}"
|
||||
]
|
||||
];
|
||||
$where = [
|
||||
[$definitions[Model::SIBLING_KEY], "{$connecting_table}.{$definitions[Model::SIBLING_THROUGH_KEY]}"],
|
||||
["{$connecting_table}.{$definitions[Model::SELF_THROUGH_KEY]}", $this->{$definitions[Model::SELF_KEY]}]
|
||||
];
|
||||
return $this->factory
|
||||
->find($sibling_class)
|
||||
->join($joins)
|
||||
->select("{$sibling_table}.*")
|
||||
->where($where)
|
||||
->many();
|
||||
}
|
||||
|
||||
public function toArray(): array {
|
||||
return $this->as_array();
|
||||
}
|
||||
|
||||
protected static function parseInput($input): array {
|
||||
return array_intersect_key((array) $input, array_combine(static::$fields, static::$fields));
|
||||
}
|
||||
public static function add(ModelFactory $factory, $input): ?ModelInterface {
|
||||
$data = static::parseInput($input);
|
||||
$class = get_called_class();
|
||||
if (method_exists($class, 'find')) {
|
||||
$obj = static::find($factory, $input);
|
||||
} else {
|
||||
$where = $data;
|
||||
array_walk($where, function(&$item, $key) {
|
||||
$item = [$key, $item];
|
||||
});
|
||||
$where = array_values($where);
|
||||
$obj = $factory->find($class)->where($where)->one();
|
||||
}
|
||||
if ($obj === null) {
|
||||
$obj = $factory->create($class, $data);
|
||||
}
|
||||
return $obj;
|
||||
}
|
||||
public function edit($input): ?array {
|
||||
$data = static::parseInput($input);
|
||||
foreach (static::$fields as $field) {
|
||||
if ($this->{$field} != $data[$field]) {
|
||||
$this->{$field} = $data[$field];
|
||||
}
|
||||
}
|
||||
return $this->save();
|
||||
}
|
||||
}
|
80
common/Controller/Bancos.php
Normal file
80
common/Controller/Bancos.php
Normal file
@ -0,0 +1,80 @@
|
||||
<?php
|
||||
namespace Incoviba\API\Common\Controller;
|
||||
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Incoviba\API\Common\Factory\Model as Factory;
|
||||
use Incoviba\API\Common\Define\Controller\Json;
|
||||
use Incoviba\Common\Banco;
|
||||
|
||||
class Bancos {
|
||||
use Json;
|
||||
|
||||
public function __invoke(Request $request, Response $response, Factory $factory): Response {
|
||||
$bancos = $factory->find(Banco::class)->array();
|
||||
$url = '' . $request->getUri();
|
||||
array_walk($bancos, function (&$item) use ($url) {
|
||||
$item['link'] = [
|
||||
'rel' => 'banco',
|
||||
'title' => $item['nombre'],
|
||||
'href' => str_replace('/bancos', "/banco/{$item['id']}", $url)
|
||||
];
|
||||
});
|
||||
return $this->withJson($response, compact('bancos'));
|
||||
}
|
||||
public function show(Request $request, Response $response, Factory $factory, $banco_id): Response {
|
||||
$banco = $factory->find(Banco::class)->one($banco_id);
|
||||
$output = [
|
||||
'input' => $banco_id,
|
||||
'banco' => $banco->toArray(),
|
||||
'link' => [
|
||||
'rel' => 'bancos',
|
||||
'title' => 'Bancos',
|
||||
'href' => str_replace("/banco/{$banco_id}", '/bancos', $request->getUri())
|
||||
]
|
||||
];
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function add(Request $request, Response $response, Factory $factory): Response {
|
||||
$post = $request->getParsedBody();
|
||||
$output = [
|
||||
'input' => $post
|
||||
];
|
||||
if (in_array('bancos', $post)) {
|
||||
$output['bancos'] = [];
|
||||
foreach ($post['bancos'] as $input) {
|
||||
$banco = Banco::add($factory, $input);
|
||||
$banco []= [
|
||||
'banco' => $banco->toArray(),
|
||||
'created' => $banco->is_new() ? $banco->save() : false
|
||||
];
|
||||
}
|
||||
} elseif (in_array('banco', $post)) {
|
||||
$banco = Banco::add($factory, $post);
|
||||
$output['banco'] = $banco;
|
||||
$output['created'] = $banco->is_new() ? $banco->save() : false;
|
||||
}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function edit(Request $request, Response $response, Factory $factory, $banco_id): Response {
|
||||
$post = $request->getParsedBody();
|
||||
$input = compact('banco_id', 'post');
|
||||
$banco = $factory->find(Banco::class)->one($banco_id);
|
||||
$output = [
|
||||
'input' => $input,
|
||||
'banco' => $banco->toArray()
|
||||
];
|
||||
$output['edited'] = $banco->edit($post);
|
||||
$output['changes'] = $banco->toArray();
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function delete(Request $request, Response $response, Factory $factory, $banco_id): Response {
|
||||
$banco = $factory->find(Banco::class)->one($banco_id);
|
||||
$output = [
|
||||
'input' => $banco_id,
|
||||
'banco' => $banco->toArray()
|
||||
];
|
||||
$output['deleted'] = $banco->delete();
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
}
|
22
common/Controller/Base.php
Normal file
22
common/Controller/Base.php
Normal file
@ -0,0 +1,22 @@
|
||||
<?php
|
||||
namespace Incoviba\API\Common\Controller;
|
||||
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Incoviba\API\Common\Define\Controller\Json;
|
||||
|
||||
class Base {
|
||||
use Json;
|
||||
|
||||
public function __invoke(Request $request, Response $response): Response {
|
||||
return $this->withJson($response, [
|
||||
'api' => [
|
||||
'version' => '1.0.0'
|
||||
]
|
||||
]);
|
||||
}
|
||||
public function info(Request $request, Response $response): Response {
|
||||
phpinfo();
|
||||
return $response;
|
||||
}
|
||||
}
|
166
common/Controller/Inmobiliarias.php
Normal file
166
common/Controller/Inmobiliarias.php
Normal file
@ -0,0 +1,166 @@
|
||||
<?php
|
||||
namespace Incoviba\API\Common\Controller;
|
||||
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Incoviba\API\Common\Define\Controller\Json;
|
||||
use Incoviba\API\Common\Factory\Model as Factory;
|
||||
use Incoviba\Inmobiliaria\Inmobiliaria;
|
||||
|
||||
class Inmobiliarias {
|
||||
use Json;
|
||||
|
||||
public function __invoke(Request $request, Response $response, Factory $factory): Response {
|
||||
$inmobiliarias = $factory->find(Inmobiliaria::class)->array();
|
||||
$base_url = str_replace('/inmobiliarias', '{URL}', $request->getUri());
|
||||
array_walk($inmobiliarias, function (&$item) use ($base_url) {
|
||||
$link = [
|
||||
'rel' => 'inmobiliaria',
|
||||
'title' => $item['abreviacion'],
|
||||
'href' => str_replace('{URL}',"/inmobiliaria/{$item['rut']}", $base_url)
|
||||
];
|
||||
$item['link'] = $link;
|
||||
});
|
||||
return $this->withJson($response, compact('inmobiliarias'));
|
||||
}
|
||||
protected function getInmobiliaria(Factory $factory, $inmobiliaria_rut): bool|Inmobiliaria {
|
||||
return $factory->find(Inmobiliaria::class)->where([['rut', $inmobiliaria_rut]])->one();
|
||||
}
|
||||
public function show(Request $request, Response $response, Factory $factory, $inmobiliaria_rut): Response {
|
||||
$inmobiliaria = $this->getInmobiliaria($factory, $inmobiliaria_rut);
|
||||
$output = [
|
||||
'input' => $inmobiliaria_rut,
|
||||
'inmobiliaria' => $inmobiliaria->toArray(),
|
||||
'link' => [
|
||||
'rel' => 'inmobiliarias',
|
||||
'title' => 'Inmobiliarias',
|
||||
'href' => str_replace("/inmobiliaria/{$inmobiliaria_rut}", '/inmobiliarias', $request->getUri())
|
||||
]
|
||||
];
|
||||
$base_url = str_replace("/inmobiliaria/{$inmobiliaria_rut}", "/inmobiliaria/{$inmobiliaria_rut}{URL}", $request->getUri());
|
||||
$output['inmobiliaria']['links'] = [
|
||||
[
|
||||
'rel' => 'banco',
|
||||
'title' => $inmobiliaria->banco()->nombre,
|
||||
'href' => str_replace("/inmobiliaria/{$inmobiliaria_rut}", "/banco/{$inmobiliaria->banco}", $request->getUri())
|
||||
],
|
||||
[
|
||||
'rel' => 'sociedad',
|
||||
'title' => $inmobiliaria->sociedad()->descripcion,
|
||||
'href' => str_replace("/inmobiliaria/{$inmobiliaria_rut}", "/sociedad/{$inmobiliaria->sociedad}", $request->getUri())
|
||||
],
|
||||
[
|
||||
'rel' => 'proyectos',
|
||||
'title' => 'Proyectos',
|
||||
'href' => str_replace('{URL}', '/proyectos', $base_url)
|
||||
]
|
||||
];
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function add(Request $request, Response $response, Factory $factory): Response {
|
||||
$post = $request->getParsedBody();
|
||||
$output = [
|
||||
'input' => $post
|
||||
];
|
||||
if (in_array('inmobiliarias', $post)) {
|
||||
$output['inmobiliarias'] = [];
|
||||
foreach ($post['inmobiliarias'] as $input) {
|
||||
$inmobiliaria = Inmobiliaria::add($factory, $input);
|
||||
$inmobiliarias []= [
|
||||
'inmobiliaria' => $inmobiliaria->toArray(),
|
||||
'created' => $inmobiliaria->is_new() ? $inmobiliaria->save() : false
|
||||
];
|
||||
}
|
||||
} elseif (in_array('inmobiliaria', $post)) {
|
||||
$inmobiliaria = Inmobiliaria::add($factory, $post);
|
||||
$output['inmobiliaria'] = $inmobiliaria;
|
||||
$output['created'] = $inmobiliaria->is_new() ? $inmobiliaria->save() : false;
|
||||
}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function edit(Request $request, Response $response, Factory $factory, $inmobiliaria_rut): Response {
|
||||
$post = $request->getParsedBody();
|
||||
$input = compact('inmobiliaria_rut', 'post');
|
||||
$inmobiliaria = $this->getInmobiliaria($factory, $inmobiliaria_rut);
|
||||
$output = [
|
||||
'input' => $input,
|
||||
'inmobiliaria' => $inmobiliaria->toArray()
|
||||
];
|
||||
$output['edited'] = $inmobiliaria->edit($post);
|
||||
$output['changes'] = $inmobiliaria->toArray();
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function delete(Request $request, Response $response, Factory $factory, $inmobiliaria_rut): Response {
|
||||
$inmobiliaria = $this->getInmobiliaria($factory, $inmobiliaria_rut);
|
||||
$output = [
|
||||
'input' => $inmobiliaria_rut,
|
||||
'inmobiliaria' => $inmobiliaria->toArray()
|
||||
];
|
||||
$output['deleted'] = $inmobiliaria->delete();
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function proyectos(Request $request, Response $response, Factory $factory, $inmobiliaria_rut): Response {
|
||||
$inmobiliaria = $this->getInmobiliaria($factory, $inmobiliaria_rut);
|
||||
$proyectos = $inmobiliaria?->proyectos();
|
||||
$base_url = str_replace("/inmobiliaria/{$inmobiliaria_rut}/proyectos", '{URL}', $request->getUri());
|
||||
$output = [
|
||||
'input' => $inmobiliaria_rut,
|
||||
'inmobiliaria' => $inmobiliaria->toArray(),
|
||||
'proyectos' => ($proyectos) ? array_map(function ($item) use ($base_url) {
|
||||
$arr = $item->toArray();
|
||||
$arr['link'] = [
|
||||
'rel' => 'proyecto',
|
||||
'title' => $item->descripcion,
|
||||
'href' => str_replace('{URL}', "/proyecto/{$item->id}", $base_url)
|
||||
];
|
||||
return $arr;
|
||||
}, $proyectos) : []
|
||||
];
|
||||
$output['inmobiliaria']['link'] = [
|
||||
'rel' => 'inmobiliaria',
|
||||
'title' => $inmobiliaria->abreviacion,
|
||||
'href' => str_replace('{URL}', "/inmobiliaria/{$inmobiliaria_rut}", $base_url)
|
||||
];
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function sociedad(Request $request, Response $response, Factory $factory, $inmobiliaria_rut): Response {
|
||||
$inmobiliaria = $this->getInmobiliaria($factory, $inmobiliaria_rut);
|
||||
$base_url = str_replace("/inmobiliaria/{$inmobiliaria_rut}/sociedad", '{URL}', $request->getUri());
|
||||
$output = [
|
||||
'input' => $inmobiliaria_rut,
|
||||
'inmobiliaria' => $inmobiliaria->toArray(),
|
||||
'sociedad' => $inmobiliaria->sociedad()->toArray()
|
||||
];
|
||||
$output['inmobiliaria']['link'] = [
|
||||
'rel' => 'inmobiliaria',
|
||||
'title' => $inmobiliaria->abreviacion,
|
||||
'href' => str_replace('{URL}', "/inmobiliaria/{$inmobiliaria_rut}", $base_url)
|
||||
];
|
||||
$output['sociedad']['link'] = [
|
||||
'rel' => 'tipo_sociedad',
|
||||
'title' => $inmobiliaria->sociedad()->descripcion,
|
||||
'href' => str_replace('{URL}', "/tipos/sociedad/{$inmobiliaria->sociedad}", $base_url)
|
||||
];
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function banco(Request $request, Response $response, Factory $factory, $inmobiliaria_rut): Response {
|
||||
$inmobiliaria = $this->getInmobiliaria($factory, $inmobiliaria_rut);
|
||||
$base_url = str_replace("/inmobiliaria/{$inmobiliaria_rut}/banco", '{URL}', $request->getUri());
|
||||
$output = [
|
||||
'input' => $inmobiliaria_rut,
|
||||
'inmobiliaria' => $inmobiliaria->toArray(),
|
||||
'banco' => $inmobiliaria->banco()->toArray()
|
||||
];
|
||||
$output['inmobiliaria']['link'] = [
|
||||
'rel' => 'inmobiliaria',
|
||||
'title' => $inmobiliaria->abreviacion,
|
||||
'href' => str_replace('{URL}', "/inmobiliaria/{$inmobiliaria_rut}", $base_url)
|
||||
];
|
||||
$output['banco']['link'] = [
|
||||
'rel' => 'banco',
|
||||
'title' => $inmobiliaria->banco()->nombre,
|
||||
'href' => str_replace('{URL}', "/banco/{$inmobiliaria->banco}", $base_url)
|
||||
];
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
}
|
91
common/Controller/Propietarios.php
Normal file
91
common/Controller/Propietarios.php
Normal file
@ -0,0 +1,91 @@
|
||||
<?php
|
||||
namespace Incoviba\API\Common\Controller;
|
||||
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Incoviba\API\Common\Define\Controller\Json;
|
||||
use Incoviba\API\Common\Factory\Model as Factory;
|
||||
use Incoviba\Venta\Propietario;
|
||||
|
||||
class Propietarios {
|
||||
use Json;
|
||||
|
||||
public function __invoke(Request $request, Response $response, Factory $factory): Response {
|
||||
$propietarios = $factory->find(Propietario::class)->array();
|
||||
$base_url = str_replace('/propietarios', '{URL}', $request->getUri());
|
||||
array_walk($propietarios, function (&$item) use ($base_url) {
|
||||
$link = [
|
||||
'rel' => 'propietario',
|
||||
'title' => implode(' ', [$item['nombres'], $item['apellido_paterno'], $item['apellido_materno']]),
|
||||
'href' => str_replace('{URL}', "/propietario/{$item['rut']}", $base_url)
|
||||
];
|
||||
$item['link'] = $link;
|
||||
});
|
||||
return $this->withJson($response, compact('propietarios'));
|
||||
}
|
||||
protected function get(Factory $factory, string $class, $rut) {
|
||||
return $factory->find($class)->where([['rut', $rut]])->one();
|
||||
}
|
||||
public function show(Request $request, Response $response, Factory $factory, $propietario_rut): Response {
|
||||
$propietario = $this->get($factory, Propietario::class, $propietario_rut);
|
||||
$output = [
|
||||
'input' => $propietario_rut,
|
||||
'propietario' => $propietario->toArray(),
|
||||
'link' => [
|
||||
'rel' => 'propietarios',
|
||||
'title' => 'Propietarios',
|
||||
'href' => str_replace("/propietario/{$propietario_rut}", '/propietarios', $request->getUri())
|
||||
]
|
||||
];
|
||||
$output['links'] = [
|
||||
[
|
||||
'rel' => 'direccion',
|
||||
'title' => $propietario->direccion()->calle,
|
||||
'href' => str_replace("/propietario/{$propietario_rut}", "/direccion/{$propietario->direccion}", $request->getUri())
|
||||
]
|
||||
];
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function add(Request $request, Response $response, Factory $factory): Response {
|
||||
$post = $request->getParsedBody();
|
||||
$output = [
|
||||
'input' => $post
|
||||
];
|
||||
if (in_array('propietarios', $post)) {
|
||||
$output['propietarios'] = [];
|
||||
foreach ($post['propietarios'] as $input) {
|
||||
$propietario = Propietario::add($factory, $input);
|
||||
$propietario []= [
|
||||
'propietario' => $propietario->toArray(),
|
||||
'created' => $propietario->is_new() ? $propietario->save() : false
|
||||
];
|
||||
}
|
||||
} elseif (in_array('propietario', $post)) {
|
||||
$propietario = Propietario::add($factory, $post);
|
||||
$output['propietario'] = $propietario;
|
||||
$output['created'] = $propietario->is_new() ? $propietario->save() : false;
|
||||
}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function edit(Request $request, Response $response, Factory $factory, $propietario_rut): Response {
|
||||
$post = $request->getParsedBody();
|
||||
$input = compact('propietario_rut', 'post');
|
||||
$propietario = $this->get($factory, Propietario::class, $propietario_rut);
|
||||
$output = [
|
||||
'input' => $input,
|
||||
'propietario' => $propietario->toArray()
|
||||
];
|
||||
$output['edited'] = $propietario->edit($post);
|
||||
$output['changes'] = $propietario->toArray();
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function delete(Request $request, Response $response, Factory $factory, $propietario_rut): Response {
|
||||
$propietario = $this->get($factory, Propietario::class, $propietario_rut);
|
||||
$output = [
|
||||
'input' => $propietario_rut,
|
||||
'propietario' => $propietario->toArray()
|
||||
];
|
||||
$output['deleted'] = $propietario->delete();
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
}
|
93
common/Controller/Proyectos.php
Normal file
93
common/Controller/Proyectos.php
Normal file
@ -0,0 +1,93 @@
|
||||
<?php
|
||||
namespace Incoviba\API\Common\Controller;
|
||||
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Incoviba\API\Common\Define\Controller\Json;
|
||||
use Incoviba\API\Common\Factory\Model as Factory;
|
||||
use Incoviba\Proyecto\Proyecto;
|
||||
|
||||
class Proyectos {
|
||||
use Json;
|
||||
|
||||
public function __invoke(Request $request, Response $response, Factory $factory): Response {
|
||||
$proyectos = $factory->find(Proyecto::class)->array();
|
||||
$base_url = str_replace('/proyectos', '{URL}', $request->getUri());
|
||||
array_walk($proyectos, function (&$item) use ($base_url) {
|
||||
$link = [
|
||||
'rel' => 'proyecto',
|
||||
'title' => $item['descripcion'],
|
||||
'href' => str_replace('{URL}', "/proyecto/{$item['id']}", $base_url)
|
||||
];
|
||||
$item['link'] = $link;
|
||||
});
|
||||
return $this->withJson($response, compact('proyectos'));
|
||||
}
|
||||
public function show(Request $request, Response $response, Factory $factory, $proyecto_id): Response {
|
||||
$proyecto = $factory->find(Proyecto::class)->one($proyecto_id);
|
||||
$output = [
|
||||
'input' => $proyecto_id,
|
||||
'proyecto' => $proyecto->toArray(),
|
||||
'link' => [
|
||||
'rel' => 'proyectos',
|
||||
'title' => 'Proyectos',
|
||||
'href' => str_replace("/proyecto/{$proyecto_id}", '/proyectos', $request->getUri())
|
||||
]
|
||||
];
|
||||
$output['links'] = [
|
||||
[
|
||||
'rel' => 'inmobiliaria',
|
||||
'title' => $proyecto->inmobiliaria()->abreviacion,
|
||||
'href' => str_replace("/proyecto/{$proyecto_id}", "/inmobiliaria/{$proyecto->inmobiliaria()->rut}", $request->getUri())
|
||||
],
|
||||
[
|
||||
'rel' => 'direccion',
|
||||
'title' => $proyecto->direccion()->calle,
|
||||
'href' => str_replace("/proyecto/{$proyecto_id}", "/direccion/{$proyecto->direccion}", $request->getUri())
|
||||
]
|
||||
];
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function add(Request $request, Response $response, Factory $factory): Response {
|
||||
$post = $request->getParsedBody();
|
||||
$output = [
|
||||
'input' => $post
|
||||
];
|
||||
if (in_array('proyectos', $post)) {
|
||||
$output['proyectos'] = [];
|
||||
foreach ($post['proyectos'] as $input) {
|
||||
$proyecto = Proyecto::add($factory, $input);
|
||||
$proyecto []= [
|
||||
'proyecto' => $proyecto->toArray(),
|
||||
'created' => $proyecto->is_new() ? $proyecto->save() : false
|
||||
];
|
||||
}
|
||||
} elseif (in_array('proyecto', $post)) {
|
||||
$proyecto = Proyecto::add($factory, $post);
|
||||
$output['proyecto'] = $proyecto;
|
||||
$output['created'] = $proyecto->is_new() ? $proyecto->save() : false;
|
||||
}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function edit(Request $request, Response $response, Factory $factory, $proyecto_id): Response {
|
||||
$post = $request->getParsedBody();
|
||||
$input = compact('proyecto_id', 'post');
|
||||
$proyecto = $factory->find(Proyecto::class)->one($proyecto_id);
|
||||
$output = [
|
||||
'input' => $input,
|
||||
'proyecto' => $proyecto->toArray()
|
||||
];
|
||||
$output['edited'] = $proyecto->edit($post);
|
||||
$output['changes'] = $proyecto->toArray();
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function delete(Request $request, Response $response, Factory $factory, $proyecto_id): Response {
|
||||
$proyecto = $factory->find(Proyecto::class)->one($proyecto_id);
|
||||
$output = [
|
||||
'input' => $proyecto_id,
|
||||
'proyecto' => $proyecto->toArray()
|
||||
];
|
||||
$output['deleted'] = $proyecto->delete();
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
}
|
39
common/Controller/Sociedades.php
Normal file
39
common/Controller/Sociedades.php
Normal file
@ -0,0 +1,39 @@
|
||||
<?php
|
||||
namespace Incoviba\API\Common\Controller;
|
||||
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Incoviba\API\Common\Define\Controller\Json;
|
||||
use Incoviba\API\Common\Factory\Model as Factory;
|
||||
use Incoviba\Inmobiliaria\TipoSociedad;
|
||||
|
||||
class Sociedades {
|
||||
use Json;
|
||||
|
||||
public function __invoke(Request $request, Response $response, Factory $factory): Response {
|
||||
$sociedades = $factory->find(TipoSociedad::class)->array();
|
||||
$base_url = str_replace('/sociedades', '{URL}', $request->getUri());
|
||||
array_walk($sociedades, function (&$item) use ($base_url) {
|
||||
$link = [
|
||||
'rel' => 'sociedad',
|
||||
'title' => $item['descripcion'],
|
||||
'href' => str_replace('{URL}', "/sociedad/{$item['id']}", $base_url)
|
||||
];
|
||||
$item['link'] = $link;
|
||||
});
|
||||
return $this->withJson($response, compact('sociedades'));
|
||||
}
|
||||
public function show(Request $request, Response $response, Factory $factory, $sociedad_id): Response {
|
||||
$sociedad = $factory->find(TipoSociedad::class)->one($sociedad_id);
|
||||
$output = [
|
||||
'input' => $sociedad_id,
|
||||
'sociedad' => $sociedad->toArray(),
|
||||
'link' => [
|
||||
'rel' => 'sociedades',
|
||||
'title' => 'Sociedades',
|
||||
'href' => str_replace("/sociedad/{$sociedad_id}", '/sociedades', $request->getUri())
|
||||
]
|
||||
];
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
}
|
92
common/Controller/Ventas.php
Normal file
92
common/Controller/Ventas.php
Normal file
@ -0,0 +1,92 @@
|
||||
<?php
|
||||
namespace Incoviba\API\Common\Controller;
|
||||
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Incoviba\API\Common\Define\Controller\Json;
|
||||
use Incoviba\API\Common\Factory\Model as Factory;
|
||||
use Incoviba\Venta\Venta;
|
||||
|
||||
class Ventas {
|
||||
use Json;
|
||||
|
||||
public function __invoke(Request $request, Response $response, Factory $factory): Response {
|
||||
$ventas = $factory->find(Venta::class)->array();
|
||||
$url = '' . $request->getUri();
|
||||
array_walk($ventas, function (&$item) use ($url) {
|
||||
$item['link'] = [
|
||||
'rel' => 'venta',
|
||||
'title' => 'Venta',
|
||||
'href' => str_replace('/ventas', "/venta/{$item['id']}", $url)
|
||||
];
|
||||
});
|
||||
return $this->withJson($response, compact('ventas'));
|
||||
}
|
||||
public function show(Request $request, Response $response, Factory $factory, $venta_id): Response {
|
||||
$venta = $factory->find(Venta::class)->one($venta_id);
|
||||
$output = [
|
||||
'input' => $venta_id,
|
||||
'venta' => $venta->toArray(),
|
||||
'link' => [
|
||||
'rel' => 'ventas',
|
||||
'title' => 'Ventas',
|
||||
'href' => str_replace("/venta/{$venta_id}", '/ventas', $request->getUri())
|
||||
]
|
||||
];
|
||||
$output['links'] = [
|
||||
[
|
||||
'rel' => 'propietario',
|
||||
'title' => $venta->propietario()->nombreCompleto(),
|
||||
'href' => str_replace("/venta/{$venta_id}", "/propietario/{$venta->propietario}", $request->getUri())
|
||||
],
|
||||
[
|
||||
'rel' => 'propiedad',
|
||||
'title' => 'Propiedad',
|
||||
'href' => str_replace("/venta/{$venta_id}", "/propiedad/{$venta->propiedad}", $request->getUri())
|
||||
]
|
||||
];
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function add(Request $request, Response $response, Factory $factory): Response {
|
||||
$post = $request->getParsedBody();
|
||||
$output = [
|
||||
'input' => $post
|
||||
];
|
||||
if (in_array('ventas', $post)) {
|
||||
$output['ventas'] = [];
|
||||
foreach ($post['ventas'] as $input) {
|
||||
$venta = Venta::add($factory, $input);
|
||||
$venta []= [
|
||||
'venta' => $venta->toArray(),
|
||||
'created' => $venta->is_new() ? $venta->save() : false
|
||||
];
|
||||
}
|
||||
} elseif (in_array('venta', $post)) {
|
||||
$venta = Venta::add($factory, $post);
|
||||
$output['venta'] = $venta;
|
||||
$output['created'] = $venta->is_new() ? $venta->save() : false;
|
||||
}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function edit(Request $request, Response $response, Factory $factory, $venta_id): Response {
|
||||
$post = $request->getParsedBody();
|
||||
$input = compact('venta_id', 'post');
|
||||
$venta = $factory->find(Venta::class)->one($venta_id);
|
||||
$output = [
|
||||
'input' => $input,
|
||||
'venta' => $venta->toArray()
|
||||
];
|
||||
$output['edited'] = $venta->edit($post);
|
||||
$output['changes'] = $venta->toArray();
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
public function delete(Request $request, Response $response, Factory $factory, $venta_id): Response {
|
||||
$venta = $factory->find(Venta::class)->one($venta_id);
|
||||
$output = [
|
||||
'input' => $venta_id,
|
||||
'venta' => $venta->toArray()
|
||||
];
|
||||
$output['deleted'] = $venta->delete();
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
}
|
13
common/Define/Controller/Json.php
Normal file
13
common/Define/Controller/Json.php
Normal file
@ -0,0 +1,13 @@
|
||||
<?php
|
||||
namespace Incoviba\API\Common\Define\Controller;
|
||||
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
|
||||
trait Json {
|
||||
public function withJson(Response $response, $data, $status = 200): Response {
|
||||
$response->getBody()->write(json_encode($data, JSON_UNESCAPED_SLASHES));
|
||||
return $response
|
||||
->withStatus($status)
|
||||
->withHeader('content-type', 'application/json');
|
||||
}
|
||||
}
|
62
common/Define/Model.php
Normal file
62
common/Define/Model.php
Normal file
@ -0,0 +1,62 @@
|
||||
<?php
|
||||
namespace Incoviba\API\Common\Define;
|
||||
|
||||
use Incoviba\API\Common\Factory\Model as ModelFactory;
|
||||
|
||||
interface Model {
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getTable(): string;
|
||||
|
||||
/**
|
||||
* @param ModelFactory $factory
|
||||
* @return Model
|
||||
*/
|
||||
public function setFactory(ModelFactory $factory): Model;
|
||||
|
||||
/**
|
||||
* Get all children models of class {$child_class}
|
||||
* @param string $child_class Class of child model
|
||||
* @param array $definitions array of conditions for connecting to the child table
|
||||
* @return array|null
|
||||
*/
|
||||
public function parentOf(string $child_class, array $definitions): ?array;
|
||||
|
||||
/**
|
||||
* Get parent model of class {$parent_class}
|
||||
* @param string $parent_class Class of parent model
|
||||
* @param array $definitions array of conditions for connecting to the parent table
|
||||
* @return Model|null
|
||||
*/
|
||||
public function childOf(string $parent_class, array $definitions): ?Model;
|
||||
|
||||
/**
|
||||
* Get all siblings of class {$sibling_class}
|
||||
* @param string $sibling_class Class of sibling model
|
||||
* @param string $connecting_table table connecting both models
|
||||
* @param array $definitions array of conditions for connecting to the sibling and connecting tables
|
||||
* @return array|null
|
||||
*/
|
||||
public function siblingOf(string $sibling_class, string $connecting_table, array $definitions): ?array;
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function toArray(): array;
|
||||
|
||||
/**
|
||||
* Add a new model of this type to the database, parsing {$input} data
|
||||
* @param ModelFactory $factory Factory object for connecting to the database
|
||||
* @param array $input Input data
|
||||
* @return Model|null
|
||||
*/
|
||||
public static function add(ModelFactory $factory, array $input): ?Model;
|
||||
|
||||
/**
|
||||
* Edit current model parsing {$input} data
|
||||
* @param array $input Input data
|
||||
* @return array|null
|
||||
*/
|
||||
public function edit(array $input): ?array;
|
||||
}
|
377
common/Factory/Model.php
Normal file
377
common/Factory/Model.php
Normal file
@ -0,0 +1,377 @@
|
||||
<?php
|
||||
namespace Incoviba\API\Common\Factory;
|
||||
|
||||
use http\Exception\InvalidArgumentException;
|
||||
use ORM;
|
||||
use Incoviba\API\Common\Alias\Model as BaseModel;
|
||||
use Incoviba\API\Common\Define\Model as ModelInterface;
|
||||
|
||||
class Model {
|
||||
public static function for(string $class): Model {
|
||||
$factory = new Model();
|
||||
return $factory->find($class);
|
||||
}
|
||||
protected function reset(): Model {
|
||||
$resets = ['columns', 'joins', 'conditions', 'groups', 'orders', 'having', 'limit', 'offset'];
|
||||
foreach ($resets as $r) {
|
||||
$this->{$r} = null;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function create(string $model_class, array $data = null): bool|ModelInterface {
|
||||
// Check if it already exists
|
||||
if ($data !== null) {
|
||||
$model = $this->find($model_class);
|
||||
foreach ($data as $f => $v) {
|
||||
$model = $model->where([[$f, $v]]);
|
||||
}
|
||||
$model = $model->one();
|
||||
if ($model !== null) {
|
||||
return $model;
|
||||
}
|
||||
}
|
||||
$model = BaseModel::factory($model_class)->create($data);
|
||||
if (is_a($model, \ORMWrapper::class)) {
|
||||
$model = $model->find_one();
|
||||
}
|
||||
$model->setFactory($this);
|
||||
return $model;
|
||||
}
|
||||
|
||||
protected string $class;
|
||||
public function find(string $class): Model {
|
||||
$this->reset();
|
||||
if (!class_exists($class)) {
|
||||
throw new InvalidArgumentException("Model {$class} not found.");
|
||||
}
|
||||
$this->class = $class;
|
||||
return $this;
|
||||
}
|
||||
|
||||
protected ?array $columns;
|
||||
public function select($columns): Model {
|
||||
if (!is_array($columns)) {
|
||||
$columns = [$columns];
|
||||
}
|
||||
foreach ($columns as $c) {
|
||||
$this->addColumn($c);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
protected function addColumn($column) {
|
||||
$col = [
|
||||
'table' => '',
|
||||
'column' => $column
|
||||
];
|
||||
if (is_array($column)) {
|
||||
$col['table'] = $column['table'] ?? $column[0];
|
||||
$col['column'] = $column['column'] ?? $column[1];
|
||||
}
|
||||
$this->columns []= $col;
|
||||
}
|
||||
protected function parseColumns(ORM $orm): ORM {
|
||||
if ($this->columns === null) {
|
||||
return $orm;
|
||||
}
|
||||
foreach ($this->columns as $column) {
|
||||
$orm = $orm->select("{$column['table']}.{$column['column']}");
|
||||
}
|
||||
return $orm;
|
||||
}
|
||||
|
||||
protected ?array $joins;
|
||||
public function join($joins): Model {
|
||||
foreach ($joins as $join) {
|
||||
$this->addJoin($join);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
protected function addJoin($join) {
|
||||
$map = [
|
||||
'table' => ['table', 't', 0],
|
||||
'from' => ['from', 'f', 1],
|
||||
'to' => ['to', 2],
|
||||
'operator' => ['operator', 'op', 'o', 3],
|
||||
'type' => 'type',
|
||||
'alias' => 'alias',
|
||||
'params' => ['parameters', 'params']
|
||||
];
|
||||
$defaults = ['operator' => '=', 'type' => 'inner'];
|
||||
$required = ['table', 'from', 'to', 'operator', 'type'];
|
||||
|
||||
$j = [];
|
||||
foreach ($join as $key => $val) {
|
||||
$k = -1;
|
||||
foreach ($map as $i => $m) {
|
||||
if (is_array($m)) {
|
||||
if (in_array($key, $m)) {
|
||||
$k = $i;
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if ($m == $key) {
|
||||
$k = $i;
|
||||
}
|
||||
}
|
||||
$j[$k] = $val;
|
||||
}
|
||||
foreach ($defaults as $key => $val) {
|
||||
if (!isset($j[$key])) {
|
||||
$j[$key] = $val;
|
||||
}
|
||||
}
|
||||
foreach ($required as $key) {
|
||||
if (!isset($j[$key])) {
|
||||
throw new InvalidArgumentException("Missing {$key} when joining in " . get_class());
|
||||
}
|
||||
}
|
||||
$this->joins []= (object) $j;
|
||||
}
|
||||
protected function parseJoins(ORM $orm): ORM {
|
||||
if ($this->joins === null) {
|
||||
return $orm;
|
||||
}
|
||||
foreach ($this->joins as $join) {
|
||||
$method = match(strtolower($join->type)) {
|
||||
'raw' => 'rawJoin',
|
||||
'inner' => 'innerJoin',
|
||||
'left', 'left outer', 'left_outer', 'leftouter' => 'leftOuterJoin',
|
||||
'right', 'right outer', 'right_outer', 'rightouter' => 'rightOuterJoin',
|
||||
'full', 'full outer', 'full_outer', 'fullouter', 'outer' => 'fullOuterJoin'
|
||||
};
|
||||
if (strtolower($join->type) == 'raw') {
|
||||
if (isset($join->alias)) {
|
||||
$orm = $orm->{$method}($join->table, [$join->from, $join->operator, $join->to], $join->alias, $join->params);
|
||||
} else {
|
||||
$orm = $orm->{$method}($join->table, [$join->from, $join->operator, $join->to], $join->params);
|
||||
}
|
||||
}
|
||||
if (isset($join->alias)) {
|
||||
$orm = $orm->{$method}($join->table, [$join->from, $join->operator, $join->to], $join->alias);
|
||||
} else {
|
||||
$orm = $orm->{$method}($join->table, [$join->from, $join->operator, $join->to]);
|
||||
}
|
||||
}
|
||||
return $orm;
|
||||
}
|
||||
|
||||
protected ?array $conditions;
|
||||
public function where(array $conditions): Model {
|
||||
foreach ($conditions as $condition) {
|
||||
$this->addCondition($condition);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
protected function addCondition(array $condition) {
|
||||
$map = [
|
||||
'column' => ['column', 'field', 'col', 'c', 'f', 0],
|
||||
'value' => ['value', 'val', 'v', 1],
|
||||
'operator' => ['operator', 'op', 'o', 'type', 't', 2]
|
||||
];
|
||||
$defaults = ['operator' => '=', 'type' => 'eq'];
|
||||
$required = ['column', 'value', 'operator'];
|
||||
|
||||
$c = [];
|
||||
foreach ($condition as $key => $val) {
|
||||
$k = -1;
|
||||
foreach ($map as $i => $m) {
|
||||
if (is_array($m)) {
|
||||
if (in_array($key, $m)) {
|
||||
$k = $i;
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if ($key == $m) {
|
||||
$k = $i;
|
||||
}
|
||||
}
|
||||
$c[$k] = $val;
|
||||
}
|
||||
foreach ($defaults as $key => $val) {
|
||||
if (!isset($c[$key])) {
|
||||
$c[$key] = $val;
|
||||
}
|
||||
}
|
||||
foreach ($required as $key) {
|
||||
if (!isset($c[$key])) {
|
||||
throw new InvalidArgumentException("Missing {$key} when adding conditions in " . get_class());
|
||||
}
|
||||
}
|
||||
$this->conditions []= (object) $c;
|
||||
}
|
||||
protected function parseConditions(ORM $orm): ORM {
|
||||
if ($this->conditions === null) {
|
||||
return $orm;
|
||||
}
|
||||
foreach ($this->conditions as $condition) {
|
||||
$method = match(strtolower($condition->operator)) {
|
||||
'', '=', 'eq', 'equal', 'equals' => 'where',
|
||||
'<', 'lt', 'less than', 'less_than', 'lessthan' => 'whereLt',
|
||||
'<=', 'lte', 'less equal', 'less equals', 'less_equal', 'less_equals', 'lessequal', 'lessequals',
|
||||
'less than equal', 'less than equals', 'less_than_equal', 'less_than_equals', 'lessthanequal',
|
||||
'lessthanequals' => 'whereLte',
|
||||
'>', 'gt', 'greater than', 'greater_than', 'greaterthan' => 'whereGt',
|
||||
'>=', 'gte', 'greater equal', 'greater equals', 'greater_equal', 'greater_equals', 'greaterequal',
|
||||
'greaterequals', 'greater than equal', 'greater than equals', 'greater_than_equal', 'greater_than_equals',
|
||||
'greaterthanequal', 'greaterthanequals' => 'whereGte',
|
||||
'!=', 'not equal', 'not equals', 'not_equal', 'not_equals', 'notequal', 'notequals' => 'whereNotEqual',
|
||||
'like' => 'whereLike',
|
||||
'not like', 'not_like', 'notlike' => 'whereNotLike',
|
||||
'in' => 'whereIn',
|
||||
'not in', 'not_in', 'notin' => 'whereNotIn',
|
||||
'raw' => 'raw'
|
||||
};
|
||||
$orm = $orm->{$method}($condition->column, $condition->value);
|
||||
}
|
||||
return $orm;
|
||||
}
|
||||
|
||||
protected ?array $groups;
|
||||
public function group($groups): Model {
|
||||
if (!is_array($groups)) {
|
||||
$groups = [$groups];
|
||||
}
|
||||
foreach ($groups as $group) {
|
||||
$this->addGroup($group);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
protected function addGroup(string $group) {
|
||||
$this->groups []= $group;
|
||||
}
|
||||
protected function parseGroups(ORM $orm): ORM {
|
||||
if ($this->groups === null) {
|
||||
return $orm;
|
||||
}
|
||||
foreach ($this->groups as $group) {
|
||||
if (str_contains($group, '(')) {
|
||||
$orm = $orm->groupByExpr($group);
|
||||
continue;
|
||||
}
|
||||
$orm = $orm->groupBy($group);
|
||||
}
|
||||
return $orm;
|
||||
}
|
||||
|
||||
protected ?array $orders;
|
||||
public function order($orders): Model {
|
||||
if (!is_array($orders)) {
|
||||
$orders = [$orders];
|
||||
}
|
||||
foreach ($orders as $order) {
|
||||
$this->addOrder($order);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
protected function addOrder($order) {
|
||||
$defaults = ['direction' => 'asc'];
|
||||
$required = ['column', 'direction'];
|
||||
$o = [];
|
||||
foreach ($order as $key => $val) {
|
||||
$k = match (strtolower($key)) {
|
||||
'column', 'col', 'c', 0 => 'column',
|
||||
'direction', 'dir', 'd', 1 => 'direction'
|
||||
};
|
||||
$o[$k] = $val;
|
||||
}
|
||||
foreach ($defaults as $key => $val) {
|
||||
if (!isset($o[$key])) {
|
||||
$o[$key] = $val;
|
||||
}
|
||||
}
|
||||
foreach ($required as $key) {
|
||||
if (!isset($o[$key])) {
|
||||
throw new InvalidArgumentException("Missing {$key} in order.");
|
||||
}
|
||||
}
|
||||
$this->orders []= (object) $o;
|
||||
}
|
||||
protected function parseOrders(ORM $orm): ORM {
|
||||
if ($this->orders === null) {
|
||||
return $orm;
|
||||
}
|
||||
foreach ($this->orders as $order) {
|
||||
if (str_contains($order->column, '(')) {
|
||||
$orm = $orm->orderByExpr($order->column);
|
||||
continue;
|
||||
}
|
||||
$method = match (strtolower($order->direction)) {
|
||||
'ascending', 'asc', '' => 'orderByAsc',
|
||||
'descending', 'desc' => 'orderByDesc'
|
||||
};
|
||||
$orm = $orm->{$method}($order->column);
|
||||
}
|
||||
return $orm;
|
||||
}
|
||||
|
||||
protected ?int $limit;
|
||||
public function limit(int $limit): Model {
|
||||
$this->limit = $limit;
|
||||
return $this;
|
||||
}
|
||||
protected function parseLimit(ORM $orm): ORM {
|
||||
if ($this->limit === null) {
|
||||
return $orm;
|
||||
}
|
||||
return $orm->limit($this->limit);
|
||||
}
|
||||
|
||||
protected ?int $offset;
|
||||
public function offset(int $offset): Model {
|
||||
$this->offset = $offset;
|
||||
return $this;
|
||||
}
|
||||
protected function parseOffset(ORM $orm): ORM {
|
||||
if ($this->offset === null) {
|
||||
return $orm;
|
||||
}
|
||||
return $orm->offset($this->offset);
|
||||
}
|
||||
|
||||
public function build(): ORM {
|
||||
$orm = BaseModel::factory($this->class);
|
||||
$methods = [
|
||||
'columns',
|
||||
'joins',
|
||||
'conditions',
|
||||
'groups',
|
||||
'orders',
|
||||
'limit',
|
||||
'offset'
|
||||
];
|
||||
foreach ($methods as $m) {
|
||||
$method = 'parse' . ucfirst($m);
|
||||
$orm = $this->{$method}($orm);
|
||||
}
|
||||
return $orm;
|
||||
}
|
||||
|
||||
public function one(?int $id = null): bool|ModelInterface {
|
||||
$result = $this->build()->find_one($id);
|
||||
if ($result !== false) {
|
||||
$result->setFactory($this);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
public function many(): bool|array {
|
||||
$results = $this->build()->find_many();
|
||||
if ($results !== false) {
|
||||
foreach ($results as &$result) {
|
||||
$result->setFactory($this);
|
||||
}
|
||||
}
|
||||
return $results;
|
||||
}
|
||||
public function array(): ?array {
|
||||
$results = $this->many();
|
||||
if ($results === false) {
|
||||
return null;
|
||||
}
|
||||
return array_map(function($item) {
|
||||
return $item->toArray();
|
||||
}, $results);
|
||||
}
|
||||
}
|
30
common/Middleware/Auth.php
Normal file
30
common/Middleware/Auth.php
Normal file
@ -0,0 +1,30 @@
|
||||
<?php
|
||||
namespace Incoviba\API\Common\Middleware;
|
||||
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
use Psr\Http\Server\RequestHandlerInterface as Handler;
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Psr\Http\Message\ResponseFactoryInterface as Factory;
|
||||
use Incoviba\API\Common\Service\Auth as Service;
|
||||
|
||||
class Auth {
|
||||
protected $service;
|
||||
protected $factory;
|
||||
protected $exceptions;
|
||||
public function __construct(Service $service, Factory $factory, array $exception_routes) {
|
||||
$this->service = $service;
|
||||
$this->factory = $factory;
|
||||
$this->exceptions = $exception_routes;
|
||||
}
|
||||
public function __invoke(Request $request, Handler $handler): Response {
|
||||
$path = $request->getUri()->getPath();
|
||||
if (in_array($path, $this->exceptions) or $this->service->isValid($request)) {
|
||||
return $handler->handle($request);
|
||||
}
|
||||
$response = $this->factory->createResponse();
|
||||
$response->getBody()->write(json_encode(['message' => 'Not authorized.']));
|
||||
return $response
|
||||
->withStatus(401) // unauthorized
|
||||
->withHeader('content-type', 'application/json');
|
||||
}
|
||||
}
|
51
common/Service/Auth.php
Normal file
51
common/Service/Auth.php
Normal file
@ -0,0 +1,51 @@
|
||||
<?php
|
||||
namespace Incoviba\API\Common\Service;
|
||||
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
|
||||
class Auth {
|
||||
protected string $key;
|
||||
public function __construct(string $key) {
|
||||
$this->key = $key;
|
||||
}
|
||||
public function isValid(Request $request): bool {
|
||||
$api_key = '';
|
||||
if ($request->hasHeader('Authorization')) {
|
||||
$api_key = $request->getHeader('Authorization');
|
||||
if (is_array($api_key)) {
|
||||
$api_key = $api_key[0];
|
||||
}
|
||||
if (str_contains($api_key, 'Bearer')) {
|
||||
$api_key = explode(' ', $api_key)[1];
|
||||
}
|
||||
} elseif ($request->getParsedBody() !== null and in_array('API_KEY', $request->getParsedBody())) {
|
||||
$api_key = $request->getParsedBody()['API_KEY'];
|
||||
} elseif ($request->getQueryParams() !== null and in_array('API_KEY', array_keys($request->getQueryParams()))) {
|
||||
$api_key = $request->getQueryParams()['API_KEY'];
|
||||
}
|
||||
if ($this->key == $api_key) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public function generate(int $length = 32, bool $removeSimilarCharacters = true): string {
|
||||
$token = "";
|
||||
try {
|
||||
$bytesWithMargin = random_bytes($length*3);
|
||||
|
||||
$base64 = base64_encode($bytesWithMargin);
|
||||
$purified = preg_replace("/[+=\/.]/", "", $base64);
|
||||
|
||||
if ($removeSimilarCharacters){
|
||||
$purified = preg_replace("/[I1l0Oo]/", "", $purified);
|
||||
}
|
||||
|
||||
$token = substr($purified, 0, $length);
|
||||
|
||||
} catch (\Exception $e){
|
||||
echo $e->getMessage();
|
||||
}
|
||||
|
||||
return $token;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user