35 Commits
Author SHA1 Message Date
Dave Mc Nicoll d71fac0f88 - Fixed ActionLogContext object_id, now allowing compound keys 2026-11-02 18:47:55 +00:00
Dave Mc Nicoll a54930b6c6 - WIP on Cronard tasks
- Added some minors features to the API web interface
2026-10-30 18:15:37 +00:00
mcndave 2d560a0857 - Removed saveError method 2026-10-27 18:29:04 +00:00
Dave Mc Nicoll 4b86ac9e82 - Added a new CSRF token verification Middleware.
- Added a new ActionLog middleware to catch every modifying request and save the changes made and the user who did.
- Added a new RequestLog to catch every request made whenever required.
2026-10-22 15:03:18 +00:00
mcndave 9571c6a462 - WIP on package manager addition 2026-07-16 14:15:22 -04:00
mcndave c657ba4f60 - Added lean 1.4.2 version to composer 2026-07-16 11:53:53 -04:00
mcndave b8daa60e66 - Added PDO as requirement
- example now defined as mixed type in ContextField
2026-07-14 16:53:26 -04:00
mcndave 9b360c4010 - Added a new ArrayCollection
- Changed Action attribute and transformed it into an abstract class
2026-07-14 14:44:30 +00:00
mcndave 0443f5a811 - WIP on exceptions handling and throwing 2026-07-06 13:41:35 +00:00
mcndave 382a4459d7 - WIP on some pushMessage and createdAt/updatedAt handling 2026-07-01 14:01:41 -04:00
Dev 993c556d30 - Added HTML output 2026-06-23 18:10:46 +00:00
Dave Mc Nicoll e51d1ea7a3 - WIP on ApiRenderer and Save Form context@ 2026-06-19 19:46:32 +00:00
Dave Mc Nicoll 78670c2fcf - Field error are now all catched as \Throwable 2026-06-17 21:03:19 +00:00
Dev f292ac63ca - WIP on validations 2026-06-09 19:30:53 +00:00
Dave Mc Nicoll c82eae5be4 - WIP on Lean's API 2026-06-01 15:11:49 +00:00
Dave Mc Nicoll c624e8bbbd - Set font-size to 14px in json output 2026-05-22 19:46:01 +00:00
Dave Mc Nicoll 2dc71cd350 - Some work done on entity generation 2026-05-21 14:58:21 +00:00
Dave Mc Nicoll 05975089e5 - Added min/max values 2026-02-27 15:17:47 +00:00
Dave Mc Nicoll a9613222f8 - Fixed a backward compat bug 2026-02-10 16:56:44 +00:00
Dave Mc Nicoll ba74c5a38e - Some minor on request debugger 2026-01-12 21:18:10 +00:00
mcndave c3e3d6a73a - New code generation made for CLI 2026-01-05 12:39:41 +00:00
Dev ae212a4377 - WIP on form/context init method 2025-12-02 20:58:13 +00:00
Dev 696386bb06 - Handled default value on ContextField. 2025-12-02 00:14:03 +00:00
mcndave 3d50cfaccb - Big WIP on forms component 2025-12-01 15:46:02 +00:00
Dev c0b0681fee - added loading anim 2025-12-01 15:42:52 +00:00
Dave Mc Nicoll c9b107809d - WIP on lean-api visual 2025-10-06 17:28:08 +00:00
Dave Mc Nicoll c5ec582bd1 - Added CORS preflight handling 2025-09-12 19:38:53 +00:00
Dave Mc Nicoll 5d6d7ff49c - Added a new initialized variable checking before adding (or not) a new value to an entity 2025-09-09 13:00:05 -04:00
mcndave 0e0f004bc1 - WIP on Forms 2025-07-17 18:39:57 +00:00
Dave Mc Nicoll 2dbcfbcb2e - Fixed a bug where Assets would not load properly 2025-05-26 18:20:22 +00:00
mcndave d181c6d3a7 Quick fix in composer.json 2025-05-21 18:40:10 +00:00
Dave Mc Nicoll 4d7053a9cb - Lean's API WIP on forms and ApiRenderer 2025-05-21 18:36:19 +00:00
Dave Mc Nicoll 3ce356e1f2 - WIP on save and delete forms 2025-04-25 20:08:52 +00:00
Dave Mc Nicoll ad310ffee5 - WIP on route descriptor 2025-04-15 18:47:58 +00:00
Dave Mc Nicoll 21f315cc22 - WIP on visual of API 2025-04-10 17:54:04 +00:00
109 changed files with 4487 additions and 217 deletions

