Skip to content

Implement Static Site Generation (SSG) feature #10

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

Open
wants to merge 1 commit into
base: 7.3
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: 5 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

7.4
---

* asd

7.3
---

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
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\HttpKernel\StaticSiteGeneration\StaticPagesGenerator;
use Symfony\Component\HttpKernel\StaticSiteGeneration\StaticPageDumperInterface;
use Symfony\Component\HttpKernel\Exception\RuntimeException;
use Symfony\Component\Routing\StaticSiteGeneration\StaticUrisProviderInterface;

/**
* @author Thomas Bibaut <[email protected]>
*/
#[AsCommand(name: 'static-site-generation:generate', description: 'Generates the static site')]
final class StaticSiteGenerationGenerateCommand extends Command
Copy link
Collaborator

Choose a reason for hiding this comment

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

invokable command

{
public function __construct(
private readonly StaticPagesGenerator $staticPagesGenerator,
private readonly StaticPageDumperInterface $staticPageDumper,
private readonly StaticUrisProviderInterface $staticUrisProvider,
) {
parent::__construct();
}

protected function configure(): void
{
$this
->setDescription('Generates static pages')
->addOption(
'filterPattern',
Copy link
Collaborator

Choose a reason for hiding this comment

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

snake case

null,
InputOption::VALUE_REQUIRED,
'A pattern to filter the pages to generate',
)
->addOption(
'dryRun',
null,
InputOption::VALUE_NONE,
'Do not dump pages',
);
}

protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$filterPattern = $input->getOption('filterPattern');
$dryRun = $input->getOption('dryRun');

foreach ($this->staticUrisProvider->provide() as $uri)
{
if (null !== $filterPattern && !preg_match($filterPattern, $uri)) {
continue;
}

try {
['content' => $content, 'format' => $format] = $this->staticPagesGenerator->generate($uri);
} catch (RuntimeException $exception) {
$io->error(sprintf('Generating page for URI "%s" failed : %s', $uri, $exception->getMessage()));

// PROBLEM : even with -vvv we don't get the stack trace for this
// @todo printTrace in SymfonyStyle ???
// @see src/Symfony/Component/Console/Application.php:899
//
// if ($io->isVerbose()) {
// $io->comment('Exception trace', OutputInterface::VERBOSITY_QUIET);
// }
}

if (false === $dryRun) {
$this->staticPageDumper->dump($uri, $content, $format);
}

// @todo output path ?
$io->info(sprintf('Generated static page for URI "%s"', $uri));
}

return Command::SUCCESS;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ class UnusedTagsPass implements CompilerPassInterface
'routing.expression_language_provider',
'routing.loader',
'routing.route_loader',
'routing.static_site.params_provider',
'scheduler.schedule_provider',
'scheduler.task',
'security.access_token_handler.oidc.encryption_algorithm',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Composer\InstalledVersions;
use Http\Client\HttpAsyncClient;
use Http\Client\HttpClient;
use Symfony\Component\Routing\StaticSiteGeneration\ParamsProviderInterface;
use phpDocumentor\Reflection\DocBlockFactoryInterface;
use phpDocumentor\Reflection\Types\ContextFactory;
use PhpParser\Parser;
Expand Down Expand Up @@ -1247,6 +1248,9 @@ private function registerRouterConfiguration(array $config, ContainerBuilder $co
$container->getDefinition('router.request_context')
->replaceArgument(0, $config['default_uri']);
}

$container->registerForAutoconfiguration(ParamsProviderInterface::class)
->addTag('routing.static_site.params_provider');
}

private function registerSessionConfiguration(array $config, ContainerBuilder $container, PhpFileLoader $loader): void
Expand Down
10 changes: 10 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/console.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
use Symfony\Bundle\FrameworkBundle\Command\TranslationExtractCommand;
use Symfony\Bundle\FrameworkBundle\Command\WorkflowDumpCommand;
use Symfony\Bundle\FrameworkBundle\Command\YamlLintCommand;
use Symfony\Bundle\FrameworkBundle\Command\StaticSiteGenerationGenerateCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\EventListener\SuggestMissingPackageSubscriber;
use Symfony\Component\Console\EventListener\ErrorListener;
Expand Down Expand Up @@ -397,5 +398,14 @@
service('console.messenger.application'),
])
->tag('messenger.message_handler')


->set('console.command.static_site_generation_generate', StaticSiteGenerationGenerateCommand::class)
->args([
service('static_site.pages_generator'),
service('static_site.page_dumper'),
service('routing.static_site.uri_provider'),
])
->tag('console.command')
;
};
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RequestContextAwareInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Routing\StaticSiteGeneration\StaticUrisProvider;

