Skip to content

Commit

Permalink
Add custom Twig loader to remove last new line of a file
Browse files Browse the repository at this point in the history
  • Loading branch information
wouterj authored and jaapio committed Mar 20, 2024
1 parent e7f9a88 commit 7dbdb05
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
4 changes: 3 additions & 1 deletion packages/guides/resources/config/guides.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
use phpDocumentor\Guides\Twig\EnvironmentBuilder;
use phpDocumentor\Guides\Twig\GlobalMenuExtension;
use phpDocumentor\Guides\Twig\Theme\ThemeManager;
use phpDocumentor\Guides\Twig\TrimFilesystemLoader;
use phpDocumentor\Guides\Twig\TwigTemplateRenderer;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\DependencyInjection\Reference;
Expand Down Expand Up @@ -223,11 +224,12 @@
param('phpdoc.guides.base_template_paths'),
)

->set(FilesystemLoader::class)
->set(TrimFilesystemLoader::class)
->arg(
'$paths',
param('phpdoc.guides.base_template_paths'),
)
->alias(FilesystemLoader::class, TrimFilesystemLoader::class)

->set(LoadSettingsFromComposer::class)
->tag('event_listener', ['event' => PostProjectNodeCreated::class])
Expand Down
41 changes: 41 additions & 0 deletions packages/guides/src/Twig/TrimFilesystemLoader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link https://phpdoc.org
*/

namespace phpDocumentor\Guides\Twig;

use Twig\Loader\FilesystemLoader;
use Twig\Source;

use function preg_replace;

/**
* A file system loader that trims the last line ending from the template
* content.
*/
class TrimFilesystemLoader extends FilesystemLoader
{
// phpcs:disable SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint

/** @param string $name */
public function getSourceContext($name): Source
{
// phpcs:enable
$source = parent::getSourceContext($name);

return new Source(
preg_replace('/\R$/', '', $source->getCode()) ?? $source->getCode(),
$source->getName(),
$source->getPath(),
);
}
}

0 comments on commit 7dbdb05

Please sign in to comment.