new api 2.0

This commit is contained in:
daniel 2024-01-17 00:15:41 +01:00
parent bdc500c1b0
commit 17edd73f35
57 changed files with 322 additions and 1793 deletions

View File

@ -7,8 +7,6 @@ use PandoraFMS\Modules\Shared\Exceptions\BadRequestException;
class Builder class Builder
{ {
public function build(Entity $entity, array $data): Entity public function build(Entity $entity, array $data): Entity
{ {
foreach ($data as $field => $value) { foreach ($data as $field => $value) {
@ -21,6 +19,4 @@ class Builder
return $entity; return $entity;
} }
} }

View File

@ -2,27 +2,26 @@
namespace PandoraFMS\Modules\Shared\Controllers; namespace PandoraFMS\Modules\Shared\Controllers;
use Nyholm\Psr7\Stream;
use PandoraFMS\Modules\Shared\Core\SerializableAbstract; use PandoraFMS\Modules\Shared\Core\SerializableAbstract;
use PandoraFMS\Modules\Shared\Enums\HttpCodesEnum; use PandoraFMS\Modules\Shared\Enums\HttpCodesEnum;
use PandoraFMS\Modules\Shared\Exceptions\BadRequestException; use PandoraFMS\Modules\Shared\Exceptions\BadRequestException;
use PandoraFMS\Modules\Shared\Exceptions\ForbiddenActionException; use PandoraFMS\Modules\Shared\Exceptions\ForbiddenActionException;
use PandoraFMS\Modules\Shared\Exceptions\InvalidClassException; use PandoraFMS\Modules\Shared\Exceptions\InvalidClassException;
use Nyholm\Psr7\Stream;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\UploadedFileInterface; use Psr\Http\Message\UploadedFileInterface;
use Slim\Routing\RouteContext; use Slim\Routing\RouteContext;
abstract class Controller abstract class Controller
{ {
public function __construct() public function __construct()
{ {
} }
public function getParam(Request $request, string $param): mixed public function getParam(Request $request, string $param): mixed
{ {
$routeContext = RouteContext::fromRequest($request); $routeContext = RouteContext::fromRequest($request);
@ -36,7 +35,6 @@ abstract class Controller
return $value; return $value;
} }
public function getFile(Request $request, string $file): UploadedFileInterface public function getFile(Request $request, string $file): UploadedFileInterface
{ {
$files = $request->getUploadedFiles(); $files = $request->getUploadedFiles();
@ -51,7 +49,6 @@ abstract class Controller
return $files[$file]; return $files[$file];
} }
public function extractParams(Request $request): array public function extractParams(Request $request): array
{ {
$queryParams = ($request->getQueryParams() ?? []); $queryParams = ($request->getQueryParams() ?? []);
@ -70,7 +67,6 @@ abstract class Controller
return $params; return $params;
} }
public function fromRequest(Request $request, string $className): mixed public function fromRequest(Request $request, string $className): mixed
{ {
$params = $this->extractParams($request); $params = $this->extractParams($request);
@ -88,11 +84,10 @@ abstract class Controller
return $class->fromArray($params); return $class->fromArray($params);
} }
public function getResponse( public function getResponse(
Response $response, Response $response,
mixed $result, mixed $result,
?string $contentType='application/json' ?string $contentType = 'application/json'
): Response { ): Response {
if ($contentType === 'application/json') { if ($contentType === 'application/json') {
$result = json_encode($result); $result = json_encode($result);
@ -102,7 +97,6 @@ abstract class Controller
return $response->withHeader('Content-Type', $contentType); return $response->withHeader('Content-Type', $contentType);
} }
public function getResponseAttachment(Response $response, string $path, string $fileName) public function getResponseAttachment(Response $response, string $path, string $fileName)
{ {
try { try {
@ -118,6 +112,4 @@ abstract class Controller
return $response->withBody($file_stream)->withHeader('Content-Disposition', 'attachment; filename='.$fileName)->withHeader('Content-Type', mime_content_type($path)); return $response->withBody($file_stream)->withHeader('Content-Disposition', 'attachment; filename='.$fileName)->withHeader('Content-Type', mime_content_type($path));
} }
} }

View File

@ -4,62 +4,38 @@ namespace PandoraFMS\Modules\Shared\Core;
abstract class DataMapperAbstract abstract class DataMapperAbstract
{ {
private null|string $tableRelated = null; private null|string $tableRelated = null;
private null|string $keyRelated = null; private null|string $keyRelated = null;
private null|string $searchFieldRelated = null; private null|string $searchFieldRelated = null;
private mixed $searchFieldValueRelated = null; private mixed $searchFieldValueRelated = null;
public function __construct( public function __construct(
private string $tableName, private string $tableName,
private string $primaryKey private string $primaryKey
) { ) {
} }
abstract public function getClassName(): string; abstract public function getClassName(): string;
abstract public function fromDatabase(array $data): MappeableInterface; abstract public function fromDatabase(array $data): MappeableInterface;
abstract public function toDatabase(MappeableInterface $data): array; abstract public function toDatabase(MappeableInterface $data): array;
/**
* Get the value of tableName.
*/
public function getTableName(): string public function getTableName(): string
{ {
return $this->tableName; return $this->tableName;
} }
/**
* Get the value of primaryKey.
*/
public function getPrimaryKey(): string public function getPrimaryKey(): string
{ {
return $this->primaryKey; return $this->primaryKey;
} }
/**
* Get the value of tableRelated.
*/
public function getTableRelated(): null|string public function getTableRelated(): null|string
{ {
return $this->tableRelated; return $this->tableRelated;
} }
/**
* Set the value of tableRelated.
*/
public function setTableRelated(null|string $tableRelated): self public function setTableRelated(null|string $tableRelated): self
{ {
$this->tableRelated = $tableRelated; $this->tableRelated = $tableRelated;
@ -67,19 +43,11 @@ abstract class DataMapperAbstract
return $this; return $this;
} }
/**
* Get the value of keyRelated.
*/
public function getKeyRelated(): null|string public function getKeyRelated(): null|string
{ {
return $this->keyRelated; return $this->keyRelated;
} }
/**
* Set the value of keyRelated.
*/
public function setKeyRelated(null|string $keyRelated): self public function setKeyRelated(null|string $keyRelated): self
{ {
$this->keyRelated = $keyRelated; $this->keyRelated = $keyRelated;
@ -87,19 +55,11 @@ abstract class DataMapperAbstract
return $this; return $this;
} }
/**
* Get the value of searchFieldRelated.
*/
public function getSearchFieldRelated(): null|string public function getSearchFieldRelated(): null|string
{ {
return $this->searchFieldRelated; return $this->searchFieldRelated;
} }
/**
* Set the value of searchFieldRelated.
*/
public function setSearchFieldRelated(null|string $searchFieldRelated): self public function setSearchFieldRelated(null|string $searchFieldRelated): self
{ {
$this->searchFieldRelated = $searchFieldRelated; $this->searchFieldRelated = $searchFieldRelated;
@ -107,19 +67,11 @@ abstract class DataMapperAbstract
return $this; return $this;
} }
/**
* Get the value of searchFieldValueRelated.
*/
public function getSearchFieldValueRelated(): mixed public function getSearchFieldValueRelated(): mixed
{ {
return $this->searchFieldValueRelated; return $this->searchFieldValueRelated;
} }
/**
* Set the value of searchFieldValueRelated.
*/
public function setSearchFieldValueRelated(mixed $searchFieldValueRelated): self public function setSearchFieldValueRelated(mixed $searchFieldValueRelated): self
{ {
$this->searchFieldValueRelated = $searchFieldValueRelated; $this->searchFieldValueRelated = $searchFieldValueRelated;
@ -127,22 +79,14 @@ abstract class DataMapperAbstract
return $this; return $this;
} }
public function getStringNameClass(): string public function getStringNameClass(): string
{ {
$strname = [ $strname = [
'PandoraFMS\\Modules\\Users\\Entities\\User' => 'User', 'PandoraFMS\\Modules\\Users\\Entities\\User' => 'User',
'PandoraFMS\\Modules\\Shared\\Workunits\\Entities\\Workunit' => 'Workunit',
'PandoraFMS\\Modules\\Shared\\Attachments\\Entities\\Attachment' => 'Attachment',
'PandoraFMS\\Modules\\Users\\UserProfiles\\Entities\\UserProfile' => 'Profile',
'PandoraFMS\\Modules\\Profiles\\Entities\\Profile' => 'Profile',
'PandoraFMS\\Modules\\Groups\\Entities\\Group' => 'Group',
]; ];
$result = ($strname[$this->getClassName()] ?? ''); $result = ($strname[$this->getClassName()] ?? '');
return $result; return $result;
} }
} }

View File

@ -19,82 +19,43 @@ abstract class FilterAbstract extends SerializableAbstract
public const DESC = 'descending'; public const DESC = 'descending';
private ?int $limit = null; private ?int $limit = null;
private ?int $offset = null; private ?int $offset = null;
private ?string $defaultFieldOrder = null; private ?string $defaultFieldOrder = null;
private ?string $defaultDirectionOrder = null; private ?string $defaultDirectionOrder = null;
private ?array $fields = null; private ?array $fields = null;
private ?Entity $entityFilter = null; private ?Entity $entityFilter = null;
public function __construct() public function __construct()
{ {
} }
// abstract public function getWhereClause(): string;
abstract public function fieldsTranslate(): array; abstract public function fieldsTranslate(): array;
/**
* Get the value of fieldsFreeSearch.
*
* @return ?array
*/
public function getFieldsFreeSearch(): ?array public function getFieldsFreeSearch(): ?array
{ {
return []; return [];
} }
/**
* Get the value of multipleSearch.
*
* @return ?array
*/
public function getMultipleSearch(): ?array public function getMultipleSearch(): ?array
{ {
return []; return [];
} }
/**
* Get the value of multipleSearchString.
*
* @return ?array
*/
public function getMultipleSearchString(): ?array public function getMultipleSearchString(): ?array
{ {
return []; return [];
} }
/**
* Get the value of fieldsFreeSearch.
*
* @return ?string
*/
public function getFieldAclGroupMysql(): ?string public function getFieldAclGroupMysql(): ?string
{ {
return ''; return '';
} }
/**
* Get the value of fieldsFreeSearch.
*
* @return ?string
*/
public function getModeAclGroupMysql(): ?string public function getModeAclGroupMysql(): ?string
{ {
return null; return null;
} }
public function fromArray(array $params): static public function fromArray(array $params): static
{ {
$fails = $this->validate($params); $fails = $this->validate($params);
@ -111,7 +72,7 @@ abstract class FilterAbstract extends SerializableAbstract
if (method_exists($this, 'set'.ucfirst($field)) === true) { if (method_exists($this, 'set'.ucfirst($field)) === true) {
$this->{'set'.ucfirst($field)}($value ?? null); $this->{'set'.ucfirst($field)}($value ?? null);
} else if ($this->getEntityFilter() !== null && method_exists($this->getEntityFilter(), 'set'.ucfirst($field)) === true) { } elseif ($this->getEntityFilter() !== null && method_exists($this->getEntityFilter(), 'set'.ucfirst($field)) === true) {
$this->getEntityFilter()->{'set'.ucfirst($field)}($value ?? null); $this->getEntityFilter()->{'set'.ucfirst($field)}($value ?? null);
} }
} }
@ -119,23 +80,11 @@ abstract class FilterAbstract extends SerializableAbstract
return $this; return $this;
} }
/**
* Get the value of limit.
*
* @return ?int
*/
public function getLimit(): ?int public function getLimit(): ?int
{ {
return $this->limit; return $this->limit;
} }
/**
* Set the value of limit.
*
* @param integer $limit
*/
public function setLimit(?int $limit): self public function setLimit(?int $limit): self
{ {
$this->limit = $limit; $this->limit = $limit;
@ -143,23 +92,11 @@ abstract class FilterAbstract extends SerializableAbstract
return $this; return $this;
} }
/**
* Get the value of offset.
*
* @return ?int
*/
public function getOffset(): ?int public function getOffset(): ?int
{ {
return $this->offset; return $this->offset;
} }
/**
* Set the value of offset.
*
* @param integer $offset
*/
public function setOffset(?int $offset): self public function setOffset(?int $offset): self
{ {
$this->offset = $offset; $this->offset = $offset;
@ -167,23 +104,11 @@ abstract class FilterAbstract extends SerializableAbstract
return $this; return $this;
} }
/**
* Get the value of defaultFieldOrder.
*
* @return ?string
*/
public function getDefaultFieldOrder(): ?string public function getDefaultFieldOrder(): ?string
{ {
return $this->defaultFieldOrder; return $this->defaultFieldOrder;
} }
/**
* Set the value of defaultFieldOrder.
*
* @param string $defaultFieldOrder
*/
public function setDefaultFieldOrder(?string $defaultFieldOrder): self public function setDefaultFieldOrder(?string $defaultFieldOrder): self
{ {
$this->defaultFieldOrder = $defaultFieldOrder; $this->defaultFieldOrder = $defaultFieldOrder;
@ -191,23 +116,11 @@ abstract class FilterAbstract extends SerializableAbstract
return $this; return $this;
} }
/**
* Get the value of defaultDirectionOrder.
*
* @return ?string
*/
public function getDefaultDirectionOrder(): ?string public function getDefaultDirectionOrder(): ?string
{ {
return $this->defaultDirectionOrder; return $this->defaultDirectionOrder;
} }
/**
* Set the value of defaultDirectionOrder.
*
* @param string $defaultDirectionOrder
*/
public function setDefaultDirectionOrder(?string $defaultDirectionOrder): self public function setDefaultDirectionOrder(?string $defaultDirectionOrder): self
{ {
$this->defaultDirectionOrder = $defaultDirectionOrder; $this->defaultDirectionOrder = $defaultDirectionOrder;
@ -215,23 +128,11 @@ abstract class FilterAbstract extends SerializableAbstract
return $this; return $this;
} }
/**
* Get the value of entityFilter.
*
* @return ?Entity
*/
public function getEntityFilter(): ?Entity public function getEntityFilter(): ?Entity
{ {
return $this->entityFilter; return $this->entityFilter;
} }
/**
* Set the value of entityFilter.
*
* @param Entity $entityFilter
*/
public function setEntityFilter(?Entity $entityFilter): self public function setEntityFilter(?Entity $entityFilter): self
{ {
$this->entityFilter = $entityFilter; $this->entityFilter = $entityFilter;
@ -239,29 +140,15 @@ abstract class FilterAbstract extends SerializableAbstract
return $this; return $this;
} }
/**
* Get the value of fields.
*
* @return ?array
*/
public function getFields(): ?array public function getFields(): ?array
{ {
return $this->fields; return $this->fields;
} }
/**
* Set the value of fields.
*
* @param array $fields
*/
public function setFields(?array $fields): self public function setFields(?array $fields): self
{ {
$this->fields = $fields; $this->fields = $fields;
return $this; return $this;
} }
} }

View File

@ -2,37 +2,29 @@
namespace PandoraFMS\Modules\Shared\Core; namespace PandoraFMS\Modules\Shared\Core;
use JsonSerializable;
use PandoraFMS\Modules\Shared\Exceptions\BadRequestException; use PandoraFMS\Modules\Shared\Exceptions\BadRequestException;
use PandoraFMS\Modules\Shared\Exceptions\InvalidFilterException; use PandoraFMS\Modules\Shared\Exceptions\InvalidFilterException;
use JsonSerializable;
abstract class SerializableAbstract implements JsonSerializable abstract class SerializableAbstract implements JsonSerializable
{ {
public function __construct() public function __construct()
{ {
} }
abstract public function fieldsReadOnly(): array; abstract public function fieldsReadOnly(): array;
abstract public function jsonSerialize(): mixed; abstract public function jsonSerialize(): mixed;
abstract public function getValidations(): array; abstract public function getValidations(): array;
abstract public function validateFields(array $filters): array; abstract public function validateFields(array $filters): array;
public function toArray() public function toArray()
{ {
return $this->jsonSerialize(); return $this->jsonSerialize();
} }
public function validate(array $params): array public function validate(array $params): array
{ {
$filters = []; $filters = [];
@ -48,7 +40,6 @@ abstract class SerializableAbstract implements JsonSerializable
return $this->validateFields($filters); return $this->validateFields($filters);
} }
public function fromArray(array $params): static public function fromArray(array $params): static
{ {
$fails = $this->validate($params); $fails = $this->validate($params);
@ -72,6 +63,4 @@ abstract class SerializableAbstract implements JsonSerializable
return $this; return $this;
} }
} }

View File

@ -6,19 +6,19 @@ use OpenApi\Annotations as OA;
/** /**
* @OA\Info( * @OA\Info(
* title="Nueva API de Pandora FMS", * title="Nueva API de Pandora FMS",
* description="Nueva Api de pandora FMS", * description="Nueva Api de pandora FMS",
* termsOfService="https://example.com/terms/", * termsOfService="https://example.com/terms/",
* @OA\Contact( * @OA\Contact(
* name="Nombre del contacto", * name="Nombre del contacto",
* url="https://www.example.com/support", * url="https://www.example.com/support",
* email="contacto@example.com" * email="contacto@example.com"
* ), * ),
* @OA\License( * @OA\License(
* name="Apache 2.0", * name="Apache 2.0",
* url="https://www.apache.org/licenses/LICENSE-2.0.html" * url="https://www.apache.org/licenses/LICENSE-2.0.html"
* ), * ),
* version="0.0.1" * version="0.0.1"
* ), * ),
* @OA\Schemes( * @OA\Schemes(
* format="http" * format="http"
@ -56,7 +56,7 @@ use OpenApi\Annotations as OA;
* in="query", * in="query",
* description="page", * description="page",
* required=false, * required=false,
* @OA\Schema( * @OA\Schema(
* type="integer", * type="integer",
* default=0 * default=0
* ), * ),
@ -68,7 +68,7 @@ use OpenApi\Annotations as OA;
* in="query", * in="query",
* description="Size page", * description="Size page",
* required=false, * required=false,
* @OA\Schema( * @OA\Schema(
* type="integer", * type="integer",
* default=0 * default=0
* ), * ),
@ -80,7 +80,7 @@ use OpenApi\Annotations as OA;
* in="query", * in="query",
* description="sort field", * description="sort field",
* required=false, * required=false,
* @OA\Schema( * @OA\Schema(
* type="string", * type="string",
* default="" * default=""
* ), * ),
@ -92,7 +92,7 @@ use OpenApi\Annotations as OA;
* in="query", * in="query",
* description="sort direction", * description="sort direction",
* required=false, * required=false,
* @OA\Schema( * @OA\Schema(
* type="string", * type="string",
* enum={ * enum={
* "ascending", * "ascending",
@ -106,12 +106,12 @@ use OpenApi\Annotations as OA;
* response="BadRequest", * response="BadRequest",
* description="Bad request", * description="Bad request",
* content={ * content={
* @OA\MediaType( * @OA\MediaType(
* mediaType="application/json", * mediaType="application/json",
* @OA\Schema( * @OA\Schema(
* type="object", * type="object",
* description="Error", * description="Error",
* @OA\Property( * @OA\Property(
* property="error", * property="error",
* type="string", * type="string",
* default="Message error" * default="Message error"
@ -125,12 +125,12 @@ use OpenApi\Annotations as OA;
* response="Unauthorized", * response="Unauthorized",
* description="Unauthorized", * description="Unauthorized",
* content={ * content={
* @OA\MediaType( * @OA\MediaType(
* mediaType="application/json", * mediaType="application/json",
* @OA\Schema( * @OA\Schema(
* type="object", * type="object",
* description="Error", * description="Error",
* @OA\Property( * @OA\Property(
* property="error", * property="error",
* type="string", * type="string",
* default="Message error" * default="Message error"
@ -144,12 +144,12 @@ use OpenApi\Annotations as OA;
* response="Forbidden", * response="Forbidden",
* description="Forbidden", * description="Forbidden",
* content={ * content={
* @OA\MediaType( * @OA\MediaType(
* mediaType="application/json", * mediaType="application/json",
* @OA\Schema( * @OA\Schema(
* type="object", * type="object",
* description="Error", * description="Error",
* @OA\Property( * @OA\Property(
* property="error", * property="error",
* type="string", * type="string",
* default="Message error" * default="Message error"
@ -163,12 +163,12 @@ use OpenApi\Annotations as OA;
* response="NotFound", * response="NotFound",
* description="Not found", * description="Not found",
* content={ * content={
* @OA\MediaType( * @OA\MediaType(
* mediaType="application/json", * mediaType="application/json",
* @OA\Schema( * @OA\Schema(
* type="object", * type="object",
* description="Error", * description="Error",
* @OA\Property( * @OA\Property(
* property="error", * property="error",
* type="string", * type="string",
* default="Message error" * default="Message error"
@ -182,12 +182,12 @@ use OpenApi\Annotations as OA;
* response="InternalServerError", * response="InternalServerError",
* description="Internal server error", * description="Internal server error",
* content={ * content={
* @OA\MediaType( * @OA\MediaType(
* mediaType="application/json", * mediaType="application/json",
* @OA\Schema( * @OA\Schema(
* type="object", * type="object",
* description="Error", * description="Error",
* @OA\Property( * @OA\Property(
* property="error", * property="error",
* type="string", * type="string",
* default="Message error" * default="Message error"
@ -201,10 +201,10 @@ use OpenApi\Annotations as OA;
* response="successfullyDeleted", * response="successfullyDeleted",
* description="Successfully deleted", * description="Successfully deleted",
* content={ * content={
* @OA\MediaType( * @OA\MediaType(
* mediaType="application/json", * mediaType="application/json",
* @OA\Schema( * @OA\Schema(
* @OA\Property( * @OA\Property(
* property="result", * property="result",
* type="string", * type="string",
* default="Successfully deleted" * default="Successfully deleted"
@ -218,35 +218,35 @@ use OpenApi\Annotations as OA;
* schema="paginationData", * schema="paginationData",
* type="object", * type="object",
* description="Info pagination data", * description="Info pagination data",
* @OA\Property( * @OA\Property(
* property="totalPages", * property="totalPages",
* type="integer", * type="integer",
* nullable=true, * nullable=true,
* description="Number of pages", * description="Number of pages",
* readOnly=true * readOnly=true
* ), * ),
* @OA\Property( * @OA\Property(
* property="sizePage", * property="sizePage",
* type="integer", * type="integer",
* nullable=true, * nullable=true,
* description="Items per page", * description="Items per page",
* readOnly=true * readOnly=true
* ), * ),
* @OA\Property( * @OA\Property(
* property="totalRegisters", * property="totalRegisters",
* type="integer", * type="integer",
* nullable=true, * nullable=true,
* description="Number of items", * description="Number of items",
* readOnly=true * readOnly=true
* ), * ),
* @OA\Property( * @OA\Property(
* property="totalRegistersPage", * property="totalRegistersPage",
* type="integer", * type="integer",
* nullable=true, * nullable=true,
* description="Number of items this page", * description="Number of items this page",
* readOnly=true * readOnly=true
* ), * ),
* @OA\Property( * @OA\Property(
* property="currentPage", * property="currentPage",
* type="integer", * type="integer",
* nullable=true, * nullable=true,

View File

@ -6,20 +6,13 @@ use JsonSerializable;
class PaginationData implements JsonSerializable class PaginationData implements JsonSerializable
{ {
private ?int $totalPages = null; private ?int $totalPages = null;
private ?int $sizePage = null; private ?int $sizePage = null;
private ?int $currentPage = null; private ?int $currentPage = null;
private ?int $totalRegisters = null; private ?int $totalRegisters = null;
private ?int $totalRegistersPage = null; private ?int $totalRegistersPage = null;
private ?array $data = null; private ?array $data = null;
public function __construct( public function __construct(
$currentPage, $currentPage,
$sizePage, $sizePage,
@ -36,13 +29,11 @@ class PaginationData implements JsonSerializable
$this->setData($data); $this->setData($data);
} }
public function toArray() public function toArray()
{ {
return $this->jsonSerialize(); return $this->jsonSerialize();
} }
public function jsonSerialize(): mixed public function jsonSerialize(): mixed
{ {
return [ return [
@ -53,27 +44,15 @@ class PaginationData implements JsonSerializable
'totalRegisters' => $this->getTotalRegisters(), 'totalRegisters' => $this->getTotalRegisters(),
'totalRegistersPage' => $this->getTotalRegistersPage(), 'totalRegistersPage' => $this->getTotalRegistersPage(),
], ],
'data' => $this->getData(), 'data' => $this->getData(),
]; ];
} }
/**
* Get the value of totalPages.
*
* @return ?int
*/
public function getTotalPages(): ?int public function getTotalPages(): ?int
{ {
return $this->totalPages; return $this->totalPages;
} }
/**
* Set the value of totalPages.
*
* @param integer $totalPages
*/
public function setTotalPages(?int $totalPages): self public function setTotalPages(?int $totalPages): self
{ {
$this->totalPages = $totalPages; $this->totalPages = $totalPages;
@ -81,23 +60,11 @@ class PaginationData implements JsonSerializable
return $this; return $this;
} }
/**
* Get the value of sizePage.
*
* @return ?int
*/
public function getSizePage(): ?int public function getSizePage(): ?int
{ {
return $this->sizePage; return $this->sizePage;
} }
/**
* Set the value of sizePage.
*
* @param integer $sizePage
*/
public function setSizePage(?int $sizePage): self public function setSizePage(?int $sizePage): self
{ {
$this->sizePage = $sizePage; $this->sizePage = $sizePage;
@ -105,23 +72,11 @@ class PaginationData implements JsonSerializable
return $this; return $this;
} }
/**
* Get the value of currentPage.
*
* @return ?int
*/
public function getCurrentPage(): ?int public function getCurrentPage(): ?int
{ {
return $this->currentPage; return $this->currentPage;
} }
/**
* Set the value of currentPage.
*
* @param integer $currentPage
*/
public function setCurrentPage(?int $currentPage): self public function setCurrentPage(?int $currentPage): self
{ {
$this->currentPage = $currentPage; $this->currentPage = $currentPage;
@ -129,23 +84,11 @@ class PaginationData implements JsonSerializable
return $this; return $this;
} }
/**
* Get the value of totalRegisters.
*
* @return ?int
*/
public function getTotalRegisters(): ?int public function getTotalRegisters(): ?int
{ {
return $this->totalRegisters; return $this->totalRegisters;
} }
/**
* Set the value of totalRegisters.
*
* @param integer $totalRegisters
*/
public function setTotalRegisters(?int $totalRegisters): self public function setTotalRegisters(?int $totalRegisters): self
{ {
$this->totalRegisters = $totalRegisters; $this->totalRegisters = $totalRegisters;
@ -153,23 +96,11 @@ class PaginationData implements JsonSerializable
return $this; return $this;
} }
/**
* Get the value of totalRegistersPage.
*
* @return ?int
*/
public function getTotalRegistersPage(): ?int public function getTotalRegistersPage(): ?int
{ {
return $this->totalRegistersPage; return $this->totalRegistersPage;
} }
/**
* Set the value of totalRegistersPage.
*
* @param integer $totalRegistersPage
*/
public function setTotalRegistersPage(?int $totalRegistersPage): self public function setTotalRegistersPage(?int $totalRegistersPage): self
{ {
$this->totalRegistersPage = $totalRegistersPage; $this->totalRegistersPage = $totalRegistersPage;
@ -177,29 +108,15 @@ class PaginationData implements JsonSerializable
return $this; return $this;
} }
/**
* Get the value of data.
*
* @return ?array
*/
public function getData(): ?array public function getData(): ?array
{ {
return $this->data; return $this->data;
} }
/**
* Set the value of data.
*
* @param array $data
*/
public function setData(?array $data): self public function setData(?array $data): self
{ {
$this->data = $data; $this->data = $data;
return $this; return $this;
} }
} }

