Compare commits

..

1 Commits

Author SHA1 Message Date
Tim
101de8916e Add setup for frankenphp symfony docker 2025-05-25 15:18:52 +02:00
25 changed files with 523 additions and 309 deletions

34
.dockerignore Normal file
View File

@ -0,0 +1,34 @@
**/*.log
**/*.md
**/*.php~
**/*.dist.php
**/*.dist
**/*.cache
**/._*
**/.dockerignore
**/.DS_Store
**/.git/
**/.gitattributes
**/.gitignore
**/.gitmodules
**/compose.*.yaml
**/compose.*.yml
**/compose.yaml
**/compose.yml
**/docker-compose.*.yaml
**/docker-compose.*.yml
**/docker-compose.yaml
**/docker-compose.yml
**/Dockerfile
**/Thumbs.db
.github/
docs/
public/bundles/
tests/
var/
vendor/
.editorconfig
.env.*.local
.env.local
.env.local.php
.env.test

76
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,76 @@
name: CI
on:
push:
branches:
- main
pull_request: ~
workflow_dispatch: ~
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
tests:
name: Tests
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v4
-
name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
-
name: Build Docker images
uses: docker/bake-action@v6
with:
pull: true
load: true
files: |
compose.yaml
compose.override.yaml
set: |
*.cache-from=type=gha,scope=${{github.ref}}
*.cache-from=type=gha,scope=refs/heads/main
*.cache-to=type=gha,scope=${{github.ref}},mode=max
-
name: Start services
run: docker compose up --wait --no-build
-
name: Check HTTP reachability
run: curl -v --fail-with-body http://localhost
-
name: Check HTTPS reachability
if: false # Remove this line when the homepage will be configured, or change the path to check
run: curl -vk --fail-with-body https://localhost
-
name: Check Mercure reachability
run: curl -vkI --fail-with-body https://localhost/.well-known/mercure?topic=test
-
name: Create test database
if: false # Remove this line if Doctrine ORM is installed
run: docker compose exec -T php bin/console -e test doctrine:database:create
-
name: Run migrations
if: false # Remove this line if Doctrine Migrations is installed
run: docker compose exec -T php bin/console -e test doctrine:migrations:migrate --no-interaction
-
name: Run PHPUnit
if: false # Remove this line if PHPUnit is installed
run: docker compose exec -T php bin/phpunit
-
name: Doctrine Schema Validator
if: false # Remove this line if Doctrine ORM is installed
run: docker compose exec -T php bin/console -e test doctrine:schema:validate
lint:
name: Docker Lint
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v4
-
name: Lint Dockerfile
uses: hadolint/hadolint-action@v3.1.0

77
Dockerfile Normal file
View File

