repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
livewire/blaze | https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/invalid-foldable/error.blade.php | tests/fixtures/components/invalid-foldable/error.blade.php | @blaze
@props(['name'])
<div>
@error($name)
<span class="error">{{ $message }}</span>
@enderror
</div>
| php | MIT | 412a05c7b333ee9ce5d8a61a23f80998ece76a9d | 2026-01-05T05:18:39.918460Z | false |
livewire/blaze | https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/kanban/comments/comments.blade.php | tests/fixtures/components/kanban/comments/comments.blade.php | Comments | php | MIT | 412a05c7b333ee9ce5d8a61a23f80998ece76a9d | 2026-01-05T05:18:39.918460Z | false |
livewire/blaze | https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/form/index.blade.php | tests/fixtures/components/form/index.blade.php | @blaze
@props([])
<form>
<div class="form-header">
{{ $header }}
</div>
<div class="form-body">
{{ $slot }}
</div>
<div class="form-footer">
{{ $footer }}
</div>
</form>
| php | MIT | 412a05c7b333ee9ce5d8a61a23f80998ece76a9d | 2026-01-05T05:18:39.918460Z | false |
livewire/blaze | https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/form/input.blade.php | tests/fixtures/components/form/input.blade.php | @blaze
@props([])
<input {{ $attributes }} />
| php | MIT | 412a05c7b333ee9ce5d8a61a23f80998ece76a9d | 2026-01-05T05:18:39.918460Z | false |
livewire/blaze | https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/components/form/fields/text.blade.php | tests/fixtures/components/form/fields/text.blade.php | @blaze
@props([])
<input type="text" {{ $attributes }} />
| php | MIT | 412a05c7b333ee9ce5d8a61a23f80998ece76a9d | 2026-01-05T05:18:39.918460Z | false |
livewire/blaze | https://github.com/livewire/blaze/blob/412a05c7b333ee9ce5d8a61a23f80998ece76a9d/tests/fixtures/layouts/app.blade.php | tests/fixtures/layouts/app.blade.php | <html>
<body>
{{ $slot }}
</body>
</html> | php | MIT | 412a05c7b333ee9ce5d8a61a23f80998ece76a9d | 2026-01-05T05:18:39.918460Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/.php-cs-fixer.php | .php-cs-fixer.php | <?php
$header = <<<'EOF'
This file is part of the "StenopePHP/Stenope" bundle.
@author Thomas Jarrand <thomas.jarrand@gmail.com>
@author Maxime Steinhausser <maxime.steinhausser@gmail.com>
EOF;
$finder = (new PhpCsFixer\Finder())
->in([__DIR__])
->exclude('doc/app')
->exclude('tests/fixtures/app/var')
->exclude('tests/fixtures/app/build')
;
return (new PhpCsFixer\Config)
->setUsingCache(true)
->setRiskyAllowed(true)
->setFinder($finder)
->setRules([
'@Symfony' => true,
'array_syntax' => ['syntax' => 'short'],
'blank_line_between_import_groups' => false,
'concat_space' => ['spacing' => 'one'],
'header_comment' => ['header' => $header],
'native_function_invocation' => ['include' => ['@compiler_optimized']],
'ordered_imports' => true,
'php_unit_namespaced' => true,
'php_unit_method_casing' => false,
'phpdoc_annotation_without_dot' => false,
'phpdoc_summary' => false,
'phpdoc_order' => true,
'phpdoc_trim_consecutive_blank_line_separation' => true,
'psr_autoloading' => true,
'single_line_throw' => false,
'simplified_null_return' => false,
'void_return' => true,
'yoda_style' => [],
// @see https://github.com/FriendsOfPHP/PHP-CS-Fixer/issues/5495
'binary_operator_spaces' => ['operators' => ['|' => null]]
])
;
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/StenopeBundle.php | src/StenopeBundle.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle;
use Stenope\Bundle\DependencyInjection\Compiler\TwigExtensionFixerCompilerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* @final
*/
class StenopeBundle extends Bundle
{
public function build(ContainerBuilder $container): void
{
parent::build($container);
$container->addCompilerPass(new TwigExtensionFixerCompilerPass());
}
public function getPath(): string
{
return \dirname(__DIR__);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Builder.php | src/Builder.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Stenope\Bundle\Builder\PageList;
use Stenope\Bundle\Builder\Sitemap;
use Stenope\Bundle\Exception\ContentNotFoundException;
use Stenope\Bundle\HttpFoundation\ContentRequest;
use Stenope\Bundle\Routing\RouteInfoCollection;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\Glob;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Mime\MimeTypesInterface;
use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Stopwatch\Stopwatch;
use Twig\Environment;
/**
* Static route builder
*/
class Builder
{
private RouterInterface $router;
private RouteInfoCollection $routesInfo;
private HttpKernelInterface $httpKernel;
private Environment $templating;
private PageList $pageList;
private Sitemap $sitemap;
/** Path to output the static site */
private string $buildDir;
private Filesystem $files;
private MimeTypesInterface $mimeTypes;
/** Files to copy after build */
private array $filesToCopy;
private LoggerInterface $logger;
private Stopwatch $stopwatch;
public function __construct(
RouterInterface $router,
RouteInfoCollection $routesInfo,
HttpKernelInterface $httpKernel,
Environment $templating,
MimeTypesInterface $mimeTypes,
PageList $pageList,
Sitemap $sitemap,
string $buildDir,
array $filesToCopy = [],
?LoggerInterface $logger = null,
?Stopwatch $stopwatch = null
) {
$this->router = $router;
$this->routesInfo = $routesInfo;
$this->httpKernel = $httpKernel;
$this->templating = $templating;
$this->mimeTypes = $mimeTypes;
$this->pageList = $pageList;
$this->sitemap = $sitemap;
$this->buildDir = $buildDir;
$this->filesToCopy = $filesToCopy;
$this->files = new Filesystem();
$this->logger = $logger ?? new NullLogger();
$this->stopwatch = $stopwatch ?? new Stopwatch(true);
}
public function iterate(
bool $sitemap = true,
bool $expose = true,
bool $ignoreContentNotFoundErrors = false
): \Generator {
return yield from $this->doBuild($sitemap, $expose, $ignoreContentNotFoundErrors);
}
/**
* Build static site
*
* @return int Number of pages built
*/
public function build(bool $sitemap = true, bool $expose = true, bool $ignoreContentNotFoundErrors = false): int
{
iterator_to_array($generator = $this->doBuild($sitemap, $expose, $ignoreContentNotFoundErrors));
return $generator->getReturn();
}
/**
* Build static site
*/
private function doBuild(
bool $sitemap = true,
bool $expose = true,
bool $ignoreContentNotFoundErrors = false
): \Generator {
yield 'start' => $this->notifyContext('Start building');
if (!$this->stopwatch->isStarted('build')) {
$this->stopwatch->start('build', 'stenope');
}
yield 'clear' => $this->notifyContext('Clearing previous build');
$this->clear();
yield 'scan' => $this->notifyContext('Scanning routes');
$this->scanAllRoutes();
yield 'build_pages' => $this->notifyContext('Building pages...');
$pagesCount = 0;
yield from $this->buildPages($pagesCount, $ignoreContentNotFoundErrors);
if ($expose) {
yield 'copy' => $this->notifyContext('Copying files');
$this->copyFiles();
}
if ($sitemap) {
yield 'build_sitemap' => $this->notifyContext('Building sitemap...');
$this->buildSitemap();
}
if ($this->stopwatch->isStarted('build')) {
$this->stopwatch->stop('build');
}
yield 'end' => $this->notifyContext();
return $pagesCount;
}
public function setBuildDir(string $buildDir): void
{
$this->buildDir = $buildDir;
}
public function getBuildDir(): string
{
return $this->buildDir;
}
/**
* Set host name
*/
public function setHost(string $host): void
{
$this->router->getContext()->setHost($host);
}
public function getHost(): string
{
return $this->router->getContext()->getHost();
}
/**
* Set HTTP Scheme
*/
public function setScheme(string $scheme): void
{
$this->router->getContext()->setScheme($scheme);
}
public function getScheme(): string
{
return $this->router->getContext()->getScheme();
}
public function setBaseUrl(string $baseUrl): void
{
$this->router->getContext()->setBaseUrl('/' . ltrim($baseUrl, '/'));
}
public function getBaseUrl(): string
{
return $this->router->getContext()->getBaseUrl();
}
/**
* Clear destination folder
*/
private function clear(): void
{
$this->stopwatch->openSection();
$this->stopwatch->start('clear');
$this->logger->notice('Clearing {build_dir} build directory...', ['build_dir' => $this->buildDir]);
if ($this->files->exists($this->buildDir)) {
$this->files->remove($this->buildDir);
}
$this->files->mkdir($this->buildDir);
$time = $this->stopwatch->lap('clear')->getDuration();
$this->stopwatch->stopSection('clear');
$this->logger->info('Cleared {build_dir} build directory! ({time})', [
'build_dir' => $this->buildDir,
'time' => self::formatTime($time),
]);
}
/**
* Scan all declared route and tries to add them to the page list.
*/
private function scanAllRoutes(): void
{
$this->stopwatch->openSection();
$this->stopwatch->start('scan_routes');
$routes = $this->routesInfo;
$this->logger->notice('Scanning {count} routes...', ['count' => \count($routes)]);
$skipped = 0;
foreach ($routes as $name => $route) {
if ($route->isIgnored() || !$route->isGettable()) {
$this->logger->debug('Route "{route}" is hidden, skipping.', ['route' => $name]);
continue;
}
try {
$url = $this->router->generate($name, [], UrlGeneratorInterface::ABSOLUTE_URL);
} catch (MissingMandatoryParametersException $exception) {
++$skipped;
$this->logger->debug('Route "{route}" requires parameters, skipping.', ['route' => $name]);
continue;
}
$this->pageList->add($url);
$this->logger->debug('Route "{route}" is successfully listed.', ['route' => $name]);
}
$lap = $this->stopwatch->lap('scan_routes');
$time = $lap->getDuration();
$memory = $lap->getMemory();
$this->stopwatch->stopSection('scan_routes');
$this->logger->info('Scanned {scanned} routes ({skipped} skipped), discovered {count} entrypoint routes! ({time}, {memory})', [
'time' => self::formatTime($time),
'scanned' => \count($routes),
'skipped' => $skipped,
'count' => \count($this->pageList),
'memory' => self::formatMemory($memory),
]);
}
/**
* Build all pages
*
* @param int Number of pages built
*/
private function buildPages(int &$pagesCount, bool $ignoreContentNotFoundErrors = false): iterable
{
$this->stopwatch->openSection();
$this->stopwatch->start('build_pages');
$this->logger->notice('Building pages...', ['entrypoints' => $this->pageList->count()]);
while ($url = $this->pageList->getNext()) {
yield $this->notifyContext("Building $url", 1, \count($this->pageList));
$this->buildUrl($url, $ignoreContentNotFoundErrors);
$this->pageList->markAsDone($url);
}
$memory = $this->stopwatch->lap('build_pages')->getMemory();
$this->stopwatch->stopSection('build_pages');
$events = $this->stopwatch->getSectionEvents('build_pages');
$this->logger->info('Built {count} pages! ({time}, {memory})', [
'time' => self::formatTime(end($events)->getDuration()),
'memory' => self::formatMemory($memory),
'count' => \count($this->pageList),
]);
$pagesCount = \count($this->pageList);
}
/**
* Build xml sitemap file
*/
private function buildSitemap(): void
{
$this->stopwatch->openSection();
$this->stopwatch->start('build_sitemap');
$this->logger->notice('Building sitemap...');
$content = $this->templating->render('@Stenope/sitemap.xml.twig', ['sitemap' => $this->sitemap]);
$this->write($content, '/', 'sitemap.xml');
$lap = $this->stopwatch->lap('build_sitemap');
$this->stopwatch->stopSection('build_sitemap');
$this->logger->info('Built sitemap! ({time}, {memory})', [
'time' => self::formatTime($lap->getDuration()),
'memory' => self::formatMemory($lap->getMemory()),
]);
}
private function copyFiles(): void
{
foreach ($this->filesToCopy as [
'src' => $src,
'dest' => $dest,
'fail_if_missing' => $failIfMissing,
'ignore_dot_files' => $ignoreDotFiles,
'excludes' => $excludes,
]) {
$dest ??= basename($src);
if (is_dir($src)) {
$this->files->mirror($src, "$this->buildDir/$dest", (new Finder())
->in($src)
->ignoreDotFiles($ignoreDotFiles)
->notPath(array_map(fn ($exclude) => Glob::toRegex($exclude, true, false), $excludes))
->files()
);
continue;
}
if (!is_file($src)) {
if ($failIfMissing) {
throw new \RuntimeException(sprintf(
'Failed to copy "%s" because the path is neither a file or a directory.',
$src
));
}
$this->logger->warning('Failed to copy "{src}" because the path is neither a file or a directory.', [
'src' => $src,
'dest' => $dest,
]);
continue;
}
$this->files->copy($src, "$this->buildDir/$dest");
}
}
/**
* Build the given Route into a file
*/
private function buildUrl(string $url, bool $ignoreContentNotFoundErrors = false): void
{
$this->logger->debug('Attempt to build page {url}…', ['url' => $url]);
$request = ContentRequest::create($url, 'GET')->withBaseUrl($this->router->getContext()->getBaseUrl());
ob_start();
try {
$response = $this->httpKernel->handle($request, HttpKernelInterface::MAIN_REQUEST, false);
} catch (\Throwable $exception) {
if ($ignoreContentNotFoundErrors && $exception instanceof ContentNotFoundException) {
$this->logger->warning('Could not build url {url}: {exception}', [
'exception' => $exception->getMessage(),
'url' => $url,
]);
return;
}
throw new \Exception(sprintf('Could not build url %s.', $url), 0, $exception);
}
$this->httpKernel->terminate($request, $response);
if ($response instanceof BinaryFileResponse || $response instanceof StreamedResponse) {
$response->sendContent();
}
$output = ob_get_clean();
$content = $response->getContent() ?: $output;
if ($this->hasNoIndexHeader($response) && !$this->hasNoIndexTag($content)) {
$this->logger->warning('Url {url} contains a "x-robots-tag: noindex" header that will be lost by going static. Consider using the HTML tag "<meta name="robots" content="noindex" />" instead.', [
'url' => $url,
]);
}
[$path, $file] = $this->getFilePath($request, $response);
$this->write($content, $path, $file);
$periods = $this->stopwatch->lap('build_pages')->getPeriods();
$period = end($periods);
$time = $period->getDuration();
$memory = $period->getMemory();
$this->logger->debug('Page {url} built ({time}, {memory})', [
'time' => self::formatTime($time),
'memory' => self::formatMemory($memory),
'url' => $url,
]);
}
/**
* Test the presence of a "NoIndex" HTTP Header.
*/
private function hasNoIndexHeader(Response $response): bool
{
return \in_array('noindex', $response->headers->all('x-robots-tag'));
}
/**
* Test the presence of a "NoIndex" meta tag.
*/
private function hasNoIndexTag(string $content): bool
{
$crawler = new Crawler($content);
return $crawler->filter('head > meta[content="noindex"]')->count() > 0;
}
/**
* Get file path from URL
*/
private function getFilePath(Request $request, Response $response): array
{
$url = rawurldecode($request->getPathInfo());
$info = pathinfo($url);
$extension = $info['extension'] ?? null;
// If the request has html format, but the .html extension is not already part of the url
if ('html' !== $extension && $this->isHtml($request, $response)) {
// we must generate an index.html file
return [$url, 'index.html'];
}
// otherwise, dump as is:
return [$info['dirname'], $info['basename']];
}
private function isHtml(Request $request, Response $response): bool
{
if ('html' === $request->getRequestFormat(null)) {
return true;
}
$contentType = explode(';', $response->headers->get('Content-Type', 'text/html'))[0];
return \in_array('html', $this->mimeTypes->getExtensions($contentType));
}
/**
* Write a file
*
* @param string $content The file content
* @param string $path The directory to put the file in (in the current destination)
* @param string $file The file name
*/
private function write(string $content, string $path, string $file): void
{
$directory = sprintf('%s/%s', $this->buildDir, trim($path, '/'));
if (!$this->files->exists($directory)) {
$this->files->mkdir($directory);
}
$this->files->dumpFile(sprintf('%s/%s', $directory, $file), $content);
}
private static function formatTime(float $time): string
{
if ($time >= 1000) {
return number_format($time / 1000, 2) . ' s';
}
return number_format($time, 2) . ' ms';
}
private static function formatMemory(int $memory): string
{
return Helper::formatMemory($memory);
}
private function notifyContext(
?string $message = null,
?int $advance = null,
?int $maxStep = null
): array {
return [
'advance' => $advance,
'maxStep' => $maxStep,
'message' => $message,
];
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/ContentManager.php | src/ContentManager.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle;
use Stenope\Bundle\Behaviour\ContentManagerAwareInterface;
use Stenope\Bundle\Behaviour\HtmlCrawlerManagerInterface;
use Stenope\Bundle\Behaviour\ProcessorInterface;
use Stenope\Bundle\Exception\ContentNotFoundException;
use Stenope\Bundle\Exception\RuntimeException;
use Stenope\Bundle\ExpressionLanguage\ExpressionLanguage;
use Stenope\Bundle\Provider\ContentProviderInterface;
use Stenope\Bundle\Provider\ReversibleContentProviderInterface;
use Stenope\Bundle\ReverseContent\Context;
use Stenope\Bundle\Serializer\Normalizer\SkippingInstantiatedObjectDenormalizer;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage as BaseExpressionLanguage;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Serializer\Encoder\DecoderInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Stopwatch\Stopwatch;
class ContentManager implements ContentManagerInterface
{
private DecoderInterface $decoder;
private DenormalizerInterface $denormalizer;
private PropertyAccessorInterface $propertyAccessor;
private HtmlCrawlerManagerInterface $crawlers;
/** @var iterable<ContentProviderInterface>|ContentProviderInterface[] */
private iterable $providers;
/** @var iterable<ProcessorInterface>|ProcessorInterface[] */
private iterable $processors;
private ?ExpressionLanguage $expressionLanguage;
private ?Stopwatch $stopwatch;
/** @var array<string,object> */
private array $cache = [];
/** @var array<string,object> */
private array $reversedCache = [];
private bool $managerInjected = false;
private ?ContentManagerInterface $contentManager;
public function __construct(
DecoderInterface $decoder,
DenormalizerInterface $denormalizer,
HtmlCrawlerManagerInterface $crawlers,
iterable $contentProviders,
iterable $processors,
?PropertyAccessorInterface $propertyAccessor = null,
?ExpressionLanguage $expressionLanguage = null,
?Stopwatch $stopwatch = null
) {
$this->decoder = $decoder;
$this->denormalizer = $denormalizer;
$this->crawlers = $crawlers;
$this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
$this->providers = $contentProviders;
$this->processors = $processors;
$this->stopwatch = $stopwatch;
if (!$expressionLanguage && class_exists(BaseExpressionLanguage::class)) {
$expressionLanguage = new ExpressionLanguage();
}
$this->expressionLanguage = $expressionLanguage;
}
public function getContents(string $type, $sortBy = null, $filterBy = null): array
{
$contents = [];
foreach ($this->getProviders($type) as $provider) {
foreach ($provider->listContents() as $content) {
if (isset($contents[$content->getSlug()])) {
throw new RuntimeException(sprintf(
'Found multiple contents of type "%s" with the same "%s" identifier.',
$content->getType(),
$content->getSlug()
));
}
$contents[$content->getSlug()] = $this->load($content);
}
}
try {
$this->filterBy($contents, $filterBy);
} catch (\Throwable $exception) {
throw new RuntimeException(sprintf('There was a problem filtering %s.', $type), 0, $exception);
}
try {
$this->sortBy($contents, $sortBy);
} catch (\Throwable $exception) {
throw new RuntimeException(sprintf('There was a problem sorting %s.', $type), 0, $exception);
}
return $contents;
}
private function filterBy(array &$contents, $filterBy = null): void
{
if ($filter = $this->getFilterFunction($filterBy)) {
$contents = array_filter($contents, $filter);
}
}
private function sortBy(array &$contents, $sortBy = null): void
{
if ($sorter = $this->getSortFunction($sortBy)) {
set_error_handler(static function (int $severity, string $message, ?string $file, ?int $line): void {
throw new \ErrorException($message, $severity, $severity, $file, $line);
});
uasort($contents, $sorter);
restore_error_handler();
}
}
public function getContent(string $type, string $id): object
{
if ($this->stopwatch) {
$event = $this->stopwatch->start('get_content', 'stenope');
}
foreach ($this->getProviders($type) as $provider) {
if ($content = $provider->getContent($id)) {
$loaded = $this->load($content);
if (isset($event)) {
$event->stop();
}
return $loaded;
}
}
throw new ContentNotFoundException($type, $id);
}
public function reverseContent(Context $context): ?Content
{
$key = md5(serialize($context));
if (\array_key_exists($key, $this->reversedCache)) {
return $this->reversedCache[$key];
}
if ($this->stopwatch) {
$event = $this->stopwatch->start('reverse_content', 'stenope');
}
try {
foreach ($this->providers as $provider) {
if (!$provider instanceof ReversibleContentProviderInterface) {
continue;
}
if ($result = $provider->reverse($context)) {
return $this->reversedCache[$key] = $result;
}
}
} finally {
if (isset($event)) {
$event->stop();
}
}
return $this->reversedCache[$key] = null;
}
/**
* @return iterable<ContentProviderInterface>|ContentProviderInterface[]
*/
private function getProviders(string $type): iterable
{
if (is_countable($this->providers) && 0 === \count($this->providers)) {
throw new \LogicException(sprintf('No content providers were configured. Did you forget to instantiate "%s" with the "$providers" argument, or to configure providers in the "content.providers" package config?', self::class));
}
$found = false;
foreach ($this->providers as $provider) {
if ($provider->supports($type)) {
$found = true;
yield $provider;
}
}
if (!$found) {
throw new \LogicException(sprintf('No provider found for type "%s"', $type));
}
}
private function load(Content $content)
{
if ($data = $this->cache[$key = "{$content->getType()}:{$content->getSlug()}"] ?? false) {
return $data;
}
$this->initProcessors();
$data = $this->decoder->decode($content->getRawContent(), $content->getFormat());
// Apply processors to decoded data
foreach ($this->processors as $processor) {
$processor($data, $content);
}
$this->crawlers->saveAll($content, $data);
$data = $this->denormalizer->denormalize($data, $content->getType(), $content->getFormat(), [
SkippingInstantiatedObjectDenormalizer::SKIP => true,
]);
return $this->cache[$key] = $data;
}
private function getSortFunction($sortBy): ?callable
{
if (!$sortBy) {
return null;
}
if (\is_string($sortBy)) {
return $this->getSortFunction([$sortBy => true]);
}
if (\is_callable($sortBy)) {
return $sortBy;
}
if (\is_array($sortBy)) {
return function ($a, $b) use ($sortBy) {
foreach ($sortBy as $key => $value) {
$asc = (bool) $value;
$valueA = $this->propertyAccessor->getValue($a, $key);
$valueB = $this->propertyAccessor->getValue($b, $key);
if ($valueA === $valueB) {
continue;
}
return ($valueA <=> $valueB) * ($asc ? 1 : -1);
}
return 0;
};
}
throw new \LogicException(sprintf('Unknown sorter "%s"', $sortBy));
}
private function getFilterFunction($filterBy): ?callable
{
if (!$filterBy) {
return null;
}
if ($filterBy instanceof Expression || \is_string($filterBy)) {
return fn ($data) => $this->expressionLanguage->evaluate($filterBy, [
'data' => $data,
'd' => $data,
'_' => $data,
]);
}
if (\is_callable($filterBy)) {
return $filterBy;
}
if (\is_array($filterBy)) {
return function ($item) use ($filterBy) {
foreach ($filterBy as $key => $expectedValue) {
$value = $this->propertyAccessor->getValue($item, $key);
if (\is_callable($expectedValue)) {
// if the expected value is a callable, call it with the current content property value:
if ($expectedValue($value)) {
continue;
}
return false;
}
if ($value == $expectedValue) {
continue;
}
return false;
}
return true;
};
}
throw new \LogicException(sprintf('Unknown filter "%s"', $filterBy));
}
public function supports(string $type): bool
{
foreach ($this->providers as $provider) {
if ($provider->supports($type)) {
return true;
}
}
return false;
}
private function initProcessors(): void
{
// Lazy inject manager to processor on first need:
if (!$this->managerInjected) {
foreach ($this->processors as $processor) {
if ($processor instanceof ContentManagerAwareInterface) {
$processor->setContentManager($this->contentManager ?? $this);
}
}
$this->managerInjected = true;
}
}
/**
* Set the actual content manager instance to inject in processors.
* Useful whenever this content manager is decorated in order for the processor to use the decorating one.
*/
public function setContentManager(ContentManagerInterface $contentManager): void
{
if ($contentManager === $this) {
return;
}
$this->contentManager = $contentManager;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/ContentManagerInterface.php | src/ContentManagerInterface.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle;
use Stenope\Bundle\ReverseContent\Context;
use Symfony\Component\ExpressionLanguage\Expression;
interface ContentManagerInterface
{
/**
* List all content for the given type
*
* @template T of object
*
* @param class-string<T> $type Model FQCN e.g. "App/Model/Article"
* @param string|array|callable $sortBy String, array or callable
* @param string|array|callable|Expression $filterBy Array, callable or an {@link Expression} instance / string
* to filter out with an expression using the ExpressionLanguage
* component.
*
* @return array<string,T> List of decoded contents with their slug as key
*/
public function getContents(string $type, $sortBy = null, $filterBy = null): array;
/**
* Fetch a specific content
*
* @template T of object
*
* @param class-string<T> $type Model FQCN e.g. "App/Model/Article"
* @param string $id Unique identifier (slug)
*
* @return T An object of the given type.
*/
public function getContent(string $type, string $id): object;
/**
* Attempt to reverse resolve a content according to a context.
* E.g: attempt to resolve a content relative to another one through its filesystem path.
*/
public function reverseContent(Context $context): ?Content;
public function supports(string $type): bool;
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Content.php | src/Content.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle;
final class Content
{
private string $slug;
private string $type;
private string $rawContent;
private string $format;
private ?\DateTimeImmutable $lastModified;
private ?\DateTimeImmutable $createdAt;
private array $metadata;
public function __construct(
string $slug,
string $type,
string $rawContent,
string $format,
?\DateTimeImmutable $lastModified = null,
?\DateTimeImmutable $createdAt = null,
array $metadata = []
) {
$this->slug = $slug;
$this->type = $type;
$this->rawContent = $rawContent;
$this->format = $format;
$this->lastModified = $lastModified;
$this->createdAt = $createdAt;
$this->metadata = $metadata;
}
public function getSlug(): string
{
return $this->slug;
}
public function getType(): string
{
return $this->type;
}
public function getRawContent(): string
{
return $this->rawContent;
}
public function getLastModified(): ?\DateTimeImmutable
{
return $this->lastModified;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
public function getFormat(): string
{
return $this->format;
}
public function getMetadata(): array
{
return $this->metadata;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Routing/UrlGenerator.php | src/Routing/UrlGenerator.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Routing;
use Stenope\Bundle\Builder\PageList;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RequestContext;
/**
* A wrapper for UrlGenerator that register every generated url in the PageList.
*
* @final
*/
class UrlGenerator implements UrlGeneratorInterface
{
private UrlGeneratorInterface $urlGenerator;
private PageList $pageList;
private RouteInfoCollection $routesInfo;
public function __construct(RouteInfoCollection $routesInfo, UrlGeneratorInterface $urlGenerator, PageList $pageList)
{
$this->urlGenerator = $urlGenerator;
$this->pageList = $pageList;
$this->routesInfo = $routesInfo;
}
public function generate($name, $parameters = [], $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string
{
if (($routeInfo = $this->routesInfo[$name] ?? null) && !$routeInfo->isIgnored()) {
$this->pageList->add(
$this->urlGenerator->generate($name, $parameters, UrlGeneratorInterface::ABSOLUTE_URL)
);
}
return $this->urlGenerator->generate($name, $parameters, $referenceType);
}
public function setContext(RequestContext $context): void
{
$this->urlGenerator->setContext($context);
}
public function getContext(): RequestContext
{
return $this->urlGenerator->getContext();
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Routing/ContentUrlResolver.php | src/Routing/ContentUrlResolver.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Routing;
use Stenope\Bundle\Content;
use Symfony\Component\Routing\RouterInterface;
class ContentUrlResolver
{
private RouterInterface $router;
/** @var ResolveContentRoute[] */
private array $routes;
/**
* @param array<string,ResolveContentRoute> $routes
*/
public function __construct(RouterInterface $router, array $routes)
{
$this->router = $router;
$this->routes = $routes;
}
public function resolveUrl(Content $content): string
{
$resolved = $this->resolveRoute($content);
return $this->router->generate($resolved->getRoute(), [
$resolved->getSlug() => $content->getSlug(),
]);
}
private function resolveRoute(Content $content): ResolveContentRoute
{
if ($resolved = $this->routes[$content->getType()] ?? null) {
return $resolved;
}
throw new \LogicException(sprintf(
'No route was defined to resolve type "%s". Did you configure "stenope.resolve_links" for this type?',
$content->getType(),
));
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Routing/ResolveContentRoute.php | src/Routing/ResolveContentRoute.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Routing;
class ResolveContentRoute
{
/** Route name */
private string $route;
/** Name of the slug placeholder */
private string $slug;
private array $defaults;
public function __construct(string $route, string $slug, array $defaults = [])
{
$this->route = $route;
$this->slug = $slug;
$this->defaults = $defaults;
}
public function getRoute(): string
{
return $this->route;
}
public function getSlug(): string
{
return $this->slug;
}
public function getDefaults(): array
{
return $this->defaults;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Routing/RouteInfo.php | src/Routing/RouteInfo.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Routing;
use Stenope\Bundle\Builder;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* Extracts content specific info from route definitions.
*/
class RouteInfo
{
private string $name;
private Route $route;
public function __construct(string $name, Route $route)
{
$this->name = $name;
$this->route = $route;
}
/**
* @return array<string,RouteInfo>
*/
public static function createFromRouteCollection(RouteCollection $collection): array
{
$routes = [];
foreach ($collection as $name => $route) {
$routes[$name] = new self($name, $route);
}
return $routes;
}
public function getName(): string
{
return $this->name;
}
/**
* Whether it should be be ignored by the static site builder or not.
* If true, the route will be ignored by the {@link Builder},
* which won't generate a static file for matching urls.
*/
public function isIgnored(): bool
{
return $this->route->getOption('stenope')['ignore'] ?? false;
}
/**
* Whether the route accepts GET requests or not.
*/
public function isGettable(): bool
{
$methods = $this->route->getMethods();
return empty($methods) || \in_array('GET', $methods);
}
/**
* Whether to expose or not the route in the generated sitemap.
*/
public function isMapped(): bool
{
return $this->route->getOption('stenope')['sitemap'] ?? !$this->isIgnored();
}
public function getRoute(): Route
{
return $this->route;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Routing/RouteInfoCollection.php | src/Routing/RouteInfoCollection.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Routing;
use Symfony\Component\Routing\RouterInterface;
/**
* @phpstan-implements \IteratorAggregate<string,RouteInfo>
*
* @final
*/
class RouteInfoCollection implements \IteratorAggregate, \ArrayAccess, \Countable
{
private RouterInterface $router;
/** @var array<string,RouteInfo>|null */
private ?array $routeInfos = null;
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
/**
* @return array<string,RouteInfo>
*/
private function getInfos(): array
{
if (!$this->routeInfos) {
$this->routeInfos = RouteInfo::createFromRouteCollection($this->router->getRouteCollection());
}
return $this->routeInfos;
}
public function getIterator(): \Traversable
{
return new \ArrayIterator($this->getInfos());
}
public function offsetExists($offset): bool
{
return isset($this->getInfos()[$offset]);
}
public function offsetGet($offset): ?RouteInfo
{
return $this->getInfos()[$offset] ?? null;
}
public function offsetSet($offset, $value): void
{
throw new \BadMethodCallException(sprintf('Unexpected call to "%s()"', __METHOD__));
}
public function offsetUnset($offset): void
{
throw new \BadMethodCallException(sprintf('Unexpected call to "%s()"', __METHOD__));
}
public function count(): int
{
return \count($this->getInfos());
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Processor/AssetsProcessor.php | src/Processor/AssetsProcessor.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Processor;
use Stenope\Bundle\Behaviour\HtmlCrawlerManagerInterface;
use Stenope\Bundle\Behaviour\ProcessorInterface;
use Stenope\Bundle\Content;
use Stenope\Bundle\Service\AssetUtils;
/**
* Attempt to resolve local assets URLs using the Asset component for images and links.
*/
class AssetsProcessor implements ProcessorInterface
{
private AssetUtils $assetUtils;
private HtmlCrawlerManagerInterface $crawlers;
private string $property;
public function __construct(
AssetUtils $assetUtils,
HtmlCrawlerManagerInterface $crawlers,
string $property = 'content'
) {
$this->assetUtils = $assetUtils;
$this->crawlers = $crawlers;
$this->property = $property;
}
public function __invoke(array &$data, Content $content): void
{
if (!isset($data[$this->property])) {
return;
}
$crawler = $this->crawlers->get($content, $data, $this->property);
if (!$crawler) {
return;
}
foreach ($crawler->filter('img') as $element) {
$element->setAttribute('src', $this->assetUtils->getUrl($element->getAttribute('src')));
}
foreach ($crawler->filter('a') as $element) {
$element->setAttribute('href', $this->assetUtils->getUrl($element->getAttribute('href')));
}
$this->crawlers->save($content, $data, $this->property);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Processor/ExtractTitleFromHtmlContentProcessor.php | src/Processor/ExtractTitleFromHtmlContentProcessor.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Processor;
use Stenope\Bundle\Behaviour\HtmlCrawlerManagerInterface;
use Stenope\Bundle\Behaviour\ProcessorInterface;
use Stenope\Bundle\Content;
/**
* Extract a content title from a HTML property by using the first available h1 tag.
*/
class ExtractTitleFromHtmlContentProcessor implements ProcessorInterface
{
private HtmlCrawlerManagerInterface $crawlers;
private string $contentProperty;
private string $titleProperty;
public function __construct(
HtmlCrawlerManagerInterface $crawlers,
string $contentProperty = 'content',
string $titleProperty = 'title'
) {
$this->crawlers = $crawlers;
$this->contentProperty = $contentProperty;
$this->titleProperty = $titleProperty;
}
public function __invoke(array &$data, Content $content): void
{
// Ignore if no content available, or if the title property is already set:
if (!\is_string($data[$this->contentProperty] ?? null) || isset($data[$this->titleProperty])) {
return;
}
$crawler = $this->crawlers->get($content, $data, $this->contentProperty);
if (!$crawler) {
return;
}
// Use the first h1 text as title:
if (($title = $crawler->filter('h1')->first())->count() > 0) {
$data[$this->titleProperty] = $title->text();
}
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Processor/CodeHighlightProcessor.php | src/Processor/CodeHighlightProcessor.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Processor;
use Stenope\Bundle\Behaviour\HighlighterInterface;
use Stenope\Bundle\Behaviour\HtmlCrawlerManagerInterface;
use Stenope\Bundle\Behaviour\ProcessorInterface;
use Stenope\Bundle\Content;
use Stenope\Bundle\Service\HtmlUtils;
/**
* Apply syntax coloration to code blocs
*/
class CodeHighlightProcessor implements ProcessorInterface
{
private HighlighterInterface $highlighter;
private HtmlCrawlerManagerInterface $crawlers;
private string $property;
public function __construct(
HighlighterInterface $highlighter,
HtmlCrawlerManagerInterface $crawlers,
string $property = 'content'
) {
$this->highlighter = $highlighter;
$this->crawlers = $crawlers;
$this->property = $property;
}
public function __invoke(array &$data, Content $content): void
{
if (!isset($data[$this->property])) {
return;
}
$crawler = $this->crawlers->get($content, $data, $this->property);
if (!$crawler) {
return;
}
foreach ($crawler->filter('code') as $element) {
$this->highlight($element);
}
$this->crawlers->save($content, $data, $this->property);
}
private function highlight(\DOMElement $element): void
{
if (preg_match('#(language|lang)-([^ ]+)#i', $element->getAttribute('class'), $matches)) {
$language = $matches[2];
HtmlUtils::setContent($element, $this->highlighter->highlight(trim($element->nodeValue), $language));
HtmlUtils::addClass($element->parentNode, 'language-' . $language);
}
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Processor/SlugProcessor.php | src/Processor/SlugProcessor.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Processor;
use Stenope\Bundle\Behaviour\ProcessorInterface;
use Stenope\Bundle\Content;
/**
* Set "slug" property from file name if not specified
*/
class SlugProcessor implements ProcessorInterface
{
private string $property;
public function __construct(string $property = 'slug')
{
$this->property = $property;
}
public function __invoke(array &$data, Content $content): void
{
if (isset($data[$this->property])) {
// Slug already set.
return;
}
$data[$this->property] = $content->getSlug();
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Processor/HtmlAnchorProcessor.php | src/Processor/HtmlAnchorProcessor.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Processor;
use Stenope\Bundle\Behaviour\HtmlCrawlerManagerInterface;
use Stenope\Bundle\Behaviour\ProcessorInterface;
use Stenope\Bundle\Content;
/**
* Add anchor to elements with ids
*/
class HtmlAnchorProcessor implements ProcessorInterface
{
private HtmlCrawlerManagerInterface $crawlers;
private string $property;
private string $selector;
public function __construct(
HtmlCrawlerManagerInterface $crawlers,
string $property = 'content',
string $selector = 'h1, h2, h3, h4, h5'
) {
$this->crawlers = $crawlers;
$this->property = $property;
$this->selector = $selector;
}
public function __invoke(array &$data, Content $content): void
{
if (!isset($data[$this->property])) {
return;
}
$crawler = $this->crawlers->get($content, $data, $this->property);
if (!$crawler) {
return;
}
foreach ($crawler->filter($this->selector) as $element) {
$this->addAnchor($element);
}
$this->crawlers->save($content, $data, $this->property);
}
/**
* Set title id and add anchor
*/
private function addAnchor(\DOMElement $element): void
{
$child = $element->ownerDocument->createDocumentFragment();
if (!$id = $element->getAttribute('id')) {
return;
}
$child->appendXML(sprintf('<a href="#%s" class="anchor"></a>', $id));
$element->appendChild($child);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Processor/HtmlExternalLinksProcessor.php | src/Processor/HtmlExternalLinksProcessor.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Processor;
use Stenope\Bundle\Behaviour\HtmlCrawlerManagerInterface;
use Stenope\Bundle\Behaviour\ProcessorInterface;
use Stenope\Bundle\Content;
/**
* Add target="_blank" to external links
*/
class HtmlExternalLinksProcessor implements ProcessorInterface
{
private HtmlCrawlerManagerInterface $crawlers;
private string $property;
public function __construct(HtmlCrawlerManagerInterface $crawlers, string $property = 'content')
{
$this->crawlers = $crawlers;
$this->property = $property;
}
public function __invoke(array &$data, Content $content): void
{
if (!isset($data[$this->property])) {
return;
}
$crawler = $this->crawlers->get($content, $data, $this->property);
if (!$crawler) {
return;
}
foreach ($crawler->filter('a') as $element) {
$this->processLink($element);
}
$this->crawlers->save($content, $data, $this->property);
}
private function processLink(\DOMElement $element): void
{
if ($element->hasAttribute('target')) {
return;
}
if (preg_match('#^(https?:)?//#i', $element->getAttribute('href'))) {
$element->setAttribute('target', '_blank');
}
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Processor/TableOfContentProcessor.php | src/Processor/TableOfContentProcessor.php | <?php
declare(strict_types=1);
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Processor;
use Stenope\Bundle\Behaviour\HtmlCrawlerManagerInterface;
use Stenope\Bundle\Behaviour\ProcessorInterface;
use Stenope\Bundle\Content;
use Stenope\Bundle\TableOfContent\CrawlerTableOfContentGenerator;
/**
* Build a table of content from the content titles if it exposes a tableOfContent value as true.
* If the content exposes a tableOfContent value as int, it'll be used as the max depth for this specific content.
*/
class TableOfContentProcessor implements ProcessorInterface
{
private CrawlerTableOfContentGenerator $generator;
private HtmlCrawlerManagerInterface $crawlers;
private string $tableOfContentProperty;
private string $contentProperty;
private int $minDepth;
private int $maxDepth;
public function __construct(
CrawlerTableOfContentGenerator $generator,
HtmlCrawlerManagerInterface $crawlers,
string $tableOfContentProperty = 'tableOfContent',
string $contentProperty = 'content',
int $minDepth = 1,
int $maxDepth = 6
) {
$this->generator = $generator;
$this->crawlers = $crawlers;
$this->tableOfContentProperty = $tableOfContentProperty;
$this->contentProperty = $contentProperty;
$this->minDepth = $minDepth;
$this->maxDepth = $maxDepth;
}
public function __invoke(array &$data, Content $content): void
{
if (!isset($data[$this->contentProperty], $data[$this->tableOfContentProperty])) {
// Skip on unavailable content property or no TOC property configured
return;
}
$tocValue = $data[$this->tableOfContentProperty];
if (!\is_int($tocValue) && true !== $tocValue) {
// if it's neither an int or true,
// disable the TOC generation for this specific content and unset the value,
// so denormalization can rely on a default value.
unset($data[$this->tableOfContentProperty]);
return;
}
$crawler = $this->crawlers->get($content, $data, $this->contentProperty);
if (\is_null($crawler)) {
return;
}
$data[$this->tableOfContentProperty] = $this->generator->getTableOfContent(
$crawler,
$this->minDepth,
// Use the int value as max depth if specified, or fallback to default max depth otherwise:
\is_int($tocValue) ? $tocValue : $this->maxDepth
);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Processor/LastModifiedProcessor.php | src/Processor/LastModifiedProcessor.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Processor;
use Stenope\Bundle\Behaviour\ProcessorInterface;
use Stenope\Bundle\Content;
use Stenope\Bundle\Provider\Factory\LocalFilesystemProviderFactory;
use Stenope\Bundle\Service\Git\LastModifiedFetcher;
/**
* Set a "LastModified" property based on the last modified date set by the provider.
* E.g, for the {@see LocalFilesystemProvider}, the file mtime on the filesystem.
*
* If available, for local files, it'll use Git to get the last commit date for this file.
*/
class LastModifiedProcessor implements ProcessorInterface
{
private string $property;
private ?LastModifiedFetcher $gitLastModified;
public function __construct(string $property = 'lastModified', ?LastModifiedFetcher $gitLastModified = null)
{
$this->property = $property;
$this->gitLastModified = $gitLastModified;
}
public function __invoke(array &$data, Content $content): void
{
if (\array_key_exists($this->property, $data)) {
// Last modified already set (even if explicitly set as null).
return;
}
$data[$this->property] = $content->getLastModified();
if (LocalFilesystemProviderFactory::TYPE !== ($content->getMetadata()['provider'] ?? null)) {
// Won't attempt with a non local filesystem content.
return;
}
if (null === $this->gitLastModified) {
return;
}
$filePath = $content->getMetadata()['path'];
if ($lastModified = ($this->gitLastModified)($filePath)) {
$data[$this->property] = $lastModified;
}
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Processor/ResolveContentLinksProcessor.php | src/Processor/ResolveContentLinksProcessor.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Processor;
use Stenope\Bundle\Behaviour\ContentManagerAwareInterface;
use Stenope\Bundle\Behaviour\ContentManagerAwareTrait;
use Stenope\Bundle\Behaviour\HtmlCrawlerManagerInterface;
use Stenope\Bundle\Behaviour\ProcessorInterface;
use Stenope\Bundle\Content;
use Stenope\Bundle\ReverseContent\RelativeLinkContext;
use Stenope\Bundle\Routing\ContentUrlResolver;
/**
* Resolve relative links between contents using the route declared in config.
*/
class ResolveContentLinksProcessor implements ProcessorInterface, ContentManagerAwareInterface
{
use ContentManagerAwareTrait;
private ContentUrlResolver $resolver;
private HtmlCrawlerManagerInterface $crawlers;
private string $property;
public function __construct(
ContentUrlResolver $resolver,
HtmlCrawlerManagerInterface $crawlers,
string $property = 'content'
) {
$this->resolver = $resolver;
$this->crawlers = $crawlers;
$this->property = $property;
}
public function __invoke(array &$data, Content $content): void
{
if (!isset($data[$this->property])) {
return;
}
$crawler = $this->crawlers->get($content, $data, $this->property);
if (!$crawler) {
return;
}
foreach ($crawler->filter('a') as $link) {
$this->processLink($link, $content);
}
$this->crawlers->save($content, $data, $this->property);
}
private function processLink(\DOMElement $link, Content $currentContent): void
{
if (!$href = $link->getAttribute('href')) {
return;
}
// External link / link with a scheme
if (preg_match('@^(\w+:)?//@', $href)) {
return;
}
// anchors
if (str_starts_with($href, '#')) {
return;
}
// Link to website root
if (str_starts_with($href, '/')) {
return;
}
// Internal content link
$path = parse_url($href, PHP_URL_PATH);
// Extract fragment (hash / anchor, if any)
$fragment = parse_url($href, PHP_URL_FRAGMENT);
$context = new RelativeLinkContext($currentContent->getMetadata(), $path);
if ($content = $this->contentManager->reverseContent($context)) {
$url = $this->resolver->resolveUrl($content);
// redirect to proper content, with specified anchor:
$link->setAttribute('href', $fragment ? "$url#$fragment" : $url);
}
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Processor/HtmlIdProcessor.php | src/Processor/HtmlIdProcessor.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Processor;
use Stenope\Bundle\Behaviour\HtmlCrawlerManagerInterface;
use Stenope\Bundle\Behaviour\ProcessorInterface;
use Stenope\Bundle\Content;
use Symfony\Component\String\Slugger\AsciiSlugger;
use Symfony\Component\String\Slugger\SluggerInterface;
/**
* Add ids to HTML elements in the content
*/
class HtmlIdProcessor implements ProcessorInterface
{
private HtmlCrawlerManagerInterface $crawlers;
private string $property;
private SluggerInterface $slugger;
public function __construct(
HtmlCrawlerManagerInterface $crawlers,
string $property = 'content',
?SluggerInterface $slugger = null
) {
$this->crawlers = $crawlers;
$this->property = $property;
$this->slugger = $slugger ?? new AsciiSlugger();
}
public function __invoke(array &$data, Content $content): void
{
if (!isset($data[$this->property])) {
return;
}
$crawler = $this->crawlers->get($content, $data, $this->property);
if (!$crawler) {
return;
}
foreach ($crawler->filter('h1, h2, h3, h4, h5, h6') as $element) {
$this->setIdFromContent($element);
}
foreach ($crawler->filter('code, quote') as $element) {
$this->setIdFromHashedContent($element);
}
foreach ($crawler->filter('img') as $element) {
$this->setIdForImage($element);
}
$this->crawlers->save($content, $data, $this->property);
}
private function setIdFromContent(\DOMElement $element): void
{
if (!$element->getAttribute('id')) {
$element->setAttribute('id', $this->slugify($element->textContent));
}
}
private function setIdFromHashedContent(\DOMElement $element): void
{
if (!$element->getAttribute('id')) {
$element->setAttribute('id', $this->hash($element->textContent));
}
}
private function setIdForImage(\DOMElement $element): void
{
if (!$element->getAttribute('id')) {
$name = $element->getAttribute('alt') ?: basename($element->getAttribute('src'));
$element->setAttribute('id', $this->slugify($name));
}
}
/**
* Get an url valid ID from the given value
*/
private function slugify(string $value, int $maxLength = 32): string
{
return $this->slugger->slug($value)->truncate($maxLength, '', false)->lower();
}
/**
* Get an url valid ID from hashed value
*/
private function hash(string $value, string $algo = 'md5'): string
{
return hash($algo, $value);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Builder/Sitemap.php | src/Builder/Sitemap.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Builder;
/**
* @phpstan-implements \Iterator<string,string>
*
* @phpstan-type Url = array{
* location: string,
* lastModified?: \DateTime,
* priority?: int,
* frequency?: string,
* }
*
* @final
*/
class Sitemap implements \Iterator, \Countable
{
/**
* Mapped URLs
*
* @var array<string, Url>
*/
private array $urls = [];
private int $position = 0;
/**
* Add location
*
* @param string $location The URL
* @param \DateTime|null $lastModified Date of last modification
* @param int|null $priority Location priority
*/
public function add(
string $location,
?\DateTime $lastModified = null,
?int $priority = null,
?string $frequency = null,
): void {
$url = ['location' => $location];
if ($priority === null && empty($this->urls)) {
$priority = 0;
}
if ($lastModified) {
$url['lastModified'] = $lastModified;
}
if ($priority !== null) {
$url['priority'] = $priority;
}
if ($frequency) {
$url['frequency'] = $frequency;
}
$this->urls[$location] = $url;
}
public function rewind(): void
{
$this->position = 0;
}
/**
* @return array<string, Url>
*/
#[\ReturnTypeWillChange]
public function current(): array
{
return $this->urls[array_keys($this->urls)[$this->position]];
}
#[\ReturnTypeWillChange]
public function key(): string
{
return array_keys($this->urls)[$this->position];
}
public function next(): void
{
++$this->position;
}
public function valid(): bool
{
return isset(array_keys($this->urls)[$this->position]);
}
public function count(): int
{
return \count($this->urls);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Builder/PageList.php | src/Builder/PageList.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Builder;
/**
* Page List
*/
class PageList implements \Countable
{
/** @var array<string,bool> */
private array $urls = [];
public function add(string $url): void
{
if (!isset($this->urls[$url])) {
$this->urls[$url] = true;
}
}
public function markAsDone(string $url): void
{
if (isset($this->urls[$url])) {
$this->urls[$url] = false;
}
}
public function getNext(): string
{
return current($this->getQueue());
}
public function count(): int
{
return \count($this->urls);
}
private function getQueue(): array
{
return array_keys(array_filter($this->urls));
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Highlighter/Prism.php | src/Highlighter/Prism.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Highlighter;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Stenope\Bundle\Behaviour\HighlighterInterface;
use Symfony\Component\Process\InputStream;
use Symfony\Component\Process\Process;
use Symfony\Component\Stopwatch\Stopwatch;
/**
* Prism code highlight
*/
class Prism implements HighlighterInterface
{
private const IDLE_TIMEOUT = 60;
private string $executable;
private ?Process $server = null;
private ?InputStream $input = null;
private ?Stopwatch $stopwatch;
private LoggerInterface $logger;
public function __construct(?string $executable = null, ?Stopwatch $stopwatch = null, ?LoggerInterface $logger = null)
{
$this->executable = $executable ?? __DIR__ . '/../../dist/bin/prism.js';
$this->stopwatch = $stopwatch;
$this->logger = $logger ?? new NullLogger();
}
public function start(): void
{
if (!$this->server) {
$this->input = new InputStream();
$this->server = new Process(['node', $this->executable], null, null, $this->input, null);
}
if (!$this->server->isRunning()) {
$this->server->start();
}
$this->server->setIdleTimeout(self::IDLE_TIMEOUT);
}
public function stop(): void
{
if (!$this->server || !$this->server->isRunning()) {
return;
}
$this->server->stop();
$this->server = null;
$this->input->close();
}
/**
* Highlight a portion of code with pygmentize
*/
public function highlight(string $value, string $language): string
{
if ($this->stopwatch) {
$event = $this->stopwatch->start('highlight', 'stenope');
}
$this->start();
$this->input->write(
json_encode(['language' => $language, 'value' => $value]) . PHP_EOL
);
$errors = [];
$this->server->waitUntil(function ($type, $output) use (&$errors) {
$lines = array_filter(explode(PHP_EOL, $output));
if ($type === Process::ERR) {
foreach ($lines as $line) {
if ($line === 'DONE') {
return true;
}
$errors[] = $line;
}
}
return false;
});
// Code highlight was processed.
// Let's remove the idle timeout for the running server until next call:
$this->server->setIdleTimeout(null);
if (isset($event)) {
$event->stop();
}
if (\count($errors) > 0) {
foreach ($errors as $error) {
$this->logger->error('Highlight error: {message}', ['message' => $error]);
}
return $value;
}
return $this->server->getIncrementalOutput();
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Highlighter/Pygments.php | src/Highlighter/Pygments.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Highlighter;
use Stenope\Bundle\Behaviour\HighlighterInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\Process;
/**
* Pygments code highlight
*/
class Pygments implements HighlighterInterface
{
/**
* File system
*
* @var Filesystem
*/
private $files;
/**
* Temporary directory path
*
* @var string
*/
private $temporaryPath;
public function __construct(?string $temporaryPath = null)
{
$this->temporaryPath = $temporaryPath ?: sys_get_temp_dir();
$this->files = new Filesystem();
}
/**
* Is pygmentize available?
*/
public static function isAvailable(): bool
{
$process = new Process('pygmentize -V');
$process->run();
return $process->isSuccessful();
}
/**
* Highlight a portion of code with pygmentize
*/
public function highlight(string $value, string $language): string
{
$path = tempnam($this->temporaryPath, 'pyg');
if ($language === 'php' && substr($value, 0, 5) !== '<?php') {
$value = '<?php ' . PHP_EOL . $value;
}
$this->files->dumpFile($path, $value);
$value = $this->execute($language, $path);
unlink($path);
if (preg_match('#^<div class="highlight"><pre>#', $value) && preg_match('#</pre></div>$#', $value)) {
return substr($value, 28, \strlen($value) - 40);
}
return $value;
}
/**
* Run 'pygmentize' command on the given file
*/
private function execute(string $language, string $path): string
{
$process = Process::fromShellCommandline(sprintf('pygmentize -f html -l %s %s', $language, $path));
$process->run();
if (!$process->isSuccessful()) {
throw new \RuntimeException($process->getErrorOutput());
}
return trim($process->getOutput());
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/ReverseContent/Context.php | src/ReverseContent/Context.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\ReverseContent;
use Stenope\Bundle\ContentManagerInterface;
/**
* Context from which to resolve a content.
*
* @see ContentManagerInterface::reverseContent()
*/
abstract class Context
{
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/ReverseContent/RelativeLinkContext.php | src/ReverseContent/RelativeLinkContext.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\ReverseContent;
/**
* Context to resolve a link to a content relative to the current one.
*/
class RelativeLinkContext extends Context
{
private array $currentMetadata;
private string $targetPath;
public function __construct(array $currentMetadata, string $targetPath)
{
$this->currentMetadata = $currentMetadata;
$this->targetPath = $targetPath;
}
public function getCurrentMetadata(): array
{
return $this->currentMetadata;
}
public function getTargetPath(): string
{
return $this->targetPath;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Twig/ContentExtension.php | src/Twig/ContentExtension.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* @final
*/
class ContentExtension extends AbstractExtension
{
public function getFunctions(): array
{
return [
new TwigFunction('content_get', [ContentRuntime::class, 'getContent']),
new TwigFunction('content_list', [ContentRuntime::class, 'listContents']),
new TwigFunction('content_expr', '\Stenope\Bundle\ExpressionLanguage\expr'),
new TwigFunction('content_expr_or', '\Stenope\Bundle\ExpressionLanguage\exprOr'),
];
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Twig/ContentRuntime.php | src/Twig/ContentRuntime.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Twig;
use Stenope\Bundle\ContentManagerInterface;
use Twig\Extension\RuntimeExtensionInterface;
class ContentRuntime implements RuntimeExtensionInterface
{
private ContentManagerInterface $contentManager;
public function __construct(ContentManagerInterface $contentManager)
{
$this->contentManager = $contentManager;
}
public function getContent(string $type, string $slug): object
{
return $this->contentManager->getContent($type, $slug);
}
/**
* @return object[]
*/
public function listContents(string $type, $sortBy = null, $filterBy = null): array
{
return $this->contentManager->getContents($type, $sortBy, $filterBy);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/ExpressionLanguage/ExpressionLanguageProvider.php | src/ExpressionLanguage/ExpressionLanguageProvider.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\ExpressionLanguage;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
/**
* @internal
*/
class ExpressionLanguageProvider implements ExpressionFunctionProviderInterface
{
/** @var iterable<ExpressionFunctionProviderInterface> */
private iterable $providers;
public function __construct(iterable $providers = [])
{
$this->providers = $providers;
}
public function getFunctions(): array
{
// prepend the default functions to let users override these easily:
$functions = [
new ExpressionFunction('date', function ($arg) {
return sprintf('(new \DateTimeImmutable(%s))->setTime(0, 0)', $arg);
}, function (array $variables, $value) {
return (new \DateTimeImmutable($value))->setTime(0, 0);
}),
new ExpressionFunction('datetime', function ($arg) {
return sprintf('new \DateTimeImmutable(%s)', $arg);
}, function (array $variables, $value) {
return new \DateTimeImmutable($value);
}),
ExpressionFunction::fromPhp('strtoupper', 'upper'),
ExpressionFunction::fromPhp('strtolower', 'lower'),
ExpressionFunction::fromPhp('str_contains', 'contains'),
ExpressionFunction::fromPhp('str_starts_with', 'starts_with'),
ExpressionFunction::fromPhp('str_ends_with', 'ends_with'),
ExpressionFunction::fromPhp('array_keys', 'keys'),
];
foreach ($this->providers as $provider) {
$functions = array_merge($functions, $provider->getFunctions());
}
return $functions;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/ExpressionLanguage/Expression.php | src/ExpressionLanguage/Expression.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\ExpressionLanguage;
use Symfony\Component\ExpressionLanguage\Expression as BaseExpression;
if (!class_exists(\Symfony\Component\ExpressionLanguage\ExpressionLanguage::class)) {
throw new \LogicException(sprintf('You must install the Symfony ExpressionLanguage component ("symfony/expression-language") in order to use the "%s" class.', Expression::class));
}
final class Expression extends BaseExpression
{
public static function combineAnd(string ...$exprs): self
{
if (\count($exprs) === 1) {
return new Expression(...$exprs);
}
return new self(implode(' and ', array_map(static fn ($e) => sprintf('(%s)', $e), $exprs)));
}
public static function combineOr(string ...$exprs): self
{
if (\count($exprs) === 1) {
return new Expression(...$exprs);
}
return new self(implode(' or ', array_map(static fn ($e) => sprintf('(%s)', $e), $exprs)));
}
public function getExpression(): string
{
return $this->expression;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/ExpressionLanguage/ExpressionLanguage.php | src/ExpressionLanguage/ExpressionLanguage.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\ExpressionLanguage;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage as BaseExpressionLanguage;
class ExpressionLanguage extends BaseExpressionLanguage
{
/**
* @param iterable<ExpressionFunctionProviderInterface> $providers
*/
public function __construct(iterable $providers = [], ?CacheItemPoolInterface $cache = null)
{
parent::__construct($cache, [new ExpressionLanguageProvider($providers)]);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/ExpressionLanguage/exprs.php | src/ExpressionLanguage/exprs.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\ExpressionLanguage;
function expr(string ...$exprs): Expression
{
return Expression::combineAnd(...$exprs);
}
function exprOr(string ...$exprs): Expression
{
return Expression::combineOr(...$exprs);
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Serializer/Normalizer/SkippingInstantiatedObjectDenormalizer.php | src/Serializer/Normalizer/SkippingInstantiatedObjectDenormalizer.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Serializer\Normalizer;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
/**
* Avoiding double-denormalization for already instantiated objects inside $data.
*
* @final
*/
class SkippingInstantiatedObjectDenormalizer implements DenormalizerInterface
{
public const SKIP = 'skip_instantiated_object';
public function denormalize($data, string $type, ?string $format = null, array $context = []): object
{
return $data;
}
public function supportsDenormalization($data, string $type, ?string $format = null, array $context = []): bool
{
return ($context[self::SKIP] ?? false) && \is_object($data);
}
public function getSupportedTypes(?string $format): array
{
return [
'object' => true,
];
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/DependencyInjection/Configuration.php | src/DependencyInjection/Configuration.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\DependencyInjection;
use Stenope\Bundle\Provider\Factory\LocalFilesystemProviderFactory;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* @final
*/
class Configuration implements ConfigurationInterface
{
private const NATIVE_PROVIDERS_TYPES = [
LocalFilesystemProviderFactory::TYPE,
];
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('stenope');
$rootNode = method_exists(TreeBuilder::class, 'getRootNode') ? $treeBuilder->getRootNode() : $treeBuilder->root('stenope');
$rootNode->children()
->scalarNode('build_dir')
->info('The directory where to build the static version of the app')
->cannotBeEmpty()
->defaultValue('%kernel.project_dir%/build')
->end()
->booleanNode('shared_html_crawlers')
->info('Activate the sharing of HTML crawlers for better performances.')
->defaultFalse()
->end()
->arrayNode('copy')
->defaultValue([
[
'src' => '%kernel.project_dir%/public',
'dest' => '.',
'fail_if_missing' => true,
'ignore_dot_files' => true,
'excludes' => ['*.php'],
],
])
->example([
'%kernel.project_dir%/public/build',
'%kernel.project_dir%/public/robots.txt',
[
'src' => '%kernel.project_dir%/public/some-file-or-dir',
'dest' => 'to-another-dest-name',
'excludes' => ['*.php', '*.map'],
'fail_if_missing' => 'false',
'ignore_dot_files' => 'false',
],
])
->arrayPrototype()
->addDefaultsIfNotSet()
->beforeNormalization()
->ifString()
->then(static fn (string $v) => ['src' => $v, 'dest' => basename($v)])
->end()
->validate()
->ifTrue(static fn (array $v) => !isset($v['dest']))
->then(static function (array $v) {
$v['dest'] = basename($v['src']);
return $v;
})
->end()
->children()
->scalarNode('src')
->info('Full source path to the file/dir to copy')
->cannotBeEmpty()
->end()
->scalarNode('dest')
->defaultNull()
->info('Destination path relative to the configured build_dir. If null, defaults to the same name as source.')
->end()
->arrayNode('excludes')
->fixXmlConfig('exclude')
->defaultValue([])
->info('List of files patterns to exclude')
->beforeNormalization()->ifString()->castToArray()->end()
->scalarPrototype()->end()
->end()
->scalarNode('fail_if_missing')
->defaultTrue()
->info('Make the build fail if the source file is missing')
->end()
->scalarNode('ignore_dot_files')
->defaultTrue()
->info('Whether to ignore or not dotfiles')
->end()
->end()
->end()
->end()
->end();
$this->addProvidersSection($rootNode);
$this->addResolveLinksSection($rootNode);
$this->addProcessorsSection($rootNode);
return $treeBuilder;
}
private function addResolveLinksSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
->fixXmlConfig('resolve_link')
->children()
->arrayNode('resolve_links')
->info('Indicates of to resolve a content type when a link to it is encountered inside anotehr content')
->example([
'App\Content\Model\Recipe' => [
'route' => 'show_recipe',
'slug' => 'recipe',
],
])
->useAttributeAsKey('class')
->arrayPrototype()
->children()
->scalarNode('route')
->example('show_recipe')
->info('The name of the route to generate the URL')
->isRequired()
->end()
->scalarNode('slug')
->example('recipe')
->info('The name of the route argument in which will be injected the content\'s slug')
->isRequired()
->end()
->end()
->end()
->end()
->end()
;
}
private function addProvidersSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
->fixXmlConfig('provider')
->children()
->arrayNode('providers')
->example([
'App\Content\Model\Recipe' => '%kernel.project_dir%/content/recipes',
'App\Content\Model\Another' => [
'#type' => 'files # (default)',
'path' => '%kernel.project_dir%/content/recipes',
'patterns' => '*.md',
],
'App\Content\Model\MyModelWithCustomProviderFactory' => [
'type' => 'custom_type',
'your-custom-key' => 'your-value',
],
])
->useAttributeAsKey('class')
->arrayPrototype()
->beforeNormalization()
->ifString()
->then(static fn ($path) => ['config' => ['path' => $path]])
->end()
->beforeNormalization()
->ifTrue(static fn ($p) => !isset($p['config']))
->then(\Closure::fromCallable([$this, 'normalizeShortcutConfig']))
->end()
->beforeNormalization()
->ifTrue(static fn ($p) => isset($p['type']) && !\in_array($p['type'], self::NATIVE_PROVIDERS_TYPES, true))
->then(\Closure::fromCallable([$this, 'saveCustomProviderKeys']))
->end()
->children()
->scalarNode('type')
->example(self::NATIVE_PROVIDERS_TYPES)
->info('The provider type used to fetch contents')
->defaultValue(LocalFilesystemProviderFactory::TYPE)
->end()
->arrayNode('config')
->normalizeKeys(false)
->ignoreExtraKeys(false)
->fixXmlConfig('pattern')
->fixXmlConfig('exclude')
->children()
// Files provider
->scalarNode('path')->info('Required: The directory path for "files" providers')->end()
->scalarNode('depth')
->defaultNull()
->example('< 2')
->info(<<<INFO
The directory depth for "files" providers.
See "Symfony\Component\Finder\Finder::depth()"
https://symfony.com/doc/current/components/finder.html#directory-depth
INFO)
->end()
->arrayNode('patterns')
->defaultValue(['*'])
->info('The patterns to match for "files" providers')
->beforeNormalization()->ifString()->castToArray()->end()
->scalarPrototype()->end()
->end()
->arrayNode('excludes')
->info('The patterns to exclude for "files" providers')
->beforeNormalization()->ifString()->castToArray()->end()
->scalarPrototype()->end()
->end()
->end()
->end()
->end()
->validate()
->always()
->then(\Closure::fromCallable([$this, 'filterProviderConfig']))
->end()
->validate()
// Files provider validation
->ifTrue(static fn ($p) => LocalFilesystemProviderFactory::TYPE === $p['type'] && empty($p['config']['path']))
->thenInvalid('The "path" has to be specified to use the "files" provider')
->end()
->end()
->end()
->end()
;
}
private function addProcessorsSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
->children()
->arrayNode('processors')
->info('Built-in processors configuration. Disable to unregister all of the preconfigured processors.')
->canBeDisabled()
->addDefaultsIfNotSet()
->children()
->scalarNode('content_property')
->info('Key used by default by every processors to access and modify the main text of your contents')
->defaultValue('content')
->cannotBeEmpty()
->end()
->arrayNode('slug')
->canBeDisabled()
->children()
->scalarNode('property')
->info('Inject the content slug in a property of your model. See SlugProcessor.')
->defaultValue('slug')
->cannotBeEmpty()
->end()
->end()
->end()
->arrayNode('assets')
->info('Attempt to resolve local assets URLs using the Asset component for images and links. See AssetsProcessor.')
->canBeDisabled()
->end()
->arrayNode('resolve_content_links')
->info('Attempt to resolve relative links between contents using the route declared in config. See ResolveContentLinksProcessor.')
->canBeDisabled()
->end()
->arrayNode('external_links')
->info('Automatically add target="_blank" to external links. See HtmlExternalLinksProcessor.')
->canBeDisabled()
->end()
->arrayNode('anchors')
->canBeDisabled()
->info('Automatically add anchor links to elements with an id. See HtmlAnchorProcessor.')
->children()
->scalarNode('selector')
->defaultValue('h1, h2, h3, h4, h5')
->cannotBeEmpty()
->end()
->end()
->end()
->arrayNode('html_title')
->canBeDisabled()
->info('Extract a content title from a HTML property by using the first available h1 tag. See ExtractTitleFromHtmlContentProcessor.')
->children()
->scalarNode('property')
->info('Property where to inject the title in your model')
->defaultValue('title')
->cannotBeEmpty()
->end()
->end()
->end()
->arrayNode('html_elements_ids')
->canBeDisabled()
->info('Add ids to titles, images and other HTML elements in the content. See HtmlIdProcessor.')
->end()
->arrayNode('code_highlight')
->canBeDisabled()
->info('Enabled the syntax highlighting for code blocks using Prism.js. See CodeHighlightProcessor.')
->end()
->arrayNode('toc')
->canBeDisabled()
->info('Build a table of content from the HTML titles. See TableOfContentProcessor.')
->children()
->scalarNode('property')
->info('Property used to configure and inject the TableOfContent object in your model')
->defaultValue('tableOfContent')
->cannotBeEmpty()
->end()
->integerNode('min_depth')
->defaultValue(2)
->end()
->integerNode('max_depth')
->defaultValue(6)
->end()
->end()
->end()
->arrayNode('last_modified')
->canBeDisabled()
->info('Attempt to fetch and populate the last modified date to a property. See LastModifiedProcessor.')
->children()
->scalarNode('property')
->info('Property where to inject the last modified date of the content according to its provider.')
->defaultValue('lastModified')
->cannotBeEmpty()
->end()
->arrayNode('git')
->canBeDisabled()
->info('Whether to attempt using Git to get the last modified date of the content according to commits.')
->children()
->scalarNode('path')
->info('Git binary path to use')
->defaultValue('git')
->cannotBeEmpty()
->end()
->end()
->end()
->end()
->end()
->end()
->end()
;
}
/**
* Filters out provider config entries by factory type.
*/
private function filterProviderConfig(array $provider): array
{
switch ($provider['type']) {
case LocalFilesystemProviderFactory::TYPE:
$keys = ['path', 'depth', 'patterns', 'excludes'];
$provider['config'] = array_intersect_key($provider['config'], array_flip($keys));
break;
default:
if ($keys = $provider['config']['_keys'] ?? false) {
// Only pass explicitly provided keys to userland factory:
$provider['config'] = array_intersect_key($provider['config'], array_flip($keys));
}
}
return $provider;
}
/**
* Save internally explicitly specified keys for userland provider factories.
*/
private function saveCustomProviderKeys(array $provider): array
{
$provider['config']['_keys'] = array_keys($provider['config'] ?? []);
return $provider;
}
/**
* Normalizes shortcut config format to ['type' => ..., 'config' => [...]]
*/
private function normalizeShortcutConfig(array $provider): array
{
$config = $provider;
unset($config['type'], $config['config']);
$normalized = ['config' => $config];
if ($type = $provider['type'] ?? false) {
$normalized['type'] = $type;
}
return $normalized;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/DependencyInjection/StenopeExtension.php | src/DependencyInjection/StenopeExtension.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\DependencyInjection;
use Stenope\Bundle\Behaviour\HtmlCrawlerManagerInterface;
use Stenope\Bundle\Behaviour\ProcessorInterface;
use Stenope\Bundle\Builder;
use Stenope\Bundle\Command\DebugCommand;
use Stenope\Bundle\ExpressionLanguage\ExpressionLanguage as StenopeExpressionLanguage;
use Stenope\Bundle\Processor\AssetsProcessor;
use Stenope\Bundle\Processor\CodeHighlightProcessor;
use Stenope\Bundle\Processor\ExtractTitleFromHtmlContentProcessor;
use Stenope\Bundle\Processor\HtmlAnchorProcessor;
use Stenope\Bundle\Processor\HtmlExternalLinksProcessor;
use Stenope\Bundle\Processor\HtmlIdProcessor;
use Stenope\Bundle\Processor\LastModifiedProcessor;
use Stenope\Bundle\Processor\ResolveContentLinksProcessor;
use Stenope\Bundle\Processor\SlugProcessor;
use Stenope\Bundle\Processor\TableOfContentProcessor;
use Stenope\Bundle\Provider\ContentProviderInterface;
use Stenope\Bundle\Provider\Factory\ContentProviderFactory;
use Stenope\Bundle\Provider\Factory\ContentProviderFactoryInterface;
use Stenope\Bundle\Routing\ContentUrlResolver;
use Stenope\Bundle\Routing\ResolveContentRoute;
use Stenope\Bundle\Service\SharedHtmlCrawlerManager;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
/**
* @final
*/
class StenopeExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container): void
{
$loader = new PhpFileLoader($container, new FileLocator(__DIR__ . '/../../config'));
$loader->load('services.php');
$container->registerForAutoconfiguration(ContentProviderFactoryInterface::class)->addTag('stenope.content_provider_factory');
$container->registerForAutoconfiguration(ContentProviderInterface::class)->addTag('stenope.content_provider');
$container->registerForAutoconfiguration(ProcessorInterface::class)->addTag('stenope.processor');
$config = $this->processConfiguration($this->getConfiguration($configs, $container), $configs);
$container->getDefinition(Builder::class)->replaceArgument('$buildDir', $config['build_dir']);
$container->getDefinition(Builder::class)->replaceArgument('$filesToCopy', $config['copy']);
if ($config['shared_html_crawlers']) {
$container->setAlias(HtmlCrawlerManagerInterface::class, SharedHtmlCrawlerManager::class);
}
$this->processProcessors($loader, $container, $config['processors']);
$this->processProviders($container, $config['providers']);
$this->processLinkResolvers($container, $config['resolve_links']);
$registeredTypes = array_keys($config['providers']);
sort($registeredTypes, SORT_NATURAL);
$container->getDefinition(DebugCommand::class)
->replaceArgument('$registeredTypes', $registeredTypes)
;
if (!class_exists(ExpressionLanguage::class)) {
$container->removeDefinition(StenopeExpressionLanguage::class);
}
}
public function getNamespace(): string
{
return 'http://stenope.com/schema/dic/stenope';
}
public function getXsdValidationBasePath(): string
{
return __DIR__ . '/../../config/schema';
}
private function processProviders(ContainerBuilder $container, array $providersConfig): void
{
foreach ($providersConfig as $class => ['type' => $type, 'config' => $config]) {
$container->register("stenope.provider.$type.$class", ContentProviderInterface::class)
->setFactory([new Reference(ContentProviderFactory::class), 'create'])
->setArgument('$type', $type)
->setArgument('$config', ['class' => $class] + $config)
->addTag('stenope.content_provider')
;
}
}
private function processLinkResolvers(ContainerBuilder $container, array $links): void
{
$references = [];
foreach ($links as $class => $link) {
$id = sprintf(".%s.$class", ResolveContentRoute::class);
$container->register($id, ResolveContentRoute::class)->setArguments([
$link['route'],
$link['slug'],
$link['defaults'] ?? [],
]);
$references[$class] = new Reference($id);
}
$container->getDefinition(ContentUrlResolver::class)->replaceArgument('$routes', $references);
}
private function processProcessors(PhpFileLoader $loader, ContainerBuilder $container, array $processorsConfig): void
{
if (false === $processorsConfig['enabled']) {
return;
}
$loader->load('processors.php');
$contentProperty = $processorsConfig['content_property'];
if ($this->isProcessorEnabled($processorsConfig['slug'], SlugProcessor::class, $container)) {
$container->getDefinition(SlugProcessor::class)
->setArgument('$property', $processorsConfig['slug']['property'])
;
}
if ($this->isProcessorEnabled($processorsConfig['assets'], AssetsProcessor::class, $container)) {
$container->getDefinition(AssetsProcessor::class)
->setArgument('$property', $contentProperty)
;
}
if ($this->isProcessorEnabled($processorsConfig['resolve_content_links'], ResolveContentLinksProcessor::class, $container)) {
$container->getDefinition(ResolveContentLinksProcessor::class)
->setArgument('$property', $contentProperty)
;
}
if ($this->isProcessorEnabled($processorsConfig['external_links'], HtmlExternalLinksProcessor::class, $container)) {
$container->getDefinition(HtmlExternalLinksProcessor::class)
->setArgument('$property', $contentProperty)
;
}
if ($this->isProcessorEnabled($processorsConfig['anchors'], HtmlAnchorProcessor::class, $container)) {
$container->getDefinition(HtmlAnchorProcessor::class)
->setArgument('$selector', $processorsConfig['anchors']['selector'])
->setArgument('$property', $contentProperty)
;
}
if ($this->isProcessorEnabled($processorsConfig['html_title'], ExtractTitleFromHtmlContentProcessor::class, $container)) {
$container->getDefinition(ExtractTitleFromHtmlContentProcessor::class)
->setArgument('$titleProperty', $processorsConfig['html_title']['property'])
->setArgument('$contentProperty', $contentProperty)
;
}
if ($this->isProcessorEnabled($processorsConfig['html_elements_ids'], HtmlIdProcessor::class, $container)) {
$container->getDefinition(HtmlIdProcessor::class)
->setArgument('$property', $contentProperty)
;
}
if ($this->isProcessorEnabled($processorsConfig['code_highlight'], CodeHighlightProcessor::class, $container)) {
$container->getDefinition(CodeHighlightProcessor::class)
->setArgument('$property', $contentProperty)
;
}
if ($this->isProcessorEnabled($processorsConfig['toc'], TableOfContentProcessor::class, $container)) {
$container->getDefinition(TableOfContentProcessor::class)
->setArgument('$tableOfContentProperty', $processorsConfig['toc']['property'])
->setArgument('$minDepth', $processorsConfig['toc']['min_depth'])
->setArgument('$maxDepth', $processorsConfig['toc']['max_depth'])
->setArgument('$contentProperty', $contentProperty)
;
}
if ($this->isProcessorEnabled($processorsConfig['last_modified'], LastModifiedProcessor::class, $container)) {
$container->getDefinition(LastModifiedProcessor::class)
->setArgument('$property', $processorsConfig['last_modified']['property'])
;
if ($processorsConfig['last_modified']['git']['enabled']) {
// Configure the git fetcher inlined service definition:
/** @var Definition $fetcherDef */
$fetcherDef = $container->getDefinition(LastModifiedProcessor::class)->getArgument('$gitLastModified');
$fetcherDef->setArgument('$gitPath', $processorsConfig['last_modified']['git']['path']);
} else {
// Remove the git fetcher inlined service definition if disabled:
$container->getDefinition(LastModifiedProcessor::class)->setArgument('$gitLastModified', null);
}
}
}
private function isProcessorEnabled(array $config, string $processorId, ContainerBuilder $container): bool
{
if (!$enabled = $config['enabled']) {
$container->removeDefinition($processorId);
}
return $enabled;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/DependencyInjection/Compiler/TwigExtensionFixerCompilerPass.php | src/DependencyInjection/Compiler/TwigExtensionFixerCompilerPass.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class TwigExtensionFixerCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
$container->getDefinition('twig.extension.routing')
->replaceArgument(0, new Reference(UrlGeneratorInterface::class));
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/HttpKernel/Controller/ArgumentResolver/ContentArgumentResolver.php | src/HttpKernel/Controller/ArgumentResolver/ContentArgumentResolver.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\HttpKernel\Controller\ArgumentResolver;
use Stenope\Bundle\ContentManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\Controller\ValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
// Legacy (<6.2) resolver
if (!interface_exists(ValueResolverInterface::class)) {
/**
* @final
*/
class ContentArgumentResolver implements ArgumentValueResolverInterface
{
private ContentManagerInterface $contentManager;
public function __construct(ContentManagerInterface $contentManager)
{
$this->contentManager = $contentManager;
}
public function resolve(Request $request, ArgumentMetadata $argument): iterable
{
$slug = $request->attributes->get($argument->getName());
if (null === $slug) {
throw new \LogicException(sprintf('No value provided in the route attributes for the $%s argument of type "%s". Did your forget to make it nullable?', $argument->getName(), $argument->getType()));
}
yield $this->contentManager->getContent($argument->getType(), $slug);
}
public function supports(Request $request, ArgumentMetadata $argument): bool
{
if (null === $argument->getType() || !$this->contentManager->supports($argument->getType())) {
return false;
}
$slug = $request->attributes->get($argument->getName());
// Let the other resolvers (e.g: the default value resolver) try to handle it if no slug is provided:
if (null === $slug && $argument->isNullable()) {
return false;
}
return true;
}
}
return;
}
/**
* @final
*/
class ContentArgumentResolver implements ValueResolverInterface
{
private ContentManagerInterface $contentManager;
public function __construct(ContentManagerInterface $contentManager)
{
$this->contentManager = $contentManager;
}
public function resolve(Request $request, ArgumentMetadata $argument): iterable
{
if (null === $argument->getType() || !$this->contentManager->supports($argument->getType())) {
return [];
}
$slug = $request->attributes->get($argument->getName());
// Let the other resolvers (e.g: the default value resolver) try to handle it if no slug is provided:
if (null === $slug && $argument->isNullable()) {
return [];
}
if (null === $slug) {
throw new \LogicException(sprintf('No value provided in the route attributes for the $%s argument of type "%s". Did your forget to make it nullable?', $argument->getName(), $argument->getType()));
}
return [$this->contentManager->getContent($argument->getType(), $slug)];
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Exception/ContentNotFoundException.php | src/Exception/ContentNotFoundException.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Exception;
class ContentNotFoundException extends \InvalidArgumentException implements ExceptionInterface
{
public function __construct(string $type, string $id)
{
parent::__construct(sprintf('Content not found for type "%s" and id "%s".', $type, $id));
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Exception/ExceptionInterface.php | src/Exception/ExceptionInterface.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Exception;
/**
* Marker interface for all the meaningful exceptions from the Stenope package
*/
interface ExceptionInterface
{
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Exception/RuntimeException.php | src/Exception/RuntimeException.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Exception;
/**
* Generic Stenope exception for runtime issues.
*/
class RuntimeException extends \RuntimeException implements ExceptionInterface
{
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/TableOfContent/TableOfContent.php | src/TableOfContent/TableOfContent.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\TableOfContent;
/**
* @implements \IteratorAggregate<Headline>
*/
class TableOfContent extends \ArrayObject
{
/**
* @param Headline[] $headlines
*/
public function __construct(array $headlines = [])
{
parent::__construct($headlines, 0, \ArrayIterator::class);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/TableOfContent/Headline.php | src/TableOfContent/Headline.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\TableOfContent;
class Headline implements \JsonSerializable
{
public int $level;
public ?string $content;
private ?string $id;
/** @var Headline[] */
public array $children = [];
public ?Headline $parent = null;
public function __construct(int $level, ?string $id, ?string $content, array $children = [])
{
$this->level = $level;
$this->content = $content;
$this->id = $id;
foreach ($children as $child) {
$this->addChild($child);
}
}
public function addChild(Headline $headline): void
{
$this->children[] = $headline;
$headline->setParent($this);
}
public function setParent(Headline $parent): void
{
$this->parent = $parent;
}
public function hasChildren(): bool
{
return \count($this->children) > 0;
}
public function getChildren(): array
{
return $this->children;
}
public function getId(): ?string
{
return $this->id;
}
public function getContent(): ?string
{
return $this->content;
}
public function getLevel(): int
{
return $this->level;
}
public function getHn(): string
{
return sprintf('h%d', $this->level);
}
public function isParent(): bool
{
return $this->parent !== null;
}
public function getParent(): ?Headline
{
return $this->parent;
}
public function getParentForLevel(int $level): ?Headline
{
if ($this->level < $level) {
return $this;
}
if ($this->parent === null) {
return null;
}
return $this->parent->getParentForLevel($level);
}
public function jsonSerialize(): array
{
return [
'id' => $this->id,
'level' => $this->level,
'content' => $this->content,
'children' => array_map(fn ($child) => $child->jsonSerialize(), $this->children),
];
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/TableOfContent/CrawlerTableOfContentGenerator.php | src/TableOfContent/CrawlerTableOfContentGenerator.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\TableOfContent;
use Symfony\Component\DomCrawler\Crawler;
class CrawlerTableOfContentGenerator
{
public const MIN_DEPTH = 1;
public const MAX_DEPTH = 6;
/**
* @return Headline[]
*/
public function getTableOfContent(Crawler $crawler, ?int $fromDepth = null, ?int $toDepth = null): TableOfContent
{
$filters = $this->getFilters($fromDepth ?? static::MIN_DEPTH, $toDepth ?? static::MAX_DEPTH);
$headlines = [];
$previous = null;
/* @var \DOMElement $element */
foreach ($crawler->filter($filters) as $element) {
\assert($element instanceof \DOMElement);
$level = (int) $element->tagName[1];
$current = new Headline($level, $element->getAttribute('id'), $element->textContent);
$parent = $previous !== null ? $previous->getParentForLevel($level) : null;
$previous = $current;
if ($parent === null) {
$headlines[] = $current;
continue;
}
$parent->addChild($current);
}
return new TableOfContent($headlines);
}
private function getFilters(int $fromDepth, int $toDepth): string
{
$from = max(static::MIN_DEPTH, min($fromDepth, static::MAX_DEPTH));
$to = max(static::MIN_DEPTH, min($toDepth, static::MAX_DEPTH));
return implode(
', ',
array_map(
fn ($index) => 'h' . $index,
array_keys(array_fill($from, $to - $from + 1, null))
)
);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/HttpFoundation/ContentRequest.php | src/HttpFoundation/ContentRequest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\HttpFoundation;
use Symfony\Component\HttpFoundation\Request;
/**
* A request with the base url explicitly provided.
*/
class ContentRequest extends Request
{
public function withBaseUrl(string $baseUrl)
{
$this->baseUrl = $baseUrl;
return $this;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Behaviour/HighlighterInterface.php | src/Behaviour/HighlighterInterface.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Behaviour;
interface HighlighterInterface
{
/**
* Highlight the given code
*/
public function highlight(string $value, string $language): string;
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Behaviour/ContentManagerAwareTrait.php | src/Behaviour/ContentManagerAwareTrait.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Behaviour;
use Stenope\Bundle\ContentManagerInterface;
/**
* @see ContentManagerAwareInterface
*/
trait ContentManagerAwareTrait
{
private ContentManagerInterface $contentManager;
public function setContentManager(ContentManagerInterface $contentManager): void
{
$this->contentManager = $contentManager;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Behaviour/HtmlCrawlerManagerInterface.php | src/Behaviour/HtmlCrawlerManagerInterface.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Behaviour;
use Stenope\Bundle\Content;
use Symfony\Component\DomCrawler\Crawler;
/**
* Manager for getting an HTML crawler instance for HTML content properties,
* meant to be rendered inside a page.
*/
interface HtmlCrawlerManagerInterface
{
/**
* Get HTML Crawler for the given property (creates it if needed)
*/
public function get(Content $content, array $data, string $property): ?Crawler;
/**
* Dump the current state of the HTML Crawler into data for the given property.
*/
public function save(Content $content, array &$data, string $property): void;
/**
* Dump the current state of all HTML Crawlers into data for their respective property.
*/
public function saveAll(Content $content, array &$data): void;
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Behaviour/ProcessorInterface.php | src/Behaviour/ProcessorInterface.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Behaviour;
use Stenope\Bundle\Content;
interface ProcessorInterface
{
/**
* Apply modifications to decoded data before denormalization
*
* @param array $data The decoded data
* @param Content $content The source content
*/
public function __invoke(array &$data, Content $content): void;
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Behaviour/ContentManagerAwareInterface.php | src/Behaviour/ContentManagerAwareInterface.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Behaviour;
use Stenope\Bundle\ContentManagerInterface;
interface ContentManagerAwareInterface
{
/**
* Sets the owning ContentManager object.
*/
public function setContentManager(ContentManagerInterface $contentManager);
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Attribute/SuggestedDebugQuery.php | src/Attribute/SuggestedDebugQuery.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Attribute;
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::IS_REPEATABLE)]
class SuggestedDebugQuery
{
public array $orders;
public function __construct(
public string $description,
public ?string $filters = null,
array|string|null $orders = null
) {
$this->orders = (array) $orders;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Decoder/HtmlDecoder.php | src/Decoder/HtmlDecoder.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Decoder;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\Serializer\Encoder\DecoderInterface;
/**
* Parse Html data
*
* @final
*/
class HtmlDecoder implements DecoderInterface
{
/**
* Supported format
*/
public const FORMAT = 'html';
public function decode($data, $format, array $context = []): array
{
$crawler = new Crawler($data);
$attributes = [];
$crawler->filterXPath('//head/meta')->each(function ($node) use (&$attributes): void {
$attributes[$node->attr('name')] = $node->attr('content');
});
return array_merge(
$attributes,
[
'title' => $crawler->filterXPath('//head/title')->text(),
'content' => $crawler->filterXPath('//body')->html(),
]
);
}
public function supportsDecoding($format, array $context = []): bool
{
return self::FORMAT === $format;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Decoder/MarkdownDecoder.php | src/Decoder/MarkdownDecoder.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Decoder;
use Stenope\Bundle\Service\Parsedown;
use Symfony\Component\Serializer\Encoder\DecoderInterface;
use Symfony\Component\Yaml\Yaml;
/**
* Parse Markdown data
*
* @final
*/
class MarkdownDecoder implements DecoderInterface
{
/**
* Supported format
*/
public const FORMAT = 'markdown';
private const HEAD_SEPARATOR = '---';
/**
* Markdown parser
*/
private Parsedown $parser;
public function __construct(Parsedown $parser)
{
$this->parser = $parser;
}
public function decode($data, $format, array $context = []): array
{
$content = trim($data);
$separator = static::HEAD_SEPARATOR;
$start = strpos($content, $separator);
$stop = strpos($content, $separator, $start + 1);
$length = \strlen($separator) + 1;
if ($start === 0 && $stop) {
return array_merge(
$this->parseYaml(substr($content, $start + $length, $stop - $length)),
['content' => $this->markdownToHtml(substr($content, $stop + $length))]
);
}
return ['content' => $this->markdownToHtml($content)];
}
public function supportsDecoding($format, array $context = []): bool
{
return self::FORMAT === $format;
}
private function parseYaml(string $data): array
{
return Yaml::parse($data, true);
}
private function markdownToHtml(string $data): string
{
return $this->parser->parse($data);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Provider/ReversibleContentProviderInterface.php | src/Provider/ReversibleContentProviderInterface.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Provider;
use Stenope\Bundle\Content;
use Stenope\Bundle\ReverseContent\Context;
interface ReversibleContentProviderInterface extends ContentProviderInterface
{
public function reverse(Context $context): ?Content;
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Provider/ContentProviderInterface.php | src/Provider/ContentProviderInterface.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Provider;
use Stenope\Bundle\Content;
interface ContentProviderInterface
{
/**
* @return iterable<Content>|Content[]
*/
public function listContents(): iterable;
public function getContent(string $slug): ?Content;
/**
* @param class-string<object> $className
*/
public function supports(string $className): bool;
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Provider/LocalFilesystemProvider.php | src/Provider/LocalFilesystemProvider.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Provider;
use Stenope\Bundle\Content;
use Stenope\Bundle\Provider\Factory\LocalFilesystemProviderFactory;
use Stenope\Bundle\ReverseContent\Context;
use Stenope\Bundle\ReverseContent\RelativeLinkContext;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\Glob;
class LocalFilesystemProvider implements ReversibleContentProviderInterface
{
private string $supportedClass;
private string $path;
private ?string $depth;
private array $excludes;
/** @var string[] */
private array $patterns;
public function __construct(
string $supportedClass,
string $path,
?string $depth = null,
array $excludes = [],
array $patterns = ['*']
) {
$this->supportedClass = $supportedClass;
$this->path = $path;
$this->depth = $depth;
$this->excludes = $excludes;
$this->patterns = $patterns;
}
public function listContents(): iterable
{
foreach ($this->files() as $file) {
yield $this->fromFile($file);
}
}
public function getContent(string $slug): ?Content
{
$files = $this->files()->filter(
fn (\SplFileInfo $fileInfo) => trim("{$fileInfo->getRelativePath()}/{$fileInfo->getFilenameWithoutExtension()}", '/') === trim($slug, '/')
);
return ($file = current(iterator_to_array($files))) ? $this->fromFile($file) : null;
}
public function reverse(Context $context): ?Content
{
if (!$context instanceof RelativeLinkContext) {
return null;
}
if (LocalFilesystemProviderFactory::TYPE !== ($context->getCurrentMetadata()['provider'] ?? null)) {
// Cannot resolve relative to a non local filesystem content.
return null;
}
$currentPath = $context->getCurrentMetadata()['path'] ?? null; // current Content path
$target = $context->getTargetPath(); // relative path (to current) of the target we want to resolve
$expectedPath = \dirname($currentPath) . '/' . $target;
if (false === $expectedPath = realpath($expectedPath)) {
return null;
}
foreach ($this->files() as $file) {
if ($file->getRealPath() === $expectedPath) {
return $this->fromFile($file);
}
}
return null;
}
public function supports(string $className): bool
{
return $this->supportedClass === $className;
}
private function fromFile(\SplFileInfo $file): Content
{
return new Content(
$this->getSlug($file),
$this->supportedClass,
file_get_contents($file->getPathname()),
self::getFormat($file),
new \DateTimeImmutable("@{$file->getMTime()}"),
null,
[
'path' => $file->getRealPath(),
'provider' => LocalFilesystemProviderFactory::TYPE,
]
);
}
private function files(): Finder
{
if (!is_dir($this->path)) {
throw new \LogicException(sprintf('Path "%s" is not a directory.', $this->path));
}
// Speedup filtering dirs by using `Finder::exclude()` when we identify a dir:
$excludedDirs = array_filter($this->excludes, fn (string $pattern) => is_dir("{$this->path}/$pattern"));
// Remaining files to exclude can either:
// - be an exact file path with same name as an excluded dir
// - or the ones from the excluded patterns, minus the previously directories matched.
$excludedPatterns = array_diff(
$this->excludes,
array_filter($excludedDirs, fn (string $pattern) => !is_file("{$this->path}/$pattern"))
);
$finder = (new Finder())
->in($this->path)
->exclude($excludedDirs)
->notPath(array_map(fn ($exclude) => $this->convertPattern($exclude), $excludedPatterns))
->path(array_map(fn ($pattern) => $this->convertPattern($pattern), $this->patterns))
->sortByName()
;
if ($this->depth) {
$finder->depth($this->depth);
}
return $finder->files();
}
/**
* Converts a pattern (which can either be a glob pattern or a simple path)
* for usage with {@link Finder::path()} and {@link Finder::notPath()}
*/
private function convertPattern(string $pattern): string
{
if (str_ends_with($pattern, '/')) {
// If it ends with a "/", it was explicit as a directory,
// the user is very likely to mean "anything inside":
$pattern = "$pattern**";
}
return Glob::toRegex($pattern, true, false);
}
/**
* Get the format of a file from its extension
*/
private static function getFormat(\SplFileInfo $file): string
{
$ext = $file->getExtension();
switch ($ext) {
case 'md':
return 'markdown';
case 'yml':
case 'yaml':
return 'yaml';
default:
return $ext;
}
}
private function getSlug(\SplFileInfo $file): string
{
return substr($file->getRelativePathname(), 0, -(\strlen($file->getExtension()) + 1));
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Provider/Factory/ContentProviderFactory.php | src/Provider/Factory/ContentProviderFactory.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Provider\Factory;
use Stenope\Bundle\Provider\ContentProviderInterface;
/**
* Choose the first matching factory for type.
*/
class ContentProviderFactory implements ContentProviderFactoryInterface
{
/** @var iterable<ContentProviderFactoryInterface>|ContentProviderFactoryInterface[] */
private iterable $factories;
public function __construct(iterable $factories)
{
$this->factories = $factories;
}
public function create(string $type, array $config): ContentProviderInterface
{
foreach ($this->factories as $factory) {
if ($factory->supports($type, $config)) {
return $factory->create($type, $config);
}
}
throw new \LogicException(sprintf('No content provider factory found for type "%s"', $type));
}
public function supports(string $type, array $config): bool
{
return true;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Provider/Factory/LocalFilesystemProviderFactory.php | src/Provider/Factory/LocalFilesystemProviderFactory.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Provider\Factory;
use Stenope\Bundle\Provider\ContentProviderInterface;
use Stenope\Bundle\Provider\LocalFilesystemProvider;
class LocalFilesystemProviderFactory implements ContentProviderFactoryInterface
{
public const TYPE = 'files';
public function create(string $type, array $config): ContentProviderInterface
{
return new LocalFilesystemProvider(
$config['class'],
$config['path'],
$config['depth'] ?? null,
$config['excludes'] ?? [],
$config['patterns'] ?? ['*'],
);
}
public function supports(string $type, array $config): bool
{
return self::TYPE === $type;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Provider/Factory/ContentProviderFactoryInterface.php | src/Provider/Factory/ContentProviderFactoryInterface.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Provider\Factory;
use Stenope\Bundle\Provider\ContentProviderInterface;
/**
* A factory to instantiate content providers based on type and config
*/
interface ContentProviderFactoryInterface
{
public function create(string $type, array $config): ContentProviderInterface;
public function supports(string $type, array $config): bool;
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/EventListener/Informator.php | src/EventListener/Informator.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Environment;
/**
* @final
*/
class Informator implements EventSubscriberInterface
{
/**
* @var UrlGeneratorInterface
*/
private $urlGenerator;
/**
* Twig rendering engine
*
* @var Environment
*/
private $twig;
public function __construct(UrlGeneratorInterface $urlGenerator, Environment $twig)
{
$this->urlGenerator = $urlGenerator;
$this->twig = $twig;
}
public static function getSubscribedEvents(): array
{
return [KernelEvents::REQUEST => 'onRequest'];
}
public function onRequest(RequestEvent $event): void
{
$request = $event->getRequest();
if ($canonical = $this->getCanonicalUrl($request)) {
$request->attributes->set('_canonical', $canonical);
$this->twig->addGlobal('canonical', $canonical);
}
if ($root = $this->getRootUrl($request)) {
$request->attributes->set('_root', $root);
$this->twig->addGlobal('root', $root);
}
}
private function getCanonicalUrl(Request $request): string
{
if (!$request->attributes->get('_route')) {
return '';
}
return $this->urlGenerator->generate(
$request->attributes->get('_route'),
$request->attributes->get('_route_params'),
UrlGeneratorInterface::ABSOLUTE_URL
);
}
private function getRootUrl(Request $request): string
{
return sprintf('%s://%s', $request->getScheme(), $request->getHost());
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/EventListener/SitemapListener.php | src/EventListener/SitemapListener.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\EventListener;
use Stenope\Bundle\Builder\Sitemap;
use Stenope\Bundle\Routing\RouteInfoCollection;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Map all routes into a Sitemap
*
* @final
*/
class SitemapListener implements EventSubscriberInterface
{
private RouteInfoCollection $routesInfo;
private Sitemap $sitemap;
public function __construct(RouteInfoCollection $routesInfo, Sitemap $sitemap)
{
$this->routesInfo = $routesInfo;
$this->sitemap = $sitemap;
}
public function onKernelResponse(ResponseEvent $event): void
{
$request = $event->getRequest();
$response = $event->getResponse();
if (!$routeName = $request->attributes->get('_route')) {
return;
}
$route = $this->routesInfo[$routeName];
if ($route && $route->isMapped() && $request->attributes->get('_canonical')) {
$this->sitemap->add(
$request->attributes->get('_canonical'),
new \DateTime($response->headers->get('Last-Modified') ?? 'now')
);
}
}
public static function getSubscribedEvents(): array
{
return [KernelEvents::RESPONSE => 'onKernelResponse'];
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Service/AssetUtils.php | src/Service/AssetUtils.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Service;
use Symfony\Component\Asset\Packages;
class AssetUtils
{
private Packages $assets;
public function __construct(Packages $assets)
{
$this->assets = $assets;
}
public function getUrl(string $url): string
{
if (null === parse_url($url, PHP_URL_SCHEME) && !str_starts_with($url, '//') && !str_starts_with($url, '#')) {
// Only process local assets (ignoring urls starting by a scheme or "//").
return $this->assets->getUrl($url);
}
return $url;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Service/SharedHtmlCrawlerManager.php | src/Service/SharedHtmlCrawlerManager.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Service;
use Stenope\Bundle\Behaviour\HtmlCrawlerManagerInterface;
use Stenope\Bundle\Content;
use Symfony\Component\DomCrawler\Crawler;
class SharedHtmlCrawlerManager implements HtmlCrawlerManagerInterface
{
/**
* @var array<string,array<string,Crawler>>
*/
private array $crawlers = [];
public function get(Content $content, array $data, string $property): ?Crawler
{
$key = "{$content->getType()}:{$content->getSlug()}";
if (isset($this->crawlers[$key][$property])) {
return $this->crawlers[$key][$property];
}
$crawler = $this->createCrawler($data[$property]);
if (!$crawler) {
return null;
}
if (!isset($this->crawlers[$key])) {
$this->crawlers[$key] = [];
}
return $this->crawlers[$key][$property] = $crawler;
}
public function save(Content $content, array &$data, string $property): void
{
// Will be saved only once in saveAll.
}
public function saveAll(Content $content, array &$data): void
{
$key = "{$content->getType()}:{$content->getSlug()}";
if (!isset($this->crawlers[$key])) {
return;
}
foreach ($this->crawlers[$key] as $property => $crawler) {
$data[$property] = $crawler->filterXPath('//body')->first()->html();
}
unset($this->crawlers[$key]);
}
public function createCrawler(string $content): ?Crawler
{
$crawler = new Crawler($content);
try {
$crawler->html();
} catch (\Exception $e) {
// Content is not valid HTML.
return null;
}
return $crawler;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Service/NaiveHtmlCrawlerManager.php | src/Service/NaiveHtmlCrawlerManager.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Service;
use Stenope\Bundle\Behaviour\HtmlCrawlerManagerInterface;
use Stenope\Bundle\Content;
use Symfony\Component\DomCrawler\Crawler;
class NaiveHtmlCrawlerManager implements HtmlCrawlerManagerInterface
{
/**
* @var array<string,array<string,Crawler>>
*/
private array $crawlers = [];
public function get(Content $content, array $data, string $property): ?Crawler
{
$key = "{$content->getType()}:{$content->getSlug()}";
$crawler = $this->createCrawler($data[$property]);
if (!$crawler) {
return null;
}
if (!isset($this->crawlers[$key])) {
$this->crawlers[$key] = [];
}
return $this->crawlers[$key][$property] = $crawler;
}
public function save(Content $content, array &$data, string $property): void
{
$key = "{$content->getType()}:{$content->getSlug()}";
if (isset($this->crawlers[$key][$property])) {
$data[$property] = $this->crawlers[$key][$property]->filterXPath('//body')->first()->html();
unset($this->crawlers[$key][$property]);
}
}
public function saveAll(Content $content, array &$data): void
{
foreach ($this->crawlers as $crawlers) {
foreach ($crawlers as $property => $crawler) {
$data[$property] = $crawler->filterXPath('//body')->first()->html();
}
}
$this->crawlers = [];
}
public function createCrawler(string $html): ?Crawler
{
$crawler = new Crawler($html);
try {
$crawler->html();
} catch (\Exception $e) {
// Content is not valid HTML.
return null;
}
return $crawler;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Service/Parsedown.php | src/Service/Parsedown.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Service;
use Parsedown as BaseParsedown;
/**
* Parsedown as a service
*/
class Parsedown extends BaseParsedown
{
public function __construct()
{
$this->BlockTypes['!'][] = 'Image';
$this->BlockTypes['!'][] = 'Admonition';
}
protected function blockAdmonition($line, $block = null)
{
if (preg_match('#^!!! (?<types>[^"]{1,})( ?(\"(?<title>.*)\"))?#', $line['text'], $matches)) {
$types = array_filter(explode(' ', $matches['types']));
$type = $types[0];
$classes = implode(' ', array_map('trim', array_map('strtolower', $types)));
$title = $matches['title'] ?? $type;
$admonitionContentRef = null;
$block = [
'$admonitionContentRef' => &$admonitionContentRef,
'element' => [
'name' => 'div',
'handler' => 'elements',
'attributes' => [
'class' => "admonition $classes",
],
'text' => [
'title' => [
'handler' => 'line',
'name' => 'p',
'attributes' => [
'class' => 'admonition-title',
],
'text' => $title,
],
'content' => [
'handler' => 'line',
'name' => 'p',
'text' => &$admonitionContentRef,
],
],
],
];
// Remove title if explicitly unset:
if ($title === '') {
unset($block['element']['text']['title']);
}
return $block;
}
return null;
}
protected function blockAdmonitionContinue($line, $block = null)
{
// A blank newline has occurred, or text without indent:
if (isset($block['interrupted']) || $line['indent'] < 4) {
return null;
}
$previous = $block['$admonitionContentRef'] ?? "\n";
$indent = $line['indent'];
$current = str_repeat(' ', $indent) . $line['text'];
// Add the next admonition content line:
$block['$admonitionContentRef'] = "{$previous}{$current}\n";
return $block;
}
protected function blockAdmonitionComplete($block)
{
unset($block['$admonitionContentRef']);
return $block;
}
protected function blockFencedCodeComplete($Block)
{
$data = parent::blockCodeComplete($Block);
$data['element']['attributes']['class'] = 'code-multiline';
return $data;
}
protected function inlineCode($Excerpt)
{
$data = parent::inlineCode($Excerpt);
$data['element']['attributes']['class'] = 'code-inline';
return $data;
}
protected function blockImage($Line, $Block = null)
{
if (preg_match('/^!\[(.*)]\((.+)\)/', $Line['text'], $matches)) {
$Block = [
'element' => [
'name' => 'img',
'attributes' => [
'src' => $matches[2],
'alt' => $matches[1],
'title' => $matches[1],
],
],
];
return $Block;
}
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Service/HtmlUtils.php | src/Service/HtmlUtils.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Service;
class HtmlUtils
{
/**
* Add class to the given element
*/
public static function addClass(\DOMElement $element, string $class): void
{
$element->setAttribute('class', implode(' ', array_filter([
trim($element->getAttribute('class')),
$class,
])));
}
/**
* Set element HTML content
*/
public static function setContent(\DOMElement $element, string $content): void
{
$element->nodeValue = '';
$child = $element->ownerDocument->createDocumentFragment();
$child->appendXML($content);
$element->appendChild($child);
}
/**
* Wrap content
*/
public static function wrapContent(\DOMElement $element, string $wrapTag, array $wrapAttributes = []): void
{
$wrapper = $element->ownerDocument->createElement($wrapTag);
foreach ($wrapAttributes as $key => $value) {
$wrapper->setAttribute($key, $value);
}
foreach ($element->childNodes as $child) {
$wrapper->appendChild($child);
}
$element->appendChild($wrapper);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Service/ContentUtils.php | src/Service/ContentUtils.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Service;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
class ContentUtils
{
private static ?PropertyAccessorInterface $propertyAccessor = null;
/**
* Get max value of the given property in the given content list
*/
public static function max(array $contents, string $property)
{
return max(static::getAttributes($contents, $property));
}
/**
* Get min value of the given property in the given content list
*/
public static function min(array $contents, string $property)
{
return min(static::getAttributes($contents, $property));
}
/**
* List all values for given property in the given list of contents
*/
public static function getAttributes(array $contents, string $property): array
{
return array_map(
fn ($content) => static::getPropertyAccessor()->getValue($content, $property),
$contents
);
}
private static function getPropertyAccessor(): PropertyAccessorInterface
{
if (!static::$propertyAccessor) {
static::$propertyAccessor = PropertyAccess::createPropertyAccessor();
}
return static::$propertyAccessor;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Service/Git/LastModifiedFetcher.php | src/Service/Git/LastModifiedFetcher.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Service\Git;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Exception\RuntimeException;
use Symfony\Component\Process\Process;
use Symfony\Contracts\Service\ResetInterface;
class LastModifiedFetcher implements ResetInterface
{
/** Git executable path on the system / PATH used to get the last commit date for the file, or null to disable. */
private ?string $gitPath;
private LoggerInterface $logger;
private static ?bool $gitAvailable = null;
public function __construct(
?string $gitPath = 'git',
?LoggerInterface $logger = null
) {
$this->gitPath = $gitPath;
$this->logger = $logger ?? new NullLogger();
}
/**
* @throws ProcessFailedException
*/
public function __invoke(string $filePath): ?\DateTimeImmutable
{
if (null === $this->gitPath || false === self::$gitAvailable) {
// Don't go further if the git command is not available or the git feature is disabled
return null;
}
$executable = explode(' ', $this->gitPath);
if (null === self::$gitAvailable) {
// Check once if the git command is available
$process = new Process([...$executable, '--version']);
try {
$process->run();
} catch (RuntimeException $e) {
self::$gitAvailable = false;
$this->logger->warning('An unexpected error occurred while trying to check the git binary at path "{gitPath}"', [
'gitPath' => $this->gitPath,
'exception' => $e,
'exception_message' => $e->getMessage(),
]);
return null;
}
if (!$process->isSuccessful()) {
self::$gitAvailable = false;
$this->logger->warning('Git was not found at path "{gitPath}". Check the binary path is correct or part of your PATH.', [
'gitPath' => $this->gitPath,
'output' => $process->getOutput(),
'err_output' => $process->getErrorOutput(),
]);
return null;
}
}
if (null === self::$gitAvailable) {
// Check once if the project is a git repository
$process = new Process([...$executable, 'rev-parse', '--is-inside-work-tree']);
$process->run();
if (!$process->isSuccessful()) {
self::$gitAvailable = false;
$this->logger->warning('The current project is not a git repository. Last modified date will not be available using the LastModifiedFetcher.', [
'output' => $process->getOutput(),
'err_output' => $process->getErrorOutput(),
]);
return null;
}
self::$gitAvailable = true;
}
$process = new Process([...$executable, 'log', '-1', '--format=%cd', '--date=iso', $filePath]);
$process->run();
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
if ($output = $process->getOutput()) {
return new \DateTimeImmutable(trim($output));
}
return null;
}
public function reset(): void
{
self::$gitAvailable = null;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Command/StopwatchHelperTrait.php | src/Command/StopwatchHelperTrait.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Command;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Stopwatch\StopwatchEvent;
/**
* @internal
*/
trait StopwatchHelperTrait
{
private static function formatEvent(StopwatchEvent $event): string
{
return sprintf(
'Start time: %s — End time: %s — Duration: %s — Memory used: %s',
date('H:i:s', (int) (($event->getOrigin() + $event->getStartTime()) / 1000)),
date('H:i:s', (int) (($event->getOrigin() + $event->getEndTime()) / 1000)),
static::formatTimePrecision((int) $event->getDuration() / 1000),
Helper::formatMemory($event->getMemory())
);
}
private static function formatTimePrecision($secs): string
{
static $timeFormats = [
[0, 'sec', 1, 2],
[2, 'secs', 1, 2],
[60, '1 min'],
[120, 'mins', 60],
[3600, '1 hr'],
[7200, 'hrs', 3600],
[86400, '1 day'],
[172800, 'days', 86400],
];
foreach ($timeFormats as $index => $format) {
if ($secs >= $format[0]) {
if ((isset($timeFormats[$index + 1]) && $secs < $timeFormats[$index + 1][0])
|| $index === \count($timeFormats) - 1
) {
switch (\count($format)) {
case 2:
return $format[1];
case 4:
return round($secs / $format[2], $format[3]) . ' ' . $format[1];
default:
return floor($secs / $format[2]) . ' ' . $format[1];
}
}
}
}
return '0 sec';
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Command/DebugCommand.php | src/Command/DebugCommand.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Command;
use Stenope\Bundle\Attribute\SuggestedDebugQuery;
use Stenope\Bundle\ContentManagerInterface;
use function Stenope\Bundle\ExpressionLanguage\expr;
use Stenope\Bundle\ExpressionLanguage\Expression;
use Stenope\Bundle\TableOfContent\Headline;
use Stenope\Bundle\TableOfContent\TableOfContent;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Dumper;
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\DependencyInjection\ExpressionLanguage;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Component\VarDumper\Cloner\Stub;
use Symfony\Component\VarDumper\Cloner\VarCloner;
class DebugCommand extends Command
{
use StopwatchHelperTrait;
private ContentManagerInterface $manager;
private Stopwatch $stopwatch;
private array $registeredTypes;
public function __construct(ContentManagerInterface $manager, Stopwatch $stopwatch, array $registeredTypes = [])
{
$this->manager = $manager;
$this->stopwatch = $stopwatch;
$this->registeredTypes = $registeredTypes;
parent::__construct();
}
protected function configure(): void
{
$this
->setName('debug:stenope:content')
->setDescription('Debug Stenope managed contents')
->addArgument('class', InputArgument::REQUIRED, 'Content FQCN')
->addArgument('id', InputArgument::OPTIONAL, 'Content identifier')
->addOption('order', 'o', InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Order by field(s)')
->addOption('filter', 'f', InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Filter by field(s)')
->addOption('suggest', 's', InputOption::VALUE_NONE, 'Suggest common queries')
->setHelp(<<<HELP
The <info>%command.name%</info> allows to list and display content managed by Stenope:
<info>php %command.full_name% "App\Model\Author"</info>
will list all authors.
<info>php %command.full_name% "App\Model\Author ogi"</info>
will fetch and display the processed Author with id "ogi".
Change <info>verbosity</info> in order to get more details <comment>(-v, -vv, -vvv)</comment>.
--- Sort
The command allows to order the list:
<info>php %command.full_name% "App\Model\Author" --order=slug</info>
<info>php %command.full_name% "App\Model\Author" --order=integrationDate</info>
In <info>desc</info> order:
<info>php %command.full_name% "App\Model\Author" --order='desc:integrationDate'</info>
same as:
<info>php %command.full_name% "App\Model\Author" --order='-integrationDate'</info>
You can order by multiple fields:
<info>php %command.full_name% "App\Model\Author" --order='desc:active' --order='integrationDate'</info>
--- Filter
The command allows to filter out the list in various ways, using an expression read by the ExpressionLanguage component.
See https://symfony.com/doc/current/components/expression_language/syntax.html
The current item is referred using "data", "d" or "_":
<info>php %command.full_name% "App\Model\Author" --filter=data.active</info>
<info>php %command.full_name% "App\Model\Author" --filter=d.active</info>
<info>php %command.full_name% "App\Model\Author" --filter=_.active</info>
Negation:
<info>php %command.full_name% "App\Model\Author" --filter='not d.active'</info>
<info>php %command.full_name% "App\Model\Author" --filter='!d.active'</info>
Contains:
<info>php %command.full_name% "App\Model\Article" --filter='contains(_.slug, "symfony")'</info>
You can also use multiple filters at once:
<info>php %command.full_name% "App\Model\Article" \
--filter='not _.outdated' \
--filter='contains(_.slug, "dev")' \
--filter='"symfony" in _.tags' \
--filter='_.date > date("2021-01-23")'</info>
Built-in functions are:
* date
* datetime
* upper
* lower
* contains
* starts_with
* ends_with
* keys
HELP
)
;
}
protected function interact(InputInterface $input, OutputInterface $output): void
{
$io = new SymfonyStyle($input, $output);
if (!$input->getArgument('class')) {
if (0 === \count($this->registeredTypes)) {
$io->error('It seems there is no type known by Stenope. Did you configure stenope.providers?');
return;
}
$chosenType = $io->choice('Which content type would you like to inspect?', $this->registeredTypes);
$input->setArgument('class', $chosenType);
}
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$io->title('Debug Stenope Contents');
$class = $this->guessOrAskClass($input, $io);
$id = $input->getArgument('id');
[$suggestedFilter, $suggestedOrder] = $this->suggest($io, $input, $class, $id);
if (!$this->stopwatch->isStarted('fetch')) {
$this->stopwatch->start('fetch', 'stenope');
}
if (null === $id) {
$this->list(
$io,
$class,
$this->getOrders($suggestedOrder ?? $input->getOption('order')),
$suggestedFilter ? expr($suggestedFilter) : $this->getFilters($input)
);
} else {
$this->describe($io, $class, $id);
}
if ($this->stopwatch->isStarted('fetch')) {
$this->stopwatch->stop('fetch');
}
$io->comment("Fetched info:\n" . self::formatEvent($this->stopwatch->getEvent('fetch')));
return Command::SUCCESS;
}
private function getOrders(array $rawOrders): array
{
$orders = [];
foreach ($rawOrders as $field) {
if (str_starts_with($field, 'desc:')) {
$orders[substr($field, 5)] = false;
continue;
}
if (str_starts_with($field, '-')) {
$orders[substr($field, 1)] = false;
continue;
}
$orders[$field] = true;
}
return $orders;
}
private function getFilters(InputInterface $input): ?Expression
{
if ([] === $filterExpr = $input->getOption('filter')) {
return null;
}
if (!class_exists(ExpressionLanguage::class)) {
throw new \LogicException('You must install the Symfony ExpressionLanguage component ("symfony/expression-language") to use the "--filter" option.');
}
return expr(...$filterExpr);
}
private function list(SymfonyStyle $io, string $class, array $sort, ?Expression $filters): void
{
$io->section("\"$class\" items");
if ($filters) {
$io->writeln("Filtered with: <info>$filters</info>");
$io->newLine();
}
$list = $this->manager->getContents($class, $sort, $filters);
$io->listing(array_keys($list));
$io->note(sprintf('Found %d items', \count($list)));
}
private function describe(SymfonyStyle $io, string $class, string $id): void
{
$io->section("\"$class\" item with id \"$id\"");
$item = $this->manager->getContent($class, $id);
$cloner = new VarCloner();
if (!$io->isVeryVerbose()) {
// Except on very verbose mode, display a simplified TOC representation:
$cloner->addCasters([
TableOfContent::class => \Closure::fromCallable([self::class, 'castTableOfContent']),
]);
}
// Show full strings on very verbose mode:
$cloner->setMaxString($io->isVeryVerbose() ? -1 : 250);
// Show full data tree on verbose mode:
$cloner->setMaxItems($io->isVerbose() ? -1 : 15);
$dump = new Dumper($io, null, $cloner);
$io->writeln($dump($item));
}
private static function castTableOfContent(TableOfContent $toc, array $a, Stub $s): array
{
$appendHeadline = static function (&$headlines, Headline $headline) use (&$appendHeadline): void {
$childHeadlines = [];
foreach ($headline->getChildren() as $child) {
$appendHeadline($childHeadlines, $child);
}
$headlines["H{$headline->getLevel()} - {$headline->getContent()}"] = $childHeadlines;
};
$headlines = [];
/** @var Headline $headline */
foreach ($toc as $headline) {
$appendHeadline($headlines, $headline);
}
$s->type = Stub::TYPE_ARRAY;
$s->class = Stub::ARRAY_ASSOC;
$s->value = 'headlines';
return $headlines;
}
private function suggest(
SymfonyStyle $io,
InputInterface $input,
string $class,
?string $id
): array {
if ($input->getOption('suggest')) {
if (PHP_MAJOR_VERSION < 8) {
throw new \LogicException('You need PHP 8.0 at least to use this option.');
}
if (!$input->isInteractive()) {
throw new \LogicException('Cannot use the --suggest option in non-interactive mode.');
}
$suggestedQueries = $this->getSuggestedQueries($class);
$choices = array_map(
static fn (SuggestedDebugQuery $suggestion): string => sprintf(
'<info>%s</info> (filter: %s, order: %s)',
$suggestion->description,
$suggestion->filters ?? '-',
$suggestion->orders ? implode(', ', $suggestion->orders) : '-',
),
$suggestedQueries,
);
/** @var SuggestedDebugQuery $choice */
$choice = $suggestedQueries[array_search(
$io->choice('Which query would you like to execute?', $choices),
$choices,
true
)];
$filter = $choice->filters;
$orders = $choice->orders;
$io->comment($this->getCommandLine($class, $choice));
return [$filter, $orders];
}
if (PHP_MAJOR_VERSION >= 8 && null === $id && $input->isInteractive()) {
$io->section('Suggested queries');
if (!$suggestedQueries = $this->getSuggestedQueries($class)) {
$io->writeln(sprintf(
' 💡 <fg=cyan>Use the <comment>"%s"</comment> attribute on the <info>"%s"</info> class to register common queries.</>',
SuggestedDebugQuery::class,
$class,
));
}
$io->definitionList(...array_map(
fn (SuggestedDebugQuery $suggestion): array => [
$suggestion->description => $this->getCommandLine($class, $suggestion),
],
$suggestedQueries,
));
$io->writeln(' 💡 <fg=cyan>Use <comment>--suggest</comment> to interactively run one of those queries.</>');
}
return [null, null];
}
private function getSuggestedQueries(string $class): array
{
return array_map(
static fn (\ReflectionAttribute $attribute) => $attribute->newInstance(),
(new \ReflectionClass($class))->getAttributes(SuggestedDebugQuery::class),
);
}
private function getCommandLine(string $class, SuggestedDebugQuery $query): string
{
$commandLine = sprintf('bin/console %s "%s"', $this->getName(), $class);
foreach ($query->orders as $order) {
$commandLine .= sprintf(' --order="%s"', $order);
}
if ($query->filters) {
$commandLine .= sprintf(' --filter="%s"', strtr($query->filters, ['"' => '\"']));
}
return $commandLine;
}
private function guessOrAskClass(InputInterface $input, SymfonyStyle $io): string
{
$class = $input->getArgument('class');
if ($input->isInteractive() && !\in_array($class, $this->registeredTypes, true)) {
$shorthands = array_combine(
$this->registeredTypes,
array_map(
static fn (string $fqcn) => strtolower(basename(str_replace('\\', '/', $fqcn))),
$this->registeredTypes
)
);
$comparedClassInput = strtolower($class);
$scores = array_combine(
array_keys($shorthands),
array_map(fn (string $shortname) => levenshtein($comparedClassInput, $shortname), $shorthands)
);
$bestScore = min($scores);
$matches = array_keys($scores, $bestScore, true);
if (\count($matches) > 1) {
$class = $io->choice('Did you mean one of these content types?', $matches);
} else {
$match = current($matches);
$class = $match;
$io->comment("Assuming you meant \"$class\"");
}
}
return $class;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/src/Command/BuildCommand.php | src/Command/BuildCommand.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Command;
use Stenope\Bundle\Builder;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
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\Console\Terminal;
use Symfony\Component\Stopwatch\Stopwatch;
class BuildCommand extends Command
{
use StopwatchHelperTrait;
private Builder $builder;
private Stopwatch $stopwatch;
public function __construct(Builder $builder, Stopwatch $stopwatch)
{
$this->builder = $builder;
$this->stopwatch = $stopwatch;
parent::__construct();
}
protected function configure(): void
{
$this
->setName('stenope:build')
->setDescription('Build static website')
->addArgument(
'buildDir',
InputArgument::OPTIONAL,
'Full path to build directory',
$this->builder->getBuildDir(),
)
->addOption(
'host',
null,
InputOption::VALUE_REQUIRED,
'What should be used as domain name for absolute url generation?'
)
->addOption(
'base-url',
null,
InputOption::VALUE_REQUIRED,
'What should be used as base-url for absolute url generation?'
)
->addOption(
'scheme',
null,
InputOption::VALUE_REQUIRED,
'What should be used as scheme for absolute url generation?'
)
->addOption(
'no-sitemap',
null,
InputOption::VALUE_NONE,
'Don\'t build the sitemap'
)
->addOption(
'no-expose',
null,
InputOption::VALUE_NONE,
'Don\'t expose the public directory'
)
->addOption(
'ignore-content-not-found',
null,
InputOption::VALUE_NONE,
'Ignore content not found errors'
)
;
}
protected function initialize(InputInterface $input, OutputInterface $output): void
{
if ($destination = $input->getArgument('buildDir')) {
$this->builder->setBuildDir($destination);
}
if ($host = $input->getOption('host')) {
$this->builder->setHost($host);
}
if ($scheme = $input->getOption('scheme')) {
$this->builder->setScheme($scheme);
}
if ($baseUrl = $input->getOption('base-url')) {
$this->builder->setBaseUrl($baseUrl);
}
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$io->title('Building static site');
$io->definitionList(
['buildDir' => $this->builder->getBuildDir()],
['scheme' => $this->builder->getScheme()],
['host' => $this->builder->getHost()],
['baseUrl' => $this->builder->getBaseUrl()],
);
if (!$this->stopwatch->isStarted('build')) {
$this->stopwatch->start('build', 'stenope');
}
$sitemap = $input->getOption('no-sitemap');
$expose = $input->getOption('no-expose');
$ignoreContentNotFoundErrors = $input->getOption('ignore-content-not-found');
if ($input->isInteractive() && $output->isDecorated() && $output->getVerbosity() === OutputInterface::VERBOSITY_NORMAL) {
// In interactive, ansi compatible envs with normal verbosity, use a progress bar
iterator_to_array($progressIterator = new BuildProgressIterator($output, $this->builder->iterate(
!$sitemap,
!$expose,
$ignoreContentNotFoundErrors,
)));
$count = \count($progressIterator);
} else {
// Otherwise, let the user controls shown information in logs through verbosity
$count = $this->builder->build(!$sitemap, !$expose, $ignoreContentNotFoundErrors);
$io->newLine();
}
if ($this->stopwatch->isStarted('build')) {
$this->stopwatch->stop('build');
}
$io->success("Built $count pages.\n" . self::formatEvent($this->stopwatch->getEvent('build')));
return Command::SUCCESS;
}
}
/**
* A build iterator that shows progress using a Symfony CLI ProgressBar
*/
class BuildProgressIterator implements \IteratorAggregate, \Countable
{
private ProgressBar $progressBar;
private \Generator $buildIterator;
private int $count = 1;
public function __construct(OutputInterface $output, \Generator $buildIterator)
{
$this->progressBar = new ProgressBar($output);
$this->progressBar->minSecondsBetweenRedraws(0.02);
$this->progressBar->maxSecondsBetweenRedraws(0.05);
$this->progressBar->setMessage('...', 'step');
$this->progressBar->setBarCharacter('<fg=green>-</>');
$this->progressBar->setEmptyBarCharacter(' ');
$this->progressBar->setProgressCharacter('<fg=green>➤</>');
$this->progressBar->setFormat(<<<TXT
<bg=green;fg=black>[%step%]</bg=green;fg=black> %current%/%max% [%bar%] %percent:3s%% <info>%elapsed:6s%/%estimated:-6s%</info> <fg=white;bg=blue>%memory:6s%</fg=white;bg=blue>
<comment>%message%</comment>
TXT
);
$this->buildIterator = $buildIterator;
}
public function getIterator(): \Traversable
{
yield from $this->progressBar->iterate((function (): iterable {
foreach ($this->buildIterator as $step => $context) {
$this->notifyProgress(
\is_string($step) ? $step : null,
$context['maxStep'] ?? null,
$context['message'] ?? null,
);
for ($x = 0; $x < $context['advance']; ++$x) {
// Show progress for each advancement in build steps
yield;
}
}
$this->progressBar->finish();
$this->count = $this->buildIterator->getReturn();
})(), $this->count());
$this->progressBar->clear();
}
public function count(): int
{
return $this->count ?? 1;
}
private function notifyProgress(?string $stepName = null, ?int $maxStep = null, ?string $message = null): void
{
if ($maxStep) {
$this->progressBar->setMaxSteps($maxStep);
}
if ($message) {
$this->progressBar->setMessage($this->padMessage($message));
}
if ($stepName && $this->progressBar->getMessage('step') !== $stepName) {
$this->progressBar->setMessage($stepName, 'step');
// Reset message on changed step
$this->progressBar->setMessage($this->padMessage($message ?? ''));
// Force display change:
$this->progressBar->display();
}
}
private function padMessage(string $message): string
{
static $messagePadding = null;
if (!$messagePadding) {
// Fixup the progress bar %message% placeholder clearing according to terminal width
// (multi-line progress bars are a bit messed up)
$messagePadding = (new Terminal())->getWidth() - 3;
}
return str_pad($message, $messagePadding, ' ');
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/bootstrap.php | tests/bootstrap.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
$loader = require __DIR__ . '/../vendor/autoload.php';
const PACKAGE_ROOT_DIR = __DIR__ . '/..';
const FIXTURES_DIR = __DIR__ . '/../tests/fixtures';
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Integration/ContentArgumentResolverTest.php | tests/Integration/ContentArgumentResolverTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Integration;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ContentArgumentResolverTest extends WebTestCase
{
private static array $kernelOptions = [
'environment' => 'prod',
'debug' => true,
];
public function testOptionalArgumentForwardsToDefaultResolver(): void
{
$client = self::createClient(self::$kernelOptions);
$client->request('GET', '/recipes/optional-recipe');
self::assertResponseIsSuccessful();
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Integration/ResolvedLinkedContentsTest.php | tests/Integration/ResolvedLinkedContentsTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Integration;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ResolvedLinkedContentsTest extends WebTestCase
{
private static array $kernelOptions = [
'environment' => 'prod',
'debug' => true,
];
public function testItResolvesCrossLinkedContents(): void
{
$client = self::createClient(self::$kernelOptions);
$client->request('GET', '/recipes/ogito');
self::assertResponseIsSuccessful();
self::assertStringContainsString(
<<<HTML
Cheers <a href="/authors/ogi">Ogi</a> for this recipe.
Check his <a href="/authors/ogi#recipes">other recipes</a>.
HTML,
$client->getResponse()->getContent(),
'Response contains proper link to author'
);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Integration/TableOfContentTest.php | tests/Integration/TableOfContentTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Integration;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class TableOfContentTest extends WebTestCase
{
private static array $kernelOptions = [
'environment' => 'prod',
'debug' => true,
];
public function testItResolvesTableOfContent(): void
{
$client = self::createClient(self::$kernelOptions);
$client->request('GET', '/recipes/ogito');
self::assertResponseIsSuccessful();
self::assertSelectorExists('.table-of-content');
self::assertSelectorTextContains('.table-of-content > ol > li:nth-child(1)', 'First step');
self::assertSelectorTextContains('.table-of-content > ol > li:nth-child(1) li', 'Sub-step');
self::assertSelectorTextContains('.table-of-content > ol > li:nth-child(2)', 'Second step');
}
public function testItResolvesTableOfContentWithLimit(): void
{
$client = self::createClient(self::$kernelOptions);
$client->request('GET', '/recipes/cheesecake');
self::assertResponseIsSuccessful();
self::assertSelectorExists('.table-of-content');
self::assertSelectorTextContains('.table-of-content > ol > li:nth-child(1)', 'First step');
self::assertSelectorNotExists('.table-of-content > ol > li:nth-child(1) li');
self::assertSelectorTextContains('.table-of-content > ol > li:nth-child(2)', 'Second step');
}
public function testDisabledTableOfContent(): void
{
$client = self::createClient(self::$kernelOptions);
$client->request('GET', '/recipes/tomiritsu');
self::assertResponseIsSuccessful();
self::assertSelectorNotExists('.table-of-content');
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Integration/BuildTest.php | tests/Integration/BuildTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Integration;
use Psr\Log\Test\TestLogger;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Tester\ApplicationTester;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\DomCrawler\Link;
use Symfony\Component\Filesystem\Filesystem;
class BuildTest extends KernelTestCase
{
public static array $kernelOptions = [
'environment' => 'prod',
'debug' => true,
];
protected function setUp(): void
{
static::bootKernel(self::$kernelOptions);
}
/**
* This test is a dependency of all other tests,
* so failing will skip the next tests.
*/
public function testBuildApp(): void
{
// Empty build & cache
($fs = new Filesystem())->remove(($kernel = self::createKernel(self::$kernelOptions))->getCacheDir());
$fs->remove($kernel->getProjectDir() . '/build');
$kernel = static::bootKernel(self::$kernelOptions);
$application = new Application($kernel);
$application->setAutoExit(false);
$tester = new ApplicationTester($application);
$tester->run(['stenope:build', '--ansi'], [
'interactive' => false,
'verbosity' => ConsoleOutput::VERBOSITY_NORMAL,
]);
$output = $tester->getDisplay(true);
self::assertSame(Command::SUCCESS, $tester->getStatusCode(), <<<TXT
The site cannot be build properly.
Inspect output below:
---
$output
TXT
);
$this->assertStringContainsString('[OK] Built 19 pages.', $output);
/** @var TestLogger $logger */
$logger = static::getContainer()->get('logger');
$logger->hasWarningThatContains('Url "http://localhost/without-noindex" contains a "x-robots-tag: noindex" header that will be lost by going static.');
}
/**
* @depends testBuildApp
*/
public function testBuildDirIsCreated(): void
{
self::assertDirectoryExists(self::$kernel->getProjectDir() . '/build');
}
/**
* @depends testBuildApp
*/
public function testCopiedFiles(): void
{
self::assertDirectoryExists(self::$kernel->getProjectDir() . '/build/build');
self::assertFileExists(self::$kernel->getProjectDir() . '/build/build/app.css');
self::assertFileExists(self::$kernel->getProjectDir() . '/build/robots.txt');
self::assertFileDoesNotExist(self::$kernel->getProjectDir() . '/build/index.php');
}
/**
* @depends testBuildApp
*/
public function testSiteMap(): void
{
self::assertFileExists(self::$kernel->getProjectDir() . '/build/sitemap.xml');
$crawler = new Crawler(file_get_contents(self::$kernel->getProjectDir() . '/build/sitemap.xml'));
self::assertEqualsCanonicalizing([
'http://localhost/',
'http://localhost/foo.html',
'http://localhost/authors/john.doe',
'http://localhost/authors/ogi',
'http://localhost/authors/tom32i',
'http://localhost/recipes/',
'http://localhost/recipes/cheesecake',
'http://localhost/recipes/ogito',
'http://localhost/recipes/stockholm%20mule',
'http://localhost/recipes/tomiritsu',
'http://localhost/with-noindex',
'http://localhost/without-noindex',
], $crawler->filter('url > loc')->extract(['_text']));
}
/**
* @depends testBuildApp
*/
public function testHomepage(): void
{
self::assertFileExists(self::$kernel->getProjectDir() . '/build/index.html');
}
/**
* @depends testBuildApp
*/
public function testRecipes(): void
{
$buildDir = self::$kernel->getProjectDir() . '/build';
self::assertDirectoryExists($buildDir . '/recipes');
self::assertFileExists($buildDir . '/recipes/index.html');
self::assertFileExists($buildDir . '/recipes/cheesecake/index.html');
self::assertFileExists($buildDir . '/recipes/stockholm mule/index.html');
self::assertFileExists($buildDir . '/recipes/ogito/index.html');
$crawler = new Crawler(file_get_contents($buildDir . '/recipes/index.html'), 'http://localhost/recipes/');
$links = array_map(fn (Link $link) => $link->getUri(), $crawler->filter('main .container a.recipe-link')->links());
self::assertSame([
'http://localhost/recipes/stockholm%20mule',
'http://localhost/recipes/cheesecake',
'http://localhost/recipes/ogito',
'http://localhost/recipes/tomiritsu',
], $links, 'all recipes links generated in right order');
}
/**
* We can have custom controllers rendering content in another format than html, with their own extension in url.
* For such routes, the Builder won't generate an index.html file as soon as the proper format
* is provided into the request (through the route `format` option or the request `_format` attribute).
*
* @depends testBuildApp
*/
public function testRecipesAsPdf(): void
{
$buildDir = self::$kernel->getProjectDir() . '/build';
self::assertDirectoryExists($buildDir . '/recipes');
self::assertFileExists($path = $buildDir . '/recipes/cheesecake.pdf');
self::assertDirectoryDoesNotExist($path);
self::assertFileExists($path = $buildDir . '/recipes/ogito.pdf');
self::assertDirectoryDoesNotExist($path);
self::assertFileExists($path = $buildDir . '/recipes/stockholm mule.pdf');
self::assertDirectoryDoesNotExist($path);
}
/**
* @depends testBuildApp
*/
public function testAuthors(): void
{
self::assertFileExists(self::$kernel->getProjectDir() . '/build/authors/ogi/index.html');
self::assertFileExists(
self::$kernel->getProjectDir() . '/build/authors/john.doe/index.html',
'Ensures content with dot in slug generates an index.html file.',
);
}
/**
* In the same way as {@link self::testRecipesAsPdf},
* we can expose a micro API as plain JSON files for authors.
*
* @depends testBuildApp
*/
public function testAuthorsAsJson(): void
{
self::assertFileExists($path = self::$kernel->getProjectDir() . '/build/authors/ogi.json');
self::assertDirectoryDoesNotExist($path);
self::assertFileExists($path = self::$kernel->getProjectDir() . '/build/authors/john.doe.json');
self::assertDirectoryDoesNotExist($path);
}
/**
* The builder should not generate a dir/index.html for an url already ending with ".html".
*
* @depends testBuildApp
*/
public function testWithHtmlExtensionDoesNotGeneratesDir(): void
{
self::assertFileExists($path = self::$kernel->getProjectDir() . '/build/foo.html');
self::assertDirectoryDoesNotExist($path);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Integration/Command/DebugCommandTest.php | tests/Integration/Command/DebugCommandTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Integration\Command;
use App\Model\Author;
use App\Model\Recipe;
use Composer\InstalledVersions;
use Stenope\Bundle\Command\DebugCommand;
use Symfony\Bridge\PhpUnit\ClassExistsMock;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\DependencyInjection\ExpressionLanguage;
class DebugCommandTest extends KernelTestCase
{
/**
* @dataProvider provide testList data
*/
public function testList(string $class, string $expected, array $filters = [], array $orders = []): void
{
$kernel = static::createKernel();
$application = new Application($kernel);
$command = $application->find('debug:stenope:content');
$tester = new CommandTester($command);
$tester->execute([
'class' => $class,
'--filter' => $filters,
'--order' => $orders,
], ['verbosity' => ConsoleOutput::VERBOSITY_VERY_VERBOSE, 'interactive' => false]);
self::assertStringMatchesFormat(<<<TXT
Debug Stenope Contents
======================
"$class" items
--------------%A
$expected
! [NOTE] Found %d items %w
%A
TXT
, $tester->getDisplay(true));
}
public function provide testList data(): iterable
{
yield 'list' => [Author::class,
<<<TXT
* john.doe
* ogi
* tom32i
TXT
];
yield 'order' => [Author::class,
<<<TXT
* john.doe
* ogi
* tom32i
TXT
, [], ['slug'], ];
yield 'order desc:' => [Author::class,
<<<TXT
* tom32i
* ogi
* john.doe
TXT
, [], ['desc:slug'], ];
yield 'order desc (- notation)' => [Author::class,
<<<TXT
* tom32i
* ogi
* john.doe
TXT
, [], ['-slug'], ];
yield 'filter property (data prefix)' => [Author::class,
<<<TXT
* ogi
* tom32i
TXT
, ['_.core'], ];
yield 'filter property (d prefix)' => [Author::class,
<<<TXT
* ogi
* tom32i
TXT
, ['d.core'], ];
yield 'filter property (_ prefix)' => [Author::class,
<<<TXT
* ogi
* tom32i
TXT
, ['_.core'], ];
yield 'filter not' => [Author::class,
<<<TXT
* john.doe
TXT
, ['not _.core'], ];
yield 'filter not (! notation)' => [Author::class,
<<<TXT
* john.doe
TXT
, ['!_.core'], ];
// As of Symfony 6.1, a new contains operator conflicts with our custom contains function:
// https://github.com/symfony/symfony/issues/46406
// Anyway, a Symfony 6.1 user should rather use the operator.
// But we'll keep the function for Symfony < 6.1 users.
if (-1 === version_compare(InstalledVersions::getVersion('symfony/expression-language'), '6.1.0')) {
yield 'filter contains' => [Author::class,
<<<TXT
* ogi
* tom32i
TXT
, ['contains(_.slug, "i")'], ];
}
yield 'filter dates' => [Recipe::class,
<<<TXT
* ogito
* tomiritsu
TXT
, ['_.date > date("2019-01-01") and _.date < date("2020-01-01")'], ];
yield 'filter and order' => [Author::class,
<<<TXT
* tom32i
* ogi
TXT
, ['_.core'], ['desc:slug'], ];
yield 'multiple filters' => [Author::class,
<<<TXT
* ogi
TXT
, ['_.core', '"cooking" in _.tags'], ];
}
public function testShow(): void
{
$kernel = static::createKernel();
$application = new Application($kernel);
$command = $application->find('debug:stenope:content');
$tester = new CommandTester($command);
$tester->execute([
'class' => Author::class,
'id' => 'ogi',
]);
self::assertStringMatchesFormat(
<<<TXT
Debug Stenope Contents
======================
"App\Model\Author" item with id "ogi"
-------------------------------------
App\Model\Author {
+slug: "ogi"
+firstname: "Maxime"
+lastname: "Steinhausser"
+nickname: "ogi"
%A
}
%A
TXT,
$tester->getDisplay(true)
);
}
/**
* @runInSeparateProcess
*/
public function testUnavailableExpressionLanguageHint(): void
{
ClassExistsMock::register(DebugCommand::class);
ClassExistsMock::withMockedClasses([ExpressionLanguage::class => false]);
$kernel = static::createKernel();
$application = new Application($kernel);
$command = $application->find('debug:stenope:content');
$tester = new CommandTester($command);
try {
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('You must install the Symfony ExpressionLanguage component ("symfony/expression-language")');
$tester->execute([
'class' => Author::class,
'--filter' => ['_.core'],
], ['verbosity' => ConsoleOutput::VERBOSITY_VERY_VERBOSE]);
} finally {
ClassExistsMock::withMockedClasses([ExpressionLanguage::class => true]);
}
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/fixtures/app/src/Kernel.php | tests/fixtures/app/src/Kernel.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
/**
* @final
*/
class Kernel extends BaseKernel
{
use MicroKernelTrait;
public function getProjectDir(): string
{
return __DIR__ . '/..';
}
protected function configureContainer(ContainerConfigurator $container): void
{
$container->import('../config/{config}.yaml');
$container->import('../config/{services}.yaml');
}
protected function configureRoutes(RoutingConfigurator $routes): void
{
$routes->import('../config/{routes}.yaml');
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/fixtures/app/src/Model/Author.php | tests/fixtures/app/src/Model/Author.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace App\Model;
class Author
{
public string $slug;
public string $firstname;
public string $lastname;
public string $nickname;
public array $tags;
public bool $core = false;
public \DateTimeInterface $lastModified;
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/fixtures/app/src/Model/Recipe.php | tests/fixtures/app/src/Model/Recipe.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace App\Model;
use Stenope\Bundle\TableOfContent\TableOfContent;
class Recipe
{
public string $title;
public ?string $description = null;
public string $slug;
public string $content;
public ?TableOfContent $tableOfContent = null;
public array $authors;
public array $tags;
public \DateTimeInterface $date;
public \DateTimeInterface $lastModified;
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/fixtures/app/src/Controller/NoIndexController.php | tests/fixtures/app/src/Controller/NoIndexController.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
class NoIndexController extends AbstractController
{
#[Route(path: '/with-noindex', name: 'with_noindex')]
public function withNoIndex()
{
$response = $this->render('noindex/with.html.twig');
$response->headers->set('X-Robots-Tag', 'noindex');
return $response;
}
#[Route(path: '/without-noindex', name: 'without_noindex')]
public function withoutNoIndex()
{
$response = $this->render('noindex/without.html.twig');
$response->headers->set('X-Robots-Tag', 'noindex');
return $response;
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/fixtures/app/src/Controller/DefaultController.php | tests/fixtures/app/src/Controller/DefaultController.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class DefaultController extends AbstractController
{
#[Route(path: '/', name: 'homepage')]
public function index()
{
$response = $this->render('homepage.html.twig');
$response->headers->set('X-Robots-Tag', 'noindex');
return $response;
}
#[Route(path: '/foo.html', name: 'foo_html')]
public function foo()
{
return new Response('foo');
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/fixtures/app/src/Controller/AuthorsController.php | tests/fixtures/app/src/Controller/AuthorsController.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace App\Controller;
use App\Model\Author;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
#[Route(path: '/authors')]
class AuthorsController extends AbstractController
{
#[Route(path: '/{author<[\w.]+>}.json', name: 'author_json', options: ['stenope' => ['sitemap' => false]])]
public function showAsJson(Author $author)
{
return $this->json([
'slug' => $author->slug,
'firstname' => $author->firstname,
'lastname' => $author->lastname,
'nickname' => $author->nickname,
'tags' => $author->tags,
]);
}
#[Route(path: '/{author}', name: 'author')]
public function show(Author $author)
{
return $this->render('author/show.html.twig', [
'author' => $author,
])->setLastModified($author->lastModified);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/fixtures/app/src/Controller/RecipesController.php | tests/fixtures/app/src/Controller/RecipesController.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace App\Controller;
use App\Model\Recipe;
use Stenope\Bundle\ContentManager;
use Stenope\Bundle\HttpKernel\Controller\ArgumentResolver\ContentArgumentResolver;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
#[Route(path: '/recipes')]
class RecipesController extends AbstractController
{
public function __construct(private ContentManager $manager)
{
}
#[Route(path: '/', name: 'recipes')]
public function index()
{
$recipes = $this->manager->getContents(Recipe::class, ['date' => false]);
$lastModified = max(array_map(fn (Recipe $recipe): \DateTimeInterface => $recipe->lastModified, $recipes));
return $this->render('recipe/index.html.twig', [
'recipes' => $recipes,
])->setLastModified($lastModified);
}
/**
* Ensure {@link ContentArgumentResolver} handles nullable arguments properly.
*/
#[Route(path: '/optional-recipe', name: 'optional-recipe', options: ['stenope' => ['ignore' => true]])]
public function optionalRecipe(?Recipe $recipe)
{
return new Response('OK');
}
#[Route(path: '/{recipe}.pdf', name: 'recipe_pdf', options: ['stenope' => ['sitemap' => false]])]
public function downloadAsPdf(Recipe $recipe)
{
$response = $this->file(__DIR__ . '/../../var/pdf/dummy.pdf', "{$recipe->slug}.pdf");
$response->headers->set('Content-Type', 'application/pdf');
return $response;
}
#[Route(path: '/{recipe}', name: 'recipe')]
public function show(Recipe $recipe)
{
return $this->render('recipe/show.html.twig', [
'recipe' => $recipe,
])->setLastModified($recipe->lastModified);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/fixtures/app/public/index.php | tests/fixtures/app/public/index.php | php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false | |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/fixtures/app/config/bundles.php | tests/fixtures/app/config/bundles.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
return [
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
Stenope\Bundle\StenopeBundle::class => ['all' => true],
];
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/fixtures/Unit/Service/Git/bin/git.php | tests/fixtures/Unit/Service/Git/bin/git.php | #!/usr/bin/env php
<?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
/**
* @see Stenope\Bundle\Tests\Unit\Service\Git\LastModifiedFetcherTest
*/
$path = end($argv);
switch ($path) {
case 'fail':
exit(1);
case 'empty':
echo '';
exit(0);
default:
echo '2021-06-14 10:25:47 +0200' . PHP_EOL;
exit(0);
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/ContentManagerTest.php | tests/Unit/ContentManagerTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Stenope\Bundle\Behaviour\ContentManagerAwareInterface;
use Stenope\Bundle\Behaviour\HtmlCrawlerManagerInterface;
use Stenope\Bundle\Behaviour\ProcessorInterface;
use Stenope\Bundle\Content;
use Stenope\Bundle\ContentManager;
use function Stenope\Bundle\ExpressionLanguage\expr;
use Stenope\Bundle\Provider\ContentProviderInterface;
use Stenope\Bundle\Provider\ReversibleContentProviderInterface;
use Stenope\Bundle\ReverseContent\RelativeLinkContext;
use Symfony\Component\Serializer\Encoder\DecoderInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
class ContentManagerTest extends TestCase
{
use ProphecyTrait;
public function testGetContents(): void
{
$manager = new ContentManager(
($decoder = $this->prophesize(DecoderInterface::class))->reveal(),
($denormalizer = $this->prophesize(DenormalizerInterface::class))->reveal(),
$this->prophesize(HtmlCrawlerManagerInterface::class)->reveal(),
[
($provider1 = $this->prophesize(ContentProviderInterface::class))->reveal(),
($provider2 = $this->prophesize(ContentProviderInterface::class))->reveal(),
($provider3 = $this->prophesize(ContentProviderInterface::class))->reveal(),
],
[
($processor = $this->prophesize(ContentManagerAwareProcessorInterface::class))->reveal(),
],
null
);
$provider1->supports('App\Foo')->willReturn(true);
$provider1->listContents()->willReturn([
new Content('foo1', 'App\Foo', 'Foo 1', 'markdown'),
new Content('foo2', 'App\Foo', 'Foo 2', 'html'),
]);
$provider2->supports('App\Foo')->willReturn(false);
$provider2->listContents()->willReturn([
new Content('bar1', 'App\Foo', 'Bar 1', 'markdown'),
]);
$provider3->supports('App\Foo')->willReturn(true);
$provider3->listContents()->willReturn([
new Content('foo3', 'App\Foo', 'Foo 3', 'markdown'),
]);
$decoder
->decode(Argument::type('string'), Argument::type('string'))
->will(fn ($args) => ['content' => $args[0]])
->shouldBeCalledTimes(3)
;
$processor
->__invoke(Argument::type('array'), Argument::type(Content::class))
->shouldBeCalled()
;
$processor->setContentManager($manager)->shouldBeCalledOnce();
$orders = [2, 1, 3];
$denormalizer
->denormalize(Argument::type('array'), 'App\Foo', Argument::any(), Argument::any())
->will(function ($args) use (&$orders) {
[$data] = $args;
$std = new \stdClass();
$std->content = $data['content'];
$std->order = current($orders);
next($orders);
return $std;
})
->shouldBeCalledTimes(3)
;
$getResults = static fn (array $results): array => array_combine(array_keys($results), array_column($results, 'content'));
self::assertSame([
'foo1' => 'Foo 1',
'foo2' => 'Foo 2',
'foo3' => 'Foo 3',
], $getResults($manager->getContents('App\Foo')), 'no sort');
self::assertSame([
'foo2' => 'Foo 2',
'foo1' => 'Foo 1',
'foo3' => 'Foo 3',
], $getResults($manager->getContents('App\Foo', 'order')), 'asc order, directly as string');
self::assertSame([
'foo3' => 'Foo 3',
'foo1' => 'Foo 1',
'foo2' => 'Foo 2',
], $getResults($manager->getContents('App\Foo', ['order' => false])), 'desc order');
self::assertSame([
'foo2' => 'Foo 2',
'foo1' => 'Foo 1',
'foo3' => 'Foo 3',
], $getResults($manager->getContents('App\Foo', fn ($a, $b) => $a->order <=> $b->order)), 'ordered by function');
self::assertSame([
'foo1' => 'Foo 1',
], $getResults($manager->getContents('App\Foo', null, ['content' => 'Foo 1'])), 'filtered by key');
self::assertSame([
'foo1' => 'Foo 1',
], $getResults($manager->getContents(
'App\Foo',
null,
['content' => static fn ($content) => $content === 'Foo 1'],
)), 'filtered with a property function');
self::assertSame([
'foo2' => 'Foo 2',
], $getResults($manager->getContents('App\Foo', null, fn ($foo) => $foo->content === 'Foo 2')), 'filtered by function');
self::assertSame([
'foo2' => 'Foo 2',
], $getResults($manager->getContents('App\Foo', null, expr('_.content === "Foo 2"'))), 'filtered using an expression');
self::assertSame([
'foo2' => 'Foo 2',
], $getResults($manager->getContents('App\Foo', null, '_.content === "Foo 2"')), 'filtered using an expression directly provided as string');
}
public function testReverseContent(): void
{
$manager = new ContentManager(
($decoder = $this->prophesize(DecoderInterface::class))->reveal(),
($denormalizer = $this->prophesize(DenormalizerInterface::class))->reveal(),
($crawlers = $this->prophesize(HtmlCrawlerManagerInterface::class))->reveal(),
[
($provider = $this->prophesize(ContentProviderInterface::class))->reveal(),
($reversibleProvider = $this->prophesize(ReversibleContentProviderInterface::class))->reveal(),
],
[],
);
$provider->supports(Argument::any())->shouldNotBeCalled();
$decoder->decode(Argument::any())->shouldNotBeCalled();
$denormalizer->denormalize(Argument::any())->shouldNotBeCalled();
$context = new RelativeLinkContext(
['path' => '/workspace/project/bar/baz/baz.md'],
'../../foo.md',
);
$reversibleProvider->reverse($context)->shouldBeCalledOnce()
->willReturn($content = new Content('bar1', 'App\Foo', 'Bar 1', 'markdown'))
;
self::assertSame($content, $manager->reverseContent($context), 'content found');
$context = new RelativeLinkContext(
['path' => '/workspace/project/bar/baz/baz.md'],
'../../will-not-find.md',
);
$reversibleProvider->reverse($context)->shouldBeCalledOnce()->willReturn(null);
self::assertNull($manager->reverseContent($context), 'content not found');
}
}
interface ContentManagerAwareProcessorInterface extends ProcessorInterface, ContentManagerAwareInterface
{
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/Routing/ContentUrlResolverTest.php | tests/Unit/Routing/ContentUrlResolverTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit\Routing;
use PHPUnit\Framework\TestCase;
use Prophecy\PhpUnit\ProphecyTrait;
use Stenope\Bundle\Content;
use Stenope\Bundle\Routing\ContentUrlResolver;
use Stenope\Bundle\Routing\ResolveContentRoute;
use Symfony\Component\Routing\RouterInterface;
class ContentUrlResolverTest extends TestCase
{
use ProphecyTrait;
/** @var \Prophecy\Prophecy\ObjectProphecy|RouterInterface */
private $router;
protected function setUp(): void
{
$this->router = $this->prophesize(RouterInterface::class);
}
public function testResolveUrl(): void
{
$generator = new ContentUrlResolver($this->router->reveal(), [
'Foo' => $route = new ResolveContentRoute('show_foo', 'foo'),
]);
$this->router->generate($route->getRoute(), [
$route->getSlug() => 'the-slug',
])->shouldBeCalledOnce()->willReturn($url = '/foo/bar');
self::assertSame($url, $generator->resolveUrl(new Content('the-slug', 'Foo', 'rawContent', 'markdown')));
}
public function testGenerateThrowsOnMissingResolveContentRoute(): void
{
$generator = new ContentUrlResolver($this->router->reveal(), []);
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('No route was defined to resolve type "Foo". Did you configure "stenope.resolve_links" for this type?');
$generator->resolveUrl(new Content('the-slug', 'Foo', 'rawContent', 'markdown'));
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/Processor/ExtractTitleFromHtmlContentProcessorTest.php | tests/Unit/Processor/ExtractTitleFromHtmlContentProcessorTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit\Processor;
use PHPUnit\Framework\TestCase;
use Stenope\Bundle\Content;
use Stenope\Bundle\Processor\ExtractTitleFromHtmlContentProcessor;
use Stenope\Bundle\Service\NaiveHtmlCrawlerManager;
class ExtractTitleFromHtmlContentProcessorTest extends TestCase
{
public function testDefaults(): void
{
$data = [
'content' => <<<HTML
<h1>If you wrestle or remain with a new affirmation, density feels you.</h1>
<h2>Foo</h2>
Lorem ipsum
<h1>Not the first title</h1>
HTML,
];
$processor = new ExtractTitleFromHtmlContentProcessor(new NaiveHtmlCrawlerManager());
$processor->__invoke($data, $this->getDummyContent());
self::assertSame('If you wrestle or remain with a new affirmation, density feels you.', $data['title']);
}
public function testConfiguredProperties(): void
{
$data = [
'html' => <<<HTML
<h1>If you wrestle or remain with a new affirmation, density feels you.</h1>
Lorem ipsum
HTML,
];
$processor = new ExtractTitleFromHtmlContentProcessor(new NaiveHtmlCrawlerManager(), 'html', 'name');
$processor->__invoke($data, $this->getDummyContent());
self::assertSame('If you wrestle or remain with a new affirmation, density feels you.', $data['name']);
}
public function testWithoutH1(): void
{
$data = [
'content' => <<<HTML
<h2>Foo</h2>
Lorem ipsum
HTML,
];
$processor = new ExtractTitleFromHtmlContentProcessor(new NaiveHtmlCrawlerManager());
$processor->__invoke($data, $this->getDummyContent());
self::assertSame($data, $data, 'data are unchanged, no title set.');
}
/**
* @dataProvider provideIgnoresWhenNoProperContentAvailable
*/
public function testIgnoresWhenNoProperContentAvailable(array $data): void
{
$processor = new ExtractTitleFromHtmlContentProcessor(new NaiveHtmlCrawlerManager());
$processor->__invoke($data, $this->getDummyContent());
self::assertSame($data, $data, 'data are unchanged');
}
public function provideIgnoresWhenNoProperContentAvailable()
{
yield 'not content set' => [[]];
yield 'not string' => [['content' => new \stdClass()]];
yield 'not html' => [['content' => '{ "foo" : "bar" }']];
}
public function testIgnoresWhenTitleAlreadySet(): void
{
$data = ['title' => 'Expected title', 'content' => '<h1>Another title</h1>'];
$processor = new ExtractTitleFromHtmlContentProcessor(new NaiveHtmlCrawlerManager());
$processor->__invoke($data, $this->getDummyContent());
self::assertSame($data, $data, 'data are unchanged');
}
private function getDummyContent(): Content
{
return new Content('slug', \stdClass::class, 'content', 'markdown');
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/Processor/ResolveContentLinksProcessorTest.php | tests/Unit/Processor/ResolveContentLinksProcessorTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit\Processor;
use PHPUnit\Framework\TestCase;
use Prophecy\PhpUnit\ProphecyTrait;
use Stenope\Bundle\Content;
use Stenope\Bundle\ContentManagerInterface;
use Stenope\Bundle\Processor\ResolveContentLinksProcessor;
use Stenope\Bundle\ReverseContent\RelativeLinkContext;
use Stenope\Bundle\Routing\ContentUrlResolver;
use Stenope\Bundle\Service\NaiveHtmlCrawlerManager;
class ResolveContentLinksProcessorTest extends TestCase
{
use ProphecyTrait;
public function testResolveLinks(): void
{
$data = [
'content' => <<<HTML
<a href="/absolute-link">Don't change this</a>
<a href="http://external.com">Don't change this</a>
<a href="//external.com">Don't change this</a>
<a href="#anchor">Don't change this</a>
<a href="../other-contents/another-content.md">Another content</a>
<a href="../other-contents/another-content.md#some-anchor">Another content with anchor</a>
HTML,
];
$currentContent = new Content('some-content', 'SomeContent', 'rawContent', 'markdown', null, null, [
'path' => '/workspace/project/content/current.md',
'provider' => 'files',
]);
$urlGenerator = $this->prophesize(ContentUrlResolver::class);
$processor = new ResolveContentLinksProcessor($urlGenerator->reveal(), new NaiveHtmlCrawlerManager());
$manager = $this->prophesize(ContentManagerInterface::class);
$processor->setContentManager($manager->reveal());
$manager->reverseContent(new RelativeLinkContext(
$currentContent->getMetadata(),
'../other-contents/another-content.md',
))->shouldBeCalledTimes(2)->willReturn(
$resolvedContent = new Content('some-content', 'AnotherContent', 'rawContent', 'markdown', null, null, [
'path' => '/workspace/project/other-contents/another-content.md',
])
);
$urlGenerator->resolveUrl($resolvedContent)->shouldBeCalledTimes(2)->willReturn('/other-contents-route-path/another-contents');
$processor->__invoke($data, $currentContent);
self::assertXmlStringEqualsXmlString(<<<HTML
<body>
<a href="/absolute-link">Don't change this</a>
<a href="http://external.com">Don't change this</a>
<a href="//external.com">Don't change this</a>
<a href="#anchor">Don't change this</a>
<a href="/other-contents-route-path/another-contents">Another content</a>
<a href="/other-contents-route-path/another-contents#some-anchor">Another content with anchor</a>
</body>
HTML,
<<<HTML
<body>
{$data['content']}
</body>
HTML,
);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/Processor/LastModifiedProcessorTest.php | tests/Unit/Processor/LastModifiedProcessorTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit\Processor;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Stenope\Bundle\Content;
use Stenope\Bundle\Processor\LastModifiedProcessor;
use Stenope\Bundle\Provider\Factory\LocalFilesystemProviderFactory;
use Stenope\Bundle\Service\Git\LastModifiedFetcher;
class LastModifiedProcessorTest extends TestCase
{
use ProphecyTrait;
public function testFromContent(): void
{
$processor = new LastModifiedProcessor('lastModified');
$data = [];
$content = new Content('slug', 'type', 'content', 'format', new \DateTimeImmutable('2021-06-14 10:25:47 +0200'));
$processor->__invoke($data, $content);
self::assertInstanceOf(\DateTimeImmutable::class, $data['lastModified']);
self::assertEquals($content->getLastModified(), $data['lastModified']);
}
public function testFromGit(): void
{
$gitFetcher = $this->prophesize(LastModifiedFetcher::class);
$gitFetcher->__invoke(Argument::type('string'))
->willReturn($expectedDate = new \DateTimeImmutable('2021-05-10 10:00:00 +0000'))
->shouldBeCalledOnce()
;
$processor = new LastModifiedProcessor('lastModified', $gitFetcher->reveal());
$data = [];
$content = new Content('slug', 'type', 'content', 'format', new \DateTimeImmutable('2021-06-14 10:25:47 +0200'), new \DateTimeImmutable(), [
'provider' => LocalFilesystemProviderFactory::TYPE,
'path' => 'some-path.md',
]);
$processor->__invoke($data, $content);
self::assertInstanceOf(\DateTimeImmutable::class, $data['lastModified']);
self::assertEquals($expectedDate, $data['lastModified']);
}
public function testWontUseGitOnNonFilesProvider(): void
{
$gitFetcher = $this->prophesize(LastModifiedFetcher::class);
$gitFetcher->__invoke(Argument::type('string'))->shouldNotBeCalled();
$processor = new LastModifiedProcessor('lastModified', $gitFetcher->reveal());
$data = [];
$content = new Content('slug', 'type', 'content', 'format', new \DateTimeImmutable('2021-06-14 10:25:47 +0200'));
$processor->__invoke($data, $content);
self::assertInstanceOf(\DateTimeImmutable::class, $data['lastModified']);
self::assertEquals($content->getLastModified(), $data['lastModified']);
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/ExpressionLanguage/ExpressionTest.php | tests/Unit/ExpressionLanguage/ExpressionTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit\ExpressionLanguage;
use PHPUnit\Framework\TestCase;
use function Stenope\Bundle\ExpressionLanguage\expr;
use Stenope\Bundle\ExpressionLanguage\Expression;
use function Stenope\Bundle\ExpressionLanguage\exprOr;
use Symfony\Bridge\PhpUnit\ClassExistsMock;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
class ExpressionTest extends TestCase
{
/**
* @runInSeparateProcess
*/
public function testUnavailableExpressionLanguageHint(): void
{
ClassExistsMock::register(Expression::class);
ClassExistsMock::withMockedClasses([ExpressionLanguage::class => false]);
try {
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('You must install the Symfony ExpressionLanguage component ("symfony/expression-language")');
new Expression('_.foo');
} finally {
ClassExistsMock::withMockedClasses([ExpressionLanguage::class => true]);
}
}
public function testCombineAnd(): void
{
self::assertSame('(_.active) and (!_.outdated)', (string) Expression::combineAnd('_.active', '!_.outdated'));
self::assertSame('(_.active) and (!_.outdated)', (string) expr('_.active', '!_.outdated'));
}
public function testCombineOr(): void
{
self::assertSame('(!_.active) or (_.outdated)', (string) Expression::combineOr('!_.active', '_.outdated'));
self::assertSame('(!_.active) or (_.outdated)', (string) exprOr('!_.active', '_.outdated'));
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
StenopePHP/Stenope | https://github.com/StenopePHP/Stenope/blob/eda6b30e7280aec07e7970f708b9246ac4217cc2/tests/Unit/DependencyInjection/ConfigurationTest.php | tests/Unit/DependencyInjection/ConfigurationTest.php | <?php
/*
* This file is part of the "StenopePHP/Stenope" bundle.
*
* @author Thomas Jarrand <thomas.jarrand@gmail.com>
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
namespace Stenope\Bundle\Tests\Unit\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Stenope\Bundle\DependencyInjection\Configuration;
use Stenope\Bundle\Provider\Factory\LocalFilesystemProviderFactory;
use Symfony\Component\Config\Definition\Processor;
class ConfigurationTest extends TestCase
{
public function testDefaultConfig(): void
{
$processor = new Processor();
$config = $processor->processConfiguration(new Configuration(), [[]]);
self::assertEquals($this->getDefaultConfig(), $config);
}
public function testDirsConfig(): void
{
$processor = new Processor();
$config = $processor->processConfiguration(new Configuration(), [[
'build_dir' => '%kernel.project_dir%/site',
]]);
self::assertEquals([
'build_dir' => '%kernel.project_dir%/site',
] + $this->getDefaultConfig(), $config);
}
public function testCopyConfig(): void
{
$processor = new Processor();
$config = $processor->processConfiguration(new Configuration(), [[
'copy' => [
['src' => '%kernel.project_dir%/public/build', 'dest' => 'dist', 'excludes' => ['*.excluded']],
'%kernel.project_dir%/public/robots.txt',
['src' => '%kernel.project_dir%/public/missing-file', 'fail_if_missing' => false],
],
]]);
self::assertEquals([
'copy' => [
[
'src' => '%kernel.project_dir%/public/build',
'dest' => 'dist',
'excludes' => ['*.excluded'],
'fail_if_missing' => true,
'ignore_dot_files' => true,
],
[
'src' => '%kernel.project_dir%/public/robots.txt',
'dest' => 'robots.txt',
'excludes' => [],
'fail_if_missing' => true,
'ignore_dot_files' => true,
],
[
'src' => '%kernel.project_dir%/public/missing-file',
'dest' => 'missing-file',
'excludes' => [],
'fail_if_missing' => false,
'ignore_dot_files' => true,
],
],
] + $this->getDefaultConfig(), $config);
}
public function testResolveLinksConfig(): void
{
$processor = new Processor();
$config = $processor->processConfiguration(new Configuration(), [[
'resolve_links' => [
'Foo\Bar' => ['route' => 'show_bar', 'slug' => 'bar'],
'Foo\Baz' => ['route' => 'show_baz', 'slug' => 'slug'],
],
]]);
self::assertEquals([
'resolve_links' => [
'Foo\Bar' => ['route' => 'show_bar', 'slug' => 'bar'],
'Foo\Baz' => ['route' => 'show_baz', 'slug' => 'slug'],
],
] + $this->getDefaultConfig(), $config);
}
/**
* @dataProvider providerProvidersConfig
*/
public function testProvidersConfig(array $config, array $expected): void
{
$processor = new Processor();
$config = $processor->processConfiguration(new Configuration(), [$config]);
self::assertEquals($expected + $this->getDefaultConfig(), $config);
}
public function providerProvidersConfig(): iterable
{
yield 'minimal "files" config' => [
'config' => [
'providers' => [
'Foo\Bar' => [
'type' => LocalFilesystemProviderFactory::TYPE,
'config' => [
'path' => 'foo/bar',
],
],
],
],
'expected' => [
'providers' => [
'Foo\Bar' => [
'type' => LocalFilesystemProviderFactory::TYPE,
'config' => [
'path' => 'foo/bar',
'depth' => null,
'patterns' => ['*'],
'excludes' => [],
],
],
],
],
];
yield 'full "files" config' => [
'config' => [
'providers' => [
'Foo\Bar' => [
'type' => LocalFilesystemProviderFactory::TYPE,
'config' => [
'path' => 'foo/bar',
'depth' => '< 2',
'patterns' => ['*.md', '*.html'],
'excludes' => ['excluded.md'],
],
],
],
],
'expected' => [
'providers' => [
'Foo\Bar' => [
'type' => LocalFilesystemProviderFactory::TYPE,
'config' => [
'path' => 'foo/bar',
'depth' => '< 2',
'patterns' => ['*.md', '*.html'],
'excludes' => ['excluded.md'],
],
],
],
],
];
yield 'normalized "files" config' => [
'config' => [
'providers' => [
'Foo\Bar' => [
'type' => LocalFilesystemProviderFactory::TYPE,
'config' => [
'path' => 'foo/bar',
'patterns' => '*.md',
'excludes' => 'excluded.md',
],
],
],
],
'expected' => [
'providers' => [
'Foo\Bar' => [
'type' => LocalFilesystemProviderFactory::TYPE,
'config' => [
'path' => 'foo/bar',
'depth' => null,
'patterns' => ['*.md'],
'excludes' => ['excluded.md'],
],
],
],
],
];
yield 'custom provider config' => [
'config' => [
'providers' => [
'Foo\Bar' => [
'type' => 'custom',
'config' => [
'foo' => 'bar',
'baz' => 'qux',
],
],
],
],
'expected' => [
'providers' => [
'Foo\Bar' => [
'type' => 'custom',
'config' => [
'foo' => 'bar',
'baz' => 'qux',
],
],
],
],
];
yield 'shortcut config' => [
'config' => [
'providers' => [
'Foo\Bar' => [
'path' => 'foo/bar',
'patterns' => '*.md',
'excludes' => 'excluded.md',
],
],
],
'expected' => [
'providers' => [
'Foo\Bar' => [
'type' => LocalFilesystemProviderFactory::TYPE,
'config' => [
'path' => 'foo/bar',
'depth' => null,
'patterns' => ['*.md'],
'excludes' => ['excluded.md'],
],
],
],
],
];
yield 'shortcut "files" config' => [
'config' => [
'providers' => [
'Foo\Bar' => 'foo/bar',
],
],
'expected' => [
'providers' => [
'Foo\Bar' => [
'type' => LocalFilesystemProviderFactory::TYPE,
'config' => [
'path' => 'foo/bar',
'depth' => null,
'patterns' => ['*'],
'excludes' => [],
],
],
],
],
];
}
private function getDefaultConfig(): array
{
return [
'build_dir' => '%kernel.project_dir%/build',
'copy' => [
[
'src' => '%kernel.project_dir%/public',
'dest' => '.',
'excludes' => ['*.php'],
'fail_if_missing' => true,
'ignore_dot_files' => true,
],
],
'providers' => [],
'resolve_links' => [],
'shared_html_crawlers' => false,
'processors' => [
'enabled' => true,
'content_property' => 'content',
'slug' => [
'enabled' => true,
'property' => 'slug',
],
'assets' => [
'enabled' => true,
],
'resolve_content_links' => [
'enabled' => true,
],
'external_links' => [
'enabled' => true,
],
'anchors' => [
'enabled' => true,
'selector' => 'h1, h2, h3, h4, h5',
],
'html_title' => [
'enabled' => true,
'property' => 'title',
],
'html_elements_ids' => [
'enabled' => true,
],
'code_highlight' => [
'enabled' => true,
],
'toc' => [
'enabled' => true,
'property' => 'tableOfContent',
'min_depth' => 2,
'max_depth' => 6,
],
'last_modified' => [
'enabled' => true,
'property' => 'lastModified',
'git' => [
'enabled' => true,
'path' => 'git',
],
],
],
];
}
}
| php | MIT | eda6b30e7280aec07e7970f708b9246ac4217cc2 | 2026-01-05T05:19:06.407340Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.