View File

@ -4,89 +4,67 @@ namespace PandoraFMS\Modules\Shared\Enums;
enum HttpCodesEnum: int enum HttpCodesEnum: int
{ {
public const CONTINUE = 100; public const CONTINUE = 100;
public const SWITCHING_PROTOCOLS = 101; public const SWITCHING_PROTOCOLS = 101;
public const PROCESSING = 102; public const PROCESSING = 102; // RFC2518
// RFC2518 public const EARLY_HINTS = 103; // RFC8297
public const EARLY_HINTS = 103; public const OK = 200;
// RFC8297 public const CREATED = 201;
public const OK = 200; public const ACCEPTED = 202;
public const CREATED = 201; public const NON_AUTHORITATIVE_INFORMATION = 203;
public const ACCEPTED = 202; public const NO_CONTENT = 204;
public const NON_AUTHORITATIVE_INFORMATION = 203; public const RESET_CONTENT = 205;
public const NO_CONTENT = 204; public const PARTIAL_CONTENT = 206;
public const RESET_CONTENT = 205; public const MULTI_STATUS = 207; // RFC4918
public const PARTIAL_CONTENT = 206; public const ALREADY_REPORTED = 208; // RFC5842
public const MULTI_STATUS = 207; public const IM_USED = 226; // RFC3229
// RFC4918 public const MULTIPLE_CHOICES = 300;
public const ALREADY_REPORTED = 208; public const MOVED_PERMANENTLY = 301;
// RFC5842 public const FOUND = 302;
public const IM_USED = 226; public const SEE_OTHER = 303;
// RFC3229 public const NOT_MODIFIED = 304;
public const MULTIPLE_CHOICES = 300; public const USE_PROXY = 305;
public const MOVED_PERMANENTLY = 301; public const RESERVED = 306;
public const FOUND = 302; public const TEMPORARY_REDIRECT = 307;
public const SEE_OTHER = 303; public const PERMANENTLY_REDIRECT = 308; // RFC7238
public const NOT_MODIFIED = 304; public const BAD_REQUEST = 400;
public const USE_PROXY = 305; public const UNAUTHORIZED = 401;
public const RESERVED = 306; public const PAYMENT_REQUIRED = 402;
public const TEMPORARY_REDIRECT = 307; public const FORBIDDEN = 403;
public const PERMANENTLY_REDIRECT = 308; public const NOT_FOUND = 404;
// RFC7238 public const METHOD_NOT_ALLOWED = 405;
public const BAD_REQUEST = 400; public const NOT_ACCEPTABLE = 406;
public const UNAUTHORIZED = 401; public const PROXY_AUTHENTICATION_REQUIRED = 407;
public const PAYMENT_REQUIRED = 402; public const REQUEST_TIMEOUT = 408;
public const FORBIDDEN = 403; public const CONFLICT = 409;
public const NOT_FOUND = 404; public const GONE = 410;
public const METHOD_NOT_ALLOWED = 405; public const LENGTH_REQUIRED = 411;
public const NOT_ACCEPTABLE = 406; public const PRECONDITION_FAILED = 412;
public const PROXY_AUTHENTICATION_REQUIRED = 407; public const REQUEST_ENTITY_TOO_LARGE = 413;
public const REQUEST_TIMEOUT = 408; public const REQUEST_URI_TOO_LONG = 414;
public const CONFLICT = 409; public const UNSUPPORTED_MEDIA_TYPE = 415;
public const GONE = 410; public const REQUESTED_RANGE_NOT_SATISFIABLE = 416;
public const LENGTH_REQUIRED = 411; public const EXPECTATION_FAILED = 417;
public const PRECONDITION_FAILED = 412; public const I_AM_A_TEAPOT = 418; // RFC2324
public const REQUEST_ENTITY_TOO_LARGE = 413; public const MISDIRECTED_REQUEST = 421; // RFC7540
public const REQUEST_URI_TOO_LONG = 414; public const UNPROCESSABLE_ENTITY = 422; // RFC4918
public const UNSUPPORTED_MEDIA_TYPE = 415; public const LOCKED = 423; // RFC4918
public const REQUESTED_RANGE_NOT_SATISFIABLE = 416; public const FAILED_DEPENDENCY = 424; // RFC4918
public const EXPECTATION_FAILED = 417; public const TOO_EARLY = 425; // RFC-ietf-httpbis-replay-04
public const I_AM_A_TEAPOT = 418; public const UPGRADE_REQUIRED = 426; // RFC2817
// RFC2324 public const PRECONDITION_REQUIRED = 428; // RFC6585
public const MISDIRECTED_REQUEST = 421; public const TOO_MANY_REQUESTS = 429; // RFC6585
// RFC7540 public const REQUEST_HEADER_FIELDS_TOO_LARGE = 431; // RFC6585
public const UNPROCESSABLE_ENTITY = 422; public const UNAVAILABLE_FOR_LEGAL_REASONS = 451; // RFC7725
// RFC4918 public const INTERNAL_SERVER_ERROR = 500;
public const LOCKED = 423; public const NOT_IMPLEMENTED = 501;
// RFC4918 public const BAD_GATEWAY = 502;
public const FAILED_DEPENDENCY = 424; public const SERVICE_UNAVAILABLE = 503;
// RFC4918 public const GATEWAY_TIMEOUT = 504;
public const TOO_EARLY = 425; public const VERSION_NOT_SUPPORTED = 505;
// RFC-ietf-httpbis-replay-04 public const VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506; // RFC2295
public const UPGRADE_REQUIRED = 426; public const INSUFFICIENT_STORAGE = 507; // RFC4918
// RFC2817 public const LOOP_DETECTED = 508; // RFC5842
public const PRECONDITION_REQUIRED = 428; public const NOT_EXTENDED = 510; // RFC2774
// RFC6585 public const NETWORK_AUTHENTICATION_REQUIRED = 511; // RFC6585
public const TOO_MANY_REQUESTS = 429;
// RFC6585
public const REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
// RFC6585
public const UNAVAILABLE_FOR_LEGAL_REASONS = 451;
// RFC7725
public const INTERNAL_SERVER_ERROR = 500;
public const NOT_IMPLEMENTED = 501;
public const BAD_GATEWAY = 502;
public const SERVICE_UNAVAILABLE = 503;
public const GATEWAY_TIMEOUT = 504;
public const VERSION_NOT_SUPPORTED = 505;
public const VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506;
// RFC2295
public const INSUFFICIENT_STORAGE = 507;
// RFC4918
public const LOOP_DETECTED = 508;
// RFC5842
public const NOT_EXTENDED = 510;
// RFC2774
public const NETWORK_AUTHENTICATION_REQUIRED = 511;
// RFC6585
} }