@ -0,0 +1,77 @@
#syntax=docker/dockerfile:1
# Versions
FROM dunglas/frankenphp:1-php8.4 AS frankenphp_upstream
# The different stages of this Dockerfile are meant to be built into separate images
# https://docs.docker.com/develop/develop-images/multistage-build/#stop-at-a-specific-build-stage
# https://docs.docker.com/compose/compose-file/#target
# Base FrankenPHP image
FROM frankenphp_upstream AS frankenphp_base
WORKDIR /app
VOLUME /app/var/
# persistent / runtime deps
# hadolint ignore=DL3008
RUN apt-get update && apt-get install -y --no-install-recommends \
acl \
file \
gettext \
git \
&& rm -rf /var/lib/apt/lists/*
RUN set -eux; \
install-php-extensions \
@composer \
apcu \
intl \
opcache \
zip \
;
# https://getcomposer.org/doc/03-cli.md#composer-allow-superuser
ENV COMPOSER_ALLOW_SUPERUSER=1
# Transport to use by Mercure (default to Bolt)
ENV MERCURE_TRANSPORT_URL=bolt:///data/mercure.db
ENV PHP_INI_SCAN_DIR=":$PHP_INI_DIR/app.conf.d"
###> recipes ###
###> doctrine/doctrine-bundle ###
#RUN install-php-extensions pdo pdo_mysql
RUN docker-php-ext-install pdo pdo_mysql
RUN docker-php-ext-enable pdo pdo_mysql
###< doctrine/doctrine-bundle ###
###< recipes ###
COPY --link frankenphp/conf.d/10-app.ini $PHP_INI_DIR/app.conf.d/
COPY --link --chmod=755 frankenphp/docker-entrypoint.sh /usr/local/bin/docker-entrypoint
COPY --link frankenphp/Caddyfile /etc/frankenphp/Caddyfile
ENTRYPOINT ["docker-entrypoint"]
HEALTHCHECK --start-period=60s CMD curl -f http://localhost:2019/metrics || exit 1
CMD [ "frankenphp", "run", "--config", "/etc/frankenphp/Caddyfile" ]
# Dev FrankenPHP image
FROM frankenphp_base AS frankenphp_dev
ENV APP_ENV=dev
ENV XDEBUG_MODE=off
#ENV FRANKENPHP_WORKER_CONFIG=watch
RUN mv "$PHP_INI_DIR/php.ini-development" "$PHP_INI_DIR/php.ini"
RUN set -eux; \
install-php-extensions \
xdebug \
;
COPY --link frankenphp/conf.d/20-app.dev.ini $PHP_INI_DIR/app.conf.d/
CMD [ "frankenphp", "run", "--config", "/etc/frankenphp/Caddyfile", "--watch" ]

32
compose.override.yaml Normal file
View File

@ -0,0 +1,32 @@
# Development environment override
services:
php:
build:
context: .
target: frankenphp_dev
volumes:
- ./:/app
- ./frankenphp/Caddyfile:/etc/frankenphp/Caddyfile:ro
- ./frankenphp/conf.d/20-app.dev.ini:/usr/local/etc/php/app.conf.d/20-app.dev.ini:ro
# If you develop on Mac or Windows you can remove the vendor/ directory
# from the bind-mount for better performance by enabling the next line:
#- /app/vendor
environment:
#FRANKENPHP_WORKER_CONFIG: watch
MERCURE_EXTRA_DIRECTIVES: demo
# See https://xdebug.org/docs/all_settings#mode
XDEBUG_MODE: "${XDEBUG_MODE:-off}"
APP_ENV: "${APP_ENV:-dev}"
extra_hosts:
# Ensure that host.docker.internal is correctly defined on Linux
- host.docker.internal:host-gateway
tty: true
###> symfony/mercure-bundle ###
###< symfony/mercure-bundle ###
###> doctrine/doctrine-bundle ###
database:
ports:
- "3306"
###< doctrine/doctrine-bundle ###

10
compose.prod.yaml Normal file
View File

@ -0,0 +1,10 @@
# Production environment override
services:
php:
build:
context: .
target: frankenphp_prod
environment:
APP_SECRET: ${APP_SECRET}
MERCURE_PUBLISHER_JWT_KEY: ${CADDY_MERCURE_JWT_SECRET}
MERCURE_SUBSCRIBER_JWT_KEY: ${CADDY_MERCURE_JWT_SECRET}

69
compose.yaml Normal file
View File

@ -0,0 +1,69 @@
version: "3"
services:
php:
image: ${IMAGES_PREFIX:-}app-php
restart: unless-stopped
depends_on:
- database
environment:
SERVER_NAME: ${SERVER_NAME:-localhost}, php:80
MERCURE_PUBLISHER_JWT_KEY: ${CADDY_MERCURE_JWT_SECRET:-!ChangeThisMercureHubJWTSecretKey!}
MERCURE_SUBSCRIBER_JWT_KEY: ${CADDY_MERCURE_JWT_SECRET:-!ChangeThisMercureHubJWTSecretKey!}
# Run "composer require symfony/orm-pack" to install and configure Doctrine ORM
#DATABASE_URL: postgresql://${POSTGRES_USER:-app}:${POSTGRES_PASSWORD:-!ChangeMe!}@database:5432/${POSTGRES_DB:-app}?serverVersion=${POSTGRES_VERSION:-15}&charset=${POSTGRES_CHARSET:-utf8}
DATABASE_URL: mysql://root:password@database:3306/snips?serverVersion=11.7.2-MariaDB
# Run "composer require symfony/mercure-bundle" to install and configure the Mercure integration
MERCURE_URL: ${CADDY_MERCURE_URL:-http://php/.well-known/mercure}
MERCURE_PUBLIC_URL: ${CADDY_MERCURE_PUBLIC_URL:-https://${SERVER_NAME:-localhost}:${HTTPS_PORT:-443}/.well-known/mercure}
MERCURE_JWT_SECRET: ${CADDY_MERCURE_JWT_SECRET:-!ChangeThisMercureHubJWTSecretKey!}
# The two next lines can be removed after initial installation
SYMFONY_VERSION: ${SYMFONY_VERSION:-}
STABILITY: ${STABILITY:-stable}
volumes:
- caddy_data:/data
- caddy_config:/config
ports:
# HTTP
- target: 80
published: ${HTTP_PORT:-80}
protocol: tcp
# HTTPS
- target: 443
published: ${HTTPS_PORT:-443}
protocol: tcp
# HTTP/3
- target: 443
published: ${HTTP3_PORT:-443}
protocol: udp
# Mercure is installed as a Caddy module, prevent the Flex recipe from installing another service
###> symfony/mercure-bundle ###
###< symfony/mercure-bundle ###
###> doctrine/doctrine-bundle ###
database:
image: 'mariadb:latest'
environment:
MARIADB_USER: app
MARIADB_PASSWORD: password
MARIADB_DATABASE: snips
MARIADB_ROOT_PASSWORD: password
ports:
# To allow the host machine to access the ports below, modify the lines below.
# For example, to allow the host to connect to port 3306 on the container, you would change
# "3306" to "3306:3306". Where the first port is exposed to the host and the second is the container port.
# See https://docs.docker.com/compose/compose-file/compose-file-v3/#ports for more information.
- '3306'
volumes:
- database_data:/var/lib/mysql
###< doctrine/doctrine-bundle ###
volumes:
caddy_data:
caddy_config:
###> symfony/mercure-bundle ###
###< symfony/mercure-bundle ###
###> doctrine/doctrine-bundle ###
database_data:
###< doctrine/doctrine-bundle ###

View File

@ -14,7 +14,6 @@
"league/pipeline": "^1.0", "league/pipeline": "^1.0",
"phpdocumentor/reflection-docblock": "^5.6", "phpdocumentor/reflection-docblock": "^5.6",
"phpstan/phpdoc-parser": "^2.1", "phpstan/phpdoc-parser": "^2.1",
"symfony/asset": "7.2.*",
"symfony/console": "*", "symfony/console": "*",
"symfony/dotenv": "*", "symfony/dotenv": "*",
"symfony/flex": "^2", "symfony/flex": "^2",
@ -30,7 +29,6 @@
"symfony/uid": "*", "symfony/uid": "*",
"symfony/validator": "*", "symfony/validator": "*",
"symfony/yaml": "*", "symfony/yaml": "*",
"tempest/highlight": "^2.11",
"twig/extra-bundle": "^2.12|^3.0", "twig/extra-bundle": "^2.12|^3.0",
"twig/twig": "^3.0" "twig/twig": "^3.0"
}, },
@ -84,7 +82,8 @@
"extra": { "extra": {
"symfony": { "symfony": {
"allow-contrib": false, "allow-contrib": false,
"require": "7.2.*" "require": "7.2.*",
"docker": true
} }
} }
} }

129
composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "6bdfa9b2a81e0169ca083ef4d344b876", "content-hash": "4f33fd23b3dd7a367af9ebf6f69f9c0a",
"packages": [ "packages": [
{ {
"name": "dflydev/dot-access-data", "name": "dflydev/dot-access-data",
@ -2370,75 +2370,6 @@
}, },
"time": "2024-09-11T13:17:53+00:00" "time": "2024-09-11T13:17:53+00:00"
}, },
{
"name": "symfony/asset",
"version": "v7.2.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/asset.git",
"reference": "cb926cd59fefa1f9b4900b3695f0f846797ba5c0"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/asset/zipball/cb926cd59fefa1f9b4900b3695f0f846797ba5c0",
"reference": "cb926cd59fefa1f9b4900b3695f0f846797ba5c0",
"shasum": ""
},
"require": {
"php": ">=8.2"
},
"conflict": {
"symfony/http-foundation": "<6.4"
},
"require-dev": {
"symfony/http-client": "^6.4|^7.0",
"symfony/http-foundation": "^6.4|^7.0",
"symfony/http-kernel": "^6.4|^7.0"
},
"type": "library",
"autoload": {
"psr-4": {
"Symfony\\Component\\Asset\\": ""
},
"exclude-from-classmap": [
"/Tests/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Manages URL generation and versioning of web assets such as CSS stylesheets, JavaScript files and image files",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/asset/tree/v7.2.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2024-10-25T15:15:23+00:00"
},
{ {
"name": "symfony/cache", "name": "symfony/cache",
"version": "v7.2.6", "version": "v7.2.6",
@ -6505,64 +6436,6 @@
], ],
"time": "2025-04-04T10:10:11+00:00" "time": "2025-04-04T10:10:11+00:00"
}, },
{
"name": "tempest/highlight",
"version": "2.11.4",
"source": {
"type": "git",
"url": "https://github.com/tempestphp/highlight.git",
"reference": "5a239a92ad6bd3e506ca86a0de3e99ac9dbcb0dd"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/tempestphp/highlight/zipball/5a239a92ad6bd3e506ca86a0de3e99ac9dbcb0dd",
"reference": "5a239a92ad6bd3e506ca86a0de3e99ac9dbcb0dd",
"shasum": ""
},
"require": {
"php": "^8.3"
},
"require-dev": {
"assertchris/ellison": "^1.0.2",
"friendsofphp/php-cs-fixer": "^3.21",
"league/commonmark": "^2.4",
"phpstan/phpstan": "^1.10.0",
"phpunit/phpunit": "^10.0",
"symfony/var-dumper": "^6.4|^7.0"
},
"suggest": {
"assertchris/ellison": "Allows you to analyse sentence complexity",
"league/commonmark": "Adds markdown support"
},
"type": "library",
"autoload": {
"psr-4": {
"Tempest\\Highlight\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Brent Roose",
"email": "brendt@stitcher.io"
}
],
"description": "Fast, extensible, server-side code highlighting",
"support": {
"issues": "https://github.com/tempestphp/highlight/issues",
"source": "https://github.com/tempestphp/highlight/tree/2.11.4"
},
"funding": [
{
"url": "https://github.com/brendt",
"type": "github"
}
],
"time": "2025-03-19T05:38:35+00:00"
},
{ {
"name": "twig/extra-bundle", "name": "twig/extra-bundle",
"version": "v3.21.0", "version": "v3.21.0",

57
frankenphp/Caddyfile Normal file
View File

@ -0,0 +1,57 @@
{
{$CADDY_GLOBAL_OPTIONS}
frankenphp {
{$FRANKENPHP_CONFIG}
}
}
{$CADDY_EXTRA_CONFIG}
{$SERVER_NAME:localhost} {
log {
{$CADDY_SERVER_LOG_OPTIONS}
# Redact the authorization query parameter that can be set by Mercure
format filter {
request>uri query {
replace authorization REDACTED
}
}
}
root /app/public
encode zstd br gzip
mercure {
# Publisher JWT key
publisher_jwt {env.MERCURE_PUBLISHER_JWT_KEY} {env.MERCURE_PUBLISHER_JWT_ALG}
# Subscriber JWT key
subscriber_jwt {env.MERCURE_SUBSCRIBER_JWT_KEY} {env.MERCURE_SUBSCRIBER_JWT_ALG}
# Allow anonymous subscribers (double-check that it's what you want)
anonymous
# Enable the subscription API (double-check that it's what you want)
subscriptions
# Extra directives
{$MERCURE_EXTRA_DIRECTIVES}
}
vulcain
{$CADDY_SERVER_EXTRA_DIRECTIVES}
# Disable Topics tracking if not enabled explicitly: https://github.com/jkarlin/topics
header ?Permissions-Policy "browsing-topics=()"
@phpRoute {
not path /.well-known/mercure*
not file {path}
}
rewrite @phpRoute index.php
@frontController path index.php
php @frontController
file_server {
hide *.php
}
}

View File

@ -0,0 +1,13 @@
expose_php = 0
date.timezone = UTC
apc.enable_cli = 1
session.use_strict_mode = 1
zend.detect_unicode = 0
; https://symfony.com/doc/current/performance.html
realpath_cache_size = 4096K
realpath_cache_ttl = 600
opcache.interned_strings_buffer = 16
opcache.max_accelerated_files = 20000
opcache.memory_consumption = 256
opcache.enable_file_override = 1

View File

@ -0,0 +1,5 @@
; See https://docs.docker.com/desktop/networking/#i-want-to-connect-from-a-container-to-a-service-on-the-host
; See https://github.com/docker/for-linux/issues/264
; The `client_host` below may optionally be replaced with `discover_client_host=yes`
; Add `start_with_request=yes` to start debug session on each request
xdebug.client_host = host.docker.internal

View File

@ -0,0 +1,5 @@
; https://symfony.com/doc/current/performance.html#use-the-opcache-class-preloading
opcache.preload_user = root
opcache.preload = /app/config/preload.php
; https://symfony.com/doc/current/performance.html#don-t-check-php-files-timestamps
opcache.validate_timestamps = 0

67
frankenphp/docker-entrypoint.sh Executable file
View File

@ -0,0 +1,67 @@
#!/bin/sh
set -e
if [ "$1" = 'frankenphp' ] || [ "$1" = 'php' ] || [ "$1" = 'bin/console' ]; then
# Install the project the first time PHP is started
# After the installation, the following block can be deleted
if [ ! -f composer.json ]; then
rm -Rf tmp/
composer create-project "symfony/skeleton $SYMFONY_VERSION" tmp --stability="$STABILITY" --prefer-dist --no-progress --no-interaction --no-install
cd tmp
cp -Rp . ..
cd -
rm -Rf tmp/
composer require "php:>=$PHP_VERSION" runtime/frankenphp-symfony
composer config --json extra.symfony.docker 'true'
if grep -q ^DATABASE_URL= .env; then
echo 'To finish the installation please press Ctrl+C to stop Docker Compose and run: docker compose up --build --wait'
sleep infinity
fi
fi
if [ -z "$(ls -A 'vendor/' 2>/dev/null)" ]; then
composer install --prefer-dist --no-progress --no-interaction
fi
# Display information about the current project
# Or about an error in project initialization
php bin/console -V
if grep -q ^DATABASE_URL= .env.local; then
echo 'Waiting for database to be ready...'
ATTEMPTS_LEFT_TO_REACH_DATABASE=60
until [ $ATTEMPTS_LEFT_TO_REACH_DATABASE -eq 0 ] || DATABASE_ERROR=$(php bin/console dbal:run-sql -q "SELECT 1" 2>&1); do
if [ $? -eq 255 ]; then
# If the Doctrine command exits with 255, an unrecoverable error occurred
ATTEMPTS_LEFT_TO_REACH_DATABASE=0
break
fi
sleep 1
ATTEMPTS_LEFT_TO_REACH_DATABASE=$((ATTEMPTS_LEFT_TO_REACH_DATABASE - 1))
echo "Still waiting for database to be ready... Or maybe the database is not reachable. $ATTEMPTS_LEFT_TO_REACH_DATABASE attempts left."
done
if [ $ATTEMPTS_LEFT_TO_REACH_DATABASE -eq 0 ]; then
echo 'The database is not up or not reachable:'
echo "$DATABASE_ERROR"
exit 1
else
echo 'The database is now ready and reachable'
fi
if [ "$( find ./migrations -iname '*.php' -print -quit )" ]; then
echo 'Migrating database...'
php bin/console doctrine:migrations:migrate --no-interaction --all-or-nothing
fi
fi
setfacl -R -m u:www-data:rwX -m u:"$(whoami)":rwX var
setfacl -dR -m u:www-data:rwX -m u:"$(whoami)":rwX var
echo 'PHP app ready!'
fi
exec docker-php-entrypoint "$@"

View File

@ -1,87 +0,0 @@
pre, code {
color: #1f2328;
background-color: #ffffff;
}
.hl-keyword {
color: #cf222e;
}
.hl-property {
color: #8250df;
}
.hl-attribute {
font-style: italic;
}
.hl-type {
color: #EA4334;
}
.hl-generic {
color: #9d3af6;
}
.hl-value {
color: #0a3069;
}
.hl-literal {
color: #0a3069;
}
.hl-number {
color: #0a3069;
}
.hl-variable {
color: #953800;
}
.hl-comment {
color: #6e7781;
}
.hl-blur {
filter: blur(2px);
}
.hl-strong {
font-weight: bold;
}
.hl-em {
font-style: italic;
}
.hl-addition {
display: inline-block;
min-width: 100%;
background-color: #00FF0022;
}
.hl-deletion {
display: inline-block;
min-width: 100%;
background-color: #FF000011;
}
.hl-gutter {
display: inline-block;
font-size: 0.9em;
color: #555;
padding: 0 1ch;
margin-right: 1ch;
user-select: none;
}
.hl-gutter-addition {
background-color: #34A853;
color: #fff;
}
.hl-gutter-deletion {
background-color: #EA4334;
color: #fff;
}

View File

@ -22,8 +22,7 @@ class SnipController extends AbstractController
{ {
public function __construct( public function __construct(
private readonly SnipRepository $repository, private readonly SnipRepository $repository,
) { ) {}
}
#[Route('/', name: '_index')] #[Route('/', name: '_index')]
public function index(#[MapQueryCached] SnipFilterRequest $request): Response public function index(#[MapQueryCached] SnipFilterRequest $request): Response
@ -67,7 +66,8 @@ class SnipController extends AbstractController
->setVary(['Accept', 'Accept-Encoding']) ->setVary(['Accept', 'Accept-Encoding'])
->setEtag(md5($response->getContent())) ->setEtag(md5($response->getContent()))
->setTtl(3600) ->setTtl(3600)
->setClientTtl(300); ->setClientTtl(300)
;
if (!$request->isNoCache()) { if (!$request->isNoCache()) {
$response->isNotModified($request); $response->isNotModified($request);
@ -90,9 +90,11 @@ class SnipController extends AbstractController
$this->addFlash('error', 'Snip is not the latest version, changes will not be saved.'); $this->addFlash('error', 'Snip is not the latest version, changes will not be saved.');
} }
$form = $this->createForm(SnipType::class, $snip) $form = $this->createForm(SnipType::class, $snip);
->add('Save', SubmitType::class); $form->add('Save', SubmitType::class);
$form->get('content')->setData($snip->getActiveText()); if ($snip->getId()) {
$form->get('content')->setData($snip->getActiveText());
}
$form->handleRequest($request); $form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) { if ($form->isSubmitted() && $form->isValid()) {
@ -126,31 +128,10 @@ class SnipController extends AbstractController
{ {
$snip = new Snip(); $snip = new Snip();
$snip->setCreatedAtNow() $snip->setCreatedAtNow()
->setCreatedBy($this->getUser()); ->setCreatedBy($this->getUser())
;
$form = $this->createForm(SnipType::class, $snip); return $this->edit($snip, $request, $contentService);
$form->add('Create', SubmitType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->repository->save($snip);
$contentService->update(
$snip,
$form->get('content')->getData(),
$form->get('contentName')->getData()
);
$this->addFlash('success', sprintf('Snip "%s" created', $snip));
return $this->redirectToRoute('snip_single', [
'snip' => $snip->getId(),
]);
}
return $this->render('snip/create.html.twig', [
'snip' => $snip,
'form' => $form->createView(),
]);
} }
#[Route('/delete/{snip}', name: '_delete')] #[Route('/delete/{snip}', name: '_delete')]

View File

@ -20,7 +20,7 @@ abstract class AbstractParser implements ParserInterface
try { try {
return $this->safeParseView($content); return $this->safeParseView($content);
} catch (\Exception $exception) { } catch (\Exception $exception) {
return sprintf('<pre><code>%s</code></pre>', htmlspecialchars($exception->getMessage())); return sprintf('<pre><code class="hljs">%s</code></pre>', htmlspecialchars($exception->getMessage()));
} }
} }

View File

@ -17,9 +17,9 @@ class GenericParser extends AbstractParser
$builder = new PipelineBuilder(); $builder = new PipelineBuilder();
$pipeline = $builder $pipeline = $builder
->add(new HtmlEscapeStage()) ->add(new HtmlEscapeStage())
// ->add(new ReplaceBlocksStage('<pre>', '</pre>', '```'))
// ->add(new ReplaceBlocksStage('<code>', '</code>', '``'))
->add(new ReplaceStage(PHP_EOL, '<br>')) ->add(new ReplaceStage(PHP_EOL, '<br>'))
->add(new ReplaceBlocksStage('<pre><code class="hljs">', '</code></pre>', '```'))
->add(new ReplaceBlocksStage('<code class="hljs">', '</code>', '``'))
->add($this->referenceStage) ->add($this->referenceStage)
->add($this->includeStage) ->add($this->includeStage)
->build() ->build()
@ -27,4 +27,13 @@ class GenericParser extends AbstractParser
return $pipeline->process($content); return $pipeline->process($content);
} }
public function parseRaw(string $content): string
{
return str_replace(
['```', '``'],
'',
$content
);
}
} }

View File

@ -4,14 +4,13 @@ namespace App\Service\SnipParser\Generic;
use InvalidArgumentException; use InvalidArgumentException;
use League\Pipeline\StageInterface; use League\Pipeline\StageInterface;
use Tempest\Highlight\Highlighter;
readonly class ReplaceBlocksStage implements StageInterface class ReplaceBlocksStage implements StageInterface
{ {
public function __construct( public function __construct(
public string $openTag = '<pre><code>', public readonly string $openTag = '<pre><code>',
public string $closeTag = '</code></pre>', public readonly string $closeTag = '</code></pre>',
public string $delimiter = '```' public readonly string $delimiter = '```'
) {} ) {}
public function __invoke(mixed $payload): string public function __invoke(mixed $payload): string
@ -27,9 +26,8 @@ readonly class ReplaceBlocksStage implements StageInterface
{ {
$pattern = sprintf('/%s(.+?)%s/s', preg_quote($this->delimiter), preg_quote($this->delimiter)); $pattern = sprintf('/%s(.+?)%s/s', preg_quote($this->delimiter), preg_quote($this->delimiter));
$highlighter = new Highlighter()->withGutter(); return preg_replace_callback($pattern, function ($matches) {
return preg_replace_callback($pattern, function ($matches) use ($highlighter) { return $this->openTag . trim($matches[1]) . $this->closeTag;
return $this->openTag . $highlighter->parse(trim($matches[1]), 'php') . $this->closeTag;
}, $text); }, $text);
} }
} }

View File

@ -3,14 +3,11 @@
namespace App\Service\SnipParser\Html; namespace App\Service\SnipParser\Html;
use App\Service\SnipParser\AbstractParser; use App\Service\SnipParser\AbstractParser;
use Tempest\Highlight\Highlighter;
class HtmlParser extends AbstractParser class HtmlParser extends AbstractParser
{ {
public function safeParseView(string $content): string public function safeParseView(string $content): string
{ {
$highlighter = new Highlighter()->withGutter(); return sprintf('<pre><code class="hljs">%s</code></pre>', htmlspecialchars($content));
return '<pre data-lang="html" class="notranslate">' . $highlighter->parse($content, 'html') . '</pre>';
} }
} }

View File

@ -6,16 +6,11 @@ use App\Repository\SnipRepository;
use App\Service\SnipParser\AbstractParser; use App\Service\SnipParser\AbstractParser;
use League\CommonMark\Event\DocumentParsedEvent; use League\CommonMark\Event\DocumentParsedEvent;
use League\CommonMark\Extension\CommonMark\Node\Inline\Link; use League\CommonMark\Extension\CommonMark\Node\Inline\Link;
use League\CommonMark\Extension\DefaultAttributes\DefaultAttributesExtension;
use League\CommonMark\Extension\Footnote\FootnoteExtension;
use League\CommonMark\Extension\Table\Table;
use League\CommonMark\GithubFlavoredMarkdownConverter; use League\CommonMark\GithubFlavoredMarkdownConverter;
use League\CommonMark\Node\Inline\Text; use League\CommonMark\Node\Inline\Text;
use League\CommonMark\Node\Query; use League\CommonMark\Node\Query;
use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Routing\RouterInterface; use Symfony\Component\Routing\RouterInterface;
use Tempest\Highlight\CommonMark\HighlightExtension;
use Tempest\Highlight\Highlighter;
class MarkdownParser extends AbstractParser class MarkdownParser extends AbstractParser
{ {
@ -26,25 +21,8 @@ class MarkdownParser extends AbstractParser
public function safeParseView(string $content): string public function safeParseView(string $content): string
{ {
$config = [ $converter = new GithubFlavoredMarkdownConverter();
'default_attributes' => [ $converter->getEnvironment()->addEventListener(DocumentParsedEvent::class, $this->documentParsed(...));
Table::class => [
'class' => 'table table-hover',
],
Link::class => [
'class' => 'btn btn-sm btn-secondary',
],
],
];
$converter = new GithubFlavoredMarkdownConverter($config);
$converter
->getEnvironment()
->addExtension(new HighlightExtension(new Highlighter()->withGutter()))
->addExtension(new FootnoteExtension())
->addExtension(new DefaultAttributesExtension())
->addEventListener(DocumentParsedEvent::class, $this->documentParsed(...))
;
return $converter->convert($content); return $converter->convert($content);
} }
@ -54,17 +32,11 @@ class MarkdownParser extends AbstractParser
$linkNodes = new Query() $linkNodes = new Query()
->where(Query::type(Link::class)) ->where(Query::type(Link::class))
->findAll($document) ->findAll($document);
;
/** @var Link $linkNode */
foreach ($linkNodes as $linkNode) { foreach ($linkNodes as $linkNode) {
$url = $linkNode->getUrl(); $url = $linkNode->getUrl();
if (!is_numeric($url)) {
continue;
}
$snip = $this->snipRepo->find($url); $snip = $this->snipRepo->find($url);
if ($snip === null) { if ($snip === null) {
continue; continue;

View File

@ -14,7 +14,7 @@
] ]
}, },
"doctrine/doctrine-migrations-bundle": { "doctrine/doctrine-migrations-bundle": {
"version": "3.2", "version": "3.4",
"recipe": { "recipe": {
"repo": "github.com/symfony/recipes", "repo": "github.com/symfony/recipes",
"branch": "main", "branch": "main",
@ -39,7 +39,7 @@
] ]
}, },
"symfony/debug-bundle": { "symfony/debug-bundle": {
"version": "6.2", "version": "7.2",
"recipe": { "recipe": {
"repo": "github.com/symfony/recipes", "repo": "github.com/symfony/recipes",
"branch": "main", "branch": "main",
@ -95,7 +95,7 @@
] ]
}, },
"symfony/maker-bundle": { "symfony/maker-bundle": {
"version": "1.48", "version": "1.63",
"recipe": { "recipe": {
"repo": "github.com/symfony/recipes", "repo": "github.com/symfony/recipes",
"branch": "main", "branch": "main",
@ -161,8 +161,7 @@
"branch": "main", "branch": "main",
"version": "7.0", "version": "7.0",
"ref": "0df5844274d871b37fc3816c57a768ffc60a43a5" "ref": "0df5844274d871b37fc3816c57a768ffc60a43a5"
}, }
"files": []
}, },
"symfony/validator": { "symfony/validator": {
"version": "7.2", "version": "7.2",
@ -190,6 +189,6 @@
] ]
}, },
"twig/extra-bundle": { "twig/extra-bundle": {
"version": "v3.5.1" "version": "v3.21.0"
} }
} }

