Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(doc): use vitepress for documentation #1042

Open
wants to merge 20 commits into
base: 5.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
5 changes: 2 additions & 3 deletions EMS/core-bundle/src/Command/ActivateContentTypeCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,18 +35,17 @@ public function __construct(private readonly LoggerInterface $logger, protected
protected function configure(): void
{
parent::configure();
$fileNames = \implode(', ', $this->contentTypeService->getAllNames());
$this
->addArgument(
self::ARGUMENT_CONTENTTYPES,
InputArgument::IS_ARRAY,
\sprintf('Optional array of contenttypes to create. Allowed values: [%s]', $fileNames)
\sprintf('Optional array of contenttypes to create')
)
->addOption(
self::OPTION_ALL,
null,
InputOption::VALUE_NONE,
\sprintf('Make all contenttypes: [%s]', $fileNames)
\sprintf('Make all contenttypes')
)
->addOption(
self::DEACTIVATE,
Expand Down
8 changes: 6 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ stop: ## stop docker, admin server, web server
cache-clear: ## cache clear
@$(RUN_ADMIN) c:cl
@$(RUN_WEB) c:cl
docs: ## serve docs
@docsify serve ./docs
status: ## status
@$(DOCKER_COMPOSE) ps

Expand All @@ -61,6 +59,12 @@ server-stop/%: ## server-stop/(admin|web)
server-log/%: ## server-log/(admin|web)
symfony server:log --dir=elasticms-${*}

## —— Doc ——————————————————————————————————————————————————————————————————————————————————————————————————————————————
docs: ## serve docs
npm run --prefix ./doc docs:dev
docs-init: ## init docs
npm install --prefix ./doc

## —— Build ————————————————————————————————————————————————————————————————————————————————————————————————————————————
build-translations: ## build translations
@php build/translations en EMSCoreBundle --write --format=yml -d emsco-core
Expand Down
12 changes: 12 additions & 0 deletions build/doc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env php
<?php

require __DIR__.'/../vendor/autoload.php';

use Build\Doc\Application;
use Build\Doc\Command;

$application = new Application();
$application->add(new Command\DocCommandsCommand());

$application->run();
38 changes: 38 additions & 0 deletions build/src/Doc/Application.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

namespace Build\Doc;

use Symfony\Component\Console\Application as SymfonyApplication;
use Symfony\Component\Console\Command\HelpCommand;
use Symfony\Component\Console\Command\ListCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;

class Application extends SymfonyApplication
{
public function __construct()
{
parent::__construct('EMS doc', '1.0.0');
}

protected function getDefaultCommands(): array
{
return [
new HelpCommand(),
new ListCommand(),
];
}

protected function getDefaultInputDefinition(): InputDefinition
{
return new InputDefinition([
new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display help for the given command.'),
new InputOption('--verbose', '-v|vv|vvv', InputOption::VALUE_NONE, 'Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug'),
new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'),
]);
}
}
159 changes: 159 additions & 0 deletions build/src/Doc/Command/DocCommandsCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
<?php

declare(strict_types=1);

namespace Build\Doc\Command;

use App\Admin\Kernel;
use Build\Doc\Markdown\Content;
use Build\Doc\Markdown\MarkdownFile;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Dotenv\Dotenv;

class DocCommandsCommand extends Command
{
protected static $defaultName = 'commands';

private Application $application;

private const CONFIG = [
['EMS\CommonBundle\Command\\', __DIR__.'/../../../../doc/ems/common/commands.md'],
];

private const EXCLUDE_OPTIONS = ['help', 'quiet', 'verbose', 'version', 'ansi', 'no-interaction', 'env', 'no-debug'];

protected function initialize(InputInterface $input, OutputInterface $output): void
{
$this->application = $this->getAdminApplication();
}

protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$io->title('Doc: commands');

try {
foreach (self::CONFIG as list($namespace, $filename)) {
$groupedCommands = $this->getGroupedCommands($namespace);

$file = new MarkdownFile($filename);
$sectionCommands = $file->block->getSection('Commands');
$sectionCommands->content->newLine();

foreach ($groupedCommands as $group => $commands) {
$parentSection = (\count($commands) > 1) ? $sectionCommands->getSection(\ucfirst($group)) : $sectionCommands;
$parentSection->content->newLine();

foreach ($commands as $name => $command) {
$content = $parentSection->getSection(\ucfirst($name))->content;
$this->writeCommand($command, $content);
}
}
}
} catch (\Throwable $e) {
$io->error($e->getMessage());
}

return self::SUCCESS;
}

private function getAdminApplication(): Application
{
(new Dotenv())->load(__DIR__.'/../../../../elasticms-admin/.env');
$adminKernel = new Kernel('test', true);
$adminKernel->boot();

return new Application($adminKernel);
}

/**
* @return array<string, array<string, Command>>
*/
private function getGroupedCommands(string $namespace): array
{
$allCommands = \array_filter(
$this->application->all(),
fn (Command $command) => \str_starts_with(\get_class($command), $namespace)
);

$result = [];
foreach ($allCommands as $command) {
if (null === $name = $command->getName()) {
continue;
}

$explodeName = \explode(':', $name);
$group = $explodeName[1];
$name = \array_pop($explodeName);
$result[$group][$name] = $command;
}

return $result;
}

private function writeCommand(Command $command, Content $content): void
{
$arguments = $command->getDefinition()->getArguments();
$options = \array_filter(
array: $command->getDefinition()->getOptions(),
callback: fn (InputOption $option) => !\in_array($option->getName(), self::EXCLUDE_OPTIONS)
);

$content
->newLine()
->startStopAutoGeneration('command')
->write('' !== $command->getDescription() ? $command->getDescription() : null, true)
->writeCode('bash', $command->getSynopsis(true))
->write(\count($arguments) > 0 ? '**Arguments**' : null, true)
->list(\array_map([$this, 'parseInput'], $arguments))
->write(\count($options) > 0 ? '**Options**' : null, true)
->list(\array_map([$this, 'parseInput'], $options))
->startStopAutoGeneration('command')
->newLine();
}

/**
* @return array{'title': string, 'content': string[]}
*/
private function parseInput(InputArgument|InputOption $input): array
{
$name = $input instanceof InputOption ? '--'.$input->getName() : $input->getName();
$shortcut = $input instanceof InputOption && \is_string($input->getShortcut())
? \sprintf('```-%s``` ', $input->getShortcut())
: '';

$extra = [];
if ($input instanceof InputArgument && $input->isRequired()) {
$extra[] = 'required';
}

if (null !== $input->getDefault() && (!$input instanceof InputOption || $input->acceptValue())) {
$default = match (\gettype($input->getDefault())) {
'boolean' => true === $input->getDefault() ? 'true' : 'false',
'array' => \sprintf('["%s"]', \implode('", "', $input->getDefault())),
'string' => \sprintf('"%s"', $input->getDefault()),
default => (string) $input->getDefault()
};
$extra[] = \sprintf('default: %s', $default);
}

if ($input->isArray()) {
$extra[] = 'multiple values allowed';
}

$extraString = \count($extra) ? ' '.\implode(' ', $extra) : '';

return [
'title' => \sprintf('%s```%s```%s', $shortcut, $name, $extraString),
'content' => [
\sprintf('> %s', $input->getDescription()),
],
];
}
}
102 changes: 102 additions & 0 deletions build/src/Doc/Markdown/Block.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?php

declare(strict_types=1);

namespace Build\Doc\Markdown;

use function Symfony\Component\String\u;

class Block
{
/** @var array<string, Block> */
private array $sections = [];
public Content $content;

public function __construct(
public readonly string $title,
public readonly int $level,
public readonly bool $sortSections = false
) {
$this->content = new Content();
}

public function __toString(): string
{
$dump = '';
if ($this->level > 0) {
$prefix = u('#')->repeat($this->level)->append(' ')->toString();
$dump .= u($this->title)->prepend($prefix)->toString().\PHP_EOL;
}

$dump .= $this->content;

return \array_reduce($this->sections, static fn (string $carry, Block $block) => $carry.$block, $dump);
}

/**
* @param string[] $lines
*/
public static function fromLines(string $title, array $lines, int $level = 0): Block
{
$block = new self($title, $level);

$flagInCodeBlock = false;
foreach ($lines as $i => $line) {
if (\str_starts_with(\ltrim($line), '```')) {
$flagInCodeBlock = !$flagInCodeBlock;
}
if (\str_starts_with($line, '#') && !$flagInCodeBlock) {
break;
}
if (\str_starts_with($line, Content::AUTO_GENERATED)) {
$block->content->startStopAutoGeneration($line);
} else {
$block->content->write($line);
}
unset($lines[$i]);
}

$childrenPrefix = u('#')->repeat($level + 1)->append(' ')->toString();
$currentChild = false;
$groupChildren = [];

$flagInCodeBlock = false;
foreach ($lines as $line) {
if (\str_starts_with(\ltrim($line), '```')) {
$flagInCodeBlock = !$flagInCodeBlock;
}
if (\str_starts_with($line, $childrenPrefix) && !$flagInCodeBlock) {
$title = u($line)->trimPrefix($childrenPrefix)->toString();
$groupChildren[$title] = [];
$currentChild = $title;
} elseif ($currentChild) {
$groupChildren[$currentChild][] = $line;
}
}

foreach ($groupChildren as $title => $lines) {
$block->addSection(Block::fromLines($title, $lines, $level + 1));
}

return $block;
}

public function getSection(string $title, bool $sort = true): Block
{
if (!isset($this->sections[$title])) {
$this->addSection(new self(
title: $title,
level: $this->level + 1,
sortSections: $sort
));
}

return $this->sections[$title];
}

private function addSection(Block $section): void
{
$this->sections[$section->title] = $section;
\ksort($this->sections);
}
}
Loading
Loading