return static function (ContainerConfigurator $container) {
$container->parameters()
Expand Down Expand Up @@ -208,5 +209,11 @@
service('twig')->ignoreOnInvalid(),
])
->public()

->set('routing.static_site.uri_provider', StaticUrisProvider::class)
->args([
service('router'),
tagged_locator('routing.static_site.params_provider'),
])
;
};
14 changes: 14 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@
use Symfony\Component\HttpKernel\EventListener\LocaleListener;
use Symfony\Component\HttpKernel\EventListener\ResponseListener;
use Symfony\Component\HttpKernel\EventListener\ValidateRequestListener;
use Symfony\Component\HttpKernel\StaticSiteGeneration\FilesystemStaticPageDumper;
use Symfony\Component\HttpKernel\StaticSiteGeneration\StaticPageDumperInterface;
use Symfony\Component\HttpKernel\StaticSiteGeneration\StaticPagesGenerator;

return static function (ContainerConfigurator $container) {
$container->services()
Expand Down Expand Up @@ -145,5 +148,16 @@
->set('controller.cache_attribute_listener', CacheAttributeListener::class)
->tag('kernel.event_subscriber')

->set('static_site.pages_generator', StaticPagesGenerator::class)
->args([
service('http_kernel'),
service('routing.static_site.uri_provider'),
])

->set('static_site.page_dumper', FilesystemStaticPageDumper::class)
->args([
param('kernel.project_dir'),
])
->alias(StaticPageDumperInterface::class, 'static_static.page_dumper')
;
};
6 changes: 6 additions & 0 deletions src/Symfony/Component/HttpKernel/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
CHANGELOG
=========

7.4
---

* asd


7.3
---

Expand Down
16 changes: 16 additions & 0 deletions src/Symfony/Component/HttpKernel/Exception/RuntimeException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpKernel\Exception;

class RuntimeException extends \RuntimeException
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpKernel\StaticSiteGeneration;

use Symfony\Component\Filesystem\Filesystem;

/**
* @author Thomas Bibaut <[email protected]>
*/
final readonly class FilesystemStaticPageDumper implements StaticPageDumperInterface
{
private Filesystem $filesystem;

public function __construct(
private string $projectDir,
) {
$this->filesystem = new Filesystem();
}

public function dump(string $uri, string $content, ?string $format = null): void
{
$fileName = $uri === '/'
? 'index.html'
: $uri;

if ($format && !str_ends_with($uri, '.' . $format)) {
$fileName = sprintf('%s.%s', $uri, $format);
}

$staticPagesDirectory = sprintf('%s/%s/static-pages', $this->projectDir, $this->getPublicDirectory());
$this->filesystem->dumpFile(sprintf('%s/%s', $staticPagesDirectory, $fileName), $content);
}

private function getPublicDirectory(): string
{
$defaultPublicDir = 'public';
$composerFilePath = sprintf('%s/composer.json', $this->projectDir);

if (!file_exists($composerFilePath)) {
return $defaultPublicDir;
}

$composerConfig = json_decode($this->filesystem->readFile($composerFilePath), true, flags: \JSON_THROW_ON_ERROR);

return $composerConfig['extra']['public-dir'] ?? $defaultPublicDir;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpKernel\StaticSiteGeneration;

/**
* @author Thomas Bibaut <[email protected]>
*/
interface StaticPageDumperInterface
{
public function dump(string $uri, string $content, ?string $format): void;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpKernel\StaticSiteGeneration;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;
use Symfony\Component\HttpKernel\Exception\RuntimeException;

/**
* @author Thomas Bibaut <[email protected]>
*/
final readonly class StaticPagesGenerator
{
public function __construct(
private HttpKernelInterface $kernel,
) {
}

/**
* Generate page content for URI.
*
* @return array{content: string, format: ?string}
*
* @throws RuntimeException
*/
public function generate(string $uri): array
{
$request = Request::create($uri);
try {
$response = $this->kernel->handle($request, HttpKernelInterface::MAIN_REQUEST);

if ($this->kernel instanceof TerminableInterface) {
$this->kernel->terminate($request, $response);
}
} catch (\Exception $e) {
throw new RuntimeException(sprintf('Cannot generate page for URI "%s".', $uri), $e->getCode(), $e);
}

if (Response::HTTP_OK !== $response->getStatusCode()) {
throw new RuntimeException(sprintf('Expected URI "%s" to return status code 200, got %d.', $uri, $response->getStatusCode()));
}

return [
'content' => $response->getContent(),
'format' => $request->getFormat($response->headers->get('Content-Type'))
];
}
}
Loading
Loading