View File

@ -53,4 +53,22 @@
</p> </p>
</div> </div>
</div> </div>
{% endblock %}
{% block css %}
{{ parent() }}
<link rel="stylesheet"
href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css">
{% endblock %}
{% block js %}
{{ parent() }}
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<script>
const codeBlocks = document.querySelectorAll('code.hljs');
codeBlocks.forEach((block) => {
hljs.highlightElement(block);
});
</script>
{% endblock %} {% endblock %}

View File

@ -1,7 +0,0 @@
{% extends 'base/one.column.html.twig' %}
{% set title = 'Create Snip' %}
{% block body %}
{{ form(form) }}
{% endblock %}

View File

@ -1,6 +1,10 @@
{% extends 'snip/base.html.twig' %} {% extends 'snip/base.html.twig' %}
{% set title %}{{ snip }} - Edit{% endset %} {% if snip.id %}
{% set title %}{{ snip }} - Edit{% endset %}
{% else %}
{% set title = 'Create Snip' %}
{% endif %}
{% set active = 'edit' %} {% set active = 'edit' %}
{% block buttons %} {% block buttons %}

View File

@ -15,5 +15,18 @@
{% block css %} {% block css %}
{{ parent() }} {{ parent() }}
<link rel="stylesheet" href="{{ asset('github-light-default.css') }}"> <link rel="stylesheet"
href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css">
{% endblock %} {% endblock %}
{% block js %}
{{ parent() }}
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<script>
const codeBlocks = document.querySelectorAll('code.hljs');
codeBlocks.forEach((block) => {
hljs.highlightElement(block);
});
</script>
{% endblock %}