Skip to content
This repository was archived by the owner on Sep 15, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 37 additions & 18 deletions .github/workflows/lint.yaml
Original file line number Diff line number Diff line change
@@ -1,21 +1,40 @@
name: Lint
on: [push, pull_request]
name: Coding standards
on: [push]
jobs:
lint:
name: PHP Lint
runs-on: ubuntu-latest
steps:
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: 8.3
lint:
name: Coding standards
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
php: [ '8.3', '8.4' ]

- name: Cache Composer dependencies
uses: actions/cache@v4
with:
path: /tmp/composer-cache
key: ${{ runner.os }}-${{ hashFiles('**/composer.lock') }}
steps:
- name: Checkout
uses: actions/checkout@v4

- uses: actions/checkout@v4
- name: lint
run: make app:lint
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
tools: composer:v2

- name: Setup cache
run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV

- name: Cache dependencies installed with composer
uses: actions/cache@v4
with:
path: ${{ env.COMPOSER_CACHE_DIR }}
key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }}
restore-keys: |
php${{ matrix.php }}-composer-latest-

- name: Update composer
run: composer self-update

- name: Install dependencies with composer
run: composer install --prefer-dist --no-interaction --no-progress --optimize-autoloader --ansi

- name: Run code quality analysis
run: composer app:lint
55 changes: 37 additions & 18 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -1,21 +1,40 @@
name: Test
on: [push, pull_request]
name: Tests
on: [push]
jobs:
lint:
name: PHP Test
runs-on: ubuntu-latest
steps:
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: 8.3
test:
name: Tests
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
php: [ '8.3', '8.4' ]

- name: Cache Composer dependencies
uses: actions/cache@v4
with:
path: /tmp/composer-cache
key: ${{ runner.os }}-${{ hashFiles('**/composer.lock') }}
steps:
- name: Checkout
uses: actions/checkout@v4

- uses: actions/checkout@v4
- name: test
run: make app:test
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
tools: composer:v2

- name: Setup cache
run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV

- name: Cache dependencies installed with composer
uses: actions/cache@v4
with:
path: ${{ env.COMPOSER_CACHE_DIR }}
key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }}
restore-keys: |
php${{ matrix.php }}-composer-latest-

- name: Update composer
run: composer self-update

- name: Install dependencies with composer
run: composer install --prefer-dist --no-interaction --no-progress --optimize-autoloader --ansi

- name: Run tests
run: composer app:test
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
],
"app:lint:fix": [
"vendor/bin/ecs check --fix",
"venodr/bin/rector"
"vendor/bin/rector"
],
"app:test": "vendor/bin/phpunit"
}
Expand Down
12 changes: 6 additions & 6 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