View File

@ -8,12 +8,12 @@ enum LanguagesEnum: string
{ {
use EnumTrait; use EnumTrait;
case CATALONIAN = 'ca'; case CATALONIAN = 'ca';
case ENGLISH = 'en_GB'; case ENGLISH = 'en_GB';
case SPANISH = 'es'; case SPANISH = 'es';
case FRENCH = 'fr'; case FRENCH = 'fr';
case JAPANESE = 'ja'; case JAPANESE = 'ja';
case RUSSIAN = 'ru'; case RUSSIAN = 'ru';
case CHINESE = 'zh_CN'; case CHINESE = 'zh_CN';
} }

View File

@ -7,12 +7,8 @@ use PandoraFMS\Modules\Shared\Enums\HttpCodesEnum;
class BadRequestException extends Exception class BadRequestException extends Exception
{ {
public function __construct(string $fails) public function __construct(string $fails)
{ {
parent::__construct($fails, HttpCodesEnum::BAD_REQUEST); parent::__construct($fails, HttpCodesEnum::BAD_REQUEST);
} }
} }

View File

@ -7,12 +7,8 @@ use PandoraFMS\Modules\Shared\Enums\HttpCodesEnum;
class ForbiddenACLException extends Exception class ForbiddenACLException extends Exception
{ {
public function __construct(string $fails) public function __construct(string $fails)
{ {
parent::__construct($fails, HttpCodesEnum::FORBIDDEN); parent::__construct($fails, HttpCodesEnum::FORBIDDEN);
} }
} }

View File

@ -6,12 +6,8 @@ use Exception;
class ForbiddenActionException extends Exception class ForbiddenActionException extends Exception
{ {
public function __construct(string $fails, int $httpCodesEnum) public function __construct(string $fails, int $httpCodesEnum)
{ {
parent::__construct($fails, $httpCodesEnum); parent::__construct($fails, $httpCodesEnum);
} }
} }

View File

@ -7,12 +7,8 @@ use PandoraFMS\Modules\Shared\Enums\HttpCodesEnum;
class InvalidClassException extends Exception class InvalidClassException extends Exception
{ {
public function __construct(string $fails) public function __construct(string $fails)
{ {
parent::__construct($fails, HttpCodesEnum::NOT_IMPLEMENTED); parent::__construct($fails, HttpCodesEnum::NOT_IMPLEMENTED);
} }
} }

View File

@ -7,8 +7,6 @@ use PandoraFMS\Modules\Shared\Enums\HttpCodesEnum;
class InvalidFilterException extends Exception class InvalidFilterException extends Exception
{ {
public function __construct(array $fails) public function __construct(array $fails)
{ {
$str = ''; $str = '';
@ -18,6 +16,4 @@ class InvalidFilterException extends Exception
parent::__construct(__($str), HttpCodesEnum::BAD_REQUEST); parent::__construct(__($str), HttpCodesEnum::BAD_REQUEST);
} }
} }

View File

@ -7,12 +7,8 @@ use PandoraFMS\Modules\Shared\Enums\HttpCodesEnum;
class NotFoundException extends Exception class NotFoundException extends Exception
{ {
public function __construct(string $fails) public function __construct(string $fails)
{ {
parent::__construct($fails, HttpCodesEnum::NOT_FOUND); parent::__construct($fails, HttpCodesEnum::NOT_FOUND);
} }
} }

View File

@ -11,8 +11,6 @@ use Psr\Http\Message\ServerRequestInterface as Request;
class UserTokenMiddleware class UserTokenMiddleware
{ {
public function __construct( public function __construct(
private readonly ValidateUserTokenService $validateUserTokenService, private readonly ValidateUserTokenService $validateUserTokenService,
private readonly GetUserTokenService $getUserTokenService, private readonly GetUserTokenService $getUserTokenService,
@ -21,7 +19,6 @@ class UserTokenMiddleware
) { ) {
} }
public function check(Request $request): bool public function check(Request $request): bool
{ {
global $config; global $config;
@ -66,6 +63,4 @@ class UserTokenMiddleware
return $token !== null && $validToken; return $token !== null && $validToken;
} }
} }

View File

