Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f341d6781 |
No files matched your search
@@ -0,0 +1,7 @@
|
|||||||
|
class ApiConsole {
|
||||||
|
constructor(options) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
+5
-12
@@ -10,21 +10,15 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"require": {
|
"require": {
|
||||||
"php": "^8.4",
|
"php": "^8.2",
|
||||||
"php-di/php-di": "dev-master",
|
"php-di/php-di": "dev-master",
|
||||||
"ext-json": "*",
|
"ext-json": "*",
|
||||||
"ext-pdo": "*",
|
"mcnd/lean": "dev-master"
|
||||||
"mcnd/lean": "^1.4.2",
|
|
||||||
"assets-package/ace": "^1.0.0"
|
|
||||||
},
|
},
|
||||||
"repositories": [
|
"repositories": [
|
||||||
{
|
{
|
||||||
"type": "composer",
|
"type": "vcs",
|
||||||
"url": "https://git.mcnd.ca/api/packages/mcndave/composer"
|
"url": "https://git.mcnd.ca/mcndave/lean.git"
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "composer",
|
|
||||||
"url": "https://git.mcnd.ca/api/packages/assets-package/composer"
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"autoload": {
|
"autoload": {
|
||||||
@@ -44,8 +38,7 @@
|
|||||||
"lean" : {
|
"lean" : {
|
||||||
"autoload": {
|
"autoload": {
|
||||||
"definitions" : [
|
"definitions" : [
|
||||||
"meta/definitions/software.php",
|
"meta/definitions/software.php"
|
||||||
"meta/definitions/storage.php"
|
|
||||||
],
|
],
|
||||||
"config": [
|
"config": [
|
||||||
"meta/config.php"
|
"meta/config.php"
|
||||||
|
|||||||
+1
-20
@@ -1,28 +1,9 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
$path = dirname(__DIR__, 1);
|
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'lean' => [
|
'lean' => [
|
||||||
'autoload' => [
|
'autoload' => [
|
||||||
'lean.api',
|
'lean.api',
|
||||||
]
|
]
|
||||||
],
|
],
|
||||||
|
];
|
||||||
'ulmus' => [
|
|
||||||
'connections' => [
|
|
||||||
'lean.api' => [
|
|
||||||
'adapter' => getenv("LEAN_API_ADAPTER") ?: "SQLite",
|
|
||||||
'path' => getenv('PROJECT_PATH') . DIRECTORY_SEPARATOR . ( getenv("LEAN_API_PATH") ?: "var/lean-api.sqlite3" ),
|
|
||||||
'pragma_begin' => array_merge(
|
|
||||||
explode(',', getenv("LEAN_API_PRAGMA_BEGIN") ?: "foreign_keys=ON,synchronous=NORMAL"),
|
|
||||||
explode(',', getenv('DEBUG') ? getenv("LEAN_API_PRAGMA_DEBUG_BEGIN") : "journal_mode=WAL")
|
|
||||||
),
|
|
||||||
'pragma_close' => array_merge(
|
|
||||||
explode(',', getenv("LEAN_API_PRAGMA_CLOSE") ?: "analysis_limit=500,optimize"),
|
|
||||||
explode(',', getenv('DEBUG') ? getenv("LEAN_API_PRAGMA_DEBUG_CLOSE") : "")
|
|
||||||
),
|
|
||||||
],
|
|
||||||
]
|
|
||||||
]
|
|
||||||
];
|
|
||||||
@@ -1,10 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use Ulmus\ConnectionAdapter;
|
$path = dirname(__DIR__, 2);
|
||||||
|
|
||||||
use function DI\{ get, env };
|
|
||||||
|
|
||||||
define('LEAN_API_PROJECT_PATH', $path = dirname(__DIR__, 2));
|
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'lean.api' => [
|
'lean.api' => [
|
||||||
@@ -26,17 +22,6 @@ return [
|
|||||||
],
|
],
|
||||||
],
|
],
|
||||||
|
|
||||||
'cli' => [
|
|
||||||
'Lean\\Api\\Cli' => implode(DIRECTORY_SEPARATOR, [ $path, "src", "Cli", "" ]),
|
|
||||||
],
|
|
||||||
|
|
||||||
'ulmus' => [
|
|
||||||
'entities' => [ 'Lean\\Api\\Entity' => implode(DIRECTORY_SEPARATOR, [ $path, 'src', 'Entity', '' ]) ],
|
|
||||||
'adapters' => [
|
|
||||||
DI\get('lean.api:storage'),
|
|
||||||
]
|
|
||||||
],
|
|
||||||
|
|
||||||
'tell' => [
|
'tell' => [
|
||||||
'json' => [
|
'json' => [
|
||||||
[
|
[
|
||||||
@@ -46,20 +31,8 @@ return [
|
|||||||
]
|
]
|
||||||
],
|
],
|
||||||
|
|
||||||
'routes' => [
|
/*'routes' => [
|
||||||
'Lean\\Api\\Controller' => implode(DIRECTORY_SEPARATOR, [ $path, "src", "Controller", "" ]),
|
'Lean\\Api\\Controller' => implode(DIRECTORY_SEPARATOR, [ $path, "src", "Controller", "" ]),
|
||||||
],
|
],*/
|
||||||
],
|
],
|
||||||
|
|
||||||
'app.middlewares' => \DI\add([
|
|
||||||
# Lean\Api\Middleware\Security\CORSMiddleware::class,
|
|
||||||
# Lean\Api\Middleware\Security\RequestLogMiddleware::class,
|
|
||||||
]),
|
|
||||||
|
|
||||||
Lean\ApplicationStrategy\NotFoundDecoratorInterface::class => DI\autowire(Lean\Api\ApplicationStrategy\NotFoundDecorator::class),
|
|
||||||
Lean\ApplicationStrategy\MethodNotAllowedInterface::class => DI\autowire(Lean\Api\ApplicationStrategy\MethodNotAllowedDecorator::class),
|
|
||||||
Lean\Api\Factory\MessageFactoryInterface::class => DI\autowire(Lean\Api\Lib\Message::class),
|
|
||||||
Lean\Api\Factory\LeanApiFormFactoryInterface::class => DI\autowire(Lean\Api\Factory\LeanApiFormFactory::class),
|
|
||||||
Lean\Api\Lib\RenderCORS::class => DI\create(Lean\Api\Lib\RenderCORS::class)->constructor(get(\Psr\Http\Message\ServerRequestInterface::class), env('LEAN_API_CORS_ORIGIN', '*')),
|
|
||||||
# League\Route\Strategy\ApplicationStrategy::class => DI\autowire(Lean\Api\ApplicationStrategy::class),
|
|
||||||
];
|
];
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use Psr\Container\ContainerInterface;
|
|
||||||
|
|
||||||
use Ulmus\ConnectionAdapter,
|
|
||||||
Ulmus\Container\AdapterProxy;
|
|
||||||
|
|
||||||
use Storage\Session;
|
|
||||||
|
|
||||||
use function DI\autowire, DI\create, DI\get;
|
|
||||||
|
|
||||||
return [
|
|
||||||
'lean.api:storage' => function($c) {
|
|
||||||
$adapter = new ConnectionAdapter('lean.api', $c->get('config')['ulmus'], false);
|
|
||||||
$adapter->resolveConfiguration();
|
|
||||||
|
|
||||||
return $adapter;
|
|
||||||
},
|
|
||||||
];
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
# LEAN API
|
|
||||||
|
|
||||||
## Debug tooling to help development within Lean's API
|
|
||||||
|
|
||||||
[Documentation](../) / Debug API queries
|
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
### Routes
|
|
||||||
|
|
||||||
{route:descriptor}
|
|
||||||
|
|
||||||
{request:debugger}
|
|
||||||
|
|
||||||
### Forms / actions
|
|
||||||
|
|
||||||
{form:descriptor}
|
|
||||||
|
|
||||||
### Entities
|
|
||||||
|
|
||||||
{entity:descriptor}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
# LEAN API
|
|
||||||
|
|
||||||
## Debug tooling to help development within Lean's API
|
|
||||||
|
|
||||||
[Lean API](../../debug) / Debug API queries
|
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
### Routes
|
|
||||||
|
|
||||||
{route:descriptor}
|
|
||||||
|
|
||||||
{request:debugger}
|
|
||||||
|
|
||||||
### Forms / actions
|
|
||||||
|
|
||||||
{form:descriptor}
|
|
||||||
|
|
||||||
### Entities
|
|
||||||
|
|
||||||
{entity:descriptor}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
# Lean API
|
|
||||||
|
|
||||||
## Lean's API internal debug API
|
|
||||||
|
|
||||||
### Routes disponibles
|
|
||||||
|
|
||||||
- [Debug / Errors](./debug/errors/documentation)
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
# LEAN API
|
|
||||||
|
|
||||||
## An action logger to keep important actions in checks / allow easy notifications handling
|
|
||||||
|
|
||||||
[Documentation](../../) / Security / Action logs
|
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
### Available routes
|
|
||||||
|
|
||||||
{route:descriptor}
|
|
||||||
|
|
||||||
{request:debugger}
|
|
||||||
|
|
||||||
### Forms
|
|
||||||
|
|
||||||
{form:descriptor}
|
|
||||||
|
|
||||||
### Entity
|
|
||||||
|
|
||||||
{entity:descriptor}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
# LEAN API
|
|
||||||
|
|
||||||
## CSRF Token generation for non-idempotent requests
|
|
||||||
|
|
||||||
[Documentation](../../) / Security / CRSF
|
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
### Available routes
|
|
||||||
|
|
||||||
{route:descriptor}
|
|
||||||
|
|
||||||
{request:debugger}
|
|
||||||
|
|
||||||
### Forms
|
|
||||||
|
|
||||||
{form:descriptor}
|
|
||||||
|
|
||||||
### Entity
|
|
||||||
|
|
||||||
{entity:descriptor}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
# LEAN API
|
|
||||||
|
|
||||||
## Logging request logs allowing deeper forensic than simple request logs
|
|
||||||
|
|
||||||
[Documentation](../../) / Security / Requests
|
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
### Available routes
|
|
||||||
|
|
||||||
{route:descriptor}
|
|
||||||
|
|
||||||
{request:debugger}
|
|
||||||
|
|
||||||
### Forms
|
|
||||||
|
|
||||||
{form:descriptor}
|
|
||||||
|
|
||||||
### Entity
|
|
||||||
|
|
||||||
{entity:descriptor}
|
|
||||||
@@ -1,26 +1,11 @@
|
|||||||
{
|
{
|
||||||
"descriptor": {
|
|
||||||
"form": {
|
|
||||||
"none": "Aucun formulaire existant pour cet API"
|
|
||||||
},
|
|
||||||
"entity": {
|
|
||||||
"none": "Aucune entité trouvée pour cet API"
|
|
||||||
},
|
|
||||||
"route": {
|
|
||||||
"none": "Aucune route trouvée pour cet API"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"form": {
|
"form": {
|
||||||
"error": {
|
|
||||||
"entity": "Une propriété $entity est nécessaire pour envoyer ce formulaire."
|
|
||||||
},
|
|
||||||
"save": {
|
"save": {
|
||||||
"error": {
|
"error": {
|
||||||
|
"entity": "Une propriété $entity est nécessaire dans ce form",
|
||||||
|
"save": "Une erreur est survenue en tenant de sauvegarder les données",
|
||||||
"pdo": "Une erreur est survenue : '{$error}'"
|
"pdo": "Une erreur est survenue : '{$error}'"
|
||||||
},
|
},
|
||||||
"warning": {
|
|
||||||
"entity": "Aucun changement apporté pour l'objet '{$entity}'."
|
|
||||||
},
|
|
||||||
"success": {
|
"success": {
|
||||||
"save": "Sauvegarde effectué avec succès"
|
"save": "Sauvegarde effectué avec succès"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,63 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace %NAMESPACE%\%API_NS%;
|
|
||||||
|
|
||||||
use Notes\Attribute\Ignore;
|
|
||||||
use Notes\Route\Attribute\Method\Route;
|
|
||||||
use Psr\Http\Message\{ ServerRequestInterface, ResponseInterface };
|
|
||||||
|
|
||||||
use %NAMESPACE%\{Lib, %USE_ENTITY_NS%, %USE_FORM_NS%, };
|
|
||||||
use function %NAMESPACE%\View\{_, lang, url, route, form};
|
|
||||||
|
|
||||||
#[\Notes\Route\Attribute\Object\Route(base:"%API_ROUTE_BASE%/%CLASSNAME_LC%")]
|
|
||||||
class %CLASSNAME% {
|
|
||||||
use Lib\ApiTrait;
|
|
||||||
|
|
||||||
#[Route(route: "/documentation", name: "api.%CLASSNAME_LC%:docs", method: "GET")]
|
|
||||||
public function index(ServerRequestInterface $request, array $arguments): ResponseInterface
|
|
||||||
{
|
|
||||||
return $this->renderMarkdown(getenv("PROJECT_PATH") . "/meta/docs/%CLASSNAME_LC%.md", [ %ENTITY_NS%\%CLASSNAME%::class, ], [ %FORM_NS%\%SAVE_FORM_CONTEXT_CLASSNAME%::class, %FORM_NS%\%DELETE_FORM_CONTEXT_CLASSNAME%::class ]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Route("/", name: "api.%CLASSNAME_LC%:list", method: "GET")]
|
|
||||||
public function list(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
$request = $this->searchEntitiesFromRequest($request, %ENTITY_NS%\%CLASSNAME%::class);
|
|
||||||
$result = $request->getAttribute("lean.searchRequest")[%ENTITY_NS%\%CLASSNAME%::class];
|
|
||||||
|
|
||||||
return $this->outputSearchResult($result);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Route("/", name: "api.%CLASSNAME_LC%:add", method: "POST")]
|
|
||||||
public function add(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
$entity = new %ENTITY_NS%\%CLASSNAME%();
|
|
||||||
|
|
||||||
form($this->formFactory->%SAVE_FORM_CLASSNAME_LC%($entity), $this->formFactory->%SAVE_FORM_CONTEXT_CLASSNAME_LC%($request));
|
|
||||||
|
|
||||||
return $this->output($entity, (int) $entity->isLoaded());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Route("/{id:\d+}", name: "api.%CLASSNAME_LC%:single", method: "GET")]
|
|
||||||
#[Route("/{id:\d+}", name: "api.%CLASSNAME_LC%:edit", method: "PATCH")]
|
|
||||||
public function single(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
$request = $this->searchEntityFromRequest($request, %ENTITY_NS%\%CLASSNAME%::class);
|
|
||||||
$result = $request->getAttribute("lean.searchRequest")[%ENTITY_NS%\%CLASSNAME%::class];
|
|
||||||
|
|
||||||
form($this->formFactory->%SAVE_FORM_CLASSNAME_LC%($result->getResult()), $this->formFactory->%SAVE_FORM_CONTEXT_CLASSNAME_LC%($request));
|
|
||||||
|
|
||||||
return $this->outputSearchResult($result);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Route("/{id:\d+}", name: "api.%CLASSNAME_LC%:delete", method: "DELETE")]
|
|
||||||
public function delete(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
$request = $this->searchEntityFromRequest($request, %ENTITY_NS%\%CLASSNAME%::class);
|
|
||||||
$result = $request->getAttribute("lean.searchRequest")[%ENTITY_NS%\%CLASSNAME%::class];
|
|
||||||
|
|
||||||
form($this->formFactory->%DELETE_FORM_CLASSNAME_LC%($result->getResult()), $this->formFactory->%DELETE_FORM_CONTEXT_CLASSNAME_LC%($request));
|
|
||||||
|
|
||||||
return $this->outputSearchResult($result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace %NAMESPACE%\%WEB_NS%;
|
|
||||||
|
|
||||||
use Notes\Breadcrumb\Attribute\Method\Breadcrumb;
|
|
||||||
use Notes\Route\Attribute\Method\Route;
|
|
||||||
|
|
||||||
use Psr\Http\Message\ServerRequestInterface,
|
|
||||||
Psr\Http\Message\ResponseInterface;
|
|
||||||
|
|
||||||
use %NAMESPACE%\{Lib, %USE_ENTITY_NS%, %USE_FORM_NS%, };
|
|
||||||
|
|
||||||
use function %NAMESPACE%\View\{_, lang, url, route, form};
|
|
||||||
|
|
||||||
#[\Notes\Route\Attribute\Object\Route(base:"%WEB_ROUTE_BASE%/%CLASSNAME_LC%")]
|
|
||||||
class %CLASSNAME% {
|
|
||||||
use Lib\ControllerTrait;
|
|
||||||
|
|
||||||
#[Route("/", name: "%CLASSNAME_LC%:index")]
|
|
||||||
##[Breadcrumb(parent: "", icon: "", lang: "app.lang.breadcrumb")]
|
|
||||||
public function index(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
$search = %ENTITY_NS%\%CLASSNAME%::searchRequest()->fromRequest($request) ;
|
|
||||||
$list = %ENTITY_NS%\%CLASSNAME%::repository()->filterServerRequest($search)->loadAll();
|
|
||||||
|
|
||||||
return $this->renderView('%CLASSNAME_LC%/index', get_defined_vars());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Route("/create", name: "%CLASSNAME_LC%:create", method: ["GET", "POST"])]
|
|
||||||
##[Breadcrumb(parent: "%CLASSNAME_LC%:index", icon: "", lang: "app.lang.breadcrumb")]
|
|
||||||
public function create(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
$entity = new %ENTITY_NS%\%CLASSNAME%();
|
|
||||||
|
|
||||||
form($this->formFactory->%SAVE_FORM_CLASSNAME_LC%($entity), $this->pushContext($this->formFactory->%SAVE_FORM_CONTEXT_CLASSNAME_LC%($request, "%CLASSNAME_LC%.create")));
|
|
||||||
|
|
||||||
if ($entity->isLoaded()) {
|
|
||||||
return $this->redirect(route("%CLASSNAME_LC%:edit", [ 'id' => $entity->id ]) );
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->renderView('%CLASSNAME_LC%/create', get_defined_vars());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Route("/{id:\d+}/edit", name: "%CLASSNAME_LC%:edit", method: ["GET", "POST"])]
|
|
||||||
##[Breadcrumb(parent: "%CLASSNAME_LC%:index", icon: "", lang: "app.lang.breadcrumb")]
|
|
||||||
public function edit(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
$search = %ENTITY_NS%\%CLASSNAME%::searchRequest()->fromRequest($request);
|
|
||||||
$entity = %ENTITY_NS%\%CLASSNAME%::repository()->filterServerRequest($search)->loadOne();
|
|
||||||
|
|
||||||
form($this->formFactory->%SAVE_FORM_CLASSNAME_LC%($entity), $this->pushContext($this->formFactory->%SAVE_FORM_CONTEXT_CLASSNAME_LC%($request, "%CLASSNAME_LC%.edit")));
|
|
||||||
|
|
||||||
return $this->renderView('%CLASSNAME_LC%/edit', get_defined_vars());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Route("/{id:\d+}/delete", name: "%CLASSNAME_LC%:delete", method: ["POST", "DELETE"])]
|
|
||||||
public function delete(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
$search = %ENTITY_NS%\%CLASSNAME%::searchRequest()->fromRequest($request);
|
|
||||||
$entity = %ENTITY_NS%\%CLASSNAME%::repository()->filterServerRequest($search)->loadOne();
|
|
||||||
|
|
||||||
form($this->formFactory->%DELETE_FORM_CLASSNAME_LC%($entity), $this->pushContext($this->formFactory->%DELETE_FORM_CONTEXT_CLASSNAME_LC%($request, "%CLASSNAME_LC%.delete")));
|
|
||||||
|
|
||||||
return $this->redirect(route("%CLASSNAME_LC%:index"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace %NAMESPACE%\%FORM_NS%;
|
|
||||||
|
|
||||||
use Picea\Ui\Method\{ FormContextInterface };
|
|
||||||
use Lean\Api\Factory\MessageFactoryInterface;
|
|
||||||
use Lean\LanguageHandler;
|
|
||||||
|
|
||||||
use %NAMESPACE%\{%USE_ENTITY_NS%, };
|
|
||||||
|
|
||||||
class %DELETE_FORM_CLASSNAME% extends \Lean\Api\Form\Delete
|
|
||||||
{
|
|
||||||
protected string $contextClass = %DELETE_FORM_CONTEXT_CLASSNAME%::class;
|
|
||||||
|
|
||||||
public function __construct(
|
|
||||||
protected LanguageHandler $languageHandler,
|
|
||||||
protected MessageFactoryInterface $message,
|
|
||||||
protected %ENTITY_NS%\%CLASSNAME% $entity,
|
|
||||||
) {}
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace %NAMESPACE%\%FORM_NS%;
|
|
||||||
|
|
||||||
use Lean\Api\Attribute\ContextField;
|
|
||||||
use %NAMESPACE%\{ %USE_ENTITY_NS% };
|
|
||||||
|
|
||||||
#[ContextField]
|
|
||||||
class %DELETE_FORM_CONTEXT_CLASSNAME% extends \Lean\Api\Lib\FormContext
|
|
||||||
{
|
|
||||||
# #[ContextField]
|
|
||||||
# public string $name;
|
|
||||||
|
|
||||||
public function valid(? %ENTITY_NS%\%CLASSNAME% $entity = null) : bool
|
|
||||||
{
|
|
||||||
if ( $entity === null ) {
|
|
||||||
$this->pushErrorMessage('lean.api.form.delete.error.entity');
|
|
||||||
}
|
|
||||||
|
|
||||||
return parent::valid();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace %NAMESPACE%\%ENTITY_NS%;
|
|
||||||
|
|
||||||
use Ulmus\{
|
|
||||||
Attribute\IndexTypeEnum,
|
|
||||||
Attribute\Obj\Table,
|
|
||||||
Attribute\Property\Field,
|
|
||||||
Attribute\Property\Index,
|
|
||||||
Attribute\Property\OrderBy,
|
|
||||||
Attribute\Property\Relation,
|
|
||||||
Attribute\Property\Virtual,
|
|
||||||
Entity\EntityInterface,
|
|
||||||
EntityCollection,
|
|
||||||
Entity\Field\Datetime,
|
|
||||||
Repository,
|
|
||||||
SearchRequest,
|
|
||||||
};
|
|
||||||
|
|
||||||
use Ulmus\SearchRequest\Attribute\SearchWhere;
|
|
||||||
use Notes\Attribute\Ignore;
|
|
||||||
|
|
||||||
use %NAMESPACE%\Lib;
|
|
||||||
|
|
||||||
#[Table(name: "%CLASSNAME_LC%")]
|
|
||||||
class %CLASSNAME% implements \JsonSerializable, EntityInterface
|
|
||||||
{
|
|
||||||
use Lib\EntityTrait;
|
|
||||||
|
|
||||||
#[Field\Id]
|
|
||||||
public int $id;
|
|
||||||
|
|
||||||
#[Ignore]
|
|
||||||
public static function searchRequest(...$arguments) : SearchRequest\SearchRequestInterface
|
|
||||||
{
|
|
||||||
return new #[SearchRequest\Attribute\SearchRequestParameter(%CLASSNAME%::class)] class(... $arguments) extends SearchRequest\SearchRequest {
|
|
||||||
|
|
||||||
#[SearchWhere(parameter: [ '%CLASSNAME_LC%_id', 'id' ], source: SearchRequest\Attribute\PropertyValueSource::RequestAttribute)]
|
|
||||||
public int $id;
|
|
||||||
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
public function %SAVE_FORM_CLASSNAME_LC%(EntityInterface|%ENTITY_NS%\%CLASSNAME% $entity): FormInterface
|
|
||||||
{
|
|
||||||
return new %FORM_NS%\%SAVE_FORM_CLASSNAME%($this->languageHandler, $this->message, $entity);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function %SAVE_FORM_CONTEXT_CLASSNAME_LC%(ServerRequestInterface $request, ? string $formName = ''): FormContextInterface
|
|
||||||
{
|
|
||||||
return new %FORM_NS%\%SAVE_FORM_CONTEXT_CLASSNAME%($this->languageHandler, $this->message, $request, $formName);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function %DELETE_FORM_CLASSNAME_LC%(EntityInterface|%ENTITY_NS%\%CLASSNAME% $entity): FormInterface
|
|
||||||
{
|
|
||||||
return new %FORM_NS%\%DELETE_FORM_CLASSNAME%($this->languageHandler, $this->message, $entity);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function %DELETE_FORM_CONTEXT_CLASSNAME_LC%(ServerRequestInterface $request, ? string $formName = ''): FormContextInterface
|
|
||||||
{
|
|
||||||
return new %FORM_NS%\%DELETE_FORM_CONTEXT_CLASSNAME%($this->languageHandler, $this->message, $request, $formName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
public function %SAVE_FORM_CLASSNAME_LC%(EntityInterface|%ENTITY_NS%\%CLASSNAME% $entity): FormInterface;
|
|
||||||
public function %SAVE_FORM_CONTEXT_CLASSNAME_LC%(ServerRequestInterface $request, ? string $formName = ''): FormContextInterface;
|
|
||||||
public function %DELETE_FORM_CLASSNAME_LC%(EntityInterface|%ENTITY_NS%\%CLASSNAME% $entity): FormInterface;
|
|
||||||
public function %DELETE_FORM_CONTEXT_CLASSNAME_LC%(ServerRequestInterface $request, ? string $formName = ''): FormContextInterface;
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace %NAMESPACE%\%FACTORY_TRAIT_NS%;
|
|
||||||
|
|
||||||
use %NAMESPACE%\{ %USE_ENTITY_NS%, %USE_FORM_NS%, };
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
|
||||||
use Picea\Ui\Method\FormInterface;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
|
|
||||||
trait %CLASSNAME%Trait
|
|
||||||
{
|
|
||||||
public function %SAVE_FORM_CLASSNAME_LC%(EntityInterface|%ENTITY_NS%\%CLASSNAME% $entity): FormInterface
|
|
||||||
{
|
|
||||||
return new %FORM_NS%\%SAVE_FORM_CLASSNAME%($this->languageHandler, $this->messageFactory, $entity);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function %SAVE_FORM_CONTEXT_CLASSNAME_LC%(ServerRequestInterface $request, ? string $formName = ''): FormContextInterface
|
|
||||||
{
|
|
||||||
return new %FORM_NS%\%SAVE_FORM_CONTEXT_CLASSNAME%($this->languageHandler, $this->messageFactory, $request, $formName);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function %DELETE_FORM_CLASSNAME_LC%(EntityInterface|%ENTITY_NS%\%CLASSNAME% $entity): FormInterface
|
|
||||||
{
|
|
||||||
return new %FORM_NS%\%DELETE_FORM_CLASSNAME%($this->languageHandler, $this->messageFactory, $entity);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function %DELETE_FORM_CONTEXT_CLASSNAME_LC%(ServerRequestInterface $request, ? string $formName = ''): FormContextInterface
|
|
||||||
{
|
|
||||||
return new %FORM_NS%\%DELETE_FORM_CONTEXT_CLASSNAME%($this->languageHandler, $this->messageFactory, $request, $formName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace %NAMESPACE%\%FORM_NS%;
|
|
||||||
|
|
||||||
use Picea\Ui\Method\{ FormContextInterface };
|
|
||||||
use Lean\Api\Factory\MessageFactoryInterface;
|
|
||||||
use Lean\LanguageHandler;
|
|
||||||
|
|
||||||
use %NAMESPACE%\{%USE_ENTITY_NS%, };
|
|
||||||
|
|
||||||
class %SAVE_FORM_CLASSNAME% extends \Lean\Api\Form\Save
|
|
||||||
{
|
|
||||||
protected string $contextClass = %SAVE_FORM_CONTEXT_CLASSNAME%::class;
|
|
||||||
|
|
||||||
public function __construct(
|
|
||||||
protected LanguageHandler $languageHandler,
|
|
||||||
protected MessageFactoryInterface $message,
|
|
||||||
protected %ENTITY_NS%\%CLASSNAME% $entity,
|
|
||||||
) {}
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace %NAMESPACE%\%FORM_NS%;
|
|
||||||
|
|
||||||
use Lean\Api\Attribute\ContextField;
|
|
||||||
use %NAMESPACE%\{ %USE_ENTITY_NS% };
|
|
||||||
|
|
||||||
#[ContextField]
|
|
||||||
class %SAVE_FORM_CONTEXT_CLASSNAME% extends \Lean\Api\Lib\FormContext
|
|
||||||
{
|
|
||||||
# #[ContextField]
|
|
||||||
# public string $name;
|
|
||||||
|
|
||||||
public function initializeEntity(%ENTITY_NS%\%CLASSNAME% $entity): void
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
public function valid(? %ENTITY_NS%\%CLASSNAME% $entity = null) : bool
|
|
||||||
{
|
|
||||||
return parent::valid();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
# Title
|
|
||||||
|
|
||||||
## API 1.0
|
|
||||||
|
|
||||||
[APP](../) / %CLASSNAME%
|
|
||||||
|
|
||||||
--------------------------------------------------------------------------------
|
|
||||||
|
|
||||||
### Routes
|
|
||||||
|
|
||||||
{route:descriptor}
|
|
||||||
|
|
||||||
{request:debugger}
|
|
||||||
|
|
||||||
### Forms
|
|
||||||
|
|
||||||
{form:descriptor}
|
|
||||||
|
|
||||||
### Entities
|
|
||||||
|
|
||||||
{entity:descriptor}
|
|
||||||
@@ -1,600 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Action\Console;
|
|
||||||
|
|
||||||
use Lean\Application;
|
|
||||||
use Lean\Composer;
|
|
||||||
use Mcnd\CLI\Terminal;
|
|
||||||
|
|
||||||
class EntityGenerate
|
|
||||||
{
|
|
||||||
# public string $applicationPath;
|
|
||||||
public string $namespace;
|
|
||||||
public string $entityNamespace;
|
|
||||||
public string $formNamespace;
|
|
||||||
public string $saveForm;
|
|
||||||
public string $saveContext;
|
|
||||||
public string $deleteForm;
|
|
||||||
public string $deleteContext;
|
|
||||||
public string $apiNamespace;
|
|
||||||
public string $apiBase;
|
|
||||||
public string $webNamespace;
|
|
||||||
public string $webBase;
|
|
||||||
public string $factoryAction;
|
|
||||||
public string $factoryNamespace;
|
|
||||||
public string $factoryTraitNamespace;
|
|
||||||
public string $factoryFile;
|
|
||||||
public string $factoryInterfaceFile;
|
|
||||||
public bool $includeDocs = false;
|
|
||||||
|
|
||||||
public readonly string $compiledEntity;
|
|
||||||
public readonly string $compiledSaveForm;
|
|
||||||
public readonly string $compiledSaveFormContext;
|
|
||||||
public readonly string $compiledDeleteForm;
|
|
||||||
public readonly string $compiledDeleteFormContext;
|
|
||||||
public readonly string $compiledFactory;
|
|
||||||
public readonly string $compiledFactoryTrait;
|
|
||||||
public readonly string $compiledFactoryInterface;
|
|
||||||
public readonly string $compiledApi;
|
|
||||||
public readonly string $compiledWeb;
|
|
||||||
public readonly string $compiledDocs;
|
|
||||||
|
|
||||||
public function __construct(
|
|
||||||
public Application $application,
|
|
||||||
public string $name,
|
|
||||||
public bool $overwrite,
|
|
||||||
public bool $default,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function writeToDisc() : void
|
|
||||||
{
|
|
||||||
$entityPath = $this->pathFromNamespace($this->entityNamespace, $this->application->entities);
|
|
||||||
|
|
||||||
if (empty($entityPath)) {
|
|
||||||
throw new \InvalidArgumentException("Could not find entities path from given namespaces.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($this->webNamespace)) {
|
|
||||||
$webPath = $this->pathFromNamespace($this->webNamespace, $this->application->routes);
|
|
||||||
|
|
||||||
if (empty($webPath)) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
sprintf("Could not find web path routes from given namespaces. Given info : %s, %s", $this->webNamespace, json_encode($this->application->routes))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($this->apiNamespace)) {
|
|
||||||
$apiPath = $this->pathFromNamespace($this->apiNamespace, $this->application->routes);
|
|
||||||
|
|
||||||
if (empty($apiPath)) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
sprintf("Could not find web path routes from given namespaces. Given info : %s, %s", $this->apiNamespace, json_encode($this->application->routes))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($this->includeDocs) {
|
|
||||||
$docPath = implode(DIRECTORY_SEPARATOR, [ getenv('META_PATH'), "docs" ]);
|
|
||||||
$docPath = $this->readline(sprintf("Path of API's documentation output (default: %s) : ", $docPath), $docPath);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($this->formNamespace)) {
|
|
||||||
$formPath = implode(DIRECTORY_SEPARATOR, [ $this->pathFromPSR($this->formNamespace), str_replace('\\', DIRECTORY_SEPARATOR, $this->formNamespace) ]);
|
|
||||||
$formPath = $this->readline(sprintf("Path of Forms (default: %s) : ", $formPath), $formPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($this->factoryNamespace)) {
|
|
||||||
$factoryPath = implode(DIRECTORY_SEPARATOR, [ $this->pathFromPSR($this->factoryNamespace), str_replace('\\', DIRECTORY_SEPARATOR, $this->factoryNamespace) ]);
|
|
||||||
$factoryPath = $this->readline(sprintf("Path of Factory (default: %s) : ", $factoryPath), $factoryPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ( Terminal::proposeListChoice("Input completed, write to files ?", [ true => 'Yes', false => 'No', ]) ) {
|
|
||||||
$this->writeToFile($entityPath, $this->name, $this->compiledEntity, );
|
|
||||||
|
|
||||||
if (isset($webPath)) {
|
|
||||||
$this->writeToFile($webPath, $this->name, $this->compiledWeb, );
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($apiPath)) {
|
|
||||||
$this->writeToFile($apiPath, $this->name, $this->compiledApi, );
|
|
||||||
|
|
||||||
if ($this->includeDocs) {
|
|
||||||
$this->writeToFile($docPath , strtolower($this->name), $this->compiledDocs, ".md");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($formPath)) {
|
|
||||||
if ($this->saveForm ?? false) {
|
|
||||||
$this->writeToFile($formPath, $this->saveForm, $this->compiledSaveForm,);
|
|
||||||
$this->writeToFile($formPath, $this->saveContext, $this->compiledSaveFormContext,);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($this->deleteForm ?? false) {
|
|
||||||
$this->writeToFile($formPath, $this->deleteForm, $this->compiledDeleteForm,);
|
|
||||||
$this->writeToFile($formPath, $this->deleteContext, $this->compiledDeleteFormContext,);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($this->factoryNamespace)) {
|
|
||||||
if (isset($this->factoryTraitNamespace)) {
|
|
||||||
$traitName = $this->name . "Trait";
|
|
||||||
|
|
||||||
$this->writeToFile(implode(DIRECTORY_SEPARATOR, [$factoryPath, "Factories"]), $traitName, $this->compiledFactoryTrait,);
|
|
||||||
$this->appendToFile($factoryPath, $this->factoryFile, "\tuse Factories\\$traitName;\n}", "");
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
$this->appendToFile($factoryPath, $this->factoryFile, $this->compiledFactory, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->appendToFile($factoryPath, $this->factoryInterfaceFile, $this->compiledFactoryInterface, "");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function appendToFile(string $path, string $filename, string $content, string $extension = ".php"): void
|
|
||||||
{
|
|
||||||
$fullpath = implode(DIRECTORY_SEPARATOR, [ rtrim($path, DIRECTORY_SEPARATOR), $filename . "$extension" ]);
|
|
||||||
|
|
||||||
$existingFileContent = file_get_contents($fullpath);
|
|
||||||
|
|
||||||
$this->writeToFile($path, $filename, rtrim($existingFileContent, '} ') . $content, $extension);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function writeToFile(string $path, string $filename, string $content, string $extension = ".php"): void
|
|
||||||
{
|
|
||||||
$fullpath = implode(DIRECTORY_SEPARATOR, [ rtrim($path, DIRECTORY_SEPARATOR), $filename . "$extension" ]);
|
|
||||||
|
|
||||||
if (file_exists($fullpath)) {
|
|
||||||
if ((! $this->overwrite) && Terminal::proposeListChoice(sprintf("Trying to write over an existing file '%s',\nOverwrite file ?", $fullpath), [ false => 'Yes', true => 'No', ])) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
elseif (! file_exists(dirname($fullpath))) {
|
|
||||||
mkdir(dirname($fullpath), 0755, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
file_put_contents($fullpath, $content, \LOCK_EX);
|
|
||||||
|
|
||||||
Terminal::sprintfline("File successfully written '%s'", $fullpath);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function pathFromNamespace(string $namespace, array $source) : false|string
|
|
||||||
{
|
|
||||||
$split = explode('\\', $namespace);
|
|
||||||
|
|
||||||
while($split) {
|
|
||||||
$ns = $this->namespace . "\\" . implode('\\', $split);
|
|
||||||
|
|
||||||
if ( isset($source[$ns]) ) {
|
|
||||||
return rtrim($source[$ns], DIRECTORY_SEPARATOR);
|
|
||||||
}
|
|
||||||
|
|
||||||
array_pop($split);
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function pathFromPSR(string $namespace) : false|string
|
|
||||||
{
|
|
||||||
$source = $this->readComposerPsr4();
|
|
||||||
$split = explode('\\', $namespace);
|
|
||||||
|
|
||||||
while($split) {
|
|
||||||
$ns = $this->namespace . "\\" . implode('\\', $split);
|
|
||||||
|
|
||||||
if (! str_ends_with($ns, '\\')) {
|
|
||||||
$ns .= "\\";
|
|
||||||
}
|
|
||||||
|
|
||||||
if ( isset($source[$ns]) ) {
|
|
||||||
return $source[$ns][0];
|
|
||||||
}
|
|
||||||
|
|
||||||
array_pop($split);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $source[$this->namespace . "\\"][0] ?? false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function outputResults() : void
|
|
||||||
{
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public function readline(? string $prompt, mixed $default = null): string|false
|
|
||||||
{
|
|
||||||
$result = Terminal::readline($prompt);
|
|
||||||
|
|
||||||
if ($this->default && $default !== null) {
|
|
||||||
return $default;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $result ?: $default;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function readNamespace() : void
|
|
||||||
{
|
|
||||||
$namespace = $this->readComposerNamespace();
|
|
||||||
$this->namespace = $this->readline(sprintf('Namespace (default: %s) : ', $namespace), $namespace);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function readApi() : void
|
|
||||||
{
|
|
||||||
$this->apiNamespace = $this->readline('API namespace (default: Api\\) : ', 'Api');
|
|
||||||
$this->apiBase = $this->readline('API URL base (default: /api) : ', '/api');
|
|
||||||
}
|
|
||||||
|
|
||||||
public function readWeb() : void
|
|
||||||
{
|
|
||||||
$this->webNamespace = $this->readline('Controller namespace (default: Controller\\) : ', 'Controller');
|
|
||||||
$this->webBase = $this->readline('Controller URL base (default: /) : ', "");
|
|
||||||
}
|
|
||||||
|
|
||||||
public function readEntity() : void
|
|
||||||
{
|
|
||||||
$this->entityNamespace = $this->readline('Entity namespace (default: Entity\\) : ', 'Entity');
|
|
||||||
}
|
|
||||||
|
|
||||||
public function readFactory() : void
|
|
||||||
{
|
|
||||||
$this->factoryNamespace ??= $this->readline('Factory namespace (default: Factory\\) : ', 'Factory');
|
|
||||||
$this->factoryFile = $this->readline('Form factory interface file (default: FormFactory.php) : ', 'FormFactory.php');
|
|
||||||
$this->factoryInterfaceFile = $this->readline('Form factory interface file (default: FormFactoryInterface.php) : ', 'FormFactoryInterface.php');
|
|
||||||
|
|
||||||
$this->factoryAction = Terminal::proposeListChoice("Use new trait or append to file ?", [ 'trait' => 'Use trait', 'append' => 'Append to file', ]);
|
|
||||||
|
|
||||||
if ($this->factoryAction === 'trait') {
|
|
||||||
$this->factoryTraitNamespace = implode('\\', [ $this->factoryNamespace, 'Factories' ]);
|
|
||||||
$this->factoryTraitNamespace = $this->readline(sprintf("Factory trait namespace (default: %s) : ", $this->factoryTraitNamespace), $this->factoryTraitNamespace);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function readSaveForm() : void
|
|
||||||
{
|
|
||||||
$this->formNamespace ??= $this->readline('Form namespace (default: Form\\) : ', 'Form');
|
|
||||||
|
|
||||||
$this->saveForm = ucfirst($this->name) . "Save";
|
|
||||||
$this->saveForm = $this->readline(sprintf('Form "create/update" name (default: %s) : ', $this->saveForm), $this->saveForm);
|
|
||||||
|
|
||||||
$this->saveContext = $this->saveForm . "Context";
|
|
||||||
$this->saveContext = $this->readline(sprintf('Context "create/update" (default: %s) : ', $this->saveContext), $this->saveContext);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function readDeleteForm() : void
|
|
||||||
{
|
|
||||||
$this->formNamespace ??= $this->readline('Form namespace (default: Form\\) : ') ?: 'Form';
|
|
||||||
|
|
||||||
$this->deleteForm = ucfirst($this->name) . "Delete";
|
|
||||||
$this->deleteForm = $this->readline(sprintf('Form "delete" name (default: %s) : ', $this->deleteForm), $this->deleteForm);
|
|
||||||
|
|
||||||
$this->deleteContext = $this->deleteForm . "Context";
|
|
||||||
$this->deleteContext = $this->readline(sprintf('Context "delete" (default: %s) : ', $this->deleteContext), $this->deleteContext);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*public function readApplicationPath(string $default) : void
|
|
||||||
{
|
|
||||||
$this->applicationPath = $this->readline(sprintf('Application path base (default: %s) : ', $default)) ?: $default;
|
|
||||||
}*/
|
|
||||||
|
|
||||||
public function generate() : void
|
|
||||||
{
|
|
||||||
$this->namespace = trim($this->namespace, '\\');
|
|
||||||
$this->formNamespace = trim($this->formNamespace, '\\');
|
|
||||||
$this->entityNamespace = trim($this->entityNamespace, '\\');
|
|
||||||
|
|
||||||
$this->compiledEntity = $this->defineEntityBoilerplate();
|
|
||||||
|
|
||||||
if (isset($this->saveForm)) {
|
|
||||||
$this->compiledSaveForm = $this->defineSaveFormBoilerplate();
|
|
||||||
$this->compiledSaveFormContext = $this->defineSaveFormContextBoilerplate();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($this->deleteForm)) {
|
|
||||||
$this->compiledDeleteForm = $this->defineDeleteFormBoilerplate();
|
|
||||||
$this->compiledDeleteFormContext = $this->defineDeleteFormContextBoilerplate();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($this->apiNamespace)) {
|
|
||||||
$this->compiledApi = $this->defineApiBoilerplate();
|
|
||||||
|
|
||||||
if ($this->includeDocs) {
|
|
||||||
$this->compiledDocs = $this->defineDocsBoilerplate();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($this->webNamespace)) {
|
|
||||||
$this->compiledWeb = $this->defineWebBoilerplate();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($this->factoryNamespace)) {
|
|
||||||
if (isset($this->factoryTraitNamespace)) {
|
|
||||||
$this->compiledFactoryTrait = $this->defineFactoryTraitBoilerplate();
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
$this->compiledFactory = $this->defineFactoryBoilerplate();
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->compiledFactoryInterface = $this->defineFactoryInterfaceBoilerplate();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function defineEntityBoilerplate() : string
|
|
||||||
{
|
|
||||||
return $this->replaceBoilerplateCode($this->getBoilerplateFile('Entity'));
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function defineSaveFormBoilerplate() : string
|
|
||||||
{
|
|
||||||
return $this->replaceBoilerplateCode($this->getBoilerplateFile('SaveForm'));
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function defineSaveFormContextBoilerplate() : string
|
|
||||||
{
|
|
||||||
return $this->replaceBoilerplateCode($this->getBoilerplateFile('SaveFormContext'));
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function defineDeleteFormBoilerplate() : string
|
|
||||||
{
|
|
||||||
return $this->replaceBoilerplateCode($this->getBoilerplateFile('DeleteForm'));
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function defineDeleteFormContextBoilerplate() : string
|
|
||||||
{
|
|
||||||
return $this->replaceBoilerplateCode($this->getBoilerplateFile('DeleteFormContext'));
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function defineFactoryInterfaceBoilerplate() : string
|
|
||||||
{
|
|
||||||
return $this->replaceBoilerplateCode($this->getBoilerplateFile('FactoryInterfaceAppend'));
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function defineFactoryTraitBoilerplate() : string
|
|
||||||
{
|
|
||||||
return $this->replaceBoilerplateCode($this->getBoilerplateFile('FactoryTrait'));
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function defineFactoryBoilerplate() : string
|
|
||||||
{
|
|
||||||
return $this->replaceBoilerplateCode($this->getBoilerplateFile('FactoryAppend'));
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function defineApiBoilerplate() : string
|
|
||||||
{
|
|
||||||
return $this->replaceBoilerplateCode($this->getBoilerplateFile('Api'));
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function defineDocsBoilerplate() : string
|
|
||||||
{
|
|
||||||
return $this->replaceBoilerplateCode($this->getBoilerplateFile('api-docs', '.md'));
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function defineWebBoilerplate() : string
|
|
||||||
{
|
|
||||||
return $this->replaceBoilerplateCode($this->getBoilerplateFile('Controller'));
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getBoilerplateFile(string $fileName, string $extension = ".php") : string
|
|
||||||
{
|
|
||||||
$path = implode(DIRECTORY_SEPARATOR, [ LEAN_API_PROJECT_PATH , 'skeleton', 'EntityGenerate', "{$fileName}{$extension}" ]);
|
|
||||||
$bp = file_get_contents($path);
|
|
||||||
|
|
||||||
if (! $bp ) {
|
|
||||||
throw new \InvalidArgumentException("Boilerplate file not found in path " . $path);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $bp;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getEntityBoilerplate() : string
|
|
||||||
{
|
|
||||||
$path = implode(DIRECTORY_SEPARATOR, [ LEAN_API_PROJECT_PATH , 'skeleton', 'EntityGenerate', 'Entity.php' ]);
|
|
||||||
$bp = file_get_contents($path);
|
|
||||||
|
|
||||||
if (! $bp ) {
|
|
||||||
throw new \InvalidArgumentException("Entity boilerplate file not found in path " . $path);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $bp;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function replaceBoilerplateCode(string $boilerplate) : string
|
|
||||||
{
|
|
||||||
# to be reworked with the |> operator in 8.5+
|
|
||||||
$boilerplate = $this->replaceNamespace($boilerplate);
|
|
||||||
$boilerplate = $this->replaceClassname($boilerplate);
|
|
||||||
$boilerplate = $this->replaceEntityNamespace($boilerplate);
|
|
||||||
$boilerplate = $this->replaceFormNamespace($boilerplate);
|
|
||||||
$boilerplate = $this->replaceSaveFormClassname($boilerplate);
|
|
||||||
$boilerplate = $this->replaceSaveFormContextClassname($boilerplate);
|
|
||||||
$boilerplate = $this->replaceDeleteFormClassname($boilerplate);
|
|
||||||
$boilerplate = $this->replaceDeleteFormContextClassname($boilerplate);
|
|
||||||
$boilerplate = $this->replaceFactoryNamespace($boilerplate);
|
|
||||||
$boilerplate = $this->replaceFactoryTraitNamespace($boilerplate);
|
|
||||||
$boilerplate = $this->replaceApiNamespace($boilerplate);
|
|
||||||
$boilerplate = $this->replaceApiBase($boilerplate);
|
|
||||||
$boilerplate = $this->replaceWebNamespace($boilerplate);
|
|
||||||
$boilerplate = $this->replaceWebBase($boilerplate);
|
|
||||||
|
|
||||||
return $boilerplate;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function replaceNamespace(string $boilerplate) : string
|
|
||||||
{
|
|
||||||
return str_replace('%NAMESPACE%', $this->namespace, $boilerplate);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function replaceEntityNamespace(string $boilerplate) : string
|
|
||||||
{
|
|
||||||
return match($this->entityNamespace ?? false) {
|
|
||||||
false => $boilerplate,
|
|
||||||
default => str_replace(
|
|
||||||
[ '%USE_ENTITY_NS%', '%ENTITY_NS%' ],
|
|
||||||
[ strstr($this->entityNamespace, '\\', true) ?: $this->entityNamespace, $this->entityNamespace ],
|
|
||||||
$boilerplate
|
|
||||||
)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function replaceSaveFormClassname(string $boilerplate) : string
|
|
||||||
{
|
|
||||||
return match($this->saveForm ?? false) {
|
|
||||||
false => $boilerplate,
|
|
||||||
default => str_replace(
|
|
||||||
[ '%SAVE_FORM_CLASSNAME%', '%SAVE_FORM_CLASSNAME_LC%' ],
|
|
||||||
[ $this->saveForm, lcfirst($this->saveForm) ],
|
|
||||||
$boilerplate
|
|
||||||
)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function replaceSaveFormContextClassname(string $boilerplate) : string
|
|
||||||
{
|
|
||||||
return match($this->saveContext ?? false) {
|
|
||||||
false => $boilerplate,
|
|
||||||
default => str_replace(
|
|
||||||
[ '%SAVE_FORM_CONTEXT_CLASSNAME%', '%SAVE_FORM_CONTEXT_CLASSNAME_LC%' ],
|
|
||||||
[ $this->saveContext, lcfirst($this->saveContext) ],
|
|
||||||
$boilerplate
|
|
||||||
)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function replaceDeleteFormClassname(string $boilerplate) : string
|
|
||||||
{
|
|
||||||
return match($this->deleteForm ?? false) {
|
|
||||||
false => $boilerplate,
|
|
||||||
default => str_replace(
|
|
||||||
[ '%DELETE_FORM_CLASSNAME%', '%DELETE_FORM_CLASSNAME_LC%' ],
|
|
||||||
[ $this->deleteForm, lcfirst($this->deleteForm) ],
|
|
||||||
$boilerplate
|
|
||||||
)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function replaceDeleteFormContextClassname(string $boilerplate) : string
|
|
||||||
{
|
|
||||||
return match($this->deleteContext ?? false) {
|
|
||||||
false => $boilerplate,
|
|
||||||
default => str_replace(
|
|
||||||
[ '%DELETE_FORM_CONTEXT_CLASSNAME%', '%DELETE_FORM_CONTEXT_CLASSNAME_LC%' ],
|
|
||||||
[ $this->deleteContext, lcfirst($this->deleteContext) ],
|
|
||||||
$boilerplate
|
|
||||||
)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function replaceFormNamespace(string $boilerplate) : string
|
|
||||||
{
|
|
||||||
return match($this->formNamespace ?? false) {
|
|
||||||
false => $boilerplate,
|
|
||||||
default => str_replace(
|
|
||||||
[ '%USE_FORM_NS%', '%FORM_NS%', ],
|
|
||||||
[ strstr($this->formNamespace, '\\', true) ?: $this->formNamespace, $this->formNamespace ],
|
|
||||||
$boilerplate
|
|
||||||
)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function replaceApiNamespace(string $boilerplate) : string
|
|
||||||
{
|
|
||||||
return match($this->apiNamespace ?? false) {
|
|
||||||
false => $boilerplate,
|
|
||||||
default => str_replace(
|
|
||||||
[ '%API_NS%', ],
|
|
||||||
[ rtrim($this->apiNamespace, '\\') ],
|
|
||||||
$boilerplate
|
|
||||||
)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function replaceApiBase(string $boilerplate) : string
|
|
||||||
{
|
|
||||||
return match($this->apiBase ?? false) {
|
|
||||||
false => $boilerplate,
|
|
||||||
default => str_replace(
|
|
||||||
[ '%API_ROUTE_BASE%', ],
|
|
||||||
[ $this->apiBase ],
|
|
||||||
$boilerplate
|
|
||||||
)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function replaceWebNamespace(string $boilerplate) : string
|
|
||||||
{
|
|
||||||
return match($this->webNamespace ?? false) {
|
|
||||||
false => $boilerplate,
|
|
||||||
default => str_replace(
|
|
||||||
[ '%WEB_NS%', ],
|
|
||||||
[ rtrim($this->webNamespace, '\\') ],
|
|
||||||
$boilerplate
|
|
||||||
)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function replaceWebBase(string $boilerplate) : string
|
|
||||||
{
|
|
||||||
return match($this->webBase ?? false) {
|
|
||||||
false => $boilerplate,
|
|
||||||
default => str_replace(
|
|
||||||
[ '%WEB_ROUTE_BASE%', ],
|
|
||||||
[ $this->webBase ],
|
|
||||||
$boilerplate
|
|
||||||
)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function replaceFactoryNamespace(string $boilerplate) : string
|
|
||||||
{
|
|
||||||
return match($this->factoryNamespace ?? false) {
|
|
||||||
false => $boilerplate,
|
|
||||||
default => str_replace(
|
|
||||||
[ '%FACTORY_NS%', ],
|
|
||||||
[ rtrim($this->factoryNamespace, '\\') ],
|
|
||||||
$boilerplate
|
|
||||||
)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function replaceFactoryTraitNamespace(string $boilerplate) : string
|
|
||||||
{
|
|
||||||
return match($this->factoryTraitNamespace ?? false) {
|
|
||||||
false => $boilerplate,
|
|
||||||
default => str_replace(
|
|
||||||
[ '%FACTORY_TRAIT_NS%', ],
|
|
||||||
[ rtrim($this->factoryTraitNamespace, '\\') ],
|
|
||||||
$boilerplate
|
|
||||||
)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function replaceClassname(string $boilerplate) : string
|
|
||||||
{
|
|
||||||
return str_replace(
|
|
||||||
[ '%CLASSNAME_LC%', '%CLASSNAME%' ],
|
|
||||||
[ strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $this->name)), $this->name ],
|
|
||||||
$boilerplate
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function readComposerNamespace() : ? string
|
|
||||||
{
|
|
||||||
if ( false !== $composerJson = Composer::readComposerJson() ) {
|
|
||||||
if ($psr4 = $composerJson['autoload']['psr-4'] ?? false) {
|
|
||||||
foreach ($psr4 as $ns => $directory) {
|
|
||||||
if ($directory === 'src/') {
|
|
||||||
return $ns;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function readComposerPsr4() : array
|
|
||||||
{
|
|
||||||
return include(implode(DIRECTORY_SEPARATOR, [ getenv('PROJECT_PATH'), 'vendor' , 'composer', 'autoload_psr4.php' ]));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api;
|
|
||||||
|
|
||||||
use League\Route\Strategy;
|
|
||||||
|
|
||||||
use League\Route\Http\Exception\NotFoundException;
|
|
||||||
use Lean\ApplicationStrategy\NotFoundDecoratorInterface;
|
|
||||||
use Lean\ApplicationStrategy\ThrowableHandler;
|
|
||||||
use Lean\Factory\HttpFactoryInterface;
|
|
||||||
use Picea\Asset\Asset;
|
|
||||||
use Psr\Container\ContainerInterface;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Psr\Http\Server\MiddlewareInterface;
|
|
||||||
use Picea\Picea;
|
|
||||||
use Psr\Http\Server\RequestHandlerInterface;
|
|
||||||
use function DI\get;
|
|
||||||
|
|
||||||
class ApplicationStrategy extends \Lean\ApplicationStrategy {
|
|
||||||
|
|
||||||
public function getNotFoundDecorator(NotFoundException $exception): MiddlewareInterface
|
|
||||||
{
|
|
||||||
return $this->getContainer()->get(NotFoundDecoratorInterface::class);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\ApplicationStrategy;
|
|
||||||
|
|
||||||
use DI\Attribute\Inject;
|
|
||||||
use Lean\Api\Lib\RenderCORS;
|
|
||||||
use Lean\ApplicationStrategy;
|
|
||||||
use Lean\Factory\HttpFactoryInterface;
|
|
||||||
use Picea\Picea;
|
|
||||||
use Psr\Container\ContainerInterface;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Psr\Http\Server\RequestHandlerInterface;
|
|
||||||
|
|
||||||
class MethodNotAllowedDecorator implements \Lean\ApplicationStrategy\MethodNotAllowedInterface
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
protected RenderCORS $cors,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
|
|
||||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
|
||||||
{
|
|
||||||
if ($request->getMethod() === 'OPTIONS') {
|
|
||||||
return $this->cors->fromResponse($handler->handle($request), true);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $handler->handle($request);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\ApplicationStrategy;
|
|
||||||
|
|
||||||
use DI\Attribute\Inject;
|
|
||||||
use Lean\Api\Middleware\ApiRenderer;
|
|
||||||
use Lean\Factory\HttpFactoryInterface;
|
|
||||||
use Picea\Picea;
|
|
||||||
use Psr\Container\ContainerInterface;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Psr\Http\Server\MiddlewareInterface;
|
|
||||||
use Psr\Http\Server\RequestHandlerInterface;
|
|
||||||
|
|
||||||
class NotFoundDecorator extends \Lean\ApplicationStrategy\NotFoundDecorator
|
|
||||||
{
|
|
||||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
|
||||||
{
|
|
||||||
if (php_sapi_name() !== 'cli' and ! defined('STDIN') and ApiRenderer::awaitingJson($request)) {
|
|
||||||
return $this->throw404api($request);
|
|
||||||
}
|
|
||||||
|
|
||||||
return parent::process($request, $handler);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function throw404api(ServerRequestInterface $request) : ResponseInterface
|
|
||||||
{
|
|
||||||
return $this->checkAssetTrigger($request) ?: $this->httpFactory->createJsonResponse([
|
|
||||||
'status' => 'error',
|
|
||||||
'message' => "Not Found",
|
|
||||||
'ts' => time(),
|
|
||||||
], 404);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\ApplicationStrategy;
|
|
||||||
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Psr\Http\Server\MiddlewareInterface;
|
|
||||||
use Psr\Http\Server\RequestHandlerInterface;
|
|
||||||
|
|
||||||
class ThrowableHandler extends \Lean\ApplicationStrategy\ThrowableHandler
|
|
||||||
{
|
|
||||||
public function process(
|
|
||||||
ServerRequestInterface $request,
|
|
||||||
RequestHandlerInterface $handler
|
|
||||||
): ResponseInterface {
|
|
||||||
try {
|
|
||||||
return $handler->handle($request);
|
|
||||||
} catch (\Throwable $ex) {
|
|
||||||
echo sprintf("%s in <strong>%s</strong> <pre>%s</pre>", $ex->getMessage(), $ex->getFile() . ":" . $ex->getLine(), $ex->getTraceAsString());
|
|
||||||
exit();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Attribute;
|
|
||||||
|
|
||||||
use Lean\Api\Attribute\Action\ActionTypeEnum;
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
|
|
||||||
abstract class Action {
|
|
||||||
abstract public function action(EntityInterface $entity, string $key, FormContextInterface $context, string $field): ActionTypeEnum;
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Attribute\Action;
|
|
||||||
|
|
||||||
enum ActionTypeEnum
|
|
||||||
{
|
|
||||||
case ValueModifier;
|
|
||||||
case Setter;
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Attribute\Action;
|
|
||||||
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
|
|
||||||
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::IS_REPEATABLE)]
|
|
||||||
class Trim extends \Lean\Api\Attribute\Action
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
public string $characters = " \n\r\t\v\0"
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function action(EntityInterface $entity, string $key, FormContextInterface $context, string $field): ActionTypeEnum
|
|
||||||
{
|
|
||||||
$context->$field = trim($context->$field, $this->characters);
|
|
||||||
|
|
||||||
return ActionTypeEnum::ValueModifier;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Attribute\Action;
|
|
||||||
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
|
|
||||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
|
||||||
class ValueAppend extends \Lean\Api\Attribute\Action
|
|
||||||
{
|
|
||||||
public function action(EntityInterface $entity, string $key, FormContextInterface $context, string $field): ActionTypeEnum
|
|
||||||
{
|
|
||||||
dump($entity->$key);
|
|
||||||
array_push($entity->$key, $context->$field);
|
|
||||||
|
|
||||||
return ActionTypeEnum::Setter;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Attribute\Action;
|
|
||||||
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
|
|
||||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
|
||||||
class ValuePrepend extends \Lean\Api\Attribute\Action
|
|
||||||
{
|
|
||||||
public function action(EntityInterface $entity, string $key, FormContextInterface $context, string $field): ActionTypeEnum
|
|
||||||
{
|
|
||||||
array_unshift($entity->$key, $context->$field);
|
|
||||||
|
|
||||||
return ActionTypeEnum::Setter;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Attribute\Action;
|
|
||||||
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
|
|
||||||
#[\Attribute(\Attribute::TARGET_PROPERTY)]
|
|
||||||
class ValueSet extends \Lean\Api\Attribute\Action
|
|
||||||
{
|
|
||||||
public function action(EntityInterface $entity, string $key, FormContextInterface $context, string $field): ActionTypeEnum
|
|
||||||
{
|
|
||||||
$entity->$key = $context->$field;
|
|
||||||
|
|
||||||
return ActionTypeEnum::Setter;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Attribute;
|
|
||||||
|
|
||||||
enum CommonRegexFormatEnum : string
|
|
||||||
{
|
|
||||||
case BasicEmail = "/[^@ \t\r\n]+@[^@ \t\r\n]+\.[^@ \t\r\n]+/i";
|
|
||||||
}
|
|
||||||
@@ -2,56 +2,15 @@
|
|||||||
|
|
||||||
namespace Lean\Api\Attribute;
|
namespace Lean\Api\Attribute;
|
||||||
|
|
||||||
use Lean\Api\Exception\MandatoryFieldException;
|
|
||||||
use Lean\Api\Exception\MaximumLengthException;
|
|
||||||
use Lean\Api\Exception\MinimumLengthException;
|
|
||||||
use Lean\Api\Exception\RegexFormatException;
|
|
||||||
|
|
||||||
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_CLASS)]
|
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_CLASS)]
|
||||||
class ContextField
|
class ContextField
|
||||||
{
|
{
|
||||||
public function __construct(
|
public function __construct(
|
||||||
public string $description = "",
|
public string $description = "",
|
||||||
public bool|MandatoryGroup $mandatory = false,
|
public bool $mandatory = false,
|
||||||
public ?int $minLength = null,
|
public ?int $minLength = null,
|
||||||
public ?int $maxLength = null,
|
public ?int $maxLength = null,
|
||||||
public ?int $minValue = null,
|
|
||||||
public ?int $maxValue = null,
|
|
||||||
public ?string $regexFormat = null,
|
public ?string $regexFormat = null,
|
||||||
public mixed $example = null,
|
public ?string $example = null,
|
||||||
public mixed $default = null,
|
|
||||||
public bool $hidden = false,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public function assertValueSpecs(mixed $value, bool $isNew) : void
|
|
||||||
{
|
|
||||||
if ($isNew && ( $this->mandatory === true && $value === null )) {
|
|
||||||
throw new MandatoryFieldException("Mandatory field must be provided a value.");
|
|
||||||
}
|
|
||||||
elseif ($value !== null) {
|
|
||||||
if (($this->minLength || $this->maxLength) && is_string($value)) {
|
|
||||||
if (mb_strlen($value) < $this->minLength) {
|
|
||||||
throw new MinimumLengthException("Minimum {$this->minLength} string length is required.");
|
|
||||||
}
|
|
||||||
elseif (mb_strlen($value) > $this->maxLength) {
|
|
||||||
throw new MaximumLengthException("Maximum {$this->maxLength} string length has been exceeded.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (($this->minValue || $this->maxValue) && is_numeric($value)) {
|
|
||||||
if ($value < $this->minValue) {
|
|
||||||
throw new MinimumLengthException("Minimum value set at {$this->minValue}.");
|
|
||||||
}
|
|
||||||
elseif ($value > $this->maxValue) {
|
|
||||||
throw new MaximumLengthException("Maximum value set at {$this->maxValue}.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($this->regexFormat) {
|
|
||||||
if (! preg_match($this->regexFormat, $value)) {
|
|
||||||
throw new RegexFormatException("Regex format {$this->regexFormat} is not valid for value {$value}.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Attribute;
|
|
||||||
|
|
||||||
enum ContextFieldActionEnum: string
|
|
||||||
{
|
|
||||||
case Replace = "replace";
|
|
||||||
case ArrayAppend = "array-append";
|
|
||||||
case ArrayPrepend = "array-prepend";
|
|
||||||
case Trim = "trim";
|
|
||||||
}
|
|
||||||
@@ -13,6 +13,5 @@ class EntityField
|
|||||||
public ?string $regexFormat = null,
|
public ?string $regexFormat = null,
|
||||||
public mixed $example = null,
|
public mixed $example = null,
|
||||||
public ?string $field = null,
|
public ?string $field = null,
|
||||||
public ?string $setterMethod = null,
|
|
||||||
) {}
|
) {}
|
||||||
}
|
}
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Attribute;
|
|
||||||
|
|
||||||
readonly class MandatoryGroup
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
public string $name,
|
|
||||||
public int $needed = 1,
|
|
||||||
) {}
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Attribute\Security;
|
|
||||||
|
|
||||||
#[\Attribute(\Attribute::TARGET_METHOD)]
|
|
||||||
class ActionLog
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
#public string $key,
|
|
||||||
) {}
|
|
||||||
}
|
|
||||||
@@ -1,120 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Cli;
|
|
||||||
|
|
||||||
use DI\Attribute\Inject;
|
|
||||||
use Lean\Lean;
|
|
||||||
use Lean\Api\Action;
|
|
||||||
use Mcnd\CLI\{Terminal, OptionValueTypeEnum, OptionStack};
|
|
||||||
use Notes\CLI\Attribute\{Option, Command};
|
|
||||||
use Psr\Http\Message\{ServerRequestInterface, ResponseInterface};
|
|
||||||
|
|
||||||
#[Command(description: PHP_EOL . <<<CLI
|
|
||||||
#[color:gray, bg: black]╔═══════════════════════════════════════════════════════════════════╗[#]
|
|
||||||
#[color:gray, bg: black]║ ║[#]
|
|
||||||
#[color:gray, bg: black]║ ║[#]
|
|
||||||
#[color:gray, bg: black]║ ║[#]
|
|
||||||
#[color:gray, bg: black]║ ║[#]
|
|
||||||
#[color:gray, bg: black]║ ░▒▓█▓▒░ ░▒▓████████▓▒░░▒▓██████▓▒░░▒▓███████▓▒░ ║[#]
|
|
||||||
#[color:gray, bg: black]║ ░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ ║[#]
|
|
||||||
#[color:gray, bg: black]║ ░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ ║[#]
|
|
||||||
#[color:gray, bg: black]║ ░▒▓█▓▒░ ░▒▓██████▓▒░ ░▒▓████████▓▒░▒▓█▓▒░░▒▓█▓▒░ ║[#]
|
|
||||||
#[color:gray, bg: black]║ ░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ ║[#]
|
|
||||||
#[color:gray, bg: black]║ ░▒▓█▓▒░ ░▒▓█▓▒░ ░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ ║[#]
|
|
||||||
#[color:gray, bg: black]║ ░▒▓████████▓▒░▒▓████████▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ ║[#]
|
|
||||||
#[color:gray, bg: black]║ ║[#]
|
|
||||||
#[color:gray, bg: black]║ ║[#]
|
|
||||||
#[color:gray, bg: black]║ A P I ║[#]
|
|
||||||
#[color:gray, bg: black]║ ║[#]
|
|
||||||
#[color:gray, bg: black]╚═══════════════════════════════════════════════════════════════════╝[#]
|
|
||||||
|
|
||||||
Try #[color:gray, bg: black]'cli lean-api --help'[#] for more information.
|
|
||||||
CLI
|
|
||||||
, command: 'lean-api')]
|
|
||||||
#[Option(switch: ['-h', '--help'], description: "Display help for the given command. When no command is given display help for the list command")]
|
|
||||||
class CodeGeneration
|
|
||||||
{
|
|
||||||
use \Lean\ControllerTrait;
|
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
public Lean $lean;
|
|
||||||
|
|
||||||
#[Command(description: "Create an entity and it's related boilerplate", command: "entity:generate")]
|
|
||||||
#[Option(switch: ['-p', '--application'], description: "Application to target", value: OptionValueTypeEnum::RequiredValue)]
|
|
||||||
#[Option(switch: ['-n', '--name'], description: "Write generated content into project", value: OptionValueTypeEnum::RequiredValue)]
|
|
||||||
#[Option(switch: ['-m', '--namespace'], description: "Which PSR-4 namespace should be used", value: OptionValueTypeEnum::OptionalValue)]
|
|
||||||
#[Option(switch: ['-f', '--form'], description: "Form and context name", value: OptionValueTypeEnum::OptionalValue)]
|
|
||||||
#[Option(switch: ['-s', '--saveForm'], description: "Include or not a save form", value: OptionValueTypeEnum::OptionalValue)]
|
|
||||||
#[Option(switch: ['-d', '--deleteForm'], description: "Include or not a delete form", value: OptionValueTypeEnum::OptionalValue)]
|
|
||||||
#[Option(switch: ['-a', '--api'], description: "Include or not an API controller", value: OptionValueTypeEnum::OptionalValue)]
|
|
||||||
#[Option(switch: ['-c', '--api-docs'], description: "Include or not an API documentation page", value: OptionValueTypeEnum::OptionalValue)]
|
|
||||||
#[Option(switch: ['-w', '--web'], description: "Include or not a web controller", value: OptionValueTypeEnum::OptionalValue)]
|
|
||||||
#[Option(switch: ['-f', '--factory'], description: "Factory file to add to", value: OptionValueTypeEnum::OptionalValue)]
|
|
||||||
#[Option(switch: ['-w', '--write'], description: "Write generated content into project's folder path",)]
|
|
||||||
#[Option(switch: ['-o', '--overwrite'], description: "Overwrite every files by default", value: OptionValueTypeEnum::NoValue)]
|
|
||||||
#[Option(switch: ['-t', '--default-answers'], description: "Auto-accept every default answers", value: OptionValueTypeEnum::NoValue)]
|
|
||||||
##[Option(switch: ['-p', '--path'], description: "Base project save path", value: OptionValueTypeEnum::OptionalValue)]
|
|
||||||
public function generate(ServerRequestInterface $request, array $arguments, OptionStack $options, string $rest): ResponseInterface
|
|
||||||
{
|
|
||||||
$name = $options->get('name')->value() ?: readline('Entity name : ');
|
|
||||||
|
|
||||||
if ( empty($name)) {
|
|
||||||
throw new \InvalidArgumentException("An entity name must be provided");
|
|
||||||
}
|
|
||||||
|
|
||||||
$applicationList = array_reverse(array_map(fn($e) => $e->name, $this->lean->applications));
|
|
||||||
$app = $options->get('application')->value() ?? Terminal::proposeListChoice("Select an application : ", $applicationList);
|
|
||||||
|
|
||||||
$entityGenerate = new Action\Console\EntityGenerate(
|
|
||||||
application: $this->lean->getApplication($applicationList[$app]),
|
|
||||||
name: $name,
|
|
||||||
overwrite: $options->get('overwrite')->value() ?? false,
|
|
||||||
default: $options->get('default-answers')->value() ?? false,
|
|
||||||
);
|
|
||||||
|
|
||||||
if ("" === ( $entityGenerate->namespace = $options->get('namespace')->value() ?: "" )) {
|
|
||||||
$entityGenerate->readNamespace();
|
|
||||||
}
|
|
||||||
|
|
||||||
$entityGenerate->readEntity();
|
|
||||||
|
|
||||||
if ($options->get('saveForm')->value() ?? Terminal::proposeListChoice("Add a save form ?", [ true => 'Yes', false => 'No', ])) {
|
|
||||||
$entityGenerate->readSaveForm();
|
|
||||||
$hasFactory = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($options->get('deleteForm')->value() ?? Terminal::proposeListChoice("Add a delete form ?", [ true => 'Yes', false => 'No', ])) {
|
|
||||||
$entityGenerate->readDeleteForm();
|
|
||||||
$hasFactory = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($hasFactory) && (
|
|
||||||
$options->get('factory')->value() ?? Terminal::proposeListChoice("Add to form factory ?", [ true => 'Yes', false => 'No', ]))
|
|
||||||
) {
|
|
||||||
$entityGenerate->readFactory();
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($options->get('web')->value() ?? Terminal::proposeListChoice("Add a Web controller ?", [ true => 'Yes', false => 'No', ])) {
|
|
||||||
$entityGenerate->readWeb();
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($options->get('api')->value() ?? Terminal::proposeListChoice("Add an API controller ?", [ true => 'Yes', false => 'No', ])) {
|
|
||||||
$entityGenerate->readApi();
|
|
||||||
|
|
||||||
if ($options->get('api-docs')->value() ?? Terminal::proposeListChoice("Provides documentation for this route ?", [ true => 'Yes', false => 'No', ])) {
|
|
||||||
$entityGenerate->includeDocs = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$entityGenerate->generate();
|
|
||||||
|
|
||||||
if ($options->get('write')->value() ?? Terminal::proposeListChoice("Write to disc or output results only ?", [ true => 'Write to disc', false => 'Output results only', ])) {
|
|
||||||
$entityGenerate->writeToDisc();
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
$entityGenerate->outputResults();
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->renderCLI($request, "done");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Controller\Debug;
|
|
||||||
|
|
||||||
use Lean\Api\{Controller, Entity, Form, Lib};
|
|
||||||
use Notes\Route\Attribute\Method\Route;
|
|
||||||
use Notes\Route\Attribute\Object\Route as RouteObj;
|
|
||||||
use Notes\Security\Attribute\Security;
|
|
||||||
use Notes\Security\Attribute\Taxus;
|
|
||||||
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
|
|
||||||
|
|
||||||
#[Security(locked: false)]
|
|
||||||
## [Taxus(Entity\UserTypeEnum::Developer)]
|
|
||||||
#[RouteObj(base: "/lean/debug/errors")]
|
|
||||||
class Errors {
|
|
||||||
use \Lean\Api\Lib\ControllerTrait;
|
|
||||||
|
|
||||||
#[Route("/documentation", name: "lean.api:errors-doc", method: "GET", description: "Documentation section")]
|
|
||||||
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
return $this->renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/debug/errors.md", [ Entity\Error::class, ], [ Form\Debug\ErrorContext::class ]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Route("/", name: "lean.api:errors-list", method: [ "GET" ], description: "List every errors received")]
|
|
||||||
public function list(ServerRequestInterface $request, array $arguments): ResponseInterface
|
|
||||||
{
|
|
||||||
$search = Entity\Error::searchRequest()->fromRequest($request);
|
|
||||||
$collection = Entity\Error::repository()->filterServerRequest($search)->loadAll()->iterate(function($e) {
|
|
||||||
unset($e->trace);
|
|
||||||
});
|
|
||||||
|
|
||||||
return $this->output($collection, $search->count);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Route("/{id:\d+}", name: "lean.api:errors-single", method: [ "GET" ], description: "Get a single error from it's ID")]
|
|
||||||
public function single(ServerRequestInterface $request, array $arguments): ResponseInterface
|
|
||||||
{
|
|
||||||
$type = Entity\Error::class;
|
|
||||||
$request = $this->searchEntityFromRequest($request, $type);
|
|
||||||
$result = $request->getAttribute('lean.searchRequest');
|
|
||||||
|
|
||||||
return $this->output($result[$type]->entity, $result[$type]->search->count);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Controller;
|
|
||||||
|
|
||||||
use Lean\Api\{Controller, Entity, Form, Lib};
|
|
||||||
use Notes\Route\Attribute\Method\Route;
|
|
||||||
use Notes\Route\Attribute\Object\Route as RouteObj;
|
|
||||||
use Notes\Security\Attribute\Security;
|
|
||||||
use Notes\Security\Attribute\Taxus;
|
|
||||||
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
|
|
||||||
|
|
||||||
#[Security(locked: false)]
|
|
||||||
#[RouteObj(base: "/lean")]
|
|
||||||
class LeanApi {
|
|
||||||
use \Lean\Api\Lib\ControllerTrait;
|
|
||||||
|
|
||||||
#[Route("/", name: "lean.api:doc", method: "GET", description: "Documentation section")]
|
|
||||||
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
return $this->renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/lean-api.md", [ ], [ ]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Controller\Security;
|
|
||||||
|
|
||||||
use DI\Attribute\Inject;
|
|
||||||
use CSSLSJ\TransportScolaire\Api\{Entity, Form};
|
|
||||||
use Notes\Route\Attribute\Method\Route;
|
|
||||||
use Notes\Security\Attribute\Security;
|
|
||||||
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
|
|
||||||
use Ulmus\User\Entity\UserInterface;
|
|
||||||
|
|
||||||
#[Security(locked: true)]
|
|
||||||
##[Taxus(Entity\UserTypeEnum::Developer)]
|
|
||||||
#[\Notes\Route\Attribute\Object\Route(base: "/lean/security/action-logs")]
|
|
||||||
class ActionLog {
|
|
||||||
use \Lean\Api\Lib\ControllerTrait;
|
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
protected UserInterface $user;
|
|
||||||
|
|
||||||
#[Route("/documentation", name: "lean.api:security-action-log-doc", method: "GET", description: "Route de documentation pour cette section")]
|
|
||||||
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
return $this->renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/security/action-logs.md", [ \Lean\Api\Entity\Security\ApiRequestLog::class ], [ \Lean\Api\Form\Security\RequestLogContext::class ]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Route("/", name: "lean.api:security-action-log-list", method: [ "GET" ], description: "Affiche la liste de toute les journaux d'actions")]
|
|
||||||
public function list(ServerRequestInterface $request, array $arguments): ResponseInterface
|
|
||||||
{
|
|
||||||
$result = $this->searchEntitiesFromRequest($request, $this->leanApiEntityFactory->securityApiActionLog)
|
|
||||||
->getAttribute('lean.searchRequest')[$this->leanApiEntityFactory->securityApiActionLog];
|
|
||||||
|
|
||||||
return $this->outputSearchResult($result);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Route("/{id:\d+}", name: "lean.api:security-action-log-single", method: [ "GET" ], description: "Permet de récupérer une action par son id")]
|
|
||||||
public function single(ServerRequestInterface $request, array $arguments): ResponseInterface
|
|
||||||
{
|
|
||||||
$result = $this->searchEntityFromRequest($request, $this->leanApiEntityFactory->securityApiActionLog)
|
|
||||||
->getAttribute('lean.searchRequest')[$this->leanApiEntityFactory->securityApiActionLog];
|
|
||||||
|
|
||||||
return $this->outputSearchResult($result);
|
|
||||||
}
|
|
||||||
|
|
||||||
# No routes needed, every modifying request hits this method
|
|
||||||
public function add(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
$entity = new $this->leanApiEntityFactory->securityApiActionLog();
|
|
||||||
|
|
||||||
$this->form($this->leanApiFormFactory->securityActionLogSave($entity, $this->user), $request->getAttribute('lean-api.security-action:context'));
|
|
||||||
|
|
||||||
return $this->output($entity, (int) $entity->isLoaded());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Controller\Security;
|
|
||||||
|
|
||||||
use DI\Attribute\Inject;
|
|
||||||
use CSSLSJ\TransportScolaire\Api\{Entity, Form};
|
|
||||||
use Notes\Route\Attribute\Method\Route;
|
|
||||||
use Notes\Security\Attribute\Security;
|
|
||||||
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
|
|
||||||
use Ulmus\User\Entity\UserInterface;
|
|
||||||
|
|
||||||
#[Security(locked: true)]
|
|
||||||
##[Taxus(Entity\UserTypeEnum::Developer)]
|
|
||||||
#[\Notes\Route\Attribute\Object\Route(base: "/lean/security/csrf")]
|
|
||||||
class CSRF {
|
|
||||||
use \Lean\Api\Lib\ControllerTrait;
|
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
protected UserInterface $user;
|
|
||||||
|
|
||||||
#[Route("/documentation", name: "lean.api:security-csrf-doc", method: "GET", description: "Route de documentation pour cette section")]
|
|
||||||
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
return $this->renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/security/csrf.md", [ ], [ ]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Route("/", name: "lean.api:security-csrf-generate", method: [ "GET" ], description: "Generate a CSRF token")]
|
|
||||||
public function generate(ServerRequestInterface $request, array $arguments): ResponseInterface
|
|
||||||
{
|
|
||||||
$context = $this->leanApiFormFactory->securityCsrfGenerateContext($request->withMethod('PUT'));
|
|
||||||
|
|
||||||
return $this->output([
|
|
||||||
'token' => $this->form($this->leanApiFormFactory->securityCsrfGenerate($this->user), $context)->executionStatus
|
|
||||||
], 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Route("/{token}", name: "lean.api:security-csrf-test-token", method: [ "POST", "PUT", "DELETE", "PATCH" ], description: "Verify a CSRF token")]
|
|
||||||
public function test(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
try {
|
|
||||||
$valid = $this->validate($request->withHeader('X-CSRF-Token', $arguments['token']), $arguments);
|
|
||||||
}
|
|
||||||
catch (\Throwable $ex) {
|
|
||||||
$valid = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->output([
|
|
||||||
'valid' => $valid
|
|
||||||
], 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function validate(ServerRequestInterface $request, array $arguments) : bool
|
|
||||||
{
|
|
||||||
$context = $this->leanApiFormFactory->securityCsrfVerifyTokenContext($request);
|
|
||||||
|
|
||||||
# This form call WILL throw an exception if anything is wrong (missing, invalid, outdated) with the CSRF token.
|
|
||||||
return (bool) $this->form($this->leanApiFormFactory->securityCsrfVerifyToken($this->user, $arguments['token']), $context)->executionStatus;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Controller\Security;
|
|
||||||
|
|
||||||
use DI\Attribute\Inject;
|
|
||||||
use CSSLSJ\TransportScolaire\Api\{Entity, Form};
|
|
||||||
use Notes\Route\Attribute\Method\Route;
|
|
||||||
use Notes\Security\Attribute\Security;
|
|
||||||
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
|
|
||||||
use Ulmus\User\Entity\UserInterface;
|
|
||||||
|
|
||||||
#[Security(locked: true)]
|
|
||||||
##[Taxus(Entity\UserTypeEnum::Developer)]
|
|
||||||
#[\Notes\Route\Attribute\Object\Route(base: "/lean/security/request-logs")]
|
|
||||||
class RequestLog {
|
|
||||||
use \Lean\Api\Lib\ControllerTrait;
|
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
protected UserInterface $user;
|
|
||||||
|
|
||||||
#[Route("/documentation", name: "lean.api:security-request-log-doc", method: "GET", description: "Route de documentation pour cette section")]
|
|
||||||
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
return $this->renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/security/request-logs.md", [ \Lean\Api\Entity\Security\ApiRequestLog::class ], [ \Lean\Api\Form\Security\RequestLogContext::class ]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Route("/", name: "lean.api:security-request-log-list", method: [ "GET" ], description: "Affiche la liste de toute les journaux de requête")]
|
|
||||||
public function list(ServerRequestInterface $request, array $arguments): ResponseInterface
|
|
||||||
{
|
|
||||||
$result = $this->searchEntitiesFromRequest($request, $this->leanApiEntityFactory->securityRequestLog)
|
|
||||||
->getAttribute('lean.searchRequest')[$this->leanApiEntityFactory->securityRequestLog];
|
|
||||||
|
|
||||||
return $this->outputSearchResult($result);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Route("/{id:\d+}", name: "lean.api:security-request-log-single", method: [ "GET" ], description: "Permet de récupérer une requête par son id")]
|
|
||||||
public function single(ServerRequestInterface $request, array $arguments): ResponseInterface
|
|
||||||
{
|
|
||||||
$result = $this->searchEntityFromRequest($request, $this->leanApiEntityFactory->securityRequestLog)
|
|
||||||
->getAttribute('lean.searchRequest')[$this->leanApiEntityFactory->securityRequestLog];
|
|
||||||
|
|
||||||
return $this->outputSearchResult($result);
|
|
||||||
}
|
|
||||||
|
|
||||||
# No routes needed, every request hits this method
|
|
||||||
public function add(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
$entity = new $this->leanApiEntityFactory->securityRequestLog();
|
|
||||||
|
|
||||||
$context = $this->leanApiFormFactory->securityRequestLogSaveContext($request->withAttribute('api:request-log-original-method', $request->getMethod())-> withMethod('PUT'));
|
|
||||||
|
|
||||||
$this->form($this->leanApiFormFactory->securityRequestLogSave($entity, $arguments['response'], $this->user), $context);
|
|
||||||
|
|
||||||
return $this->output($entity, (int) $entity->isLoaded());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Cronard;
|
|
||||||
|
|
||||||
use CSSLSJ\TransportScolaire\Api\{Controller\Api, Entity, Form, Lib};
|
|
||||||
use Notes\Breadcrumb\Attribute\Method\Breadcrumb;
|
|
||||||
use Notes\Cronard\Attribute\Method\Cronard;
|
|
||||||
use Notes\Route\Attribute\Method\Route;
|
|
||||||
use Notes\Route\Attribute\Object\Route as RouteObj;
|
|
||||||
use Notes\Security\Attribute\Taxus;
|
|
||||||
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
|
|
||||||
use Storage\{Cookie, Session};
|
|
||||||
use TheBugs\Email\MailerInterface;
|
|
||||||
use function CSSLSJ\TransportScolaire\Api\View\{form, route};
|
|
||||||
|
|
||||||
##[Taxus(Entity\UserTypeEnum::Developer)]
|
|
||||||
#[RouteObj(base: "/lean/cronard")]
|
|
||||||
class System {
|
|
||||||
use Lib\ControllerTrait;
|
|
||||||
|
|
||||||
#[Route("/", name: "lean-api.cronard:documentation", method: "GET", description: "Route de documentation pour cette section")]
|
|
||||||
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
|
||||||
{
|
|
||||||
return $this->renderMarkdown(getenv("PROJECT_PATH") . "/meta/docs/cronard.md", [ ], []);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Cronard('0 0 1 * *')]
|
|
||||||
#[Route("/clean/request-logs", name: "lean-api.cronard:clean-request-logs", method: ["DELETE"], description: "Fait le ménage automatiquement des logs de requêtes datant de plus d'un an")]
|
|
||||||
public function clean_request_logs(ServerRequestInterface $request, array $arguments): ResponseInterface
|
|
||||||
{
|
|
||||||
# return $this->outputSearchResult($results);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -15,9 +15,6 @@ trait DescriptorTrait
|
|||||||
elseif ($value instanceof \UnitEnum) {
|
elseif ($value instanceof \UnitEnum) {
|
||||||
return $value::class . "::" . $value->name;
|
return $value::class . "::" . $value->name;
|
||||||
}
|
}
|
||||||
elseif (is_array($value)) {
|
|
||||||
return sprintf('[ %s ]', implode(', ', array_map([ self::class, 'displayValue' ], $value)));
|
|
||||||
}
|
|
||||||
|
|
||||||
return $value;
|
return $value;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Entity;
|
|
||||||
|
|
||||||
use Picea\Ui\Method\Context\FormContextCastableInterface;
|
|
||||||
|
|
||||||
class ArrayCollection extends \Ulmus\Entity\ArrayCollection implements FormContextCastableInterface
|
|
||||||
{
|
|
||||||
public static function instance(mixed $value = [], null|string $entityClass = null) : self
|
|
||||||
{
|
|
||||||
return parent::instance($value, $entityClass);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Entity;
|
|
||||||
|
|
||||||
use Lean\Api\Attribute\EntityField;
|
|
||||||
use Ulmus\EntityTrait,
|
|
||||||
Ulmus\SearchRequest\SearchableInterface,
|
|
||||||
Ulmus\SearchRequest\SearchRequestInterface,
|
|
||||||
Ulmus\Entity\Field\Datetime;
|
|
||||||
|
|
||||||
use Ulmus\{Attribute\Obj\Table,
|
|
||||||
Entity\EntityInterface};
|
|
||||||
|
|
||||||
use Ulmus\{Api\Common\MethodEnum,
|
|
||||||
SearchRequest,
|
|
||||||
SearchRequest\Attribute\PropertyValueModifier\Split,
|
|
||||||
SearchRequest\Attribute\PropertyValueSource,
|
|
||||||
SearchRequest\Attribute\SearchOrderBy,
|
|
||||||
SearchRequest\Attribute\SearchWhere,
|
|
||||||
SearchRequest\SearchMethodEnum};
|
|
||||||
|
|
||||||
use Ulmus\Attribute\Property\{Field, Filter, FilterJoin, Relation, Join, Virtual, Where};
|
|
||||||
|
|
||||||
#[Table(name: "debug_errors", adapter: "lean.api")]
|
|
||||||
class Error implements EntityInterface, \JsonSerializable {
|
|
||||||
use EntityTrait;
|
|
||||||
|
|
||||||
#[Field\Id]
|
|
||||||
public int $id;
|
|
||||||
|
|
||||||
#[Field]
|
|
||||||
#[EntityField(description: "URL from which the error occurred")]
|
|
||||||
public string $url;
|
|
||||||
|
|
||||||
#[Field]
|
|
||||||
#[EntityField(description: "HTTP method", field: "httpMethod")]
|
|
||||||
public MethodEnum $method;
|
|
||||||
|
|
||||||
#[Field]
|
|
||||||
#[EntityField(description: "Error message")]
|
|
||||||
public string $message;
|
|
||||||
|
|
||||||
#[Field]
|
|
||||||
#[EntityField(description: "Error code")]
|
|
||||||
public int $code;
|
|
||||||
|
|
||||||
#[Field]
|
|
||||||
#[EntityField(description: "File from which the error occurred")]
|
|
||||||
public string $file;
|
|
||||||
|
|
||||||
#[Field]
|
|
||||||
#[EntityField(description: "Line in the file from which the error occurred")]
|
|
||||||
public int $line;
|
|
||||||
|
|
||||||
#[Field]
|
|
||||||
#[EntityField(description: "Stack trace of the exception")]
|
|
||||||
public array $trace;
|
|
||||||
|
|
||||||
#[Field\CreatedAt(name: "created_at")]
|
|
||||||
public Datetime $createdAt;
|
|
||||||
|
|
||||||
public function __toString() {
|
|
||||||
return mb_strlen($this->message) > 255 ? mb_substr($this->message, 0, 255) . "[...]" : $this->message;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function searchRequest(...$arguments) : SearchRequestInterface
|
|
||||||
{
|
|
||||||
return new #[SearchRequest\Attribute\SearchRequestParameter(Error::class)] class(...$arguments) extends SearchRequest\SearchRequest {
|
|
||||||
#[SearchRequest\Attribute\SearchWhere(source: SearchRequest\Attribute\PropertyValueSource::RequestAttribute)]
|
|
||||||
public int $id;
|
|
||||||
|
|
||||||
#[SearchWhere(method: SearchMethodEnum::Like)]
|
|
||||||
public string $message;
|
|
||||||
|
|
||||||
#[SearchOrderBy(parameter: "created_at",)]
|
|
||||||
public string $createdAt = SearchOrderBy::DESCENDING;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Entity\Field;
|
|
||||||
|
|
||||||
class Date extends Datetime {
|
|
||||||
|
|
||||||
public string $format = "Y-m-d";
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Entity\Field;
|
|
||||||
|
|
||||||
class Datetime extends \Ulmus\Entity\Field\Datetime
|
|
||||||
{
|
|
||||||
public function jsonSerialize(): mixed
|
|
||||||
{
|
|
||||||
return (string) $this;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Entity\Field;
|
|
||||||
|
|
||||||
class Time extends Datetime {
|
|
||||||
|
|
||||||
public string $format = "H:i:s";
|
|
||||||
}
|
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Entity\Security;
|
|
||||||
|
|
||||||
use Lean\Api\Attribute\EntityField;
|
|
||||||
use Notes\Attribute\Ignore;
|
|
||||||
use Ulmus\Attribute\Obj\Table;
|
|
||||||
use Ulmus\Attribute\Property\{Field, Filter, FilterJoin, OrderBy, Relation, Join, Virtual, Where};
|
|
||||||
use Ulmus\Common\Sql;
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
use Ulmus\Repository;
|
|
||||||
use Ulmus\User\Entity\UserInterface;
|
|
||||||
use Ulmus\SearchRequest;
|
|
||||||
|
|
||||||
#[Table(name: "lean_api_security_action_logs", adapter: "lean.api")]
|
|
||||||
class ApiActionLog implements EntityInterface, \JsonSerializable
|
|
||||||
{
|
|
||||||
use \Ulmus\EntityTrait;
|
|
||||||
|
|
||||||
#[Field\Id(name: "id")]
|
|
||||||
public int $id;
|
|
||||||
|
|
||||||
#[Field\ForeignKey(name: "object_id"), EntityField(field: "object_id")]
|
|
||||||
public int $objectId;
|
|
||||||
|
|
||||||
#[Field(name: "object_type"), EntityField(field: "object_type")]
|
|
||||||
public string $objectType;
|
|
||||||
|
|
||||||
#[Field\ForeignKey(name: "user_id"), EntityField(field: "user_id")]
|
|
||||||
public ? int $userId;
|
|
||||||
|
|
||||||
#[Field(name: "user_type", length: 100), EntityField(field: "user_type")]
|
|
||||||
public ? string $userType;
|
|
||||||
|
|
||||||
#[Field(name: "event", length: 100), EntityField]
|
|
||||||
public string $event;
|
|
||||||
|
|
||||||
#[Field(name: "method", length: 15), EntityField]
|
|
||||||
public string $method;
|
|
||||||
|
|
||||||
#[Field(name: "description"), EntityField]
|
|
||||||
public ? string $description;
|
|
||||||
|
|
||||||
#[Field(name: "data"), EntityField]
|
|
||||||
public array $data;
|
|
||||||
|
|
||||||
#[Field(name: "created_at")]
|
|
||||||
public \Ulmus\Entity\Field\Datetime $createdAt;
|
|
||||||
|
|
||||||
#[Relation("oneToOne", key: "user", foreignKey: "id")]
|
|
||||||
public UserInterface $userEntity;
|
|
||||||
|
|
||||||
public function getUser() : ? UserInterface
|
|
||||||
{
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getHash() : string
|
|
||||||
{
|
|
||||||
return md5(sprintf("%d:%s", $this->id, $this->objectType));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Ignore]
|
|
||||||
public static function searchRequest(...$arguments) : SearchRequest\SearchRequestInterface
|
|
||||||
{
|
|
||||||
return new #[SearchRequest\Attribute\SearchRequestParameter(ApiActionLog::class, description: "Les établissements peuvent être recherchés/filtrés de différentes manière en requête GET en empruntant la route de liste complète.")] class(... $arguments) extends SearchRequest\SearchRequest {
|
|
||||||
|
|
||||||
#[SearchRequest\Attribute\SearchWhere(source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)]
|
|
||||||
public string $event;
|
|
||||||
|
|
||||||
#[SearchRequest\Attribute\SearchWhere(source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)]
|
|
||||||
public string $method;
|
|
||||||
|
|
||||||
#[SearchRequest\Attribute\SearchWhere(parameter: "object_type", source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)]
|
|
||||||
public string $objectType;
|
|
||||||
|
|
||||||
#[SearchRequest\Attribute\SearchWhere(parameter: "object_id", source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)]
|
|
||||||
public int $objectId;
|
|
||||||
|
|
||||||
#[SearchRequest\Attribute\SearchWhere(parameter: "user_id", source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)]
|
|
||||||
public int $userId;
|
|
||||||
|
|
||||||
#[SearchRequest\Attribute\SearchWhere(parameter: "user_id", source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)]
|
|
||||||
public string $userType;
|
|
||||||
|
|
||||||
#[SearchRequest\Attribute\SearchOrderBy(field: "createdAt")]
|
|
||||||
public SearchRequest\Attribute\OrderByEnum $orderByDate = SearchRequest\Attribute\OrderByEnum::Descending;
|
|
||||||
|
|
||||||
#[SearchRequest\Attribute\SearchManual]
|
|
||||||
public int $page = 1;
|
|
||||||
|
|
||||||
#[SearchRequest\Attribute\SearchManual]
|
|
||||||
public int $limit = 0;
|
|
||||||
|
|
||||||
public function filter(Repository $repository) : Repository
|
|
||||||
{
|
|
||||||
return $repository;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Entity\Security;
|
|
||||||
|
|
||||||
use Lean\Api\Entity\Field\Datetime;
|
|
||||||
use Lean\Api\Lib;
|
|
||||||
use Lean\Api\Attribute\EntityField;
|
|
||||||
use Notes\Attribute\Ignore;
|
|
||||||
use Ulmus\Attribute\Obj\Table;
|
|
||||||
use Ulmus\Attribute\Property\{Field};
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
use Ulmus\SearchRequest;
|
|
||||||
|
|
||||||
#[Table(name: "lean_api_security_request_logs", adapter: "lean.api")]
|
|
||||||
class ApiRequestLog implements EntityInterface, \JsonSerializable
|
|
||||||
{
|
|
||||||
use \Ulmus\EntityTrait;
|
|
||||||
|
|
||||||
#[Field\PrimaryKey]
|
|
||||||
public int $id;
|
|
||||||
|
|
||||||
#[Field\ForeignKey(name: "user_id")]
|
|
||||||
#[EntityField(description: "ID de l'usagé (lorsque connecté) qui a lancé la requête", field: 'user_id')]
|
|
||||||
public ? int $userId = null;
|
|
||||||
|
|
||||||
#[Field(length: 10)]
|
|
||||||
#[EntityField(description: "Method HTTP")]
|
|
||||||
public string $method;
|
|
||||||
|
|
||||||
#[Field(length: 255)]
|
|
||||||
#[EntityField(description: "URI sans les paramètres")]
|
|
||||||
public string $endpoint;
|
|
||||||
|
|
||||||
#[Field(length: 15)]
|
|
||||||
#[EntityField(description: "IPv4 de l'usagé")]
|
|
||||||
public ? string $ipv4;
|
|
||||||
|
|
||||||
#[Field(length: 45)]
|
|
||||||
#[EntityField(description: "IPv6 de l'usagé")]
|
|
||||||
public ? string $ipv6;
|
|
||||||
|
|
||||||
#[Field(name: "request_headers")]
|
|
||||||
#[EntityField(field: "request_headers")]
|
|
||||||
public array $requestHeaders = [];
|
|
||||||
|
|
||||||
#[Field(name: "request_body")]
|
|
||||||
#[EntityField(field: "request_body")]
|
|
||||||
public array $requestBody = [];
|
|
||||||
|
|
||||||
#[Field(name: "status_code")]
|
|
||||||
#[EntityField(field: "status_code")]
|
|
||||||
public int $statusCode;
|
|
||||||
|
|
||||||
#[Field(name: "response_headers")]
|
|
||||||
#[EntityField(field: "response_headers")]
|
|
||||||
public array $responseHeaders = [];
|
|
||||||
|
|
||||||
#[Field(name: "response_body")]
|
|
||||||
#[EntityField(field: "response_body")]
|
|
||||||
public ? string $responseBody;
|
|
||||||
|
|
||||||
#[Field]
|
|
||||||
#[EntityField(field: "duration")]
|
|
||||||
public float $duration;
|
|
||||||
|
|
||||||
#[Field\UpdatedAt(name: "updated_at", readonly: true)]
|
|
||||||
#[EntityField(description: "Date de la dernière mise-à-jour pour cette donnée.")]
|
|
||||||
public ? Datetime $updatedAt;
|
|
||||||
|
|
||||||
#[Field\CreatedAt(name: "created_at", readonly: true)]
|
|
||||||
#[EntityField(description: "Date de création pour cette donnée.")]
|
|
||||||
public Datetime $createdAt;
|
|
||||||
|
|
||||||
#[Ignore]
|
|
||||||
public static function searchRequest(...$arguments) : SearchRequest\SearchRequestInterface
|
|
||||||
{
|
|
||||||
return new #[SearchRequest\Attribute\SearchRequestParameter(ApiRequestLog::class,)] class(... $arguments) extends SearchRequest\SearchRequest {
|
|
||||||
|
|
||||||
#[SearchRequest\Attribute\SearchWhere(parameter: 'id', description: "Récupère une requete par son id unique.", source: SearchRequest\Attribute\PropertyValueSource::RequestAttribute)]
|
|
||||||
public string $id;
|
|
||||||
|
|
||||||
#[SearchRequest\Attribute\SearchOrderBy(field: "createdAt")]
|
|
||||||
public string $orderByDate = "DESC";
|
|
||||||
|
|
||||||
#[SearchRequest\Attribute\SearchManual]
|
|
||||||
public int $page = 1;
|
|
||||||
|
|
||||||
#[SearchRequest\Attribute\SearchManual]
|
|
||||||
public int $limit = 50;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Entity\User;
|
|
||||||
|
|
||||||
interface UserPrivilegeInterface
|
|
||||||
{
|
|
||||||
public function isDeveloper() : bool;
|
|
||||||
public function isAdmin() : bool;
|
|
||||||
public function isUser() : bool;
|
|
||||||
public function isAnonymous() : bool;
|
|
||||||
}
|
|
||||||
@@ -7,7 +7,6 @@ use Lean\Factory\HttpFactory;
|
|||||||
use Notes\ObjectReflection;
|
use Notes\ObjectReflection;
|
||||||
use Notes\Route\Attribute\Method\Route;
|
use Notes\Route\Attribute\Method\Route;
|
||||||
use Ulmus\Attribute\Obj\Table;
|
use Ulmus\Attribute\Obj\Table;
|
||||||
use Ulmus\Attribute\Property\ArrayOf;
|
|
||||||
use Ulmus\Attribute\Property\Field;
|
use Ulmus\Attribute\Property\Field;
|
||||||
use Ulmus\SearchRequest\Attribute\SearchParameter;
|
use Ulmus\SearchRequest\Attribute\SearchParameter;
|
||||||
use Ulmus\SearchRequest\Attribute\SearchRequestParameter;
|
use Ulmus\SearchRequest\Attribute\SearchRequestParameter;
|
||||||
@@ -35,16 +34,8 @@ class EntityDescriptor
|
|||||||
$field = $property->getAttribute(Field::class);
|
$field = $property->getAttribute(Field::class);
|
||||||
|
|
||||||
if ($field) {
|
if ($field) {
|
||||||
$arrayOf = $property->getAttribute(ArrayOf::class);
|
|
||||||
$types = $property->getTypes();
|
$types = $property->getTypes();
|
||||||
|
|
||||||
if ($property->value ?? false) {
|
|
||||||
$default = $property->value instanceof \BackedEnum ? $property->value->value : $property->value;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
$default = $field->object->attributes['default'] ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$fields[] = [
|
$fields[] = [
|
||||||
'name' => $property->name,
|
'name' => $property->name,
|
||||||
'description' => $entityField->object->description ?? "",
|
'description' => $entityField->object->description ?? "",
|
||||||
@@ -54,8 +45,6 @@ class EntityDescriptor
|
|||||||
'allowNulls' => $property->allowsNull(),
|
'allowNulls' => $property->allowsNull(),
|
||||||
'length' => $field->object->length ?? null,
|
'length' => $field->object->length ?? null,
|
||||||
'readonly' => $field->object->readonly,
|
'readonly' => $field->object->readonly,
|
||||||
'default' => $default,
|
|
||||||
'arrayOf' => $arrayOf ?? null,
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -68,15 +57,8 @@ class EntityDescriptor
|
|||||||
$field = $property->getAttribute(SearchParameter::class);
|
$field = $property->getAttribute(SearchParameter::class);
|
||||||
|
|
||||||
if ($field) {
|
if ($field) {
|
||||||
$possibleValues = null;
|
|
||||||
$types = $property->getTypes();
|
$types = $property->getTypes();
|
||||||
|
|
||||||
foreach($types as $type) {
|
|
||||||
if (! $type->builtIn && enum_exists($type->type)) {
|
|
||||||
$possibleValues = implode(', ', array_map(fn($e) => $e->value, $type->type::cases()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$searchFields[] = [
|
$searchFields[] = [
|
||||||
'name' => $property->name,
|
'name' => $property->name,
|
||||||
'description' => $field->object->description,
|
'description' => $field->object->description,
|
||||||
@@ -84,7 +66,6 @@ class EntityDescriptor
|
|||||||
'tag' => $field->tag,
|
'tag' => $field->tag,
|
||||||
'type' => implode(' | ', array_map(fn($e) => $e->type, $types)),
|
'type' => implode(' | ', array_map(fn($e) => $e->type, $types)),
|
||||||
'allowNulls' => $property->allowsNull(),
|
'allowNulls' => $property->allowsNull(),
|
||||||
'possibleValues' => $possibleValues,
|
|
||||||
'default' => $this->displayValue($property->value ?? "")
|
'default' => $this->displayValue($property->value ?? "")
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Exception;
|
|
||||||
|
|
||||||
class CSRFInvalidToken extends \Exception {}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Exception;
|
|
||||||
|
|
||||||
class CSRFMissingToken extends \Exception {}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Exception;
|
|
||||||
|
|
||||||
class LeanApiException extends \InvalidArgumentException {}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Exception;
|
|
||||||
|
|
||||||
class MandatoryFieldException extends LeanApiException {}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Exception;
|
|
||||||
|
|
||||||
class MaximumLengthException extends LeanApiException {}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Exception;
|
|
||||||
|
|
||||||
class MinimumLengthException extends LeanApiException {}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Exception;
|
|
||||||
|
|
||||||
class RegexFormatException extends LeanApiException{}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Factory\FormFactories;
|
|
||||||
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
|
||||||
use Picea\Ui\Method\FormInterface;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
use Lean\Api\{Factory, Form, Entity, Lib};
|
|
||||||
|
|
||||||
trait DebugTrait{
|
|
||||||
|
|
||||||
public function errorSave(EntityInterface|Entity\Error $entity): FormInterface
|
|
||||||
{
|
|
||||||
return new Form\Debug\ErrorSave($this->languageHandler, $this->messageFactory, $entity);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function errorSaveContext(? ServerRequestInterface $request = null, ? string $formName = null): FormContextInterface
|
|
||||||
{
|
|
||||||
return new Form\Debug\ErrorContext($request ?: $this->request, $formName);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function errorDelete(EntityInterface|Entity\Error $entity): FormInterface
|
|
||||||
{
|
|
||||||
return new Form\Debug\ErrorDelete($this->languageHandler, $this->messageFactory, $entity);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function errorDeleteContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface
|
|
||||||
{
|
|
||||||
return new Lib\FormContext($request, $formName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Factory\FormFactories;
|
|
||||||
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
|
||||||
use Picea\Ui\Method\FormInterface;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
use Ulmus\User\Entity\UserInterface;
|
|
||||||
|
|
||||||
trait SecurityTrait
|
|
||||||
{
|
|
||||||
public function securityRequestLogSave(EntityInterface|\Lean\Api\Entity\Security\ApiRequestLog $entity, ResponseInterface $response, UserInterface $user): FormInterface
|
|
||||||
{
|
|
||||||
return new \Lean\Api\Form\Security\SaveRequestLog($this->languageHandler, $this->messageFactory, $entity, $response, $user);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function securityRequestLogSaveContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface
|
|
||||||
{
|
|
||||||
return new \Lean\Api\Form\Security\RequestLogContext($this->languageHandler, $this->messageFactory, $request ?: $this->request, $formName);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function securityCsrfGenerate(UserInterface $user): FormInterface
|
|
||||||
{
|
|
||||||
return new \Lean\Api\Form\Security\CsrfGenerate($this->languageHandler, $this->messageFactory, $user, 30);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function securityCsrfGenerateContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface
|
|
||||||
{
|
|
||||||
return new \Lean\Api\Form\Security\CsrfGenerateContext($this->languageHandler, $this->messageFactory, $request ?: $this->request, $formName);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function securityCsrfVerifyToken(UserInterface $user, string $token): FormInterface
|
|
||||||
{
|
|
||||||
return new \Lean\Api\Form\Security\CsrfVerifyToken($this->languageHandler, $this->messageFactory, $user, $token);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function securityCsrfVerifyTokenContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface
|
|
||||||
{
|
|
||||||
return new \Lean\Api\Form\Security\CsrfVerifyTokenContext($this->languageHandler, $this->messageFactory, $request ?: $this->request, $formName);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function securityActionLogSave(EntityInterface|\Lean\Api\Entity\Security\ApiActionLog $entity, UserInterface $user): FormInterface
|
|
||||||
{
|
|
||||||
return new \Lean\Api\Form\Security\SaveActionLog($this->languageHandler, $this->messageFactory, $entity, $user);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function securityActionLogSaveContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface
|
|
||||||
{
|
|
||||||
return new \Lean\Api\Form\Security\ActionLogContext($this->languageHandler, $this->messageFactory, $request->withParsedBody([]) ?: $this->request, $formName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Factory;
|
|
||||||
|
|
||||||
use Lean\Api\Entity;
|
|
||||||
|
|
||||||
class LeanApiEntityFactory
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
public string $error = Entity\Error::class,
|
|
||||||
public string $securityApiActionLog = Entity\Security\ApiActionLog::class,
|
|
||||||
public string $securityRequestLog = Entity\Security\ApiRequestLog::class,
|
|
||||||
) {}
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Factory;
|
|
||||||
|
|
||||||
use DI\Attribute\Inject;
|
|
||||||
use Lean\LanguageHandler;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
|
|
||||||
class LeanApiFormFactory implements LeanApiFormFactoryInterface
|
|
||||||
{
|
|
||||||
use FormFactories\DebugTrait, FormFactories\SecurityTrait;
|
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
protected ServerRequestInterface $request;
|
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
protected LanguageHandler $languageHandler;
|
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
protected MessageFactoryInterface $messageFactory;
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Factory;
|
|
||||||
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
|
||||||
use Picea\Ui\Method\FormInterface;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
use Lean\Api\Entity;
|
|
||||||
use Ulmus\User\Entity\UserInterface;
|
|
||||||
|
|
||||||
interface LeanApiFormFactoryInterface
|
|
||||||
{
|
|
||||||
### SECURITY / REQUEST LOGS
|
|
||||||
public function securityRequestLogSave(EntityInterface|\Lean\Api\Entity\Security\ApiRequestLog $entity, ResponseInterface $response, UserInterface $user): FormInterface;
|
|
||||||
public function securityRequestLogSaveContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface;
|
|
||||||
|
|
||||||
### SECURITY / CSRF
|
|
||||||
public function securityCsrfGenerate(UserInterface $user): FormInterface;
|
|
||||||
public function securityCsrfGenerateContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface;
|
|
||||||
|
|
||||||
### SECURITY / ACTION LOGS
|
|
||||||
public function securityActionLogSave(EntityInterface|\Lean\Api\Entity\Security\ApiActionLog $entity, UserInterface $user): FormInterface;
|
|
||||||
public function securityActionLogSaveContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface;
|
|
||||||
|
|
||||||
### DEBUG / ERROR
|
|
||||||
public function errorSave(Entity\Error|EntityInterface $entity): FormInterface;
|
|
||||||
public function errorSaveContext(?ServerRequestInterface $request = null, ? string $formName = null): FormContextInterface;
|
|
||||||
public function errorDelete(Entity\Error|EntityInterface $entity): FormInterface;
|
|
||||||
public function errorDeleteContext(?ServerRequestInterface $request = null, ? string $formName = null): FormContextInterface;
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Factory;
|
|
||||||
|
|
||||||
interface MessageFactoryInterface
|
|
||||||
{
|
|
||||||
public static function generateSuccess(string $message, ? string $header = null, ? string $class = null) : self;
|
|
||||||
public static function generateError(string $message, ? string $header = null, ? string $class = null) : self;
|
|
||||||
public static function generateWarning(string $message, ? string $header = null, ? string $class = null) : self;
|
|
||||||
public static function generateInformation(string $message, ? string $header = null, ? string $class = null) : self;
|
|
||||||
public static function generateDebug(string $message, ? string $header = null, ? string $class = null) : self;
|
|
||||||
public static function generateTrace(string $message, ? string $header = null, ? string $class = null) : self;
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Form\Debug;
|
|
||||||
|
|
||||||
use Lean\Api\{Entity};
|
|
||||||
use Lean\Api\Attribute\ContextField;
|
|
||||||
use Picea\Ui\Method\FormContext;
|
|
||||||
use Ulmus\Api\Common\MethodEnum;
|
|
||||||
use Ulmus\Entity\Field\Datetime;
|
|
||||||
|
|
||||||
#[ContextField(description: "This form saves an error received by the API")]
|
|
||||||
class ErrorContext extends FormContext
|
|
||||||
{
|
|
||||||
#[ContextField(description: "URL which the error was received from", hidden: true, )]
|
|
||||||
public string $url;
|
|
||||||
|
|
||||||
#[ContextField( description: "HTTP method used when this error was generated", hidden: true, )]
|
|
||||||
public MethodEnum|string $httpMethod;
|
|
||||||
|
|
||||||
#[ContextField(description: "Error message generated")]
|
|
||||||
public string $message;
|
|
||||||
|
|
||||||
#[ContextField(description: "HTTP error code")]
|
|
||||||
public int $code;
|
|
||||||
|
|
||||||
#[ContextField(description: "File in which the error occured")]
|
|
||||||
public string $file;
|
|
||||||
|
|
||||||
#[ContextField(description: "Line of the error")]
|
|
||||||
public int $line;
|
|
||||||
|
|
||||||
#[ContextField(description: "Complete stack trace (when available)")]
|
|
||||||
public array $trace;
|
|
||||||
|
|
||||||
public function valid(? Entity\Error $error = null): bool
|
|
||||||
{
|
|
||||||
$server = $this->getRequest()->getServerParams();
|
|
||||||
|
|
||||||
$this->url = ( ( 'on' === ( $server['HTTPS'] ?? false ) ) ? 'https' : 'http' ) . '://' . $server['HTTP_HOST'] . $server["REQUEST_URI"];
|
|
||||||
|
|
||||||
$this->httpMethod = MethodEnum::from($server['REQUEST_METHOD']);
|
|
||||||
|
|
||||||
return parent::valid();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Form\Debug;
|
|
||||||
|
|
||||||
use Lean\Api\Factory\MessageFactoryInterface;
|
|
||||||
use Lean\LanguageHandler;
|
|
||||||
use Lean\Api\{Lib, Entity};
|
|
||||||
|
|
||||||
class ErrorSave extends \Lean\Api\Form\Save {
|
|
||||||
|
|
||||||
public function __construct(
|
|
||||||
protected LanguageHandler $languageHandler,
|
|
||||||
protected MessageFactoryInterface $message,
|
|
||||||
public Entity\Error $entity,
|
|
||||||
) {
|
|
||||||
parent::__construct($this->languageHandler, $this->message);
|
|
||||||
|
|
||||||
$this->contextClass = ErrorContext::class;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+17
-8
@@ -6,28 +6,37 @@ use CSSLSJ\ExamenFga\Api\{Lib};
|
|||||||
use Picea\Ui\Method\{FormContextInterface};
|
use Picea\Ui\Method\{FormContextInterface};
|
||||||
use Ulmus\Entity\EntityInterface;
|
use Ulmus\Entity\EntityInterface;
|
||||||
|
|
||||||
abstract class Delete extends Form implements \Picea\Ui\Method\FormInterface {
|
class Delete implements \Picea\Ui\Method\FormInterface {
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
public EntityInterface $entity,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function getEntity() : EntityInterface
|
||||||
|
{
|
||||||
|
return $this->entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function initialize(FormContextInterface $context) : void {}
|
||||||
|
|
||||||
public function validate(FormContextInterface $context) : bool
|
public function validate(FormContextInterface $context) : bool
|
||||||
{
|
{
|
||||||
if ( ! $this->getEntity()->isLoaded() ) {
|
if ( ! $this->entity->isLoaded() ) {
|
||||||
$context->pushMessage($this->message::generateError(
|
$context->pushMessage(Lib\Message::generateError(
|
||||||
$this->lang('lean.api.form.delete.error.entity')
|
$this->lang('lean.api.form.delete.error.entity')
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
return $context->valid($this->getEntity()->isLoaded() ? $this->getEntity() : null);
|
return $context->valid();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function execute(FormContextInterface $context) : mixed
|
public function execute(FormContextInterface $context) : void
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
if ( $this->getEntity()::repository()->destroy($this->getEntity()) ) {
|
if ( $this->getEntity()::repository()->destroy($this->getEntity()) ) {
|
||||||
$context->pushMessage($this->message::generateSuccess(
|
$context->pushMessage(Lib\Message::generateSuccess(
|
||||||
$this->lang('lean.api.form.delete.success.save')
|
$this->lang('lean.api.form.delete.success.save')
|
||||||
));
|
));
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
throw new \InvalidArgumentException($this->lang('lean.api.form.delete.error.save'));
|
throw new \InvalidArgumentException($this->lang('lean.api.form.delete.error.save'));
|
||||||
|
|||||||
@@ -1,49 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Form;
|
|
||||||
|
|
||||||
use Lean\Api\Factory\MessageFactoryInterface;
|
|
||||||
use Lean\LanguageHandler;
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
use Ulmus\EntityCollection;
|
|
||||||
|
|
||||||
abstract class Form
|
|
||||||
{
|
|
||||||
protected string $contextClass;
|
|
||||||
|
|
||||||
public function __construct(
|
|
||||||
protected LanguageHandler $languageHandler,
|
|
||||||
protected MessageFactoryInterface $message,
|
|
||||||
# public EntityInterface $entity,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function validate(FormContextInterface $context) : bool
|
|
||||||
{
|
|
||||||
return $context->valid($this->getEntity()->isLoaded() ? $this->getEntity() : null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function initialize(FormContextInterface $context) : void
|
|
||||||
{
|
|
||||||
if(isset($this->contextClass) && ! $context instanceof $this->contextClass ) {
|
|
||||||
throw new \LogicException(
|
|
||||||
sprintf("Your context type should be a %s, received %s", $this->contextClass, $context::class)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function lang(string $key, array $variables = [])
|
|
||||||
{
|
|
||||||
return $this->languageHandler->languageFromKey($key, $variables);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getEntity() : EntityInterface|EntityCollection
|
|
||||||
{
|
|
||||||
if (! isset($this->entity)) {
|
|
||||||
throw new \InvalidArgumentException($this->lang("lean.api.form.error.entity"));
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->entity;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Form;
|
|
||||||
|
|
||||||
enum MessageTypeEnum
|
|
||||||
{
|
|
||||||
case Error;
|
|
||||||
case Success;
|
|
||||||
case Information;
|
|
||||||
case Warning;
|
|
||||||
case Debug;
|
|
||||||
case Trace;
|
|
||||||
}
|
|
||||||
+41
-139
@@ -2,194 +2,96 @@
|
|||||||
|
|
||||||
namespace Lean\Api\Form;
|
namespace Lean\Api\Form;
|
||||||
|
|
||||||
use CSLSJ\Lean\Form\Session\EmailContext;
|
use CSSLSJ\ExamenFga\Api\{Form\Location\SessionContext, Lib, Entity};
|
||||||
use Picea\Ui\Method\{FormContext, FormContextInterface};
|
use Picea\Ui\Method\{ FormContextInterface, Message\ErrorMessage };
|
||||||
|
|
||||||
use Lean\Api\Attribute\{Action, Action\ActionTypeEnum, ContextField, Action\ValueSet};
|
|
||||||
use Lean\Api\Exception\LeanApiException;
|
|
||||||
use Lean\Api\Exception\MandatoryFieldException;
|
|
||||||
use Lean\Api\Exception\MinimumLengthException;
|
|
||||||
use Notes\Common\ReflectedProperty;
|
|
||||||
use Notes\ObjectReflection;
|
|
||||||
use Ulmus\Attribute\Property\Field;
|
use Ulmus\Attribute\Property\Field;
|
||||||
use Lean\Api\Attribute\EntityField;
|
use Lean\Api\Attribute\EntityField;
|
||||||
|
use Lean\LanguageHandler;
|
||||||
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
use Ulmus\Entity\EntityInterface;
|
||||||
use Ulmus\Entity\Field\Datetime;
|
use Ulmus\Entity\Field\Datetime;
|
||||||
use Ulmus\EntityCollection;
|
use function CSSLSJ\ExamenFga\Api\View\{ lang };
|
||||||
|
|
||||||
abstract class Save extends Form implements \Picea\Ui\Method\FormInterface {
|
abstract class Save implements \Picea\Ui\Method\FormInterface {
|
||||||
|
|
||||||
protected bool $skipEntityCreatedAt = false;
|
public function __construct(
|
||||||
|
protected LanguageHandler $languageHandler,
|
||||||
|
# public EntityInterface $entity,
|
||||||
|
) {}
|
||||||
|
|
||||||
protected bool $skipEntityLastModified = false;
|
public function getEntity() : EntityInterface
|
||||||
|
|
||||||
protected string $messageSuccessSave = 'lean.api.form.save.success.save';
|
|
||||||
|
|
||||||
protected string $messageWarningSave = 'lean.api.form.save.warning.entity';
|
|
||||||
|
|
||||||
protected array $fields = [
|
|
||||||
'updatedAt' => 'updatedAt',
|
|
||||||
'createdAt' => 'createdAt'
|
|
||||||
];
|
|
||||||
|
|
||||||
protected array $reflectedProperties;
|
|
||||||
|
|
||||||
protected string $contextClass = FormContext::class;
|
|
||||||
|
|
||||||
public function initialize(FormContextInterface $context) : void
|
|
||||||
{
|
{
|
||||||
if ( $this->getEntity() instanceof EntityInterface && ! $this->getEntity()->isLoaded() ) {
|
if (! isset($this->entity)) {
|
||||||
if (method_exists($context, 'initializeEntity')) {
|
throw new \InvalidArgumentException($this->lang("lean.api.form.save.error.entity"));
|
||||||
$context->initializeEntity($this->getEntity());
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->assignContextToEntity($context);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
parent::initialize($context);
|
return $this->entity;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function validate(FormContextInterface $context) : bool
|
public function validate(FormContextInterface $context) : bool
|
||||||
{
|
{
|
||||||
# Context validates ContextField attributes containing properties on empty entity
|
# Context is validating inputs
|
||||||
$this->validateContextFields($context);
|
|
||||||
|
|
||||||
return $context->valid($this->getEntity()->isLoaded() ? $this->getEntity() : null);
|
return $context->valid($this->getEntity()->isLoaded() ? $this->getEntity() : null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function execute(FormContextInterface $context) : mixed
|
public function execute(FormContextInterface $context) : void
|
||||||
{
|
{
|
||||||
$entity = $this->getEntity();
|
$entity = $this->getEntity();
|
||||||
|
|
||||||
if ($entity->isLoaded() && ! $this->skipEntityLastModified) {
|
if ($entity->isLoaded() ) {
|
||||||
if (property_exists($entity, 'updatedAt') && $entity->repository()->generateDatasetDiff($entity) ) {
|
$entity->updatedAt = new Datetime();
|
||||||
if ($field = $entity::resolveEntity()->field('updatedAt')) {
|
|
||||||
$cls = $field->type->type;
|
|
||||||
$entity->updatedAt = new $cls();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
elseif (! $this->skipEntityCreatedAt) {
|
else {
|
||||||
if (property_exists($entity, 'createdAt') && empty($entity->createdAt)) {
|
$entity->createdAt = new Datetime();
|
||||||
if ($field = $entity::resolveEntity()->field('createdAt')) {
|
|
||||||
$cls = $field->type->type;
|
|
||||||
$entity->createdAt = new $cls();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->handleTimestamp($entity);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$this->assignContextToEntity($context);
|
$this->assignContextToEntity($context);
|
||||||
|
|
||||||
if ( $saved = $entity::repository()->save($entity) ) {
|
if ( $entity::repository()->save($entity) ) {
|
||||||
method_exists($context, 'pushSuccessMessage') && $context->pushSuccessMessage($this->messageSuccessSave);
|
$context->pushMessage(Lib\Message::generateSuccess(
|
||||||
|
$this->lang('lean.api.form.save.success.entity')
|
||||||
|
));
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
method_exists($context, 'pushWarningMessage') && $context->pushWarningMessage($this->messageWarningSave, [ 'entity' => substr($this->entity::class, strrpos($this->entity::class, '\\') + 1) ]);
|
throw new \InvalidArgumentException($this->lang('lean.api.form.save.error.entity'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch(\PDOException $ex) {
|
|
||||||
throw new \PDOException($this->lang('lean.api.form.save.error.pdo', [ 'error' => $ex->getMessage() ]));
|
|
||||||
}
|
|
||||||
catch(\Throwable $ex) {
|
catch(\Throwable $ex) {
|
||||||
method_exists($context, 'pushErrorMessage') && $context->pushErrorMessage($ex->getMessage());
|
throw new \ErrorException($this->lang('lean.api.form.save.error.pdo', [ 'error' => $ex->getMessage() ]));
|
||||||
}
|
}
|
||||||
|
|
||||||
return $saved ?? false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function validateContextFields(FormContextInterface $context) : void
|
protected function lang(string $key, array $variables = [])
|
||||||
{
|
{
|
||||||
foreach ($this->reflectedProperties($context) as $name => $property) {
|
return $this->languageHandler->languageFromKey($key, $variables);
|
||||||
$attribute = $property->getAttribute(ContextField::class);
|
|
||||||
|
|
||||||
if ($attribute) {
|
|
||||||
try {
|
|
||||||
$attribute->object->assertValueSpecs($context->$name ?? null, ! $this->getEntity()->isLoaded());
|
|
||||||
} catch (LeanApiException $e) {
|
|
||||||
throw new MandatoryFieldException("An error occured with field '$name': " . $e->getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function assignContextToEntity(FormContextInterface $context) : void
|
protected function assignContextToEntity(FormContextInterface $context) : void
|
||||||
{
|
{
|
||||||
$entity = $this->getEntity();
|
$entity = $this->getEntity();
|
||||||
|
|
||||||
foreach($entity::resolveEntity()->getPropertyHavingAttribute(EntityField::class) as $key => $entityField) {
|
foreach($entity::resolveEntity()->fieldList() as $key => $property) {
|
||||||
$property = $entity::resolveEntity()->reflectedClass->getProperties(true)[$key];
|
$field = $property->getAttribute(Field::class)->object;
|
||||||
|
|
||||||
if ($property) {
|
if (! $field->readonly) {
|
||||||
if (($property->getAttribute(Field::class)->object->readonly ?? false) && $entity->isLoaded()) {
|
$apiField = $property->getAttribute(EntityField::class)->object ?? null;
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$apiField = $entityField[0]->object ;
|
if ($apiField) {
|
||||||
$var = $apiField->field ?: $key;
|
if ($apiField->field) {
|
||||||
$attr = $this->reflectedProperties($context)[$var] ?? false;
|
if ( isset($context->{$apiField->field}) ) {
|
||||||
|
$entity->$key = $context->{$apiField->field};
|
||||||
$contextField = $attr ? $attr->getAttribute(ContextField::class) : null;
|
}
|
||||||
|
|
||||||
if ( property_exists($context, $var) && new \ReflectionProperty($context, $var)->isInitialized($context) ) {
|
|
||||||
if ($apiField->setterMethod) {
|
|
||||||
# Use a setter method
|
|
||||||
call_user_func([ $entity, $apiField->setterMethod ], $context->{$var});
|
|
||||||
}
|
}
|
||||||
elseif($attr) {
|
else {
|
||||||
$actions = [];
|
if ( isset($context->{$key}) ) {
|
||||||
|
$entity->$key = $context->{$key};
|
||||||
foreach($attr->getAttributes(Action::class) as $item) {
|
|
||||||
$actions[] = $item->object->action($entity, $key, $context, $var);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! in_array(ActionTypeEnum::Setter, $actions)) {
|
|
||||||
new ValueSet()->action($entity, $key, $context, $var);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
elseif (! $entity->isLoaded() && $contextField) {
|
|
||||||
# Applies 'default' value assigned to ContextField property
|
|
||||||
if (isset($contextField->object->default)) {
|
|
||||||
if (is_callable($contextField->object->default)) {
|
|
||||||
$entity->$key = call_user_func_array($contextField->object->default, [ $context, ]);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
$entity->$key = $contextField->object->default;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function handleTimestamp(EntityInterface $entity) : void
|
|
||||||
{
|
|
||||||
if ($entity->isLoaded()) {
|
|
||||||
if (property_exists($entity, $this->fields['updatedAt']) && $entity->repository()->generateDatasetDiff($entity) ) {
|
|
||||||
$field = $this->fields['updatedAt'];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if (property_exists($entity, $this->fields['createdAt']) && empty($entity->{$this->fields['createdAt']})) {
|
|
||||||
$field = $this->fields['createdAt'];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($field ?? false) {
|
|
||||||
$cls = $entity::resolveEntity()->field($field)->type->type;
|
|
||||||
$entity->{$field} = new $cls();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private function reflectedProperties(FormContextInterface $context) : array
|
|
||||||
{
|
|
||||||
$this->reflectedProperties ??= ObjectReflection::fromClass($context::class)->reflectProperties(\ReflectionProperty::IS_PUBLIC);
|
|
||||||
|
|
||||||
return $this->reflectedProperties;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Form\Security;
|
|
||||||
|
|
||||||
use CSSLSJ\TransportScolaire\Api\{Entity};
|
|
||||||
use Lean\Api\Attribute\ContextField;
|
|
||||||
use Lean\Api\Lib\FormContext;
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
use Ulmus\Event\Entity\DatasetFill;
|
|
||||||
use Ulmus\Ulmus;
|
|
||||||
|
|
||||||
#[ContextField(description: "")]
|
|
||||||
class ActionLogContext extends FormContext
|
|
||||||
{
|
|
||||||
protected EntityInterface $entity;
|
|
||||||
|
|
||||||
#[ContextField(mandatory: true)]
|
|
||||||
public string $event;
|
|
||||||
|
|
||||||
#[ContextField(mandatory: true)]
|
|
||||||
public string $method;
|
|
||||||
|
|
||||||
#[ContextField(mandatory: true)]
|
|
||||||
public int $object_id;
|
|
||||||
|
|
||||||
#[ContextField(mandatory: true)]
|
|
||||||
public string $object_type;
|
|
||||||
|
|
||||||
#[ContextField]
|
|
||||||
public ? int $user_id;
|
|
||||||
|
|
||||||
#[ContextField]
|
|
||||||
public string $user_type;
|
|
||||||
|
|
||||||
#[ContextField]
|
|
||||||
public string $description;
|
|
||||||
|
|
||||||
#[ContextField]
|
|
||||||
public array $data = [];
|
|
||||||
|
|
||||||
private DatasetFill $datasetFillEvent;
|
|
||||||
|
|
||||||
public function attachEntity(EntityInterface $entity) : void
|
|
||||||
{
|
|
||||||
$this->entity = $entity;
|
|
||||||
|
|
||||||
$this->datasetFillEvent = new class() implements \Ulmus\Event\Entity\DatasetFill
|
|
||||||
{
|
|
||||||
public readonly array $data;
|
|
||||||
|
|
||||||
public function execute(\Generator $generator, \Ulmus\Entity\EntityInterface $entity): void
|
|
||||||
{
|
|
||||||
$this->data = $entity::repository()->generateDatasetDiff($entity);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
$this->entity->eventRegister($this->datasetFillEvent);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function initializeEntity(\Lean\Api\Entity\Security\ApiActionLog $actionLog) : void
|
|
||||||
{
|
|
||||||
if (isset($this->entity) && $this->entity->isLoaded()) {
|
|
||||||
if ($pk = array_key_first($this->entity::resolveEntity()->getPrimaryKeyField())) {
|
|
||||||
if (isset($this->entity->$pk)) {
|
|
||||||
$this->object_id = $this->entity->$pk;
|
|
||||||
$this->object_type = $this->entity::class;
|
|
||||||
|
|
||||||
if (isset($this->datasetFillEvent->data)) {
|
|
||||||
$this->data = $this->datasetFillEvent->data;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
throw new \InvalidArgumentException("An EntityInterface must be provided using the attachEntity() method.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function valid(? \Lean\Api\Entity\Security\ApiActionLog $actionLog = null): bool
|
|
||||||
{
|
|
||||||
return isset($this->object_id) && isset($this->object_type);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Form\Security;
|
|
||||||
|
|
||||||
use Lean\Api\{Entity};
|
|
||||||
use Lean\Api\Factory\MessageFactoryInterface;
|
|
||||||
use Lean\LanguageHandler;
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Ulmus\User\Entity\UserInterface;
|
|
||||||
|
|
||||||
class CsrfGenerate extends \Lean\Api\Form\Save
|
|
||||||
{
|
|
||||||
protected string $contextClass = CsrfGenerateContext::class;
|
|
||||||
|
|
||||||
public function __construct(
|
|
||||||
protected LanguageHandler $languageHandler,
|
|
||||||
protected MessageFactoryInterface $message,
|
|
||||||
protected UserInterface $entity,
|
|
||||||
protected int $expires = (10 * 60), # 10 minutes
|
|
||||||
)
|
|
||||||
{
|
|
||||||
parent::__construct($this->languageHandler, $this->message);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function initialize(FormContextInterface $context): void { }
|
|
||||||
|
|
||||||
public function execute(FormContextInterface $context): mixed
|
|
||||||
{
|
|
||||||
$ts = ( new \Datetime() )->getTimestamp();
|
|
||||||
|
|
||||||
$jwt = new \Ulmus\User\Authorize\Bearer\JsonWebTokenEncoder([
|
|
||||||
'sub' => $this->getEntity()->isLoaded() ? $this->getEntity()->id : null,
|
|
||||||
'iat' => $ts,
|
|
||||||
'exp' => $ts + $this->expires,
|
|
||||||
], hash('sha512', getenv('LEAN_RANDOM')));
|
|
||||||
|
|
||||||
return $jwt->encode();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Form\Security;
|
|
||||||
|
|
||||||
use CSSLSJ\TransportScolaire\Api\{Entity};
|
|
||||||
use Lean\Api\Attribute\ContextField;
|
|
||||||
use Lean\Api\Exception\CSRFMissingToken;
|
|
||||||
use Lean\Api\Lib\FormContext;
|
|
||||||
use Ulmus\User\Entity\UserInterface;
|
|
||||||
|
|
||||||
#[ContextField(description: "")]
|
|
||||||
class CsrfGenerateContext extends FormContext
|
|
||||||
{
|
|
||||||
public function valid(? UserInterface $user = null): bool
|
|
||||||
{
|
|
||||||
return parent::valid();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Form\Security;
|
|
||||||
|
|
||||||
use Lean\Api\{Entity};
|
|
||||||
use Lean\Api\Factory\MessageFactoryInterface;
|
|
||||||
use Lean\LanguageHandler;
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Ulmus\User\Authorize\Bearer\JsonWebTokenDecoder;
|
|
||||||
use Ulmus\User\Entity\UserInterface;
|
|
||||||
|
|
||||||
class CsrfVerifyToken extends \Lean\Api\Form\Save
|
|
||||||
{
|
|
||||||
protected string $contextClass = CsrfVerifyTokenContext::class;
|
|
||||||
|
|
||||||
public function __construct(
|
|
||||||
protected LanguageHandler $languageHandler,
|
|
||||||
protected MessageFactoryInterface $message,
|
|
||||||
protected UserInterface $entity,
|
|
||||||
protected string $token,
|
|
||||||
)
|
|
||||||
{
|
|
||||||
parent::__construct($this->languageHandler, $this->message);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function initialize(FormContextInterface $context): void { }
|
|
||||||
|
|
||||||
public function execute(FormContextInterface $context): bool
|
|
||||||
{
|
|
||||||
$decoder = new JsonWebTokenDecoder($this->token, hash('sha512', getenv('LEAN_RANDOM')));
|
|
||||||
|
|
||||||
$decoder->decode();
|
|
||||||
# Validate JWT
|
|
||||||
# throw error if any
|
|
||||||
|
|
||||||
# Validate expires
|
|
||||||
# throw expires error if any
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Form\Security;
|
|
||||||
|
|
||||||
use CSSLSJ\TransportScolaire\Api\{Entity};
|
|
||||||
use Lean\Api\Attribute\ContextField;
|
|
||||||
use Lean\Api\Exception\CSRFMissingToken;
|
|
||||||
use Lean\Api\Lib\FormContext;
|
|
||||||
use Ulmus\User\Entity\UserInterface;
|
|
||||||
|
|
||||||
#[ContextField(description: "")]
|
|
||||||
class CsrfVerifyTokenContext extends FormContext
|
|
||||||
{
|
|
||||||
public function valid(? UserInterface $user = null): bool
|
|
||||||
{
|
|
||||||
if ( in_array($this->getRequest()->getMethod(), [ 'POST', 'PUT', 'DELETE', 'PATCH' ]) ) {
|
|
||||||
if (! $this->getRequest()->hasHeader('X-CSRF-Token')) {
|
|
||||||
throw new CSRFMissingToken("A CSRF token must be provided to run non-safe methods.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return parent::valid();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Form\Security;
|
|
||||||
|
|
||||||
use CSSLSJ\TransportScolaire\Api\{Entity};
|
|
||||||
use Lean\Api\Attribute\ContextField;
|
|
||||||
use Lean\Api\Lib\FormContext;
|
|
||||||
|
|
||||||
#[ContextField(description: "")]
|
|
||||||
class RequestLogContext extends FormContext
|
|
||||||
{
|
|
||||||
#[ContextField]
|
|
||||||
public ? int $user_id;
|
|
||||||
|
|
||||||
#[ContextField]
|
|
||||||
public string $method;
|
|
||||||
|
|
||||||
#[ContextField]
|
|
||||||
public string $endpoint;
|
|
||||||
|
|
||||||
#[ContextField]
|
|
||||||
public string $ipv4;
|
|
||||||
|
|
||||||
#[ContextField]
|
|
||||||
public string $ipv6;
|
|
||||||
|
|
||||||
#[ContextField]
|
|
||||||
public array $request_headers;
|
|
||||||
|
|
||||||
#[ContextField]
|
|
||||||
public array $request_body;
|
|
||||||
|
|
||||||
#[ContextField]
|
|
||||||
public int $status_code;
|
|
||||||
|
|
||||||
#[ContextField]
|
|
||||||
public array $response_headers;
|
|
||||||
|
|
||||||
#[ContextField]
|
|
||||||
public string $response_body;
|
|
||||||
|
|
||||||
#[ContextField]
|
|
||||||
public float $duration;
|
|
||||||
|
|
||||||
public function valid(? \Lean\Api\Entity\Security\ApiRequestLog $requestLog = null): bool
|
|
||||||
{
|
|
||||||
return parent::valid();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Form\Security;
|
|
||||||
|
|
||||||
use Lean\Api\{Attribute\Action, Entity};
|
|
||||||
use Lean\Api\Factory\MessageFactoryInterface;
|
|
||||||
use Lean\LanguageHandler;
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Ulmus\User\Entity\UserInterface;
|
|
||||||
|
|
||||||
class SaveActionLog extends \Lean\Api\Form\Save
|
|
||||||
{
|
|
||||||
protected string $contextClass = ActionLogContext::class;
|
|
||||||
|
|
||||||
public function __construct(
|
|
||||||
protected LanguageHandler $languageHandler,
|
|
||||||
protected MessageFactoryInterface $message,
|
|
||||||
protected Entity\Security\ApiActionLog $entity,
|
|
||||||
protected UserInterface $user,
|
|
||||||
)
|
|
||||||
{
|
|
||||||
parent::__construct($this->languageHandler, $this->message);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function initialize(FormContextInterface|ActionLogContext $context): void
|
|
||||||
{
|
|
||||||
parent::initialize($context);
|
|
||||||
|
|
||||||
if ($this->user->isLoaded()) {
|
|
||||||
$context->user_id = $this->user->id;
|
|
||||||
$context->user_type = $this->user::class;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Form\Security;
|
|
||||||
|
|
||||||
use Lean\Api\{Entity};
|
|
||||||
use Lean\Api\Factory\MessageFactoryInterface;
|
|
||||||
use Lean\LanguageHandler;
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Ulmus\User\Entity\UserInterface;
|
|
||||||
|
|
||||||
class SaveRequestLog extends \Lean\Api\Form\Save
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
protected LanguageHandler $languageHandler,
|
|
||||||
protected MessageFactoryInterface $message,
|
|
||||||
protected Entity\Security\ApiRequestLog $entity,
|
|
||||||
protected ResponseInterface $response,
|
|
||||||
protected UserInterface $user,
|
|
||||||
)
|
|
||||||
{
|
|
||||||
parent::__construct($this->languageHandler, $this->message);
|
|
||||||
|
|
||||||
$this->contextClass = RequestLogContext::class;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function initialize(FormContextInterface|RequestLogContext $context): void
|
|
||||||
{
|
|
||||||
parent::initialize($context);
|
|
||||||
|
|
||||||
$request = $context->getRequest();
|
|
||||||
|
|
||||||
$context->user_id = $this->user->isLoaded() ? $this->user->id : null;
|
|
||||||
$context->method = $request->getAttribute('api:request-log-original-method');
|
|
||||||
$context->endpoint = $request->getUri();
|
|
||||||
$context->ipv4 = $request->getHeaderLine('x-forwarded-for') ?: $request->getServerParams()['REMOTE_ADDR'];
|
|
||||||
$context->request_headers = array_replace($request->getHeaders(), [ 'authorization' => "{removed}", ]);
|
|
||||||
$context->request_body = $request->getBody()->getSize() > 100000 ? "{too large}" : $request->getParsedBody();
|
|
||||||
$context->status_code = $this->response->getStatusCode();
|
|
||||||
$context->response_headers = $this->response->getHeaders();
|
|
||||||
$context->response_body = substr($this->response->getBody()->getContents(), 0, 100000);
|
|
||||||
$context->duration = microtime(true) - $request->getServerParams()['REQUEST_TIME'];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+7
-23
@@ -15,6 +15,7 @@ class FormDescriptor
|
|||||||
|
|
||||||
foreach($forms as $form) {
|
foreach($forms as $form) {
|
||||||
$fields = [];
|
$fields = [];
|
||||||
|
$propertyHtml = "";
|
||||||
$formName = is_object($form) ? $form::class : $form;
|
$formName = is_object($form) ? $form::class : $form;
|
||||||
$reflector = new ObjectReflection($formName);
|
$reflector = new ObjectReflection($formName);
|
||||||
|
|
||||||
@@ -23,21 +24,17 @@ class FormDescriptor
|
|||||||
foreach($reflector->reflectProperties() as $property) {
|
foreach($reflector->reflectProperties() as $property) {
|
||||||
$field = $property->getAttribute(ContextField::class);
|
$field = $property->getAttribute(ContextField::class);
|
||||||
|
|
||||||
if ($field && ! $field->object->hidden ) {
|
if ($field) {
|
||||||
$types = $property->getTypes();
|
$types = $property->getTypes();
|
||||||
|
|
||||||
$fields[] = [
|
$fields[] = [
|
||||||
'name' => $property->name,
|
'name' => $property->name,
|
||||||
'mandatory' => $field->object->mandatory,
|
|
||||||
'description' => $field->object->description,
|
'description' => $field->object->description,
|
||||||
'type' => $field->object->type ?? $types,
|
'type' => $field->object->type ?? implode(' | ', array_map(fn($e) => $e->type, $types)),
|
||||||
'allowNulls' => $property->allowsNull(),
|
'allowNulls' => $property->allowsNull(),
|
||||||
'regexPattern' => $field->object->regexFormat ?? null,
|
'regexPattern' =>$field->object->regexFormat ?? "aucun",
|
||||||
'minLength' => $field->object->minLength ?? null,
|
'minLength' =>$field->object->minLength ?? "aucune",
|
||||||
'maxLength' => $field->object->maxLength ?? null,
|
'maxLength' =>$field->object->maxLength ?? "aucune",
|
||||||
'example' => $field->object->example ?? null,
|
'example' =>$field->object->example,
|
||||||
'default' => isset($field->object->default) ? json_encode($field->object->default) : null,
|
|
||||||
'values' => $this->generateExampleValues($types),
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -51,17 +48,4 @@ class FormDescriptor
|
|||||||
|
|
||||||
return $list;
|
return $list;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function generateExampleValues(array $types) : string|array
|
|
||||||
{
|
|
||||||
$values = [];
|
|
||||||
|
|
||||||
foreach($types as $type) {
|
|
||||||
if ( enum_exists($type->type) ) {
|
|
||||||
$values = array_merge($values, array_map(fn($e) => $e->value, $type->type::cases()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $values;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+11
-138
@@ -2,50 +2,39 @@
|
|||||||
|
|
||||||
namespace Lean\Api;
|
namespace Lean\Api;
|
||||||
|
|
||||||
use DI\Attribute\Inject;
|
|
||||||
use League\CommonMark\CommonMarkConverter;
|
use League\CommonMark\CommonMarkConverter;
|
||||||
use Lean\Api\Lib\ApiSearchRequestInterface;
|
|
||||||
use Notes\Attribute\Ignore;
|
use Notes\Attribute\Ignore;
|
||||||
use Psr\Container\ContainerInterface;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
use Psr\Http\Message\ResponseInterface;
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
use Ulmus\EntityCollection;
|
|
||||||
use Ulmus\SearchRequest\SearchRequestInterface;
|
|
||||||
|
|
||||||
trait LeanApiTrait
|
trait LeanApiTrait
|
||||||
{
|
{
|
||||||
use DescriptorTrait;
|
use DescriptorTrait;
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
protected ContainerInterface $container;
|
|
||||||
|
|
||||||
#[Ignore]
|
#[Ignore]
|
||||||
public function renderMarkdown(string $filepath, array $entities = [], array $forms = [], int $code = 200, array $headers = []): ResponseInterface
|
public function renderMarkdown(string $filepath, array $entities = [], array $forms = [], int $code = 200, array $headers = []) : ResponseInterface
|
||||||
{
|
{
|
||||||
if (!class_exists(CommonMarkConverter::class)) {
|
if ( ! class_exists(CommonMarkConverter::class)) {
|
||||||
throw new \BadFunctionCallException("League\CommonMark seems to be missing, please install dependency before trying to render Markdown content");
|
throw new \BadFunctionCallException("League\CommonMark seems to be missing, please install dependency before trying to render Markdown content");
|
||||||
}
|
}
|
||||||
|
|
||||||
$markdown = (new CommonMarkConverter())->convert(file_get_contents($filepath))->getContent();
|
$markdown = ( new CommonMarkConverter() )->convert(file_get_contents($filepath))->getContent();
|
||||||
|
|
||||||
if (str_contains($markdown, '{route:descriptor}')) {
|
if (str_contains($markdown, '{route:descriptor}'))
|
||||||
|
{
|
||||||
$markdown = str_replace('{route:descriptor}', $this->renderRawView('lean-api/route_descriptor', [
|
$markdown = str_replace('{route:descriptor}', $this->renderRawView('lean-api/route_descriptor', [
|
||||||
'routes' => (new RouteDescriptor($this, $this->picea->compiler->getExtensionFromToken('url'), $this->container))->getRoutes()
|
'routes' => (new RouteDescriptor($this, $this->picea->compiler->getExtensionFromToken('url')))->getRoutes()
|
||||||
]), $markdown);
|
]), $markdown);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (str_contains($markdown, '{request:debugger}')) {
|
if (str_contains($markdown, '{entity:descriptor}'))
|
||||||
$markdown = str_replace('{request:debugger}', $this->renderRawView('lean-api/request_debugger', []), $markdown);
|
{
|
||||||
}
|
|
||||||
|
|
||||||
if (str_contains($markdown, '{entity:descriptor}')) {
|
|
||||||
$markdown = str_replace('{entity:descriptor}', $this->renderRawView('lean-api/entity_descriptor', [
|
$markdown = str_replace('{entity:descriptor}', $this->renderRawView('lean-api/entity_descriptor', [
|
||||||
'entities' => (new EntityDescriptor())->getEntities(... $entities)
|
'entities' => (new EntityDescriptor())->getEntities(... $entities)
|
||||||
]), $markdown);
|
]), $markdown);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (str_contains($markdown, '{form:descriptor}')) {
|
if (str_contains($markdown, '{form:descriptor}'))
|
||||||
|
{
|
||||||
$markdown = str_replace('{form:descriptor}', $this->renderRawView('lean-api/form_descriptor', [
|
$markdown = str_replace('{form:descriptor}', $this->renderRawView('lean-api/form_descriptor', [
|
||||||
'forms' => (new FormDescriptor())->getForms(... $forms)
|
'forms' => (new FormDescriptor())->getForms(... $forms)
|
||||||
]), $markdown);
|
]), $markdown);
|
||||||
@@ -55,126 +44,10 @@ trait LeanApiTrait
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[Ignore]
|
#[Ignore]
|
||||||
protected function output(\JsonSerializable|array $data, int $count): ResponseInterface
|
protected function output(\JsonSerializable|array $data, int $count) {
|
||||||
{
|
|
||||||
return $this->renderJson([
|
return $this->renderJson([
|
||||||
'data' => $data,
|
'data' => $data,
|
||||||
'count' => $count,
|
'count' => $count,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[Ignore]
|
|
||||||
protected function outputSearchResult(ApiSearchRequestInterface $apiSearchRequest): ResponseInterface
|
|
||||||
{
|
|
||||||
return $this->output($apiSearchRequest->getResult(), $apiSearchRequest->getSearch()->count);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Ignore]
|
|
||||||
protected function searchEntityFromRequest(ServerRequestInterface $request, string $entityType, ?string $resultKey = null): ServerRequestInterface
|
|
||||||
{
|
|
||||||
$search = $entityType::searchRequest()->fromRequest($request);
|
|
||||||
$entity = $entityType::repository()->filterServerRequest($search, false)->loadOne() ?? false;
|
|
||||||
|
|
||||||
if (!$entity) {
|
|
||||||
throw new \InvalidArgumentException(sprintf("L'entré pour l'entité demandé (%s) est introuvable avec le ou les arguments fournis '%s'", $entityType, json_encode($request->getAttributes(), \JSON_PARTIAL_OUTPUT_ON_ERROR)));
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($request->getAttribute("lean.searchRequest") === null) {
|
|
||||||
$request = $request->withAttribute("lean.searchRequest", $this->searchEntityResult());
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($request->getAttribute('lean-api.security-action:context')) {
|
|
||||||
$request->getAttribute('lean-api.security-action:context')->attachEntity($entity);
|
|
||||||
}
|
|
||||||
|
|
||||||
$request->getAttribute("lean.searchRequest")[$resultKey ?: $entityType] = new class($search, $entity) implements ApiSearchRequestInterface {
|
|
||||||
public function __construct(
|
|
||||||
public readonly SearchRequestInterface $search,
|
|
||||||
public readonly EntityInterface $entity,
|
|
||||||
)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getSearch(): SearchRequestInterface
|
|
||||||
{
|
|
||||||
return $this->search;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getResult(): EntityCollection|EntityInterface
|
|
||||||
{
|
|
||||||
return $this->entity;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return $request;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Ignore]
|
|
||||||
protected function searchEntitiesFromRequest(ServerRequestInterface $request, string $entityType, ?string $resultKey = null, bool $count = true): ServerRequestInterface
|
|
||||||
{
|
|
||||||
$search = $entityType::searchRequest()->fromRequest($request);
|
|
||||||
$entity = $entityType::repository()->filterServerRequest($search, $count)->loadAll();
|
|
||||||
|
|
||||||
if (!$entity) {
|
|
||||||
throw new \InvalidArgumentException(sprintf("L'entré pour l'entité demandé (%s) est introuvable avec le ou les arguments fournis '%s'", $entityType, json_encode($request->getAttributes())));
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($request->getAttribute("lean.searchRequest") === null) {
|
|
||||||
$request = $request->withAttribute("lean.searchRequest", $this->searchEntityResult());
|
|
||||||
}
|
|
||||||
|
|
||||||
$request->getAttribute("lean.searchRequest")[$resultKey ?: $entityType] = new class($search, $entity) implements ApiSearchRequestInterface {
|
|
||||||
public function __construct(
|
|
||||||
public readonly SearchRequestInterface $search,
|
|
||||||
public readonly EntityCollection $collection,
|
|
||||||
)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getSearch(): SearchRequestInterface
|
|
||||||
{
|
|
||||||
return $this->search;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getResult(): EntityCollection|EntityInterface
|
|
||||||
{
|
|
||||||
return $this->collection;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return $request;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Ignore]
|
|
||||||
protected function searchEntityResult(): \ArrayObject
|
|
||||||
{
|
|
||||||
return new class() extends \ArrayObject implements ApiSearchRequestInterface {
|
|
||||||
|
|
||||||
public function getSearch(): SearchRequestInterface
|
|
||||||
{
|
|
||||||
if ($this->count() !== 1) {
|
|
||||||
throw new \LogicException("Search results contains more than one results. Impossible to continue without precising which one you needs.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this[array_key_last($this->getArrayCopy())]->getSearch();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getResult(): EntityInterface|EntityCollection
|
|
||||||
{
|
|
||||||
if ($this->count() !== 1) {
|
|
||||||
throw new \LogicException("Search results contains more than one results. Impossible to continue without precising which one you needs.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this[array_key_last($this->getArrayCopy())]->getResult();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Ignore]
|
|
||||||
protected function attachActionEntity(ServerRequestInterface $request, EntityInterface $entity): void
|
|
||||||
{
|
|
||||||
if ($request->getAttribute('lean-api.security-action:attribute')) {
|
|
||||||
$request->getAttribute('lean-api.security-action:context')->attachEntity($entity);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Lib;
|
|
||||||
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
use Ulmus\EntityCollection;
|
|
||||||
use Ulmus\SearchRequest\SearchRequestInterface;
|
|
||||||
|
|
||||||
interface ApiSearchRequestInterface
|
|
||||||
{
|
|
||||||
public function getSearch() : SearchRequestInterface;
|
|
||||||
public function getResult() : EntityCollection|EntityInterface;
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Lib;
|
|
||||||
|
|
||||||
use DI\Attribute\Inject;
|
|
||||||
use Lean\Api\Factory\LeanApiFormFactoryInterface;
|
|
||||||
use Lean\Api\Factory\LeanApiEntityFactory;
|
|
||||||
use Notes\Route\Attribute\Object\Route;
|
|
||||||
|
|
||||||
#[Route(method: ['GET', 'POST', ])]
|
|
||||||
trait ControllerTrait
|
|
||||||
{
|
|
||||||
use \Lean\ControllerTrait, \Lean\Api\LeanApiTrait {
|
|
||||||
\Lean\Api\LeanApiTrait::renderMarkdown insteadof \Lean\ControllerTrait;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
protected LeanApiFormFactoryInterface $leanApiFormFactory;
|
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
protected LeanApiEntityFactory $leanApiEntityFactory;
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Lib;
|
|
||||||
|
|
||||||
use Lean\Api\Factory\MessageFactoryInterface;
|
|
||||||
use Lean\LanguageHandler;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
|
|
||||||
class DeleteFormContext extends FormContext
|
|
||||||
{
|
|
||||||
public function valid(? EntityInterface $entity = null) : bool
|
|
||||||
{
|
|
||||||
if ( $entity === null ) {
|
|
||||||
$this->pushErrorMessage('lean.api.form.delete.error.entity');
|
|
||||||
}
|
|
||||||
|
|
||||||
return parent::valid();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Lib;
|
|
||||||
|
|
||||||
use Lean\Api\Factory\MessageFactoryInterface;
|
|
||||||
use Lean\LanguageHandler;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
|
|
||||||
class FormContext extends \Picea\Ui\Method\FormContext {
|
|
||||||
|
|
||||||
public function __construct(
|
|
||||||
protected LanguageHandler $formLanguageHandler,
|
|
||||||
protected MessageFactoryInterface $formMessage,
|
|
||||||
ServerRequestInterface $formContextRequest,
|
|
||||||
? string $formName = null
|
|
||||||
) {
|
|
||||||
parent::__construct($formContextRequest, $formName);
|
|
||||||
}
|
|
||||||
|
|
||||||
# public function initializeEntity(EntityInterface $entity) : void {}
|
|
||||||
|
|
||||||
public function lang(string $key, array $variables = [])
|
|
||||||
{
|
|
||||||
return $this->formLanguageHandler->languageFromKey($key, $variables);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function pushSuccessMessage($key, $variables = []) : void {
|
|
||||||
$this->pushMessage($this->formMessage::generateSuccess(
|
|
||||||
$this->lang($key, $variables)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
public function pushWarningMessage($key, $variables = []) : void {
|
|
||||||
$this->pushMessage($this->formMessage::generateWarning(
|
|
||||||
$this->lang($key, $variables)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
public function pushErrorMessage($key, $variables = []) : void {
|
|
||||||
$this->pushMessage($this->formMessage::generateError(
|
|
||||||
$a = $this->lang($key, $variables)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
public function pushInfoMessage($key, $variables = []) : void {
|
|
||||||
$this->pushMessage($this->formMessage::generateInfo(
|
|
||||||
$this->lang($key, $variables)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,132 +0,0 @@
|
|||||||
<?php declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace Lean\Api\Lib;
|
|
||||||
|
|
||||||
use Lean\Api\Factory\MessageFactoryInterface;
|
|
||||||
use Picea\Ui\Method\FormMessage;
|
|
||||||
|
|
||||||
class Message implements FormMessage, MessageFactoryInterface {
|
|
||||||
|
|
||||||
const MESSAGE_TYPE = [
|
|
||||||
'success' => [
|
|
||||||
'class' => 'success',
|
|
||||||
'header' => 'Succès !',
|
|
||||||
'message' => ''
|
|
||||||
],
|
|
||||||
|
|
||||||
'error' => [
|
|
||||||
'class' => 'danger',
|
|
||||||
'header' => 'Error !',
|
|
||||||
'message' => ''
|
|
||||||
],
|
|
||||||
|
|
||||||
'warning' => [
|
|
||||||
'class' => 'warning',
|
|
||||||
'header' => 'Attention !',
|
|
||||||
'message' => ''
|
|
||||||
],
|
|
||||||
|
|
||||||
'information' => [
|
|
||||||
'class' => 'information',
|
|
||||||
'header' => 'À savoir !',
|
|
||||||
'message' => ''
|
|
||||||
],
|
|
||||||
|
|
||||||
'debug' => [
|
|
||||||
'class' => 'debug',
|
|
||||||
'header' => 'Debug :',
|
|
||||||
'message' => ''
|
|
||||||
],
|
|
||||||
|
|
||||||
'trace' => [
|
|
||||||
'class' => 'trace',
|
|
||||||
'header' => 'Trace :',
|
|
||||||
'message' => ''
|
|
||||||
]
|
|
||||||
];
|
|
||||||
|
|
||||||
public string $type;
|
|
||||||
|
|
||||||
public string $message;
|
|
||||||
|
|
||||||
public string $class;
|
|
||||||
|
|
||||||
public ? string $header = null;
|
|
||||||
|
|
||||||
public function __construct(string $message = "", string $type = "error", ? string $header = null, ? string $class = null)
|
|
||||||
{
|
|
||||||
$this->message = $message;
|
|
||||||
|
|
||||||
$this->type = $type;
|
|
||||||
|
|
||||||
if ( $header !== null ) {
|
|
||||||
$this->header = $header;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
$this->header = static::MESSAGE_TYPE[$type]['header'];
|
|
||||||
}
|
|
||||||
|
|
||||||
if ( $class !== null ) {
|
|
||||||
$this->class = $class;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
$this->class = static::MESSAGE_TYPE[$type]['class'];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function render() : string
|
|
||||||
{
|
|
||||||
return <<<HTML
|
|
||||||
<article class="message is-{$this->class}" role="alert">
|
|
||||||
<div class="message-body">
|
|
||||||
<strong>{$this->header}</strong>
|
|
||||||
<span>{$this->message}</span>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
HTML;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function renderJson() : array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'name' => 'message',
|
|
||||||
'type' => $this->type,
|
|
||||||
'message' => $this->message,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function isError() : bool
|
|
||||||
{
|
|
||||||
return $this->type === "error";
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function generateSuccess(string $message, ? string $header = null, ? string $class = null) : self
|
|
||||||
{
|
|
||||||
return new static($message, 'success', $header, $class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function generateError(string $message, ? string $header = null, ? string $class = null) : self
|
|
||||||
{
|
|
||||||
return new static($message, 'error', $header, $class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function generateWarning(string $message, ? string $header = null, ? string $class = null) : self
|
|
||||||
{
|
|
||||||
return new static($message, 'warning', $header, $class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function generateInformation(string $message, ? string $header = null, ? string $class = null) : self
|
|
||||||
{
|
|
||||||
return new static($message, 'information', $header, $class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function generateDebug(string $message, ? string $header = null, ? string $class = null) : self
|
|
||||||
{
|
|
||||||
return new static($message, 'debug', $header, $class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function generateTrace(string $message, ? string $header = null, ? string $class = null) : self
|
|
||||||
{
|
|
||||||
return new static($message, 'trace', $header, $class);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Lib;
|
|
||||||
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Psr\Http\Server\RequestHandlerInterface;
|
|
||||||
use Ulmus\Api\Stream\Stream;
|
|
||||||
|
|
||||||
class RenderCORS
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
protected ServerRequestInterface $request,
|
|
||||||
public string|array $origin = [ "http://localhost", "https://localhost" ],
|
|
||||||
public bool $allowCredentials = true,
|
|
||||||
public string|array $methods = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS",],
|
|
||||||
public string|array $headers = ["Content-Type", "Authorization", "X-Requested-With", "X-CSRF-Token"],
|
|
||||||
) {
|
|
||||||
if (is_string($origin)) {
|
|
||||||
$this->origin = explode(',', $this->origin);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function renderHeader(ServerRequestInterface $request): void
|
|
||||||
{
|
|
||||||
$matched = $this->matchOrigin($this->getOrigin($request), $this->origin);
|
|
||||||
|
|
||||||
if (!$matched) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
var_dump($matched);die();
|
|
||||||
|
|
||||||
$render = fn(string|array $e) => is_string($e) ? $e : sprintf('%s', implode(', ', $e));
|
|
||||||
|
|
||||||
header(sprintf('Access-Control-Allow-Origin: %s', $matched));
|
|
||||||
header(sprintf('Access-Control-Allow-Methods: %s', $render($this->methods)));
|
|
||||||
header(sprintf('Access-Control-Allow-Headers: %s', $render($this->headers)));
|
|
||||||
header(sprintf('Access-Control-Allow-Credentials: %s', $this->allowCredentials ? 'true' : 'false'));
|
|
||||||
}
|
|
||||||
|
|
||||||
public function fromResponse(ResponseInterface $response, bool $emptyResponse = false): ResponseInterface
|
|
||||||
{
|
|
||||||
$matched = $this->matchOrigin($this->getOrigin($this->request), $this->origin);
|
|
||||||
|
|
||||||
if (!$matched) {
|
|
||||||
return $response;
|
|
||||||
}
|
|
||||||
|
|
||||||
$render = fn(string|array $e) => is_string($e) ? $e : sprintf('%s', implode(', ', $e));
|
|
||||||
|
|
||||||
$response = $response
|
|
||||||
->withHeader('Access-Control-Allow-Origin', $matched)
|
|
||||||
->withHeader('Access-Control-Allow-Methods', $render($this->methods))
|
|
||||||
->withHeader('Access-Control-Allow-Headers', $render($this->headers))
|
|
||||||
->withHeader('Access-Control-Allow-Credentials', $this->allowCredentials ? 'true' : 'false');
|
|
||||||
|
|
||||||
if ($emptyResponse) {
|
|
||||||
$response = $response->withBody(Stream::fromMemory())->withStatus(200);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $response;
|
|
||||||
}
|
|
||||||
|
|
||||||
function matchOrigin(?string $origin, string|array $allowList): ?string
|
|
||||||
{
|
|
||||||
if ($origin === null || $origin === '') {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach ((array)$allowList as $rule) {
|
|
||||||
if ($rule === '*') {
|
|
||||||
return '*';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Regex rule: "/.../"
|
|
||||||
if (is_string($rule) && strlen($rule) >= 2 && $rule[0] === '/' && substr($rule, -1) === '/') {
|
|
||||||
if (@preg_match($rule, $origin) === 1) {
|
|
||||||
return $origin;
|
|
||||||
}
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exact match
|
|
||||||
if (is_string($rule) && hash_equals($rule, $origin)) {
|
|
||||||
return $origin;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getOrigin(ServerRequestInterface $request): string
|
|
||||||
{
|
|
||||||
$server = $request->getServerParams();
|
|
||||||
|
|
||||||
if (isset($server['HTTP_ORIGIN'])) {
|
|
||||||
return $server['HTTP_ORIGIN'];
|
|
||||||
}
|
|
||||||
|
|
||||||
$protocol = $server['HTTP_X_FORWARDED_PROTO'] ?? ((!empty($server['HTTPS']) && $server['HTTPS'] !== 'off') ? 'https' : 'http');
|
|
||||||
$host = $server['HTTP_X_FORWARDED_HOST'] ?? $server['HTTP_HOST'] ?? $server['SERVER_NAME'];
|
|
||||||
|
|
||||||
return $protocol . '://' . $host;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -2,54 +2,38 @@
|
|||||||
|
|
||||||
namespace Lean\Api\Middleware;
|
namespace Lean\Api\Middleware;
|
||||||
|
|
||||||
use DI\Attribute\Inject;
|
|
||||||
use Laminas\Diactoros\Response\JsonResponse;
|
use Laminas\Diactoros\Response\JsonResponse;
|
||||||
use Lean\Factory\HttpFactory;
|
use Lean\Factory\HttpFactory;
|
||||||
use Picea\Ui\Method\FormHandler;
|
|
||||||
use Psr\Container\ContainerInterface;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
use Psr\Http\Message\ResponseInterface;
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
use Psr\Http\Server\MiddlewareInterface;
|
use Psr\Http\Server\MiddlewareInterface;
|
||||||
use Psr\Http\Server\RequestHandlerInterface;
|
use Psr\Http\Server\RequestHandlerInterface;
|
||||||
use Lean\Api\{Factory\LeanApiFormFactoryInterface, Form, Entity};
|
|
||||||
|
|
||||||
class ApiRenderer implements MiddlewareInterface {
|
class ApiRenderer implements MiddlewareInterface {
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
protected LeanApiFormFactoryInterface $leanApiFormFactory;
|
|
||||||
|
|
||||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
$response = $handler->handle($request);
|
$response = $handler->handle($request);
|
||||||
}
|
}
|
||||||
catch(\Throwable $ex) {
|
catch(\Exception $ex) {
|
||||||
if (static::awaitingJson($request)) {
|
if ( ! getenv('DEBUG') ) {
|
||||||
# $this->saveError($request, $ex);
|
|
||||||
|
|
||||||
return HttpFactory::createJsonResponse([
|
return HttpFactory::createJsonResponse([
|
||||||
'status' => 'failed',
|
'status' => 'failed',
|
||||||
|
'message' => $ex->getMessage(),
|
||||||
'ts' => time(),
|
'ts' => time(),
|
||||||
'data' => [
|
], 400);
|
||||||
# 'error_id' => $errorId,
|
}
|
||||||
'message' => $ex->getMessage(),
|
else {
|
||||||
] + (getenv('DEBUG') ? [
|
throw $ex;
|
||||||
'type' => $ex::class,
|
|
||||||
'file' => $ex->getFile(),
|
|
||||||
'line' => $ex->getLine(),
|
|
||||||
'code' => $ex->getCode(),
|
|
||||||
'backtrace' => $ex->getTrace(), ] : [])
|
|
||||||
], 500);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
throw $ex;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($response instanceof JsonResponse) {
|
if ($response instanceof JsonResponse) {
|
||||||
$payload = $response->getPayload();
|
$payload = $response->getPayload();
|
||||||
|
|
||||||
# For now, we match only response having a 'data' field
|
# For now, we match only response having a 'data' field
|
||||||
if ( (is_array($payload) || $payload instanceof \ArrayAccess) && isset($payload['data'])) {
|
if (isset($payload['data'])) {
|
||||||
return HttpFactory::createJsonResponse([
|
return HttpFactory::createJsonResponse([
|
||||||
'status' => 'success',
|
'status' => 'success',
|
||||||
'ts' => time(),
|
'ts' => time(),
|
||||||
@@ -59,46 +43,4 @@ class ApiRenderer implements MiddlewareInterface {
|
|||||||
|
|
||||||
return $response;
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*protected function saveError(ServerRequestInterface $request, \Throwable $exception) : Entity\Error
|
|
||||||
{
|
|
||||||
if ($debugFormFactory = $this->container->get(DebugFormFactoryInterface::class)) {
|
|
||||||
$request = $request->withMethod('PUT')->withParsedBody([]);
|
|
||||||
|
|
||||||
$context = $this->leanApiFormFactory->errorSaveContext($request);
|
|
||||||
|
|
||||||
$context->sets([
|
|
||||||
'message' => $exception->getMessage(),
|
|
||||||
'code' => $exception->getCode(),
|
|
||||||
'file' => $exception->getFile(),
|
|
||||||
'line' => $exception->getLine(),
|
|
||||||
'trace' => $exception->getTrace(),
|
|
||||||
]);
|
|
||||||
|
|
||||||
$form = $this->leanApiFormFactory->errorSave($entity = new Entity\Error());
|
|
||||||
|
|
||||||
new FormHandler($request, $form, $context);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $entity;
|
|
||||||
}*/
|
|
||||||
|
|
||||||
public static function awaitingJson(ServerRequestInterface $request) : bool
|
|
||||||
{
|
|
||||||
return str_contains(strtolower($request->getHeaderLine('content-type')), 'json');
|
|
||||||
}
|
|
||||||
|
|
||||||
public static function encodeHtml(iterable& $array) : iterable
|
|
||||||
{
|
|
||||||
foreach($array as &$item) {
|
|
||||||
if (is_array($item)) {
|
|
||||||
$item = static::encodeHtml($item);
|
|
||||||
}
|
|
||||||
elseif (is_string($item)) {
|
|
||||||
$item = htmlspecialchars($item);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $array;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Middleware;
|
|
||||||
|
|
||||||
use Lean\Api\Lib\RenderCORS;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Psr\Http\Server\MiddlewareInterface;
|
|
||||||
use Psr\Http\Server\RequestHandlerInterface;
|
|
||||||
use Lean\Api\{ Entity};
|
|
||||||
|
|
||||||
class CORS implements MiddlewareInterface
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
protected RenderCORS $cors,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
|
|
||||||
{
|
|
||||||
return $this->cors->fromResponse($handler->handle($request));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Middleware\Security;
|
|
||||||
|
|
||||||
use Lean\Api\Controller\Security\ActionLog;
|
|
||||||
use Lean\Api\Factory\LeanApiFormFactoryInterface;
|
|
||||||
use Lean\Api\Form;
|
|
||||||
use DI\Attribute\Inject;
|
|
||||||
use Lean\Event\RoutingMapRoutes;
|
|
||||||
use Lean\Routing;
|
|
||||||
use Mcnd\Event\EventManager;
|
|
||||||
use Notes\ObjectReflection;
|
|
||||||
use Notes\ObjectResolver;
|
|
||||||
use Notes\Route\Attribute\Method\Route;
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
|
||||||
use Psr\Container\ContainerInterface;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Psr\Http\Server\MiddlewareInterface;
|
|
||||||
use Psr\Http\Server\RequestHandlerInterface;
|
|
||||||
|
|
||||||
class ActionLogMiddleware implements MiddlewareInterface {
|
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
protected readonly LeanApiFormFactoryInterface $leanApiFormFactory;
|
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
protected readonly ActionLog $actionLogController;
|
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
protected readonly EventManager $eventManager;
|
|
||||||
|
|
||||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
|
|
||||||
{
|
|
||||||
$eventHandler = $this->createEventHandler($request);
|
|
||||||
|
|
||||||
$this->eventManager->eventRegister($eventHandler);
|
|
||||||
|
|
||||||
$handler = $handler->handle($request);
|
|
||||||
|
|
||||||
try {
|
|
||||||
if ($handler->getStatusCode() < 300) {
|
|
||||||
if (isset($eventHandler->request)) {
|
|
||||||
if ($eventHandler->request->getAttribute('lean-api.security-action:attribute')) {
|
|
||||||
$this->actionLogController->add($eventHandler->request, []);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch(\Throwable $ex) {
|
|
||||||
if (getenv('DEBUG')) {
|
|
||||||
throw $ex;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $handler;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function createEventHandler(ServerRequestInterface $request) : object
|
|
||||||
{
|
|
||||||
return new class($this->leanApiFormFactory->securityActionLogSaveContext($request)) implements RoutingMapRoutes {
|
|
||||||
|
|
||||||
public readonly ServerRequestInterface $request;
|
|
||||||
|
|
||||||
public function __construct(
|
|
||||||
public readonly Form\Security\ActionLogContext $context,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function execute(Routing $routing, ContainerInterface $container, ServerRequestInterface &$request, Route $attribute): void
|
|
||||||
{
|
|
||||||
if (in_array($request->getMethod(), [ 'PATCH', 'POST', 'PUT', 'DELETE' ])) {
|
|
||||||
$objectReflection = ObjectReflection::fromClass($attribute->class, null)->reflectClass();
|
|
||||||
$actionLog = $objectReflection->methods[$attribute->classMethod]->getAttribute(\Lean\Api\Attribute\Security\ActionLog::class);
|
|
||||||
|
|
||||||
if ($actionLog) {
|
|
||||||
$this->context->event = $attribute->name;
|
|
||||||
$this->context->method = $request->getMethod();
|
|
||||||
|
|
||||||
$request = $this->request = $request
|
|
||||||
->withAttribute('lean-api.security-action:attribute', $actionLog->object)
|
|
||||||
->withAttribute('lean-api.security-action:context', $this->context);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Middleware\Security;
|
|
||||||
|
|
||||||
use Lean\Api\Lib\RenderCORS;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Psr\Http\Server\MiddlewareInterface;
|
|
||||||
use Psr\Http\Server\RequestHandlerInterface;
|
|
||||||
use Lean\Api\{ Entity};
|
|
||||||
|
|
||||||
class CORSMiddleware implements MiddlewareInterface
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
protected RenderCORS $cors,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
|
|
||||||
{
|
|
||||||
return $this->cors->fromResponse($handler->handle($request));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Middleware\Security;
|
|
||||||
|
|
||||||
use Lean\Api\Controller\Security\CSRF;
|
|
||||||
use DI\Attribute\Inject;
|
|
||||||
use Lean\Api\Exception\{ CSRFMissingToken, CSRFInvalidToken };
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Psr\Http\Server\MiddlewareInterface;
|
|
||||||
use Psr\Http\Server\RequestHandlerInterface;
|
|
||||||
|
|
||||||
class CSRFMiddleware implements MiddlewareInterface {
|
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
protected CSRF $csrfController;
|
|
||||||
|
|
||||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
|
|
||||||
{
|
|
||||||
if ( str_contains($request->getHeaderLine('Content-Type'), 'json') && ! getenv('LEAN_API_DISABLE_CSRF')) {
|
|
||||||
$this->csrfController->validate($request, ['token' => $request->getHeaderLine('X-CSRF-Token')]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $handler->handle($request);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Middleware\Security;
|
|
||||||
|
|
||||||
use Lean\Api\Controller\Security\RequestLog;
|
|
||||||
use DI\Attribute\Inject;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Psr\Http\Server\MiddlewareInterface;
|
|
||||||
use Psr\Http\Server\RequestHandlerInterface;
|
|
||||||
|
|
||||||
class RequestLogMiddleware implements MiddlewareInterface {
|
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
protected RequestLog $requestLogController;
|
|
||||||
|
|
||||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
|
|
||||||
{
|
|
||||||
$response = $handler->handle($request);
|
|
||||||
|
|
||||||
# Skip 404
|
|
||||||
if ($response->getStatusCode() < 400 || $response->getStatusCode() >= 500) {
|
|
||||||
try {
|
|
||||||
if ( str_contains($response->getHeaderLine('Content-Type'), 'json') ) {
|
|
||||||
$this->requestLogController->add($request, [ 'response' => $response ]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch(\Throwable $ex) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $response;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Middleware;
|
|
||||||
|
|
||||||
use Lean\Api\Controller\Security\RequestLog;
|
|
||||||
use DI\Attribute\Inject;
|
|
||||||
use Psr\Http\Message\ResponseInterface;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Psr\Http\Server\MiddlewareInterface;
|
|
||||||
use Psr\Http\Server\RequestHandlerInterface;
|
|
||||||
|
|
||||||
#[\Deprecated]
|
|
||||||
class SecurityMiddleware implements MiddlewareInterface {
|
|
||||||
|
|
||||||
#[Inject]
|
|
||||||
protected RequestLog $requestLogController;
|
|
||||||
|
|
||||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
|
|
||||||
{
|
|
||||||
$response = $handler->handle($request);
|
|
||||||
|
|
||||||
try {
|
|
||||||
if ( str_contains($response->getHeaderLine('Content-Type'), 'json') ) {
|
|
||||||
$this->requestLogController->add($request, [ 'response' => $response ]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch(\Throwable $ex) {}
|
|
||||||
|
|
||||||
return $response;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+6
-50
@@ -5,27 +5,14 @@ namespace Lean\Api;
|
|||||||
use Lean\Factory\HttpFactory;
|
use Lean\Factory\HttpFactory;
|
||||||
use Notes\ObjectReflection;
|
use Notes\ObjectReflection;
|
||||||
use Notes\Route\Attribute\Method\Route;
|
use Notes\Route\Attribute\Method\Route;
|
||||||
use Notes\Security\SecurityHandler;
|
|
||||||
use Picea\Extension\UrlExtension;
|
use Picea\Extension\UrlExtension;
|
||||||
use Psr\Container\ContainerInterface;
|
|
||||||
use Taxus\Taxus;
|
|
||||||
|
|
||||||
class RouteDescriptor
|
class RouteDescriptor
|
||||||
{
|
{
|
||||||
protected SecurityHandler $securityHandler;
|
|
||||||
|
|
||||||
protected Taxus $taxus;
|
|
||||||
|
|
||||||
public function __construct(
|
public function __construct(
|
||||||
public object $controller,
|
public object $controller,
|
||||||
protected UrlExtension $urlExtension,
|
protected UrlExtension $urlExtension,
|
||||||
ContainerInterface $container
|
) {}
|
||||||
) {
|
|
||||||
if ($container->has(SecurityHandler::class) && $container->has(Taxus::class)) {
|
|
||||||
$this->securityHandler = $container->get(SecurityHandler::class);
|
|
||||||
$this->taxus = $container->get(Taxus::class);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getRoutes() : array
|
public function getRoutes() : array
|
||||||
{
|
{
|
||||||
@@ -35,25 +22,22 @@ class RouteDescriptor
|
|||||||
|
|
||||||
$attribute = $reflector->reflectClass()->getAttribute(\Notes\Route\Attribute\Object\Route::class);
|
$attribute = $reflector->reflectClass()->getAttribute(\Notes\Route\Attribute\Object\Route::class);
|
||||||
|
|
||||||
$base = $attribute ? $attribute->object->getBase() : "";
|
$base = $attribute ? $attribute->object->base : "";
|
||||||
|
|
||||||
foreach($reflector->reflectMethods(includeParents: (bool) $attribute->object->inheritRoutes) as $method) {
|
foreach($reflector->reflectMethods() as $method) {
|
||||||
foreach(array_reverse($method->getAttributes(Route::class)) as $routeAttribute) {
|
foreach(array_reverse($method->getAttributes(Route::class)) as $routeAttribute) {
|
||||||
$itemBase = $routeAttribute->object->getBase() ?? $base;
|
|
||||||
$route = $routeAttribute->object;
|
$route = $routeAttribute->object;
|
||||||
$path = rtrim($route->route, '/');
|
$path = rtrim($route->route, '/');
|
||||||
$cleaned = $this->cleanRouteFromRegex($itemBase.$path);
|
$cleaned = $this->cleanRouteFromRegex($base.$path);
|
||||||
$url = $this->urlExtension->buildUrl($cleaned);
|
$url = $this->urlExtension->buildUrl($cleaned);
|
||||||
|
|
||||||
$routes[] = [
|
$routes[] = [
|
||||||
'name' => $route->name,
|
'name' => $route->name,
|
||||||
'route' => $url,
|
'route' => $url,
|
||||||
'path' => $itemBase.$path,
|
'path' => $base.$path,
|
||||||
'cleaned' => $cleaned,
|
'cleaned' => $cleaned,
|
||||||
'description'=> $route->description,
|
'description'=> $route->description,
|
||||||
#'methods' =>implode(', ', (array)$route->method),
|
'methods' => $route->method,
|
||||||
'methods' => (array) $route->method,
|
|
||||||
'privileges' => $this->getPrivilegeFromRoute($method->name),
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -73,32 +57,4 @@ class RouteDescriptor
|
|||||||
|
|
||||||
return implode('/', $paths);
|
return implode('/', $paths);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @param string $method Which method are we inspecting
|
|
||||||
* @return false|array|null Returns NULL when securityHandler is undefined, FALSE when no security applies for this method and else an array of ['admin' => [ 'status' => true, 'description' => "' ], ...].
|
|
||||||
*/
|
|
||||||
protected function getPrivilegeFromRoute(string $method) : null|false|array
|
|
||||||
{
|
|
||||||
if ( isset($this->securityHandler) ){
|
|
||||||
$list = [];
|
|
||||||
|
|
||||||
if ( $this->securityHandler->isLocked($this->controller::class, $method) ) {
|
|
||||||
foreach($this->taxus->list as $name => $definition) {
|
|
||||||
if ($definition[0]->testableArguments !== null) {
|
|
||||||
if ( $this->securityHandler->hasGrantPermission($this->controller::class, $method, ...$definition[0]->testableArguments) ) {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $list;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user