104 changes: 66 additions & 38 deletions src/BlockFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,36 @@
*
* @author bernard-ng <bernard@devscast.tech>
*/
abstract readonly class BlockFactory
abstract class BlockFactory
{
/**
* @throws EditorException
*
* reduire la complexite de O(n) a O(1) evitant de tout le temps checker toutes les conditions
*/
private static array $blockFactories = [];

/**
* @throws EditorException
*/
public static function parse(string $data, ?array $tools = null, array $allowedTags = []): array
{
try {
/** @var array{time: int, blocks: array<array{id: string, type: string, data: mixed}>} $blocks */
$blocks = json_decode($data, true, flags: JSON_THROW_ON_ERROR);
$mapper = fn (array $block): Block => self::create($block, self::getAllowedTags($block, $allowedTags));

// TODO: whitelist tools and supported blocks
// if ($tools !== null) {
// $blocks = self::filter($blocks['blocks'], $tools);
// }

if ($tools !== null) {
$blocks = self::filter($blocks['blocks'], $tools);
$blocks['blocks'] = self::filter($blocks['blocks'], $tools);

if (empty($blocks['blocks'])) {
throw new EditorException('No valid blocks found after filtering');
}
}

return array_map($mapper, $blocks['blocks']);
Expand All @@ -55,57 +72,68 @@ public static function parse(string $data, ?array $tools = null, array $allowedT
}
}

private static function filter(array $data, array $tools): array
// private static function filter(array $data, array $tools): array
// {
// return array_filter($data, fn (array $block): bool => isset($tools[$block['type']]));
// }

private static function filter(array $blocks, array $tools): array
{
return array_filter($data, fn (array $block): bool => isset($tools[$block['type']]));
return array_filter($blocks, fn (array $block) => in_array($block['type'], $tools, true));
}

private static function initializeFactories(): void
{
if (self::$blockFactories !== []) {
return;
}
self::$blockFactories = [
'attaches' => static fn (array $data, array $allowedTags) => Attaches::create($data, $allowedTags),
'code' => static fn (array $data, array $allowedTags) => Code::create($data, $allowedTags),
'delimiter' => static fn (array $data, array $allowedTags) => Delimiter::create($data, $allowedTags),
'embed' => static fn (array $data, array $allowedTags) => Embed::create($data, $allowedTags),
'header' => static fn (array $data, array $allowedTags) => Header::create($data, $allowedTags),
'image' => static fn (array $data, array $allowedTags) => Image::create($data, $allowedTags),
'list' => static fn (array $data, array $allowedTags) => Listing::create($data, $allowedTags),
'paragraph' => static fn (array $data, array $allowedTags) => Paragraph::create($data, $allowedTags),
'quote' => static fn (array $data, array $allowedTags) => Quote::create($data, $allowedTags),
'raw' => static fn (array $data, array $allowedTags) => Raw::create($data, $allowedTags),
'table' => static fn (array $data, array $allowedTags) => Table::create($data, $allowedTags),
'warning' => static fn (array $data, array $allowedTags) => Warning::create($data, $allowedTags),
];
}

/**
* @throws EditorException
*/
private static function create(array $data, array $allowedTags = []): Block
{
try {
// TODO: I think this may be very slow for large data need to think of a better way

//dd(self::getSchema($data['type']), $data);

$schema = Schema::import(self::getSchema($data['type']));

dd($schema);

return match ($data['type']) {
'attaches' => Attaches::create($data, $allowedTags),
'code' => Code::create($data, $allowedTags),
'delimiter' => Delimiter::create($data, $allowedTags),
'embed' => Embed::create($data, $allowedTags),
'header' => Header::create($data, $allowedTags),
'image' => Image::create($data, $allowedTags),
'list' => Listing::create($data, $allowedTags),
'paragraph' => Paragraph::create($data, $allowedTags),
'quote' => Quote::create($data, $allowedTags),
'raw' => Raw::create($data, $allowedTags),
'table' => Table::create($data, $allowedTags),
'warning' => Warning::create($data, $allowedTags),
};
self::initializeFactories();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

humm là tu crées tous les blocks avec la même donné et stock en mémoire le résultat qui ne sera peut être pas utilisé ! on doit y réfléchir encore un peu mais je ne pense pas qu'il ait un problème de performance à ce niveau.

le problème c'était avec la validation du schema, mais on va gérer ça après


$type = $data['type'];
if (! isset(self::$blockFactories[$type])) {
throw new EditorException(sprintf('Block type %s not supported', $type));
}
return self::$blockFactories[$type]($data, $allowedTags);
} catch (\Throwable $e) {
throw new EditorException($e->getMessage(), previous: $e);
}
}

private static function getAllowedTags(mixed $block, array $allowedTags): array
private static function getAllowedTags(array $block, array $allowedTags): array
{
Assert::keyExists($block, 'type');

return $allowedTags[$block['type']] ?? [];
}

private static function getSchema(string $schema): array
{
$filename = sprintf("%s/schemas/%s.schema.json", dirname(__DIR__), $schema);
$content = file_get_contents($filename);
Assert::string($content, sprintf('Schema for block type %s not found', $schema));

return json_decode($content, true);
}
// private static function getSchema(string $schema): array
// {
// $filename = sprintf('%s/schemas/%s.schema.json', dirname(__DIR__), $schema);
// $content = file_get_contents($filename);
// Assert::string($content, sprintf('Schema for block type %s not found', $schema));
//
// /** @var array $schema */
// $schema = json_decode($content, true);
//
// return $schema;
// }
}
16 changes: 14 additions & 2 deletions src/Blocks/Attaches.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
*/
final readonly class Attaches extends Block
{
public function __construct(string $id, string $type, array $data, ?array $tunes, array $rules)
public function __construct(string $id, string $type, array $data, ?array $tunes = [], ?array $allowedTags = null)
{
Assert::eq($type, 'attaches');
Assert::keyExists($data, 'file');
Expand All @@ -37,6 +37,18 @@ public function __construct(string $id, string $type, array $data, ?array $tunes
Assert::keyExists($data['file'], 'extension');
Assert::keyExists($data, 'title');

parent::__construct($id, $type, $data, $tunes, $rules);
parent::__construct($id, $type, $data, $tunes, $allowedTags);
}

#[\Override]
public function toHtml(): string
{
return <<<HTML
<div id="{$this->id}">
<a href="{$this->data['file']['url']}" title="{$this->data['title']}">
<strong>{$this->data['file']['name']}</strong> ({$this->data['file']['size']} bytes)
</a>
</div>
HTML;
}
}
24 changes: 10 additions & 14 deletions src/Blocks/Block.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
/**
* Class Block.
*
* @phpstan-consistent-constructor
*
* @author bernard-ng <bernard@devscast.tech>
*/
abstract readonly class Block
Expand All @@ -33,6 +35,8 @@ public function __construct(
Assert::notEmpty($id);
}

abstract public function toHtml(): string;

public static function create(array $data, array $allowedTags = []): static
{
return new static(
Expand All @@ -44,18 +48,10 @@ public static function create(array $data, array $allowedTags = []): static
);
}

// private function sanitize(array $data, array|string $allowedTags = []): array
// {
// $sanitizer = Sanitizer::create($allowedTags);
//
// foreach ($data as $key => $value) {
// if (is_array($value)) {
// $data[$key] = $this->sanitize($value, $allowedTags);
// } else {
// $data[$key] = $sanitizer->sanitize($value);
// }
// }
//
// return $data;
// }
public function sanitize(): string
{
$sanitizer = Sanitizer::create($this->allowedTags ?? []);

return $sanitizer->sanitize($this->toHtml());
}
}
Loading