@ -2,89 +2,70 @@
namespace PandoraFMS\Modules\Shared\Repositories; namespace PandoraFMS\Modules\Shared\Repositories;
use InvalidArgumentException;
use PandoraFMS\Modules\Shared\Core\DataMapperAbstract; use PandoraFMS\Modules\Shared\Core\DataMapperAbstract;
use PandoraFMS\Modules\Shared\Core\FilterAbstract; use PandoraFMS\Modules\Shared\Core\FilterAbstract;
use PandoraFMS\Modules\Shared\Entities\Entity; use PandoraFMS\Modules\Shared\Entities\Entity;
use PandoraFMS\Modules\Shared\Enums\HttpCodesEnum; use PandoraFMS\Modules\Shared\Enums\HttpCodesEnum;
use PandoraFMS\Modules\Shared\Exceptions\NotFoundException; use PandoraFMS\Modules\Shared\Exceptions\NotFoundException;
use InvalidArgumentException;
abstract class Repository abstract class Repository
{ {
abstract protected function dbGetRow( abstract protected function dbGetRow(
string $field, string $field,
string $table, string $table,
mixed $value mixed $value
): array; ): array;
abstract protected function dbGetValue( abstract protected function dbGetValue(
string $field, string $field,
string $table, string $table,
array $filters, array $filters,
string $whereJoin='AND' string $whereJoin = 'AND'
): mixed; ): mixed;
abstract protected function dbGetValueSql( abstract protected function dbGetValueSql(
string $sql, string $sql,
?bool $cache=false ?bool $cache = false
): string; ): string;
abstract protected function dbGetRowSql( abstract protected function dbGetRowSql(
string $sql string $sql
): array; ): array;
abstract protected function dbGetAllRowsSql( abstract protected function dbGetAllRowsSql(
string $sql, string $sql,
?bool $cache=false ?bool $cache = false
): array; ): array;
abstract protected function dbInsert(string $table, array $values): mixed; abstract protected function dbInsert(string $table, array $values): mixed;
abstract protected function dbUpdate(string $table, array $values, array $condition): mixed; abstract protected function dbUpdate(string $table, array $values, array $condition): mixed;
abstract protected function dbDelete(string $table, array $where): mixed; abstract protected function dbDelete(string $table, array $where): mixed;
abstract protected function dbFormatWhereClauseSQL(array $values, $prefix = ''): string;
abstract protected function dbFormatWhereClauseSQL(array $values, $prefix=''): string;
abstract public function buildQueryFilters(FilterAbstract $filter, DataMapperAbstract $mapper): string; abstract public function buildQueryFilters(FilterAbstract $filter, DataMapperAbstract $mapper): string;
abstract public function buildQueryPagination(FilterAbstract $filter): string; abstract public function buildQueryPagination(FilterAbstract $filter): string;
abstract public function buildQueryOrderBy(FilterAbstract $filter): string; abstract public function buildQueryOrderBy(FilterAbstract $filter): string;
abstract public function checkAclGroupMysql(string $field, ?string $mode = ''): string;
abstract public function checkAclGroupMysql(string $field, ?string $mode=''): string;
abstract public function buildQuery( abstract public function buildQuery(
FilterAbstract $filter, FilterAbstract $filter,
DataMapperAbstract $mapper, DataMapperAbstract $mapper,
bool $count=false bool $count = false
): string; ): string;
abstract public function maxFieldSql(string $field): string; abstract public function maxFieldSql(string $field): string;
abstract public function safeInput(?string $value): ?string; abstract public function safeInput(?string $value): ?string;
abstract public function safeOutput(?string $value): ?string; abstract public function safeOutput(?string $value): ?string;
/** /**
* @return object[], * @return object[],
*/ */
@ -113,7 +94,6 @@ abstract class Repository
return $result; return $result;
} }
public function __rows(FilterAbstract $filter, DataMapperAbstract $mapper): array public function __rows(FilterAbstract $filter, DataMapperAbstract $mapper): array
{ {
try { try {
@ -130,7 +110,6 @@ abstract class Repository
return $rows; return $rows;
} }
public function __count(FilterAbstract $filter, DataMapperAbstract $mapper): int public function __count(FilterAbstract $filter, DataMapperAbstract $mapper): int
{ {
$sql = $this->buildQuery($filter, $mapper, true); $sql = $this->buildQuery($filter, $mapper, true);
@ -147,7 +126,6 @@ abstract class Repository
return (int) $count; return (int) $count;
} }
public function __getOne(FilterAbstract $filter, DataMapperAbstract $mapper): object public function __getOne(FilterAbstract $filter, DataMapperAbstract $mapper): object
{ {
try { try {
@ -168,7 +146,6 @@ abstract class Repository
return $mapper->fromDatabase($result); return $mapper->fromDatabase($result);
} }
public function __create(Entity $entity, DataMapperAbstract $mapper): int public function __create(Entity $entity, DataMapperAbstract $mapper): int
{ {
try { try {
@ -198,7 +175,6 @@ abstract class Repository
return $id; return $id;
} }
public function __update(Entity $entity, DataMapperAbstract $mapper, mixed $id): object public function __update(Entity $entity, DataMapperAbstract $mapper, mixed $id): object
{ {
$values = $mapper->toDatabase($entity); $values = $mapper->toDatabase($entity);
@ -220,12 +196,11 @@ abstract class Repository
return $entity; return $entity;
} }
public function __delete( public function __delete(
mixed $id, mixed $id,
DataMapperAbstract $mapper, DataMapperAbstract $mapper,
?string $key=null, ?string $key = null,
?array $where=null ?array $where = null
): void { ): void {
try { try {
if (empty($key) === true) { if (empty($key) === true) {
@ -258,7 +233,6 @@ abstract class Repository
} }
} }
public function __getValue(FilterAbstract $filter, DataMapperAbstract $mapper): mixed public function __getValue(FilterAbstract $filter, DataMapperAbstract $mapper): mixed
{ {
try { try {
@ -275,11 +249,8 @@ abstract class Repository
return $result; return $result;
} }
public function __maxField(string $field): string public function __maxField(string $field): string
{ {
return $this->maxFieldSql($field); return $this->maxFieldSql($field);
} }
} }

View File

@ -9,8 +9,6 @@ use PandoraFMS\Modules\Shared\Services\Config;
class RepositoryMySQL extends Repository class RepositoryMySQL extends Repository
{ {
protected function dbGetRow( protected function dbGetRow(
string $field, string $field,
string $table, string $table,
@ -31,20 +29,18 @@ class RepositoryMySQL extends Repository
return $result; return $result;
} }
protected function dbGetValue( protected function dbGetValue(
string $field, string $field,
string $table, string $table,
array $filters, array $filters,
string $whereJoin='AND' string $whereJoin = 'AND'
): mixed { ): mixed {
return \db_get_value_filter($field, $table, $filters, $whereJoin); return \db_get_value_filter($field, $table, $filters, $whereJoin);
} }
protected function dbGetValueSql( protected function dbGetValueSql(
string $sql, string $sql,
?bool $cache=false ?bool $cache = false
): string { ): string {
ob_start(); ob_start();
$result = \db_get_value_sql($sql, $cache); $result = \db_get_value_sql($sql, $cache);
@ -61,7 +57,6 @@ class RepositoryMySQL extends Repository
return $result; return $result;
} }
protected function dbGetRowSql( protected function dbGetRowSql(
string $sql string $sql
): array { ): array {
@ -80,10 +75,9 @@ class RepositoryMySQL extends Repository
return $result; return $result;
} }
protected function dbGetAllRowsSql( protected function dbGetAllRowsSql(
string $sql, string $sql,
?bool $cache=false ?bool $cache = false
): array { ): array {
ob_start(); ob_start();
$result = \db_get_all_rows_sql($sql, $cache); $result = \db_get_all_rows_sql($sql, $cache);
@ -100,7 +94,6 @@ class RepositoryMySQL extends Repository
return $result; return $result;
} }
protected function dbInsert(string $table, array $values): mixed protected function dbInsert(string $table, array $values): mixed
{ {
ob_start(); ob_start();
@ -117,7 +110,6 @@ class RepositoryMySQL extends Repository
return $result; return $result;
} }
protected function dbUpdate(string $table, array $values, array $condition): mixed protected function dbUpdate(string $table, array $values, array $condition): mixed
{ {
ob_start(); ob_start();
@ -138,7 +130,6 @@ class RepositoryMySQL extends Repository
return $result; return $result;
} }
protected function dbDelete(string $table, array $where): mixed protected function dbDelete(string $table, array $where): mixed
{ {
ob_start(); ob_start();
@ -156,8 +147,7 @@ class RepositoryMySQL extends Repository
return $result; return $result;
} }
protected function dbFormatWhereClauseSQL(array $values, $prefix = ''): string
protected function dbFormatWhereClauseSQL(array $values, $prefix=''): string
{ {
ob_start(); ob_start();
$result = \db_format_array_where_clause_sql($values, 'AND', $prefix); $result = \db_format_array_where_clause_sql($values, 'AND', $prefix);
@ -169,7 +159,6 @@ class RepositoryMySQL extends Repository
return $result; return $result;
} }
public function buildQueryFilters(FilterAbstract $filter, DataMapperAbstract $mapper): string public function buildQueryFilters(FilterAbstract $filter, DataMapperAbstract $mapper): string
{ {
$where_clause = '1=1'; $where_clause = '1=1';
@ -206,7 +195,6 @@ class RepositoryMySQL extends Repository
return $where_clause; return $where_clause;
} }
private function freeSearch(array $fields, string $value): string private function freeSearch(array $fields, string $value): string
{ {
$clause = ' AND ('; $clause = ' AND (';
@ -224,7 +212,6 @@ class RepositoryMySQL extends Repository
return $clause; return $clause;
} }
private function multipleSearch(FilterAbstract $filter): string private function multipleSearch(FilterAbstract $filter): string
{ {
$fields = $filter->fieldsTranslate(); $fields = $filter->fieldsTranslate();
@ -241,7 +228,6 @@ class RepositoryMySQL extends Repository
return $clause; return $clause;
} }
private function multipleSearchString(FilterAbstract $filter): string private function multipleSearchString(FilterAbstract $filter): string
{ {
$fields = $filter->fieldsTranslate(); $fields = $filter->fieldsTranslate();
@ -258,7 +244,6 @@ class RepositoryMySQL extends Repository
return $clause; return $clause;
} }
public function buildQueryPagination(FilterAbstract $filter): string public function buildQueryPagination(FilterAbstract $filter): string
{ {
$filter->setLimit($filter->getSizePage()); $filter->setLimit($filter->getSizePage());
@ -276,7 +261,6 @@ class RepositoryMySQL extends Repository
return $sqlLimit; return $sqlLimit;
} }
public function buildQueryOrderBy(FilterAbstract $filter): string public function buildQueryOrderBy(FilterAbstract $filter): string
{ {
$default = ''; $default = '';
@ -307,7 +291,6 @@ class RepositoryMySQL extends Repository
return $return; return $return;
} }
public function buildQueryGroupBy(FilterAbstract $filter): string public function buildQueryGroupBy(FilterAbstract $filter): string
{ {
$groupBy = ''; $groupBy = '';
@ -330,7 +313,6 @@ class RepositoryMySQL extends Repository
return $groupBy; return $groupBy;
} }
private function checkDirectionOrderByMsql(?string $direction): string private function checkDirectionOrderByMsql(?string $direction): string
{ {
$directionArray = [ $directionArray = [
@ -341,8 +323,7 @@ class RepositoryMySQL extends Repository
return (isset($directionArray[$direction]) === true) ? $directionArray[$direction] : 'ASC'; return (isset($directionArray[$direction]) === true) ? $directionArray[$direction] : 'ASC';
} }
public function checkAclGroupMysql(string $field, ?string $mode = ''): string
public function checkAclGroupMysql(string $field, ?string $mode=''): string
{ {
$config = new Config(); $config = new Config();
$isAdmin = users_is_admin($config->get('id_user')); $isAdmin = users_is_admin($config->get('id_user'));
@ -351,7 +332,7 @@ class RepositoryMySQL extends Repository
} }
$userGroups = array_keys( $userGroups = array_keys(
\get_user_groups( \users_get_groups(
$config->get('id_user'), $config->get('id_user'),
'IM', 'IM',
true, true,
@ -390,11 +371,10 @@ class RepositoryMySQL extends Repository
return $filter; return $filter;
} }
public function buildQuery( public function buildQuery(
FilterAbstract $filter, FilterAbstract $filter,
DataMapperAbstract $mapper, DataMapperAbstract $mapper,
bool $count=false bool $count = false
): string { ): string {
$filters = $this->buildQueryFilters($filter, $mapper); $filters = $this->buildQueryFilters($filter, $mapper);
if (empty($mapper->getSearchFieldRelated()) === false) { if (empty($mapper->getSearchFieldRelated()) === false) {
@ -462,23 +442,18 @@ class RepositoryMySQL extends Repository
return $sql; return $sql;
} }
public function maxFieldSql(string $field): string public function maxFieldSql(string $field): string
{ {
return 'MAX('.$field.')'; return 'MAX('.$field.')';
} }
public function safeInput(?string $value): ?string public function safeInput(?string $value): ?string
{ {
return \io_safe_input($value); return \io_safe_input($value);
} }
public function safeOutput(?string $value): ?string public function safeOutput(?string $value): ?string
{ {
return \io_safe_output($value); return \io_safe_output($value);
} }
} }

View File

@ -4,18 +4,15 @@ namespace PandoraFMS\Modules\Shared\Services;
class Audit class Audit
{ {
public function __construct( public function __construct(
private Config $config, private Config $config,
) { ) {
} }
public function write( public function write(
string $action, string $action,
string $message='', string $message = '',
string $extra='' string $extra = ''
): void { ): void {
$idUser ??= $this->config->get('id_user'); $idUser ??= $this->config->get('id_user');
$remoteAddr ??= $this->config->get('REMOTE_ADDR'); $remoteAddr ??= $this->config->get('REMOTE_ADDR');
@ -27,6 +24,4 @@ class Audit
$extra $extra
); );
} }
} }

View File

@ -4,16 +4,12 @@ namespace PandoraFMS\Modules\Shared\Services;
final class Config final class Config
{ {
public function get(string $key, mixed $default = null): mixed
public function get(string $key, mixed $default=null): mixed
{ {
global $config; global $config;
return ($config[$key] ?? $default); return ($config[$key] ?? $default);
} }
public function set(string $key, mixed $value): bool public function set(string $key, mixed $value): bool
{ {
global $config; global $config;
@ -25,6 +21,4 @@ final class Config
return $res; return $res;
} }
} }

View File

@ -2,26 +2,23 @@
namespace PandoraFMS\Modules\Shared\Services; namespace PandoraFMS\Modules\Shared\Services;
use InvalidArgumentException;
use PandoraFMS\Modules\Shared\Enums\HttpCodesEnum; use PandoraFMS\Modules\Shared\Enums\HttpCodesEnum;
use PandoraFMS\Modules\Shared\Exceptions\BadRequestException; use PandoraFMS\Modules\Shared\Exceptions\BadRequestException;
use PandoraFMS\Modules\Shared\Exceptions\ForbiddenActionException; use PandoraFMS\Modules\Shared\Exceptions\ForbiddenActionException;
use InvalidArgumentException;
use Psr\Http\Message\UploadedFileInterface; use Psr\Http\Message\UploadedFileInterface;
class FileService class FileService
{ {
public function __construct( public function __construct(
private Config $config, private Config $config,
) { ) {
} }
public function moveUploadedFile( public function moveUploadedFile(
UploadedFileInterface $uploadedFile, UploadedFileInterface $uploadedFile,
?string $filename=null, ?string $filename = null,
?string $subdirectory='' ?string $subdirectory = ''
) { ) {
$directory = $this->config->get('attachment_directory'); $directory = $this->config->get('attachment_directory');
$extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION); $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
@ -50,7 +47,6 @@ class FileService
return $filename; return $filename;
} }
public function removeFile(string $filename) public function removeFile(string $filename)
{ {
$directory = $this->config->get('attachment_directory'); $directory = $this->config->get('attachment_directory');
@ -62,11 +58,10 @@ class FileService
} }
} }
public function validationFile( public function validationFile(
UploadedFileInterface $file, UploadedFileInterface $file,
string $regexInvalidExtension=null, string $regexInvalidExtension = null,
int $maxSize=null int $maxSize = null
): void { ): void {
if (empty($regexInvalidExtension) === true) { if (empty($regexInvalidExtension) === true) {
$regexInvalidExtension = '/^(bat|exe|cmd|sh|php|php1|php2|php3|php4|php5|pl|cgi|386|dll|com|torrent|js|app|jar|iso| $regexInvalidExtension = '/^(bat|exe|cmd|sh|php|php1|php2|php3|php4|php5|pl|cgi|386|dll|com|torrent|js|app|jar|iso|
@ -89,7 +84,6 @@ class FileService
} }
} }
private function calculateSizeBytes(int $maxSize) private function calculateSizeBytes(int $maxSize)
{ {
$max = ini_get('upload_max_filesize'); $max = ini_get('upload_max_filesize');
@ -99,6 +93,4 @@ class FileService
return ($maxSize * 1000000); return ($maxSize * 1000000);
} }
} }

View File

@ -4,17 +4,14 @@ namespace PandoraFMS\Modules\Shared\Services;
class Timestamp class Timestamp
{ {
public function __construct( public function __construct(
private Config $config private Config $config
) { ) {
} }
public function getMysqlCurrentTimestamp( public function getMysqlCurrentTimestamp(
int $unixtime, int $unixtime,
?string $format='Y-m-d H:i:s', ?string $format = 'Y-m-d H:i:s',
): string { ): string {
if ($unixtime == 0) { if ($unixtime == 0) {
$unixtime = time(); $unixtime = time();
@ -27,12 +24,9 @@ class Timestamp
return date($format, $unixtime); return date($format, $unixtime);
} }
public function getMysqlSystemUtimestamp(): int
public function getMysqlSystemUtimestamp() : int
{ {
$return = \mysql_get_system_time(); $return = \mysql_get_system_time();
return $return; return $return;
} }
} }

View File

@ -7,8 +7,6 @@ use PandoraFMS\Modules\Users\UserProfiles\Actions\GetUserProfileAction;
class ValidateAclSystem class ValidateAclSystem
{ {
public function __construct( public function __construct(
private Config $config, private Config $config,
private Audit $audit, private Audit $audit,
@ -16,11 +14,10 @@ class ValidateAclSystem
) { ) {
} }
public function validate( public function validate(
int $idGroup, int $idGroup,
string|array $permissions, string|array $permissions,
string $message='', string $message = '',
): void { ): void {
// ACL. // ACL.
$idUser ??= $this->config->get('id_user'); $idUser ??= $this->config->get('id_user');
@ -44,11 +41,10 @@ class ValidateAclSystem
} }
} }
public function validateUserGroups( public function validateUserGroups(
int|array|null $idGroup, int|array|null $idGroup,
string $permissions, string $permissions,
string $message='', string $message = '',
): void { ): void {
$idUser ??= $this->config->get('id_user'); $idUser ??= $this->config->get('id_user');
@ -73,13 +69,10 @@ class ValidateAclSystem
} }
} }
public function validateUserProfile( public function validateUserProfile(
int $idProfile int $idProfile
): void { ): void {
$idUser ??= $this->config->get('id_user'); $idUser ??= $this->config->get('id_user');
$this->getUserProfileAction->__invoke($idUser, $idProfile); $this->getUserProfileAction->__invoke($idUser, $idProfile);
} }
} }

View File

@ -4,11 +4,9 @@ namespace PandoraFMS\Modules\Shared\Traits;
trait EnumTrait trait EnumTrait
{ {
public static function get( public static function get(
mixed $value, mixed $value,
string $type='name' string $type = 'name'
): mixed { ): mixed {
$cases = static::cases(); $cases = static::cases();
$index = array_search($value, array_column($cases, $type)); $index = array_search($value, array_column($cases, $type));
@ -18,6 +16,4 @@ trait EnumTrait
return null; return null;
} }
} }

View File

@ -4,32 +4,17 @@ namespace PandoraFMS\Modules\Shared\Traits;
trait GroupByFilterTrait trait GroupByFilterTrait
{ {
private ?array $groupByFields = null; private ?array $groupByFields = null;
/**
* Get the value of groupByFields.
*
* @return ?array
*/
public function getGroupByFields(): ?array public function getGroupByFields(): ?array
{ {
return $this->groupByFields; return $this->groupByFields;
} }
/**
* Set the value of groupByFields.
*
* @param array $groupByFields
*/
public function setGroupByFields(?array $groupByFields): self public function setGroupByFields(?array $groupByFields): self
{ {
$this->groupByFields = $groupByFields; $this->groupByFields = $groupByFields;
return $this; return $this;
} }
} }

View File

@ -4,28 +4,14 @@ namespace PandoraFMS\Modules\Shared\Traits;
trait OrderFilterTrait trait OrderFilterTrait
{ {
private ?string $sortField = null; private ?string $sortField = null;
private ?string $sortDirection = null; private ?string $sortDirection = null;
/**
* Get the value of sortField.
*
* @return ?string
*/
public function getSortField(): ?string public function getSortField(): ?string
{ {
return $this->sortField; return $this->sortField;
} }
/**
* Set the value of sortField.
*
* @param string $sortField
*/
public function setSortField(?string $sortField): self public function setSortField(?string $sortField): self
{ {
$this->sortField = $sortField; $this->sortField = $sortField;
@ -33,29 +19,15 @@ trait OrderFilterTrait
return $this; return $this;
} }
/**
* Get the value of sortDirection.
*
* @return ?string
*/
public function getSortDirection(): ?string public function getSortDirection(): ?string
{ {
return $this->sortDirection; return $this->sortDirection;
} }
/**
* Set the value of sortDirection.
*
* @param string $sortDirection
*/
public function setSortDirection(?string $sortDirection): self public function setSortDirection(?string $sortDirection): self
{ {
$this->sortDirection = $sortDirection; $this->sortDirection = $sortDirection;
return $this; return $this;
} }
} }

View File

@ -4,28 +4,14 @@ namespace PandoraFMS\Modules\Shared\Traits;
trait PaginationFilterTrait trait PaginationFilterTrait
{ {
private ?int $sizePage = null; private ?int $sizePage = null;
private ?int $page = null; private ?int $page = null;
/**
* Get the value of sizePage.
*
* @return ?int
*/
public function getSizePage(): ?int public function getSizePage(): ?int
{ {
return $this->sizePage; return $this->sizePage;
} }
/**
* Set the value of sizePage.
*
* @param integer $sizePage
*/
public function setSizePage(?int $sizePage): self public function setSizePage(?int $sizePage): self
{ {
$this->sizePage = $sizePage; $this->sizePage = $sizePage;
@ -33,29 +19,15 @@ trait PaginationFilterTrait
return $this; return $this;
} }
/**
* Get the value of page.
*
* @return ?int
*/
public function getPage(): ?int public function getPage(): ?int
{ {
return $this->page; return $this->page;
} }
/**
* Set the value of page.
*
* @param integer $page
*/
public function setPage(?int $page): self public function setPage(?int $page): self
{ {
$this->page = $page; $this->page = $page;
return $this; return $this;
} }
} }

View File

@ -4,8 +4,6 @@ namespace PandoraFMS\Modules\Shared\Utils;
final class ArrayTools final class ArrayTools
{ {
public function extractFromObjectByAttribute(string $attribute, array $list): array public function extractFromObjectByAttribute(string $attribute, array $list): array
{ {
return array_reduce( return array_reduce(
@ -18,7 +16,6 @@ final class ArrayTools
); );
} }
public function indexObjectByAttribute(string $attribute, array $list): array public function indexObjectByAttribute(string $attribute, array $list): array
{ {
return array_reduce( return array_reduce(
@ -30,6 +27,4 @@ final class ArrayTools
[] []
); );
} }
} }

View File

@ -17,12 +17,10 @@ class Validator
public const LANGUAGE = 'Language'; public const LANGUAGE = 'Language';
public const MAIL = 'Mail'; public const MAIL = 'Mail';
public function __construct() public function __construct()
{ {
} }
public function validate(array $args): array public function validate(array $args): array
{ {
$failed = []; $failed = [];
@ -48,7 +46,6 @@ class Validator
return $failed; return $failed;
} }
private function buildError(string $type, string $field, $value): ?array private function buildError(string $type, string $field, $value): ?array
{ {
if ($this->{'is'.$type}($value) !== true) { if ($this->{'is'.$type}($value) !== true) {
@ -61,56 +58,47 @@ class Validator
return null; return null;
} }
public function isInteger($arg): bool public function isInteger($arg): bool
{ {
return is_numeric($arg); return is_numeric($arg);
} }
public function isGreaterThan($arg): bool public function isGreaterThan($arg): bool
{ {
return $arg > 0; return $arg > 0;
} }
public function isGreaterEqualThan($arg): bool public function isGreaterEqualThan($arg): bool
{ {
return $arg >= 0; return $arg >= 0;
} }
public function isBool($arg): bool public function isBool($arg): bool
{ {
return is_bool($arg); return is_bool($arg);
} }
public function isString($arg): bool public function isString($arg): bool
{ {
return is_string($arg) || is_numeric($arg); return is_string($arg) || is_numeric($arg);
} }
public function isArray($arg): bool public function isArray($arg): bool
{ {
return is_array($arg); return is_array($arg);
} }
public function isDateTime($date, $format = 'Y-m-d H:i:s')
public function isDateTime($date, $format='Y-m-d H:i:s')
{ {
$d = \DateTime::createFromFormat($format, $date); $d = \DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date; return $d && $d->format($format) == $date;
} }
public function isTimeZone(string $timeZone): string public function isTimeZone(string $timeZone): string
{ {
return array_search($timeZone, timezone_identifiers_list()); return array_search($timeZone, timezone_identifiers_list());
} }
protected function isLanguage(string $language): bool protected function isLanguage(string $language): bool
{ {
$result = LanguagesEnum::get(strtoupper($language)); $result = LanguagesEnum::get(strtoupper($language));
@ -118,11 +106,8 @@ class Validator
return empty($result) === true ? false : true; return empty($result) === true ? false : true;
} }
protected function isMail(string $mail): bool protected function isMail(string $mail): bool
{ {
return filter_var($mail, FILTER_VALIDATE_EMAIL); return filter_var($mail, FILTER_VALIDATE_EMAIL);
} }
} }

View File

@ -7,18 +7,13 @@ use PandoraFMS\Modules\Users\Services\CreateUserService;
final class CreateUserAction final class CreateUserAction
{ {
public function __construct( public function __construct(
private CreateUserService $createUserService private CreateUserService $createUserService
) { ) {
} }
public function __invoke(User $user): User public function __invoke(User $user): User
{ {
return $this->createUserService->__invoke($user); return $this->createUserService->__invoke($user);
} }
} }

View File

@ -7,18 +7,13 @@ use PandoraFMS\Modules\Users\Services\DeleteUserService;
final class DeleteUserAction final class DeleteUserAction
{ {
public function __construct( public function __construct(
private DeleteUserService $deleteUserService private DeleteUserService $deleteUserService
) { ) {
} }
public function __invoke(User $user): void public function __invoke(User $user): void
{ {
$this->deleteUserService->__invoke($user); $this->deleteUserService->__invoke($user);
} }
} }

View File

@ -7,18 +7,13 @@ use PandoraFMS\Modules\Users\Services\GetUserService;
final class GetUserAction final class GetUserAction
{ {
public function __construct( public function __construct(
private GetUserService $getUserService private GetUserService $getUserService
) { ) {
} }
public function __invoke(string $idUser): User public function __invoke(string $idUser): User
{ {
return $this->getUserService->__invoke($idUser); return $this->getUserService->__invoke($idUser);
} }
} }

View File

@ -2,23 +2,19 @@
namespace PandoraFMS\Modules\Users\Actions; namespace PandoraFMS\Modules\Users\Actions;
use PandoraFMS\Modules\Shared\Entities\PaginationData;
use PandoraFMS\Modules\Users\Entities\UserFilter; use PandoraFMS\Modules\Users\Entities\UserFilter;
use PandoraFMS\Modules\Users\Services\CountUserService; use PandoraFMS\Modules\Users\Services\CountUserService;
use PandoraFMS\Modules\Users\Services\ListUserService; use PandoraFMS\Modules\Users\Services\ListUserService;
use PandoraFMS\Modules\Shared\Entities\PaginationData;
final class ListUserAction final class ListUserAction
{ {
public function __construct( public function __construct(
private ListUserService $listUserService, private ListUserService $listUserService,
private CountUserService $countUserService private CountUserService $countUserService
) { ) {
} }
public function __invoke(UserFilter $userFilter): array public function __invoke(UserFilter $userFilter): array
{ {
return (new PaginationData( return (new PaginationData(
@ -28,6 +24,4 @@ final class ListUserAction
$this->listUserService->__invoke($userFilter) $this->listUserService->__invoke($userFilter)
))->toArray(); ))->toArray();
} }
} }

View File

@ -7,18 +7,13 @@ use PandoraFMS\Modules\Users\Services\UpdateUserService;
final class UpdateUserAction final class UpdateUserAction
{ {
public function __construct( public function __construct(
private UpdateUserService $updateUserService private UpdateUserService $updateUserService
) { ) {
} }
public function __invoke(User $user, User $oldUser): User public function __invoke(User $user, User $oldUser): User
{ {
return $this->updateUserService->__invoke($user, $oldUser); return $this->updateUserService->__invoke($user, $oldUser);
} }
} }

View File

@ -2,38 +2,35 @@
namespace PandoraFMS\Modules\Users\Controllers; namespace PandoraFMS\Modules\Users\Controllers;
use PandoraFMS\Modules\Users\Actions\CreateUserAction;
use PandoraFMS\Modules\Users\Entities\User;
use PandoraFMS\Modules\Shared\Controllers\Controller; use PandoraFMS\Modules\Shared\Controllers\Controller;
use PandoraFMS\Modules\Shared\Services\ValidateAclSystem; use PandoraFMS\Modules\Shared\Services\ValidateAclSystem;
use PandoraFMS\Modules\Users\Actions\CreateUserAction;
use PandoraFMS\Modules\Users\Entities\User;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
final class CreateUserController extends Controller final class CreateUserController extends Controller
{ {
public function __construct( public function __construct(
private CreateUserAction $createUserAction, private CreateUserAction $createUserAction,
private ValidateAclSystem $acl, private ValidateAclSystem $acl,
) { ) {
} }
/** /**
* @OA\Post( * @OA\Post(
* security={{ "bearerAuth": {}}}, * security={{ "bearerAuth": {}}},
* tags={"Users"}, * tags={"Users"},
* path="/user", * path="/user",
* summary="Creates a new users", * summary="Creates a new users",
* @OA\RequestBody(ref="#/components/requestBodies/requestBodyUser"), * @OA\RequestBody(ref="#/components/requestBodies/requestBodyUser"),
* @OA\Response(response=200, ref="#/components/responses/ResponseUser"), * @OA\Response(response=200, ref="#/components/responses/ResponseUser"),
* @OA\Response(response=400, ref="#/components/responses/BadRequest"), * @OA\Response(response=400, ref="#/components/responses/BadRequest"),
* @OA\Response(response=401, ref="#/components/responses/Unauthorized"), * @OA\Response(response=401, ref="#/components/responses/Unauthorized"),
* @OA\Response(response=403, ref="#/components/responses/Forbidden"), * @OA\Response(response=403, ref="#/components/responses/Forbidden"),
* @OA\Response(response=404, ref="#/components/responses/NotFound"), * @OA\Response(response=404, ref="#/components/responses/NotFound"),
* @OA\Response(response=500, ref="#/components/responses/InternalServerError") * @OA\Response(response=500, ref="#/components/responses/InternalServerError")
* ) * )
*/ */
public function __invoke(Request $request, Response $response): Response public function __invoke(Request $request, Response $response): Response
@ -47,6 +44,4 @@ final class CreateUserController extends Controller
return $this->getResponse($response, $result); return $this->getResponse($response, $result);
} }
} }

View File

@ -2,18 +2,16 @@
namespace PandoraFMS\Modules\Users\Controllers; namespace PandoraFMS\Modules\Users\Controllers;
use PandoraFMS\Modules\Users\Actions\DeleteUserAction;
use PandoraFMS\Modules\Users\Actions\GetUserAction;
use PandoraFMS\Modules\Shared\Controllers\Controller; use PandoraFMS\Modules\Shared\Controllers\Controller;
use PandoraFMS\Modules\Shared\Services\ValidateAclSystem; use PandoraFMS\Modules\Shared\Services\ValidateAclSystem;
use PandoraFMS\Modules\Users\Actions\DeleteUserAction;
use PandoraFMS\Modules\Users\Actions\GetUserAction;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
final class DeleteUserController extends Controller final class DeleteUserController extends Controller
{ {
public function __construct( public function __construct(
private DeleteUserAction $deleteUserAction, private DeleteUserAction $deleteUserAction,
private ValidateAclSystem $acl, private ValidateAclSystem $acl,
@ -21,20 +19,19 @@ final class DeleteUserController extends Controller
) { ) {
} }
/** /**
* @OA\Delete( * @OA\Delete(
* security={{ "bearerAuth": {}}}, * security={{ "bearerAuth": {}}},
* tags={"Users"}, * tags={"Users"},
* path="/user/{id}", * path="/user/{id}",
* summary="Deletes an user object.", * summary="Deletes an user object.",
* @OA\Parameter(ref="#/components/parameters/parameterIdUser"), * @OA\Parameter(ref="#/components/parameters/parameterIdUser"),
* @OA\Response(response=200, ref="#/components/responses/successfullyDeleted"), * @OA\Response(response=200, ref="#/components/responses/successfullyDeleted"),
* @OA\Response(response=400, ref="#/components/responses/BadRequest"), * @OA\Response(response=400, ref="#/components/responses/BadRequest"),
* @OA\Response(response=401, ref="#/components/responses/Unauthorized"), * @OA\Response(response=401, ref="#/components/responses/Unauthorized"),
* @OA\Response(response=403, ref="#/components/responses/Forbidden"), * @OA\Response(response=403, ref="#/components/responses/Forbidden"),
* @OA\Response(response=404, ref="#/components/responses/NotFound"), * @OA\Response(response=404, ref="#/components/responses/NotFound"),
* @OA\Response(response=500, ref="#/components/responses/InternalServerError") * @OA\Response(response=500, ref="#/components/responses/InternalServerError")
* ) * )
*/ */
public function __invoke(Request $request, Response $response): Response public function __invoke(Request $request, Response $response): Response
@ -47,6 +44,4 @@ final class DeleteUserController extends Controller
$result = $this->deleteUserAction->__invoke($user); $result = $this->deleteUserAction->__invoke($user);
return $this->getResponse($response, $result); return $this->getResponse($response, $result);
} }
} }

View File

@ -2,37 +2,34 @@
namespace PandoraFMS\Modules\Users\Controllers; namespace PandoraFMS\Modules\Users\Controllers;
use PandoraFMS\Modules\Users\Actions\GetUserAction;
use PandoraFMS\Modules\Shared\Controllers\Controller; use PandoraFMS\Modules\Shared\Controllers\Controller;
use PandoraFMS\Modules\Shared\Services\ValidateAclSystem; use PandoraFMS\Modules\Shared\Services\ValidateAclSystem;
use PandoraFMS\Modules\Users\Actions\GetUserAction;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
final class GetUserController extends Controller final class GetUserController extends Controller
{ {
public function __construct( public function __construct(
private GetUserAction $getUserAction, private GetUserAction $getUserAction,
private ValidateAclSystem $acl private ValidateAclSystem $acl
) { ) {
} }
/** /**
* @OA\Get( * @OA\Get(
* security={{ "bearerAuth": {}}}, * security={{ "bearerAuth": {}}},
* path="/user/{id}", * path="/user/{id}",
* tags={"Users"}, * tags={"Users"},
* summary="show users", * summary="show users",
* @OA\Parameter(ref="#/components/parameters/parameterIdUser"), * @OA\Parameter(ref="#/components/parameters/parameterIdUser"),
* @OA\Response(response=200, ref="#/components/responses/ResponseUser"), * @OA\Response(response=200, ref="#/components/responses/ResponseUser"),
* @OA\Response(response=400, ref="#/components/responses/BadRequest"), * @OA\Response(response=400, ref="#/components/responses/BadRequest"),
* @OA\Response(response=401, ref="#/components/responses/Unauthorized"), * @OA\Response(response=401, ref="#/components/responses/Unauthorized"),
* @OA\Response(response=403, ref="#/components/responses/Forbidden"), * @OA\Response(response=403, ref="#/components/responses/Forbidden"),
* @OA\Response(response=404, ref="#/components/responses/NotFound"), * @OA\Response(response=404, ref="#/components/responses/NotFound"),
* @OA\Response(response=500, ref="#/components/responses/InternalServerError") * @OA\Response(response=500, ref="#/components/responses/InternalServerError")
* ) * )
*/ */
public function __invoke(Request $request, Response $response): Response public function __invoke(Request $request, Response $response): Response
@ -41,6 +38,4 @@ final class GetUserController extends Controller
$result = $this->getUserAction->__invoke($idUser); $result = $this->getUserAction->__invoke($idUser);
return $this->getResponse($response, $result); return $this->getResponse($response, $result);
} }
} }

View File

@ -2,66 +2,63 @@
namespace PandoraFMS\Modules\Users\Controllers; namespace PandoraFMS\Modules\Users\Controllers;
use PandoraFMS\Modules\Users\Actions\ListUserAction;
use PandoraFMS\Modules\Users\Entities\UserFilter;
use PandoraFMS\Modules\Shared\Controllers\Controller; use PandoraFMS\Modules\Shared\Controllers\Controller;
use PandoraFMS\Modules\Shared\Services\ValidateAclSystem; use PandoraFMS\Modules\Shared\Services\ValidateAclSystem;
use PandoraFMS\Modules\Users\Actions\ListUserAction;
use PandoraFMS\Modules\Users\Entities\UserFilter;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
final class ListUserController extends Controller final class ListUserController extends Controller
{ {
public function __construct( public function __construct(
private ListUserAction $listUserAction, private ListUserAction $listUserAction,
private ValidateAclSystem $acl, private ValidateAclSystem $acl,
) { ) {
} }
/** /**
* @OA\Post( * @OA\Post(
* security={{ "bearerAuth": {}}}, * security={{ "bearerAuth": {}}},
* tags={"Users"}, * tags={"Users"},
* path="/user/list", * path="/user/list",
* summary="List user", * summary="List user",
* @OA\Parameter(ref="#/components/parameters/parameterPage"), * @OA\Parameter(ref="#/components/parameters/parameterPage"),
* @OA\Parameter(ref="#/components/parameters/parameterSizePage"), * @OA\Parameter(ref="#/components/parameters/parameterSizePage"),
* @OA\Parameter(ref="#/components/parameters/parameterSortField"), * @OA\Parameter(ref="#/components/parameters/parameterSortField"),
* @OA\Parameter(ref="#/components/parameters/parameterSortDirection"), * @OA\Parameter(ref="#/components/parameters/parameterSortDirection"),
* @OA\RequestBody(ref="#/components/requestBodies/requestBodyUserFilter"), * @OA\RequestBody(ref="#/components/requestBodies/requestBodyUserFilter"),
* @OA\Response( * @OA\Response(
* response="200", * response="200",
* description="List Incidence object", * description="List Incidence object",
* content={ * content={
* @OA\MediaType( * @OA\MediaType(
* mediaType="application/json", * mediaType="application/json",
* @OA\Schema( * @OA\Schema(
* @OA\Property( * @OA\Property(
* property="paginationData", * property="paginationData",
* type="object", * type="object",
* ref="#/components/schemas/paginationData", * ref="#/components/schemas/paginationData",
* description="Page object", * description="Page object",
* ), * ),
* @OA\Property( * @OA\Property(
* property="data", * property="data",
* type="array", * type="array",
* @OA\Items( * @OA\Items(
* ref="#/components/schemas/User", * ref="#/components/schemas/User",
* description="Array of user objects" * description="Array of user objects"
* ) * )
* ), * ),
* ), * ),
* ) * )
* } * }
* ), * ),
* @OA\Response(response=400, ref="#/components/responses/BadRequest"), * @OA\Response(response=400, ref="#/components/responses/BadRequest"),
* @OA\Response(response=401, ref="#/components/responses/Unauthorized"), * @OA\Response(response=401, ref="#/components/responses/Unauthorized"),
* @OA\Response(response=403, ref="#/components/responses/Forbidden"), * @OA\Response(response=403, ref="#/components/responses/Forbidden"),
* @OA\Response(response=404, ref="#/components/responses/NotFound"), * @OA\Response(response=404, ref="#/components/responses/NotFound"),
* @OA\Response(response=500, ref="#/components/responses/InternalServerError") * @OA\Response(response=500, ref="#/components/responses/InternalServerError")
* ) * )
*/ */
public function __invoke(Request $request, Response $response): Response public function __invoke(Request $request, Response $response): Response
@ -73,6 +70,4 @@ final class ListUserController extends Controller
return $this->getResponse($response, $result); return $this->getResponse($response, $result);
} }
} }