No files matched your search

-7
View File
@@ -1,7 +0,0 @@
class ApiConsole {
constructor(options) {
}
}
+12 -5
View File
@@ -10,15 +10,21 @@
} }
], ],
"require": { "require": {
"php": "^8.2", "php": "^8.4",
"php-di/php-di": "dev-master", "php-di/php-di": "dev-master",
"ext-json": "*", "ext-json": "*",
"mcnd/lean": "dev-master" "ext-pdo": "*",
"mcnd/lean": "^1.4.2",
"assets-package/ace": "^1.0.0"
}, },
"repositories": [ "repositories": [
{ {
"type": "vcs", "type": "composer",
"url": "https://git.mcnd.ca/mcndave/lean.git" "url": "https://git.mcnd.ca/api/packages/mcndave/composer"
},
{
"type": "composer",
"url": "https://git.mcnd.ca/api/packages/assets-package/composer"
} }
], ],
"autoload": { "autoload": {
@@ -38,7 +44,8 @@
"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"
+19
View File
@@ -1,9 +1,28 @@
<?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") : "")
),
],
]
]
]; ];
+40 -7
View File
@@ -1,6 +1,10 @@
<?php <?php
$path = dirname(__DIR__, 2); use Ulmus\ConnectionAdapter;
use function DI\{ get, env };
define('LEAN_API_PROJECT_PATH', dirname(__DIR__, 2));
return [ return [
'lean.api' => [ 'lean.api' => [
@@ -9,30 +13,59 @@ return [
'view' => [ 'view' => [
[ [
'path' => implode(DIRECTORY_SEPARATOR, [ $path , "view", '' ]), 'path' => implode(DIRECTORY_SEPARATOR, [ LEAN_API_PROJECT_PATH , "view", '' ]),
'order' => 99, 'order' => 99,
], ],
], ],
'asset' => [ 'asset' => [
[ [
'path' => implode(DIRECTORY_SEPARATOR, [ $path, "asset", '' ]), 'path' => implode(DIRECTORY_SEPARATOR, [ LEAN_API_PROJECT_PATH, "asset", '' ]),
'order' => 10 'order' => 10
], ],
], ],
], ],
'cli' => [
'Lean\\Api\\Cli' => implode(DIRECTORY_SEPARATOR, [ LEAN_API_PROJECT_PATH, "src", "Cli", "" ]),
],
'cronard' => [
'Lean\\Api\\Cronard' => implode(DIRECTORY_SEPARATOR, [ LEAN_API_PROJECT_PATH, 'src', 'Cronard', '' ]),
],
'ulmus' => [
'entities' => [ 'Lean\\Api\\Entity' => implode(DIRECTORY_SEPARATOR, [ LEAN_API_PROJECT_PATH, 'src', 'Entity', '' ]) ],
'adapters' => [
DI\get('lean.api:storage'),
]
],
'tell' => [ 'tell' => [
'json' => [ 'json' => [
[ [
'path' => implode(DIRECTORY_SEPARATOR, [ $path, "meta", "i18n", "" ]), 'path' => implode(DIRECTORY_SEPARATOR, [ LEAN_API_PROJECT_PATH, "meta", "i18n", "" ]),
'order' => 99, 'order' => 99,
], ],
] ]
], ],
/*'routes' => [ 'routes' => [
'Lean\\Api\\Controller' => implode(DIRECTORY_SEPARATOR, [ $path, "src", "Controller", "" ]), 'Lean\\Api\\Controller' => implode(DIRECTORY_SEPARATOR, [ LEAN_API_PROJECT_PATH, "src", "Controller", "" ]),
],*/ ] + (getenv('DEBUG') ? [
'Lean\\Api\\Cronard' => implode(DIRECTORY_SEPARATOR, [ LEAN_API_PROJECT_PATH, 'src', 'Cronard', '' ]),
]: []),
], ],
'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),
]; ];
+19
View File
@@ -0,0 +1,19 @@
<?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;
},
];
+19
View File
@@ -0,0 +1,19 @@
# LEAN API
## Automated tasks
--------------------------------------------------------------------------------
### Routes
{route:descriptor}
{request:debugger}
### Forms / actions
{form:descriptor}
### Entities
{entity:descriptor}
+21
View File
@@ -0,0 +1,21 @@
# 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}
+21
View File
@@ -0,0 +1,21 @@
# 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}
+7
View File
@@ -0,0 +1,7 @@
# Lean API
## Lean's API internal debug API
### Routes disponibles
- [Debug / Errors](./debug/errors/documentation)
+21
View File
@@ -0,0 +1,21 @@
# 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}
+21
View File
@@ -0,0 +1,21 @@
# LEAN API
## CSRF Token generation for non-idempotent requests
[Documentation](../../) / Security / CRSF
--------------------------------------------------------------------------------
### Available routes
{route:descriptor}
{request:debugger}
### Forms
{form:descriptor}
### Entity
{entity:descriptor}
+21
View File
@@ -0,0 +1,21 @@
# 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}
+17 -2
View File
@@ -1,11 +1,26 @@
{ {
"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"
} }
+63
View File
@@ -0,0 +1,63 @@
<?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);
}
}
+66
View File
@@ -0,0 +1,66 @@
<?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"));
}
}
+20
View File
@@ -0,0 +1,20 @@
<?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,
) {}
}
@@ -0,0 +1,22 @@
<?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();
}
}
+43
View File
@@ -0,0 +1,43 @@
<?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;
};
}
}
+20
View File
@@ -0,0 +1,20 @@
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);
}
}
@@ -0,0 +1,5 @@
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;
}
+32
View File
@@ -0,0 +1,32 @@
<?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);
}
}
+20
View File
@@ -0,0 +1,20 @@
<?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,
) {}
}
@@ -0,0 +1,22 @@
<?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();
}
}
+21
View File
@@ -0,0 +1,21 @@
# Title
## API 1.0
[APP](../) / %CLASSNAME%
--------------------------------------------------------------------------------
### Routes
{route:descriptor}
{request:debugger}
### Forms
{form:descriptor}
### Entities
{entity:descriptor}
+600
View File
@@ -0,0 +1,600 @@
<?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' ]));
}
}
+26
View File
@@ -0,0 +1,26 @@
<?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);
}
}
@@ -0,0 +1,30 @@
<?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);
}
}
@@ -0,0 +1,34 @@
<?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);
}
}
@@ -0,0 +1,23 @@
<?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();
}
}
+11
View File
@@ -0,0 +1,11 @@
<?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;
}
+9
View File
@@ -0,0 +1,9 @@
<?php
namespace Lean\Api\Attribute\Action;
enum ActionTypeEnum
{
case ValueModifier;
case Setter;
}
+21
View File
@@ -0,0 +1,21 @@
<?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;
}
}
+18
View File
@@ -0,0 +1,18 @@
<?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;
}
}
+17
View File
@@ -0,0 +1,17 @@
<?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;
}
}
+17
View File
@@ -0,0 +1,17 @@
<?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;
}
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace Lean\Api\Attribute;
enum CommonRegexFormatEnum : string
{
case BasicEmail = "/[^@ \t\r\n]+@[^@ \t\r\n]+\.[^@ \t\r\n]+/i";
}
+43 -2
View File
@@ -2,15 +2,56 @@
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 $mandatory = false, public bool|MandatoryGroup $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 ?string $example = null, public mixed $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}.");
}
}
}
}
} }
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace Lean\Api\Attribute;
enum ContextFieldActionEnum: string
{
case Replace = "replace";
case ArrayAppend = "array-append";
case ArrayPrepend = "array-prepend";
case Trim = "trim";
}
+1
View File
@@ -13,5 +13,6 @@ 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,
) {} ) {}
} }
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace Lean\Api\Attribute;
readonly class MandatoryGroup
{
public function __construct(
public string $name,
public int $needed = 1,
) {}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace Lean\Api\Attribute\Security;
#[\Attribute(\Attribute::TARGET_METHOD)]
class ActionLog
{
public function __construct(
#public string $key,
) {}
}
+120
View File
@@ -0,0 +1,120 @@
<?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");
}
}
+45
View File
@@ -0,0 +1,45 @@
<?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);
}
}
+22
View File
@@ -0,0 +1,22 @@
<?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", [ ], [ ]);
}
}
+55
View File
@@ -0,0 +1,55 @@
<?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());
}
}
+59
View File
@@ -0,0 +1,59 @@
<?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;
}
}
+57
View File
@@ -0,0 +1,57 @@
<?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());
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace Lean\Api\Cronard;
use Lean\Api\{Controller, Entity, Form, Lib};
use DI\Attribute\Inject;
use Notes\Cronard\Attribute\Method\Cronard;
use Notes\Route\Attribute\Method\Route;
use Notes\Route\Attribute\Object\Route as RouteObj;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
use ZipArchive;
##[Taxus(Entity\UserTypeEnum::Developer)]
#[RouteObj(base: "/lean/cronard")]
class System {
use Lib\ControllerTrait;
protected int $weekRetention = 4;
#[Inject]
protected ContainerInterface $container;
#[Route("/", name: "lean-api.cronard:documentation", method: "GET", description: "Documentation route for ")]
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
{
return $this->renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/cronard.md", [ ], []);
}
#[Cronard(cron: '30 3 1 * *', method: 'DELETE')]
#[Route("/clean/request-logs", name: "lean-api.cronard:clean-request-logs", method: ["DELETE"], description: "Fait le ménage automatiquement des logs de requêtes")]
public function clean_request_logs(ServerRequestInterface $request, array $arguments): ResponseInterface
{
$date = new Entity\Field\Datetime()->sub(new \DateInterval("P{$this->weekRetention}W"));
$count = Entity\Security\ApiRequestLog::repository()
->where(Entity\Security\ApiRequestLog::field('createdAt'), $date, '<=')
->count();
if ($count) {
$table = Entity\Security\ApiRequestLog::resolveEntity()->tableName();
$zipPath = getenv('LOGS_PATH') . DIRECTORY_SEPARATOR . sprintf("lean-api.%s-%s.zip", $table, date('Ymm_Hi'));
$dbPath = $this->container->get('config')['ulmus']['connections'][Entity\Security\ApiRequestLog::repository()->adapter->name]['path'];
$zip = new ZipArchive();
$zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$sqlDump = shell_exec(sprintf("sqlite3 %s \".dump %s\"", $dbPath, $table));
$zip->addFromString('lean-api.sqlite3', $sqlDump);
$zip->close();
$count = Entity\Security\ApiRequestLog::repository()
->where(Entity\Security\ApiRequestLog::field('createdAt', false), $date, '<=')
->deleteAll();
return $this->renderJson([
'data' => [
'count' => $count
]
]);
}
return $this->renderNothing();
}
}
+3
View File
@@ -15,6 +15,9 @@ 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;
} }
+13
View File
@@ -0,0 +1,13 @@
<?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);
}
}
+79
View File
@@ -0,0 +1,79 @@
<?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;
};
}
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace Lean\Api\Entity\Field;
class Date extends Datetime {
public string $format = "Y-m-d";
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace Lean\Api\Entity\Field;
class Datetime extends \Ulmus\Entity\Field\Datetime
{
public function jsonSerialize(): mixed
{
return (string) $this;
}
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace Lean\Api\Entity\Field;
class Time extends Datetime {
public string $format = "H:i:s";
}
+101
View File
@@ -0,0 +1,101 @@
<?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 array|int|string $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;
}
};
}
}
+92
View File
@@ -0,0 +1,92 @@
<?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;
};
}
}
@@ -0,0 +1,11 @@
<?php
namespace Lean\Api\Entity\User;
interface UserPrivilegeInterface
{
public function isDeveloper() : bool;
public function isAdmin() : bool;
public function isUser() : bool;
public function isAnonymous() : bool;
}
+19
View File
@@ -7,6 +7,7 @@ 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;
@@ -34,8 +35,16 @@ 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 ?? "",
@@ -45,6 +54,8 @@ 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,
]; ];
} }
} }
@@ -57,8 +68,15 @@ 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,
@@ -66,6 +84,7 @@ 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 ?? "")
]; ];
} }
+5
View File
@@ -0,0 +1,5 @@
<?php
namespace Lean\Api\Exception;
class CSRFInvalidToken extends \Exception {}
+5
View File
@@ -0,0 +1,5 @@
<?php
namespace Lean\Api\Exception;
class CSRFMissingToken extends \Exception {}
+5
View File
@@ -0,0 +1,5 @@
<?php
namespace Lean\Api\Exception;
class LeanApiException extends \InvalidArgumentException {}
@@ -0,0 +1,5 @@
<?php
namespace Lean\Api\Exception;
class MandatoryFieldException extends LeanApiException {}
+5
View File
@@ -0,0 +1,5 @@
<?php
namespace Lean\Api\Exception;
class MaximumLengthException extends LeanApiException {}
+5
View File
@@ -0,0 +1,5 @@
<?php
namespace Lean\Api\Exception;
class MinimumLengthException extends LeanApiException {}
+5
View File
@@ -0,0 +1,5 @@
<?php
namespace Lean\Api\Exception;
class RegexFormatException extends LeanApiException{}
+32
View File
@@ -0,0 +1,32 @@
<?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);
}
}
@@ -0,0 +1,53 @@
<?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);
}
}
+14
View File
@@ -0,0 +1,14 @@
<?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,
) {}
}
+21
View File
@@ -0,0 +1,21 @@
<?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;
}
@@ -0,0 +1,32 @@
<?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;
}
+13
View File
@@ -0,0 +1,13 @@
<?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;
}
+45
View File
@@ -0,0 +1,45 @@
<?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();
}
}
+20
View File
@@ -0,0 +1,20 @@
<?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;
}
}
+8 -17
View File
@@ -6,37 +6,28 @@ use CSSLSJ\ExamenFga\Api\{Lib};
use Picea\Ui\Method\{FormContextInterface}; use Picea\Ui\Method\{FormContextInterface};
use Ulmus\Entity\EntityInterface; use Ulmus\Entity\EntityInterface;
class Delete implements \Picea\Ui\Method\FormInterface { abstract class Delete extends Form 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->entity->isLoaded() ) { if ( ! $this->getEntity()->isLoaded() ) {
$context->pushMessage(Lib\Message::generateError( $context->pushMessage($this->message::generateError(
$this->lang('lean.api.form.delete.error.entity') $this->lang('lean.api.form.delete.error.entity')
)); ));
} }
return $context->valid(); return $context->valid($this->getEntity()->isLoaded() ? $this->getEntity() : null);
} }
public function execute(FormContextInterface $context) : void public function execute(FormContextInterface $context) : mixed
{ {
try { try {
if ( $this->getEntity()::repository()->destroy($this->getEntity()) ) { if ( $this->getEntity()::repository()->destroy($this->getEntity()) ) {
$context->pushMessage(Lib\Message::generateSuccess( $context->pushMessage($this->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'));
+49
View File
@@ -0,0 +1,49 @@
<?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;
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace Lean\Api\Form;
enum MessageTypeEnum
{
case Error;
case Success;
case Information;
case Warning;
case Debug;
case Trace;
}
+139 -41
View File
@@ -2,96 +2,194 @@
namespace Lean\Api\Form; namespace Lean\Api\Form;
use CSSLSJ\ExamenFga\Api\{Form\Location\SessionContext, Lib, Entity}; use CSLSJ\Lean\Form\Session\EmailContext;
use Picea\Ui\Method\{ FormContextInterface, Message\ErrorMessage }; use Picea\Ui\Method\{FormContext, FormContextInterface};
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 function CSSLSJ\ExamenFga\Api\View\{ lang }; use Ulmus\EntityCollection;
abstract class Save implements \Picea\Ui\Method\FormInterface { abstract class Save extends Form implements \Picea\Ui\Method\FormInterface {
public function __construct( protected bool $skipEntityCreatedAt = false;
protected LanguageHandler $languageHandler,
# public EntityInterface $entity,
) {}
public function getEntity() : EntityInterface protected bool $skipEntityLastModified = false;
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 (! isset($this->entity)) { if ( $this->getEntity() instanceof EntityInterface && ! $this->getEntity()->isLoaded() ) {
throw new \InvalidArgumentException($this->lang("lean.api.form.save.error.entity")); if (method_exists($context, 'initializeEntity')) {
$context->initializeEntity($this->getEntity());
}
$this->assignContextToEntity($context);
} }
return $this->entity; parent::initialize($context);
} }
public function validate(FormContextInterface $context) : bool public function validate(FormContextInterface $context) : bool
{ {
# Context is validating inputs # Context validates ContextField attributes containing properties on empty entity
$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) : void public function execute(FormContextInterface $context) : mixed
{ {
$entity = $this->getEntity(); $entity = $this->getEntity();
if ($entity->isLoaded() ) { if ($entity->isLoaded() && ! $this->skipEntityLastModified) {
$entity->updatedAt = new Datetime(); if (property_exists($entity, 'updatedAt') && $entity->repository()->generateDatasetDiff($entity) ) {
if ($field = $entity::resolveEntity()->field('updatedAt')) {
$cls = $field->type->type;
$entity->updatedAt = new $cls();
}
}
} }
else { elseif (! $this->skipEntityCreatedAt) {
$entity->createdAt = new Datetime(); if (property_exists($entity, 'createdAt') && empty($entity->createdAt)) {
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 ( $entity::repository()->save($entity) ) { if ( $saved = $entity::repository()->save($entity) ) {
$context->pushMessage(Lib\Message::generateSuccess( method_exists($context, 'pushSuccessMessage') && $context->pushSuccessMessage($this->messageSuccessSave);
$this->lang('lean.api.form.save.success.entity')
));
} }
else { else {
throw new \InvalidArgumentException($this->lang('lean.api.form.save.error.entity')); method_exists($context, 'pushWarningMessage') && $context->pushWarningMessage($this->messageWarningSave, [ 'entity' => substr($this->entity::class, strrpos($this->entity::class, '\\') + 1) ]);
} }
} }
catch(\Throwable $ex) { catch(\PDOException $ex) {
throw new \ErrorException($this->lang('lean.api.form.save.error.pdo', [ 'error' => $ex->getMessage() ])); throw new \PDOException($this->lang('lean.api.form.save.error.pdo', [ 'error' => $ex->getMessage() ]));
} }
catch(\Throwable $ex) {
method_exists($context, 'pushErrorMessage') && $context->pushErrorMessage($ex->getMessage());
}
return $saved ?? false;
} }
protected function lang(string $key, array $variables = []) protected function validateContextFields(FormContextInterface $context) : void
{ {
return $this->languageHandler->languageFromKey($key, $variables); foreach ($this->reflectedProperties($context) as $name => $property) {
$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()->fieldList() as $key => $property) { foreach($entity::resolveEntity()->getPropertyHavingAttribute(EntityField::class) as $key => $entityField) {
$field = $property->getAttribute(Field::class)->object; $property = $entity::resolveEntity()->reflectedClass->getProperties(true)[$key];
if (! $field->readonly) { if ($property) {
$apiField = $property->getAttribute(EntityField::class)->object ?? null; if (($property->getAttribute(Field::class)->object->readonly ?? false) && $entity->isLoaded()) {
continue;
}
if ($apiField) { $apiField = $entityField[0]->object ;
if ($apiField->field) { $var = $apiField->field ?: $key;
if ( isset($context->{$apiField->field}) ) { $attr = $this->reflectedProperties($context)[$var] ?? false;
$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});
} }
else { elseif($attr) {
if ( isset($context->{$key}) ) { $actions = [];
$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;
}
} }
+94
View File
@@ -0,0 +1,94 @@
<?php
namespace Lean\Api\Form\Security;
use CSSLSJ\TransportScolaire\Api\{Entity};
use Lean\Api\Attribute\ContextField;
use Lean\Api\Lib\FormContext;
use Ulmus\Attribute\IndexTypeEnum;
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 mixed $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()) {
$this->object_type = $this->entity::class;
if (isset($this->datasetFillEvent->data)) {
$this->data = $this->datasetFillEvent->data;
}
$pk = $this->entity::resolveEntity()->getPrimaryKeyField();
if ($pk) {
$pk = array_key_first($this->entity::resolveEntity()->getPrimaryKeyField());
if (isset($this->entity->$pk)) {
$this->object_id = $this->entity->$pk;
}
}
elseif ($index = $this->entity::resolveEntity()->getCompoundKeyFields()) {
if ($index->type === IndexTypeEnum::Primary) {
$this->object_id = array_combine($index->column, array_map(fn($e) => $this->entity->$e ?? null, $index->column));
}
}
}
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);
}
}
+40
View File
@@ -0,0 +1,40 @@
<?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();
}
}
+18
View File
@@ -0,0 +1,18 @@
<?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();
}
}
+42
View File
@@ -0,0 +1,42 @@
<?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;
}
}
@@ -0,0 +1,24 @@
<?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();
}
}
+49
View File
@@ -0,0 +1,49 @@
<?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();
}
}
+35
View File
@@ -0,0 +1,35 @@
<?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;
}
}
}
+44
View File
@@ -0,0 +1,44 @@
<?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'];
}
}
+23 -7
View File
@@ -15,7 +15,6 @@ 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);
@@ -24,17 +23,21 @@ class FormDescriptor
foreach($reflector->reflectProperties() as $property) { foreach($reflector->reflectProperties() as $property) {
$field = $property->getAttribute(ContextField::class); $field = $property->getAttribute(ContextField::class);
if ($field) { if ($field && ! $field->object->hidden ) {
$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 ?? implode(' | ', array_map(fn($e) => $e->type, $types)), 'type' => $field->object->type ?? $types,
'allowNulls' => $property->allowsNull(), 'allowNulls' => $property->allowsNull(),
'regexPattern' =>$field->object->regexFormat ?? "aucun", 'regexPattern' => $field->object->regexFormat ?? null,
'minLength' =>$field->object->minLength ?? "aucune", 'minLength' => $field->object->minLength ?? null,
'maxLength' =>$field->object->maxLength ?? "aucune", 'maxLength' => $field->object->maxLength ?? null,
'example' =>$field->object->example, 'example' => $field->object->example ?? null,
'default' => isset($field->object->default) ? json_encode($field->object->default) : null,
'values' => $this->generateExampleValues($types),
]; ];
} }
} }
@@ -48,4 +51,17 @@ 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;
}
} }
+138 -11
View File
@@ -2,39 +2,50 @@
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')))->getRoutes() 'routes' => (new RouteDescriptor($this, $this->picea->compiler->getExtensionFromToken('url'), $this->container))->getRoutes()
]), $markdown); ]), $markdown);
} }
if (str_contains($markdown, '{entity:descriptor}')) if (str_contains($markdown, '{request:debugger}')) {
{ $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);
@@ -44,10 +55,126 @@ trait LeanApiTrait
} }
#[Ignore] #[Ignore]
protected function output(\JsonSerializable|array $data, int $count) { protected function output(\JsonSerializable|array $data, int $count): ResponseInterface
{
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);
}
}
} }
+13
View File
@@ -0,0 +1,13 @@
<?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;
}
+22
View File
@@ -0,0 +1,22 @@
<?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;
}
+20
View File
@@ -0,0 +1,20 @@
<?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();
}
}
+51
View File
@@ -0,0 +1,51 @@
<?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)
));
}
}
+132
View File
@@ -0,0 +1,132 @@
<?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);
}
}
+107
View File
@@ -0,0 +1,107 @@
<?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;
}
}
+66 -8
View File
@@ -2,38 +2,54 @@
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(\Exception $ex) { catch(\Throwable $ex) {
if ( ! getenv('DEBUG') ) { if (static::awaitingJson($request)) {
# $this->saveError($request, $ex);
return HttpFactory::createJsonResponse([ return HttpFactory::createJsonResponse([
'status' => 'failed', 'status' => 'failed',
'message' => $ex->getMessage(),
'ts' => time(), 'ts' => time(),
], 400); 'data' => [
} # 'error_id' => $errorId,
else { 'message' => $ex->getMessage(),
throw $ex; ] + (getenv('DEBUG') ? [
'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 (isset($payload['data'])) { if ( (is_array($payload) || $payload instanceof \ArrayAccess) && isset($payload['data'])) {
return HttpFactory::createJsonResponse([ return HttpFactory::createJsonResponse([
'status' => 'success', 'status' => 'success',
'ts' => time(), 'ts' => time(),
@@ -43,4 +59,46 @@ 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;
}
} }
+22
View File
@@ -0,0 +1,22 @@
<?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));
}
}
@@ -0,0 +1,87 @@
<?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);
}
}
}
};
}
}
@@ -0,0 +1,22 @@
<?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));
}
}
@@ -0,0 +1,26 @@
<?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);
}
}
@@ -0,0 +1,33 @@
<?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;
}
}
+31
View File
@@ -0,0 +1,31 @@
<?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;
}
}
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more