5 Commits
Author SHA1 Message Date
Dave Mc Nicoll dc45bc9b2a - Fixed ApiActionLog user entity
- WIP on ApiRenderer to add basic query metrics while debugging
- Small fixes made on request_debugger to add elapsed request timing
2026-12-03 20:09:33 +00:00
mcndave 23b84f149f - Added inline functions (new) from picea 2026-11-25 21:08:55 +00:00
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
15 changed files with 137 additions and 45 deletions

No files matched your search

+14 -8
View File
@@ -4,7 +4,7 @@ use Ulmus\ConnectionAdapter;
use function DI\{ get, env };
define('LEAN_API_PROJECT_PATH', $path = dirname(__DIR__, 2));
define('LEAN_API_PROJECT_PATH', dirname(__DIR__, 2));
return [
'lean.api' => [
@@ -13,25 +13,29 @@ return [
'view' => [
[
'path' => implode(DIRECTORY_SEPARATOR, [ $path , "view", '' ]),
'path' => implode(DIRECTORY_SEPARATOR, [ LEAN_API_PROJECT_PATH , "view", '' ]),
'order' => 99,
],
],
'asset' => [
[
'path' => implode(DIRECTORY_SEPARATOR, [ $path, "asset", '' ]),
'path' => implode(DIRECTORY_SEPARATOR, [ LEAN_API_PROJECT_PATH, "asset", '' ]),
'order' => 10
],
],
],
'cli' => [
'Lean\\Api\\Cli' => implode(DIRECTORY_SEPARATOR, [ $path, "src", "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, [ $path, 'src', 'Entity', '' ]) ],
'entities' => [ 'Lean\\Api\\Entity' => implode(DIRECTORY_SEPARATOR, [ LEAN_API_PROJECT_PATH, 'src', 'Entity', '' ]) ],
'adapters' => [
DI\get('lean.api:storage'),
]
@@ -40,15 +44,17 @@ return [
'tell' => [
'json' => [
[
'path' => implode(DIRECTORY_SEPARATOR, [ $path, "meta", "i18n", "" ]),
'path' => implode(DIRECTORY_SEPARATOR, [ LEAN_API_PROJECT_PATH, "meta", "i18n", "" ]),
'order' => 99,
],
]
],
'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([
+19
View File
@@ -0,0 +1,19 @@
# LEAN API
## Automated tasks
--------------------------------------------------------------------------------
### Routes
{route:descriptor}
{request:debugger}
### Forms / actions
{form:descriptor}
### Entities
{entity:descriptor}
-1
View File
@@ -10,7 +10,6 @@ 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;
+43 -11
View File
@@ -2,32 +2,64 @@
namespace Lean\Api\Cronard;
use CSSLSJ\TransportScolaire\Api\{Controller\Api, Entity, Form, Lib};
use Notes\Breadcrumb\Attribute\Method\Breadcrumb;
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 Notes\Security\Attribute\Taxus;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
use Storage\{Cookie, Session};
use TheBugs\Email\MailerInterface;
use function CSSLSJ\TransportScolaire\Api\View\{form, route};
use ZipArchive;
##[Taxus(Entity\UserTypeEnum::Developer)]
#[RouteObj(base: "/lean/cronard")]
class System {
use Lib\ControllerTrait;
#[Route("/", name: "lean-api.cronard:documentation", method: "GET", description: "Route de documentation pour cette section")]
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(getenv("PROJECT_PATH") . "/meta/docs/cronard.md", [ ], []);
return $this->renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/cronard.md", [ ], []);
}
#[Cronard('0 0 1 * *')]
#[Route("/clean/request-logs", name: "lean-api.cronard:clean-request-logs", method: ["DELETE"], description: "Fait le ménage automatiquement des logs de requêtes datant de plus d'un an")]
#[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
{
# return $this->outputSearchResult($results);
$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();
}
}
+2 -7
View File
@@ -21,7 +21,7 @@ class ApiActionLog implements EntityInterface, \JsonSerializable
public int $id;
#[Field\ForeignKey(name: "object_id"), EntityField(field: "object_id")]
public int $objectId;
public array|int|string $objectId;
#[Field(name: "object_type"), EntityField(field: "object_type")]
public string $objectType;
@@ -47,14 +47,9 @@ class ApiActionLog implements EntityInterface, \JsonSerializable
#[Field(name: "created_at")]
public \Ulmus\Entity\Field\Datetime $createdAt;
#[Relation("oneToOne", key: "user", foreignKey: "id")]
#[Relation("oneToOne", key: "userId", foreignKey: "id")]
public UserInterface $userEntity;
public function getUser() : ? UserInterface
{
}
public function getHash() : string
{
return md5(sprintf("%d:%s", $this->id, $this->objectType));
+8
View File
@@ -31,6 +31,7 @@ class EntityDescriptor
$table = $reflector->reflectClass()->getAttribute(Table::class);
foreach ($reflector->reflectProperties() as $property) {
$possibleValues = null;
$entityField = $property->getAttribute(EntityField::class);
$field = $property->getAttribute(Field::class);
@@ -45,6 +46,12 @@ class EntityDescriptor
$default = $field->object->attributes['default'] ?? null;
}
foreach($types as $type) {
if (! $type->builtIn && enum_exists($type->type)) {
$possibleValues = array_map(fn($e) => $e->value, $type->type::cases());
}
}
$fields[] = [
'name' => $property->name,
'description' => $entityField->object->description ?? "",
@@ -55,6 +62,7 @@ class EntityDescriptor
'length' => $field->object->length ?? null,
'readonly' => $field->object->readonly,
'default' => $default,
'possibleValues' => $possibleValues,
'arrayOf' => $arrayOf ?? null,
];
}
-1
View File
@@ -149,7 +149,6 @@ abstract class Save extends Form implements \Picea\Ui\Method\FormInterface {
if (! in_array(ActionTypeEnum::Setter, $actions)) {
new ValueSet()->action($entity, $key, $context, $var);
}
}
}
elseif (! $entity->isLoaded() && $contextField) {
+15 -4
View File
@@ -5,6 +5,7 @@ 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;
@@ -21,7 +22,7 @@ class ActionLogContext extends FormContext
public string $method;
#[ContextField(mandatory: true)]
public int $object_id;
public mixed $object_id;
#[ContextField(mandatory: true)]
public string $object_type;
@@ -60,14 +61,24 @@ class ActionLogContext extends FormContext
public function initializeEntity(\Lean\Api\Entity\Security\ApiActionLog $actionLog) : void
{
if (isset($this->entity) && $this->entity->isLoaded()) {
if ($pk = array_key_first($this->entity::resolveEntity()->getPrimaryKeyField())) {
if (isset($this->entity->$pk)) {
$this->object_id = $this->entity->$pk;
$this->object_type = $this->entity::class;
if (isset($this->datasetFillEvent->data)) {
$this->data = $this->datasetFillEvent->data;
}
$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));
}
}
}
-1
View File
@@ -5,7 +5,6 @@ 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 {
+12 -3
View File
@@ -50,17 +50,26 @@ class ApiRenderer implements MiddlewareInterface {
# For now, we match only response having a 'data' field
if ( (is_array($payload) || $payload instanceof \ArrayAccess) && isset($payload['data'])) {
$humanSize = fn($size) => @round($size / pow(1024, $i=floor(log($size,1024))),2) . ['b','kb','mb','gb',][$i];
return HttpFactory::createJsonResponse([
'status' => 'success',
'ts' => time(),
] + $payload, 200);
] + $payload + (getenv('DEBUG') ? [
'debug' => [
'elapsed_time' => round(1000 * (microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]), 2),
'memory_usage' => $humanSize(memory_get_usage()),
'memory_peak_usage' => $humanSize(memory_get_peak_usage()),
'pid' => getmypid(),
]
] : []), 200);
}
}
return $response;
}
protected function saveError(ServerRequestInterface $request, \Throwable $exception) : Entity\Error
/*protected function saveError(ServerRequestInterface $request, \Throwable $exception) : Entity\Error
{
if ($debugFormFactory = $this->container->get(DebugFormFactoryInterface::class)) {
$request = $request->withMethod('PUT')->withParsedBody([]);
@@ -81,7 +90,7 @@ class ApiRenderer implements MiddlewareInterface {
}
return $entity;
}
}*/
public static function awaitingJson(ServerRequestInterface $request) : bool
{
+7 -3
View File
@@ -32,11 +32,11 @@
%}
{% endfunction %}
{% function yesOrNo(bool $toggle) : void %}
{% function.overwrite yesOrNo(bool $toggle) : void %}
<span style="color: {{ $toggle ? 'green' : '#ac1b1b' }}">{{ $toggle ? 'oui' : 'non' }}</span>
{% endfunction %}
{% function length(int|null|string $length): void %}
{% function.overwrite length(int|null|string $length): void %}
<span style="color:{{ $length ? 'black' : 'gray' }}">{{ $length ?? "non-défini" }}</span>
{% endfunction %}
@@ -73,6 +73,10 @@
{% endif %}
<div class="length"><u>Taille</u> : {{ length($field['length']) }}</div>
<div class="readonly"><u>Lecture seule</u> : {{ yesOrNo($field['readonly']) }}</div>
{% if $field['possibleValues'] ?? false %}
<div><u>Valeurs possibles</u> : [ <u class="enum-value">{{= implode('</u><u class="enum-value">', $field['possibleValues']) }}</u> ]</div>
{% endif %}
</div>
</li>
{% endforeach %}
@@ -120,6 +124,6 @@
</div>
{% endif %}
{% or %}
<i style="color:#585858; padding:0 12px">{% _ "none" %}</i>
<i class="nothing-found">{% _ "none" %}</i>
{% endforeach %}
</div>
+3 -3
View File
@@ -1,6 +1,6 @@
{% language.set "lean.api.descriptor.form" %}
{% function yesOrNo(bool $toggle) : void %}
{% function.inline yesOrNo(bool $toggle) : void %}
<span style="color: {{ $toggle ? 'green' : '#ac1b1b' }}">{{ $toggle ? 'oui' : 'non' }}</span>
{% endfunction %}
@@ -30,7 +30,7 @@
<div class="field-desc" style="margin-top:10px;;background:#fff;padding:5px;font-size:0.9em">
<div><u>Variable POST / champ JSON</u> : {{ $field['name'] }}</div>
<div><u>Type(s)</u> : {{ implode(' | ', array_map(fn($e) => $e->type, $field['type'])) }}</div>
<div><u>Nullable</u> : {{ yesOrNo($field['allowNulls']) }}</div>
<div><u>Nullable</u> : {{ $yesOrNo($field['allowNulls']) }}</div>
{% if $field['regexPattern'] !== null %}
<div><u>Pattern regex</u> : {{ $field['regexPattern'] }}</div>
{% endif %}
@@ -59,6 +59,6 @@
{% endif %}
</div>
{% or %}
<i style="color:#585858; padding:0 12px">{% _ "none" %}</i>
<i class="nothing-found">{% _ "none" %}</i>
{% endforeach %}
</div>
+10 -1
View File
@@ -38,6 +38,7 @@
<div class="response-head">
<span class="response-code"></span>
<span class="response-message"></span>
<span class="response-timing"></span>
</div>
<hr>
<pre id="response" class="code" ace-theme="ace/theme/cloud9_day"></pre>
@@ -56,8 +57,12 @@
.request-head .url button:active {filter:contrast(85%);}
.response-head {display: flex;border:1px solid #ececec;margin-bottom: 5px;border-top:0}
.response-head .response-code {background:#dfdfdf;padding:0 8px;font-weight: bold;line-height: 29px;font-size: 80%;}
.response-head[data-code="200"] .response-code{background: #cdfbbd;}
.response-head[data-code="204"] .response-code{background: #eaeab5;}
.response-head[data-code^="5"] .response-code{background: #ffa8a8;}
.response-head .response-code {background:#dfdfdf;padding:0 8px;font-weight: bold;line-height: 30px;font-size: 80%;}
.response-head .response-message {padding:0 10px;background:#fbfbfb;line-height: 30px;font-size: 80%;}
.response-head .response-timing {line-height: 30px;font-size: 75%;font-weight: bold;flex: 1;text-align: right;color: #646060;padding:0 8px;}
.request-compose {position:relative;}
.loading-anim {display:none;position:absolute;left:0;right:0;top:0;bottom:0;justify-content: center;align-items: center;z-index: 15;background: rgba(122, 121, 121, 0.25);}
@@ -155,10 +160,14 @@
return;
}
let timeStart = performance.now();
launchRequest(requestMethod, input.value, editor.getValue())
.then((response) => {
responseHead.setAttribute("data-code", response.status);
responseHead.querySelector('.response-code').innerText = response.status;
responseHead.querySelector('.response-message').innerText = response.statusText;
responseHead.querySelector('.response-timing').innerText = (performance.now() - timeStart) + "ms";
aceMode = parseContentType(response);
+1 -1
View File
@@ -28,7 +28,7 @@
</small>
</li>
{% or %}
<i style="color:#585858; padding:0 12px">{% _ "none" %}</i>
<i class="nothing-found">{% _ "none" %}</i>
{% endforeach %}
{% endforeach %}
</ul>
+3 -1
View File
@@ -38,6 +38,8 @@
.header-fields {color: #fff;line-height: 1.8rem;font-variant: small-caps;padding: 4px 0.8rem 0 0.8rem}
/*.fields-wrapper {border-left: 3px solid #c14141; margin-left: -10px; padding-left: 10px;}*/
.nothing-found {color:#585858; padding:0 12px;font-size: 75%;}
.forms ol {background: #ccdef2;}
.forms li {border-color: #859aae;}
.forms .btn {display: flex;justify-content: center;align-items: center;padding: 0 15px;gap: 15px;background-color:#4b6080;outline: 1px #4b6080 solid;border: 4px solid #9cc5e6;outline-offset: -3px;border-radius: 5px;cursor: pointer;transition: 400ms;color: white;font-weight: 100;font-size: 0.85em;transition-duration: 400ms;}
@@ -50,7 +52,7 @@
.enum-value:nth-child(odd) {color:gray}
.enum-value:after {content: ", "; color:#677b8c}
.enum-value:not(:last-child):after {content:"":}
.enum-value:last-child:after {content:"";}
.routes-wrapper {padding:5px}
.routes-wrapper li {display:flex;border: 1px solid #ccc;align-items: stretch;cursor:pointer}