View File

@ -2,11 +2,10 @@
namespace PandoraFMS\Modules\Users\Controllers; namespace PandoraFMS\Modules\Users\Controllers;
use PandoraFMS\Modules\Shared\Controllers\Controller;
use PandoraFMS\Modules\Shared\Services\ValidateAclSystem;
use PandoraFMS\Modules\Users\Actions\GetUserAction; use PandoraFMS\Modules\Users\Actions\GetUserAction;
use PandoraFMS\Modules\Users\Actions\UpdateUserAction; use PandoraFMS\Modules\Users\Actions\UpdateUserAction;
use PandoraFMS\Modules\Shared\Controllers\Controller;
use PandoraFMS\Modules\Shared\Services\ValidateAclSystem;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -19,18 +18,16 @@ use Psr\Http\Message\ServerRequestInterface as Request;
* summary="Updates an user", * summary="Updates an user",
* @OA\Parameter(ref="#/components/parameters/parameterIdUser"), * @OA\Parameter(ref="#/components/parameters/parameterIdUser"),
* @OA\RequestBody(ref="#/components/requestBodies/requestBodyUser"), * @OA\RequestBody(ref="#/components/requestBodies/requestBodyUser"),
* @OA\Response(response=200, ref="#/components/responses/ResponseUser"), * @OA\Response(response=200, ref="#/components/responses/ResponseUser"),
* @OA\Response(response=400, ref="#/components/responses/BadRequest"), * @OA\Response(response=400, ref="#/components/responses/BadRequest"),
* @OA\Response(response=401, ref="#/components/responses/Unauthorized"), * @OA\Response(response=401, ref="#/components/responses/Unauthorized"),
* @OA\Response(response=403, ref="#/components/responses/Forbidden"), * @OA\Response(response=403, ref="#/components/responses/Forbidden"),
* @OA\Response(response=404, ref="#/components/responses/NotFound"), * @OA\Response(response=404, ref="#/components/responses/NotFound"),
* @OA\Response(response=500, ref="#/components/responses/InternalServerError") * @OA\Response(response=500, ref="#/components/responses/InternalServerError")
* ) * )
*/ */
final class UpdateUserController extends Controller final class UpdateUserController extends Controller
{ {
public function __construct( public function __construct(
private UpdateUserAction $updateUserAction, private UpdateUserAction $updateUserAction,
private ValidateAclSystem $acl, private ValidateAclSystem $acl,
@ -38,7 +35,6 @@ final class UpdateUserController extends Controller
) { ) {
} }
public function __invoke(Request $request, Response $response): Response public function __invoke(Request $request, Response $response): Response
{ {
$idUser = $this->getParam($request, 'id'); $idUser = $this->getParam($request, 'id');
@ -53,6 +49,4 @@ final class UpdateUserController extends Controller
$result = $this->updateUserAction->__invoke($user, $oldUser); $result = $this->updateUserAction->__invoke($user, $oldUser);
return $this->getResponse($response, $result); return $this->getResponse($response, $result);
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -145,12 +145,11 @@ final class UserDataMapper extends DataMapperAbstract
); );
} }
/**
* @param User $data
*/
public function toDatabase(MappeableInterface $data): array public function toDatabase(MappeableInterface $data): array
{ {
/*
@var User $data
*/
return [ return [
self::ID_USER => $data->getIdUser(), self::ID_USER => $data->getIdUser(),
self::FULLNAME => $this->repository->safeInput($data->getFullName()), self::FULLNAME => $this->repository->safeInput($data->getFullName()),

View File

@ -41,12 +41,9 @@ use PandoraFMS\Modules\Users\Validators\UserValidator;
*/ */
final class UserFilter extends FilterAbstract final class UserFilter extends FilterAbstract
{ {
private ?string $freeSearch = null; private ?string $freeSearch = null;
private ?array $multipleSearchString = null; private ?array $multipleSearchString = null;
public function __construct() public function __construct()
{ {
$this->setDefaultFieldOrder(UserDataMapper::ID_USER); $this->setDefaultFieldOrder(UserDataMapper::ID_USER);
@ -54,7 +51,6 @@ final class UserFilter extends FilterAbstract
$this->setEntityFilter(new User()); $this->setEntityFilter(new User());
} }
public function fieldsTranslate(): array public function fieldsTranslate(): array
{ {
return [ return [
@ -63,13 +59,11 @@ final class UserFilter extends FilterAbstract
]; ];
} }
public function fieldsReadOnly(): array public function fieldsReadOnly(): array
{ {
return []; return [];
} }
public function jsonSerialize(): mixed public function jsonSerialize(): mixed
{ {
return [ return [
@ -77,7 +71,6 @@ final class UserFilter extends FilterAbstract
]; ];
} }
public function getValidations(): array public function getValidations(): array
{ {
$validations = []; $validations = [];
@ -89,13 +82,11 @@ final class UserFilter extends FilterAbstract
return $validations; return $validations;
} }
public function validateFields(array $filters): array public function validateFields(array $filters): array
{ {
return (new UserValidator())->validate($filters); return (new UserValidator())->validate($filters);
} }
/** /**
* Get the value of freeSearch. * Get the value of freeSearch.
* *
@ -106,11 +97,10 @@ final class UserFilter extends FilterAbstract
return $this->freeSearch; return $this->freeSearch;
} }
/** /**
* Set the value of freeSearch. * Set the value of freeSearch.
* *
* @param string $freeSearch * @param ?string $freeSearch
*/ */
public function setFreeSearch(?string $freeSearch): self public function setFreeSearch(?string $freeSearch): self
{ {
@ -118,7 +108,6 @@ final class UserFilter extends FilterAbstract
return $this; return $this;
} }
/** /**
* Get the value of fieldsFreeSearch. * Get the value of fieldsFreeSearch.
* *
@ -132,7 +121,6 @@ final class UserFilter extends FilterAbstract
]; ];
} }
/** /**
* Get the value of multipleSearchString. * Get the value of multipleSearchString.
* *
@ -143,17 +131,14 @@ final class UserFilter extends FilterAbstract
return $this->multipleSearchString; return $this->multipleSearchString;
} }
/** /**
* Set the value of multipleSearchString. * Set the value of multipleSearchString.
* *
* @param array $multipleSearchString * @param ?array $multipleSearchString
*/ */
public function setMultipleSearchString(?array $multipleSearchString): self public function setMultipleSearchString(?array $multipleSearchString): self
{ {
$this->multipleSearchString = $multipleSearchString; $this->multipleSearchString = $multipleSearchString;
return $this; return $this;
} }
} }

View File

@ -8,19 +8,19 @@ enum UserAutoRefreshPagesEnum: string
{ {
use EnumTrait; use EnumTrait;
case AGENT_DETAIL = 'operation/agentes/estado_agente'; case AGENT_DETAIL = 'operation/agentes/estado_agente';
case ALERT_DETAIL = 'operation/agentes/alerts_status'; case ALERT_DETAIL = 'operation/agentes/alerts_status';
case CLUSTER_VIEW = 'enterprise/operation/cluster/cluster'; case CLUSTER_VIEW = 'enterprise/operation/cluster/cluster';
case GIS_MAP = 'operation/gis_maps/render_view'; case GIS_MAP = 'operation/gis_maps/render_view';
case GRAPH_VIEWER = 'operation/reporting/graph_viewer'; case GRAPH_VIEWER = 'operation/reporting/graph_viewer';
case SNMP_CONSOLE = 'operation/snmpconsole/snmp_view'; case SNMP_CONSOLE = 'operation/snmpconsole/snmp_view';
case SAP_VIEW = 'general/sap_view'; case SAP_VIEW = 'general/sap_view';
case TACTICAL_VIEW = 'operation/agentes/tactical'; case TACTICAL_VIEW = 'operation/agentes/tactical';
case GROUP_VIEW = 'operation/agentes/group_view'; case GROUP_VIEW = 'operation/agentes/group_view';
case MONITOR_DETAIL = 'operation/agentes/status_monitor'; case MONITOR_DETAIL = 'operation/agentes/status_monitor';
case SERVICES = 'enterprise/operation/services/services'; case SERVICES = 'enterprise/operation/services/services';
case DASHBOARD = 'operation/dashboard/dashboard'; case DASHBOARD = 'operation/dashboard/dashboard';
case VISUAL_CONSOLE = 'operation/visual_console/render_view'; case VISUAL_CONSOLE = 'operation/visual_console/render_view';
case EVENTS = 'operation/events/events'; case EVENTS = 'operation/events/events';
} }

View File

@ -8,14 +8,14 @@ enum UserHomeScreenEnum: string
{ {
use EnumTrait; use EnumTrait;
case default = 'default'; case DEFAULT = 'default';
case VISUAL_CONSOLE = 'visual_console'; case VISUAL_CONSOLE = 'visual_console';
case EVENT_LIST = 'event_list'; case EVENT_LIST = 'event_list';
case GROUP_VIEW = 'group_view'; case GROUP_VIEW = 'group_view';
case TACTICAL_VIEW = 'tactical_view'; case TACTICAL_VIEW = 'tactical_view';
case ALERT_DETAIL = 'alert_detail'; case ALERT_DETAIL = 'alert_detail';
case EXTERNAL_LINK = 'external_link'; case EXTERNAL_LINK = 'external_link';
case OTHER = 'other'; case OTHER = 'other';
case DASHBOARD = 'dashboard'; case DASHBOARD = 'dashboard';
} }

View File

@ -8,6 +8,6 @@ enum UserMetaconsoleAccessEnum: string
{ {
use EnumTrait; use EnumTrait;
case BASIC = 'basic'; case BASIC = 'basic';
case ADVANCED = 'advanced'; case ADVANCED = 'advanced';
} }

View File

@ -7,27 +7,18 @@ use PandoraFMS\Modules\Users\Entities\UserFilter;
interface UserRepository interface UserRepository
{ {
/** /**
* @return User[], * @return User[],
*/ */
public function list(UserFilter $userFilter): array; public function list(UserFilter $userFilter): array;
public function count(UserFilter $userFilter): int; public function count(UserFilter $userFilter): int;
public function getOne(UserFilter $userFilter): User; public function getOne(UserFilter $userFilter): User;
public function create(User $user): User; public function create(User $user): User;
public function update(User $user): User; public function update(User $user): User;
public function delete(string $id): void; public function delete(string $id): void;
} }

View File

@ -2,28 +2,23 @@
namespace PandoraFMS\Modules\Users\Repositories; namespace PandoraFMS\Modules\Users\Repositories;
use InvalidArgumentException;
use PandoraFMS\Modules\Shared\Core\DataMapperAbstract; use PandoraFMS\Modules\Shared\Core\DataMapperAbstract;
use PandoraFMS\Modules\Shared\Core\FilterAbstract; use PandoraFMS\Modules\Shared\Core\FilterAbstract;
use PandoraFMS\Modules\Shared\Enums\HttpCodesEnum; use PandoraFMS\Modules\Shared\Enums\HttpCodesEnum;
use PandoraFMS\Modules\Shared\Exceptions\NotFoundException; use PandoraFMS\Modules\Shared\Exceptions\NotFoundException;
use PandoraFMS\Modules\Shared\Repositories\RepositoryMySQL; use PandoraFMS\Modules\Shared\Repositories\RepositoryMySQL;
use PandoraFMS\Modules\Shared\Services\Config;
use PandoraFMS\Modules\Users\Entities\User; use PandoraFMS\Modules\Users\Entities\User;
use PandoraFMS\Modules\Users\Entities\UserDataMapper; use PandoraFMS\Modules\Users\Entities\UserDataMapper;
use PandoraFMS\Modules\Users\Entities\UserFilter; use PandoraFMS\Modules\Users\Entities\UserFilter;
use PandoraFMS\Modules\Users\Enums\UserLevelEnum;
use InvalidArgumentException;
class UserRepositoryMySQL extends RepositoryMySQL implements UserRepository class UserRepositoryMySQL extends RepositoryMySQL implements UserRepository
{ {
public function __construct( public function __construct(
private UserDataMapper $userDataMapper private UserDataMapper $userDataMapper
) { ) {
} }
/** /**
* @return User[], * @return User[],
*/ */
@ -52,7 +47,6 @@ class UserRepositoryMySQL extends RepositoryMySQL implements UserRepository
return $result; return $result;
} }
public function count(UserFilter $userFilter): int public function count(UserFilter $userFilter): int
{ {
$sql = $this->getUsersQuery($userFilter, $this->userDataMapper, true); $sql = $this->getUsersQuery($userFilter, $this->userDataMapper, true);
@ -69,7 +63,6 @@ class UserRepositoryMySQL extends RepositoryMySQL implements UserRepository
return (int) $count; return (int) $count;
} }
public function getOne(UserFilter $userFilter): User public function getOne(UserFilter $userFilter): User
{ {
try { try {
@ -90,14 +83,12 @@ class UserRepositoryMySQL extends RepositoryMySQL implements UserRepository
return $this->userDataMapper->fromDatabase($result); return $this->userDataMapper->fromDatabase($result);
} }
public function create(User $user): User public function create(User $user): User
{ {
$this->__create($user, $this->userDataMapper); $this->__create($user, $this->userDataMapper);
return $user; return $user;
} }
public function update(User $user): User public function update(User $user): User
{ {
return $this->__update( return $this->__update(
@ -107,17 +98,15 @@ class UserRepositoryMySQL extends RepositoryMySQL implements UserRepository
); );
} }
public function delete(string $id): void public function delete(string $id): void
{ {
$this->__delete($id, $this->userDataMapper); $this->__delete($id, $this->userDataMapper);
} }
private function getUsersQuery( private function getUsersQuery(
FilterAbstract $filter, FilterAbstract $filter,
DataMapperAbstract $mapper, DataMapperAbstract $mapper,
bool $count=false bool $count = false
): string { ): string {
$pagination = ''; $pagination = '';
$orderBy = ''; $orderBy = '';
@ -159,6 +148,4 @@ class UserRepositoryMySQL extends RepositoryMySQL implements UserRepository
return $sql; return $sql;
} }
} }

View File

@ -20,8 +20,13 @@ final class CheckOldPasswordUserService
public function __invoke(User $user): void public function __invoke(User $user): void
{ {
$userFilter = new UserFilter(); $userFilter = new UserFilter();
$userFilter->setIdUser($user->getIdUser()); /**
$userFilter->setPassword($user->getOldPassword()); @var User $entityFilter
*/
$entityFilter = $userFilter->getEntityFilter();
$entityFilter->setIdUser($user->getIdUser());
$entityFilter->setPassword($user->getOldPassword());
try { try {
$this->repository->__getOne( $this->repository->__getOne(
$userFilter, $userFilter,

View File

@ -7,18 +7,13 @@ use PandoraFMS\Modules\Users\Repositories\UserRepository;
final class CountUserService final class CountUserService
{ {
public function __construct( public function __construct(
private UserRepository $userRepository, private UserRepository $userRepository,
) { ) {
} }
public function __invoke(UserFilter $userFilter): int public function __invoke(UserFilter $userFilter): int
{ {
return $this->userRepository->count($userFilter); return $this->userRepository->count($userFilter);
} }
} }

View File

@ -2,15 +2,13 @@
namespace PandoraFMS\Modules\Users\Services; namespace PandoraFMS\Modules\Users\Services;
use PandoraFMS\Modules\Shared\Services\Audit;
use PandoraFMS\Modules\Users\Entities\User; use PandoraFMS\Modules\Users\Entities\User;
use PandoraFMS\Modules\Users\Repositories\UserRepository; use PandoraFMS\Modules\Users\Repositories\UserRepository;
use PandoraFMS\Modules\Users\Validations\UserValidation; use PandoraFMS\Modules\Users\Validations\UserValidation;
use PandoraFMS\Modules\Shared\Services\Audit;
final class CreateUserService final class CreateUserService
{ {
public function __construct( public function __construct(
private Audit $audit, private Audit $audit,
private UserRepository $userRepository, private UserRepository $userRepository,
@ -18,7 +16,6 @@ final class CreateUserService
) { ) {
} }
public function __invoke(User $user): User public function __invoke(User $user): User
{ {
$this->userValidation->__invoke($user); $this->userValidation->__invoke($user);
@ -36,6 +33,4 @@ final class CreateUserService
return $user; return $user;
} }
} }

View File

@ -2,22 +2,19 @@
namespace PandoraFMS\Modules\Users\Services; namespace PandoraFMS\Modules\Users\Services;
use PandoraFMS\Modules\Users\Entities\User;
use PandoraFMS\Modules\Users\Repositories\UserRepository;
use PandoraFMS\Modules\Shared\Services\Audit; use PandoraFMS\Modules\Shared\Services\Audit;
use PandoraFMS\Modules\Users\Entities\User;
use PandoraFMS\Modules\Users\Repositories\UserRepository;
final class DeleteUserService final class DeleteUserService
{ {
public function __construct( public function __construct(
private Audit $audit, private Audit $audit,
private UserRepository $userRepository, private UserRepository $userRepository,
) { ) {
} }
public function __invoke(User $user): void public function __invoke(User $user): void
{ {
$idUser = $user->getIdUser(); $idUser = $user->getIdUser();
@ -29,6 +26,4 @@ final class DeleteUserService
' Deleted user #'.$idUser ' Deleted user #'.$idUser
); );
} }
} }

View File

@ -5,23 +5,19 @@ namespace PandoraFMS\Modules\Users\Services;
use PandoraFMS\Modules\Users\Entities\User; use PandoraFMS\Modules\Users\Entities\User;
use PandoraFMS\Modules\Users\Entities\UserFilter; use PandoraFMS\Modules\Users\Entities\UserFilter;
use PandoraFMS\Modules\Users\Repositories\UserRepository; use PandoraFMS\Modules\Users\Repositories\UserRepository;
use PandoraFMS\Modules\Users\UserProfiles\Entities\UserProfileDataMapper;
final class GetUserService final class GetUserService
{ {
public function __construct( public function __construct(
private UserRepository $userRepository, private UserRepository $userRepository,
) { ) {
} }
public function __invoke(string $idUser): User public function __invoke(string $idUser): User
{ {
$userFilter = new UserFilter(); $userFilter = new UserFilter();
/* /**
@var User $entityFilter @var User $entityFilter
*/ */
$entityFilter = $userFilter->getEntityFilter(); $entityFilter = $userFilter->getEntityFilter();
@ -29,6 +25,4 @@ final class GetUserService
return $this->userRepository->getOne($userFilter); return $this->userRepository->getOne($userFilter);
} }
} }

View File

@ -7,18 +7,13 @@ use PandoraFMS\Modules\Users\Repositories\UserRepository;
final class ListUserService final class ListUserService
{ {
public function __construct( public function __construct(
private UserRepository $userRepository, private UserRepository $userRepository,
) { ) {
} }
public function __invoke(UserFilter $userFilter): array public function __invoke(UserFilter $userFilter): array
{ {
return $this->userRepository->list($userFilter); return $this->userRepository->list($userFilter);
} }
} }

View File

@ -9,8 +9,6 @@ use PandoraFMS\Modules\Users\Validations\UserValidation;
final class UpdateUserService final class UpdateUserService
{ {
public function __construct( public function __construct(
private Audit $audit, private Audit $audit,
private UserRepository $userRepository, private UserRepository $userRepository,
@ -18,7 +16,6 @@ final class UpdateUserService
) { ) {
} }
public function __invoke(User $user, User $oldUser): User public function __invoke(User $user, User $oldUser): User
{ {
$this->userValidation->__invoke($user, $oldUser); $this->userValidation->__invoke($user, $oldUser);
@ -38,6 +35,4 @@ final class UpdateUserService
return $user; return $user;
} }
} }

View File

@ -8,14 +8,11 @@ use PandoraFMS\Modules\Users\Entities\User;
final class ValidatePasswordUserService final class ValidatePasswordUserService
{ {
public function __construct( public function __construct(
private Config $config, private Config $config,
) { ) {
} }
public function __invoke(User $user, ?User $oldUser): void public function __invoke(User $user, ?User $oldUser): void
{ {
// Excluyes palabras. // Excluyes palabras.
@ -69,7 +66,6 @@ final class ValidatePasswordUserService
} }
} }
private function checkExcludePassword(string $newPassword): bool private function checkExcludePassword(string $newPassword): bool
{ {
if ((bool) $this->config->get('enable_pass_policy') === true if ((bool) $this->config->get('enable_pass_policy') === true
@ -88,7 +84,6 @@ final class ValidatePasswordUserService
return false; return false;
} }
private function getOldPasswords(string $idUser): array private function getOldPasswords(string $idUser): array
{ {
// TODO: create new service for this. // TODO: create new service for this.
@ -109,6 +104,4 @@ final class ValidatePasswordUserService
return $oldPasswords; return $oldPasswords;
} }
} }

View File

@ -2,6 +2,7 @@
namespace PandoraFMS\Modules\Users\Validations; namespace PandoraFMS\Modules\Users\Validations;
use Models\VisualConsole\Container as VisualConsole;
use PandoraFMS\Modules\Shared\Exceptions\BadRequestException; use PandoraFMS\Modules\Shared\Exceptions\BadRequestException;
use PandoraFMS\Modules\Shared\Exceptions\ForbiddenACLException; use PandoraFMS\Modules\Shared\Exceptions\ForbiddenACLException;
use PandoraFMS\Modules\Shared\Exceptions\NotFoundException; use PandoraFMS\Modules\Shared\Exceptions\NotFoundException;
@ -11,14 +12,10 @@ use PandoraFMS\Modules\Users\Entities\User;
use PandoraFMS\Modules\Users\Enums\UserHomeScreenEnum; use PandoraFMS\Modules\Users\Enums\UserHomeScreenEnum;
use PandoraFMS\Modules\Users\Services\CheckOldPasswordUserService; use PandoraFMS\Modules\Users\Services\CheckOldPasswordUserService;
use PandoraFMS\Modules\Users\Services\GetUserService; use PandoraFMS\Modules\Users\Services\GetUserService;
use Models\VisualConsole\Container as VisualConsole;
use PandoraFMS\Modules\Users\Services\ValidatePasswordUserService; use PandoraFMS\Modules\Users\Services\ValidatePasswordUserService;
final class UserValidation final class UserValidation
{ {
public function __construct( public function __construct(
private Config $config, private Config $config,
private Timestamp $timestamp, private Timestamp $timestamp,
@ -28,8 +25,7 @@ final class UserValidation
) { ) {
} }
public function __invoke(User $user, ?User $oldUser = null): void
public function __invoke(User $user, ?User $oldUser=null): void
{ {
$isAdmin = $this->isAdmin($this->config->get('id_user')); $isAdmin = $this->isAdmin($this->config->get('id_user'));
$this->validateIdUser($user); $this->validateIdUser($user);
@ -260,19 +256,16 @@ final class UserValidation
} }
} }
private function getCurrentTimestamp(): string private function getCurrentTimestamp(): string
{ {
return $this->timestamp->getMysqlCurrentTimestamp(0); return $this->timestamp->getMysqlCurrentTimestamp(0);
} }
private function getCurrentUtimestamp(): int private function getCurrentUtimestamp(): int
{ {
return $this->timestamp->getMysqlSystemUtimestamp(); return $this->timestamp->getMysqlSystemUtimestamp();
} }
private function existsUser(string $idUser): void private function existsUser(string $idUser): void
{ {
$exist = true; $exist = true;
@ -287,7 +280,6 @@ final class UserValidation
} }
} }
private function validateIdUser(User $user): void private function validateIdUser(User $user): void
{ {
if ($user->getIdUser() === false) { if ($user->getIdUser() === false) {
@ -302,21 +294,18 @@ final class UserValidation
} }
} }
private function generateApiToken(): string private function generateApiToken(): string
{ {
// TODO: create new service for this. // TODO: create new service for this.
return \api_token_generate(); return \api_token_generate();
} }
private function isAdmin(string $idUser): bool private function isAdmin(string $idUser): bool
{ {
// TODO: create new service for this. // TODO: create new service for this.
return \users_is_admin($idUser); return \users_is_admin($idUser);
} }
protected function validateSkin(int $idSkin): void protected function validateSkin(int $idSkin): void
{ {
// TODO: create new service for this. // TODO: create new service for this.
@ -325,7 +314,6 @@ final class UserValidation
} }
} }
protected function validateEventFilter(int $idFilter): void protected function validateEventFilter(int $idFilter): void
{ {
// TODO: create new service for this. // TODO: create new service for this.
@ -334,7 +322,6 @@ final class UserValidation
} }
} }
protected function validateCustomView(int $idView): void protected function validateCustomView(int $idView): void
{ {
// TODO: create new service for this. // TODO: create new service for this.
@ -343,7 +330,6 @@ final class UserValidation
} }
} }
protected function validateDashboard(string $idUser, int $idDashboard): void protected function validateDashboard(string $idUser, int $idDashboard): void
{ {
// TODO: create new service for this. // TODO: create new service for this.
@ -352,7 +338,6 @@ final class UserValidation
} }
} }
protected function validateVisualConsole(int $visualConsoleId): void protected function validateVisualConsole(int $visualConsoleId): void
{ {
// TODO: create new service for this. // TODO: create new service for this.
@ -362,6 +347,4 @@ final class UserValidation
throw new BadRequestException(__('Invalid visual console id')); throw new BadRequestException(__('Invalid visual console id'));
} }
} }
} }

View File

@ -11,21 +11,15 @@ class UserValidator extends Validator
public const VALIDSECTION = 'ValidSection'; public const VALIDSECTION = 'ValidSection';
public const VALIDMETACONSOLEACCESS = 'ValidMetaconsoleAccess'; public const VALIDMETACONSOLEACCESS = 'ValidMetaconsoleAccess';
protected function isValidSection($section): bool protected function isValidSection($section): bool
{ {
$result = UserHomeScreenEnum::get(strtoupper($section)); $result = UserHomeScreenEnum::get(strtoupper($section));
return empty($result) === true ? false : true; return empty($result) === true ? false : true;
} }
protected function isValidMetaconsoleAccess($metaconsoleAccess): bool protected function isValidMetaconsoleAccess($metaconsoleAccess): bool
{ {
$result = UserMetaconsoleAccessEnum::get(strtoupper($metaconsoleAccess)); $result = UserMetaconsoleAccessEnum::get(strtoupper($metaconsoleAccess));
return empty($result) === true ? false : true; return empty($result) === true ? false : true;
} }
} }