aymericcucherousset / d2-symfony
Render D2 diagrams (d2lang.com) in Symfony & Twig: local binary or Kroki, cached, profiler-ready.
Package info
github.com/aymericcucherousset/d2-symfony
Type:symfony-bundle
pkg:composer/aymericcucherousset/d2-symfony
Requires
- php: >=8.2
- psr/cache: ^2.0 || ^3.0
- psr/log: ^2.0 || ^3.0
- symfony/config: ^6.4 || ^7.4 || ^8.0
- symfony/dependency-injection: ^6.4 || ^7.4 || ^8.0
- symfony/http-kernel: ^6.4 || ^7.4 || ^8.0
- symfony/process: ^6.4 || ^7.4 || ^8.0
Requires (Dev)
- ext-phar: *
- ext-zlib: *
- deptrac/deptrac: ^4.7
- friendsofphp/php-cs-fixer: ^3.64
- league/commonmark: ^2.6
- nyholm/symfony-bundle-test: ^3.1
- phpstan/extension-installer: ^1.4
- phpstan/phpstan: ^2.1
- phpstan/phpstan-phpunit: ^2.0
- phpstan/phpstan-symfony: ^2.0
- phpunit/phpunit: ^11.5
- symfony/cache: ^6.4 || ^7.4 || ^8.0
- symfony/cache-contracts: ^2.5 || ^3.0
- symfony/console: ^6.4 || ^7.4 || ^8.0
- symfony/filesystem: ^6.4 || ^7.4 || ^8.0
- symfony/framework-bundle: ^6.4 || ^7.4 || ^8.0
- symfony/http-client: ^6.4 || ^7.4 || ^8.0
- symfony/http-client-contracts: ^3.4
- symfony/stopwatch: ^6.4 || ^7.4 || ^8.0
- symfony/twig-bundle: ^6.4 || ^7.4 || ^8.0
- symfony/validator: ^6.4 || ^7.4 || ^8.0
- symfony/web-profiler-bundle: ^6.4 || ^7.4 || ^8.0
- twig/extra-bundle: ^3.21
- twig/markdown-extra: ^3.21
- twig/twig: ^3.21
Suggests
- ext-phar: To download the d2 binary with d2:download
- ext-zlib: To download the d2 binary with d2:download
- league/commonmark: To render ```d2 code blocks in Markdown (with twig/extra-bundle and twig/markdown-extra for the |markdown_to_html filter)
- symfony/console: For the d2:download and d2:render commands
- symfony/http-client: To download the d2 binary with d2:download, and for the Kroki renderer
- symfony/twig-bundle: To render diagrams in templates with the |d2 filter
- symfony/web-profiler-bundle: To inspect rendered diagrams in the D2 profiler panel
Provides
None
Conflicts
- league/commonmark: <2.6
- symfony/console: <6.4 || >=7.0,<7.4
- symfony/http-client: <6.4 || >=7.0,<7.4
- symfony/http-client-contracts: <3.4
- twig/twig: <3.21
Replaces
None
README
Write D2 diagrams as text in your Twig templates and get inline SVG, rendered by Symfony.
Note
Early development (0.7): the API may change between minor versions. See the roadmap. 0.7 is the last minor release before 1.0 freezes the API: feedback is welcome.
This diagram was rendered by the bundle itself from docs/example.d2.
Features
- Twig:
{{ source|d2 }}filter,{% d2 %}…{% endd2 %}tag and{{ d2_file('diagrams/architecture.d2') }}function, all outputting inline SVG - Markdown:
```d2code blocks rendered by|markdown_to_html(league/commonmark) - PNG and PDF output, and
|d2_data_urifor HTML-to-PDF generators and emails - Local
d2binary, downloaded and verified bybin/console d2:download, or a Kroki server, or both with a fallback - Cached rendering, static diagrams pre-rendered at
cache:warmup untrustedoption for diagrams written by users: blocks the d2 features that read server files or inject markup (security)- Typed PHP API (
Renderer,Diagram,RenderOptions,ThemeandLayoutenums),d2:rendercommand and a Web Profiler panel
Requirements
- PHP 8.2 or later
- Symfony 6.4, 7.4 or 8.x
- Twig 3.21 or later (
symfony/twig-bundle), for the Twig filters, function and tag - The
d2binary, downloaded for you bybin/console d2:download(Linux, macOS and Windows on amd64 or arm64), or a Kroki server
Installation
composer require aymericcucherousset/d2-symfony symfony/http-client bin/console d2:download
With Symfony Flex, the bundle is registered automatically; otherwise add Aymericcucherousset\D2Symfony\D2SymfonyBundle::class => ['all' => true] to config/bundles.php. Add /var/d2/ to your .gitignore, and run d2:download when you deploy too. No configuration is required.
symfony/http-client is only needed by d2:download and the Kroki renderer, and symfony/console by the commands: with d2 installed yourself, the bundle works with the local binary and Twig alone (see Requirements).
Usage
{{ 'shop -> payment: checkout'|d2 }}
{% d2 with { theme: 200, layout: 'elk' } %}
user -> app: {{ protocol }}
app -> db
{% endd2 %}
{{ d2_file('diagrams/architecture.d2', { sketch: true }) }}
<img src="{{ architecture|d2_data_uri }}" alt="Architecture"> {# PNG, e.g. for PDF generators #}
use Aymericcucherousset\D2Symfony\Core\Diagram; use Aymericcucherousset\D2Symfony\Core\Renderer; use Aymericcucherousset\D2Symfony\Core\RenderOptions; use Aymericcucherousset\D2Symfony\Core\Theme; final class ArchitectureDiagram { public function __construct(private Renderer $renderer) // autowired { } public function svg(): string { return $this->renderer->render(new Diagram('a -> b', new RenderOptions(theme: Theme::DarkMauve))); } }
bin/console d2:render diagram.d2 -o public/diagram.svg --layout=elk
Documentation
The full documentation is in docs/:
- Installation and first diagram
- Usage: Twig, render options, PHP API, command line, Web Profiler, errors
- Configuration reference
- Guides: caching and production, rendering with Kroki, diagrams in Markdown, PNG, PDF and emails, rendering untrusted D2 sources
- Troubleshooting
Backward compatibility
From 1.0, the bundle follows Semantic Versioning (MAJOR.MINOR.PATCH):
- patch releases only fix bugs and security issues;
- minor releases add features and may deprecate some, but never break the public API;
- major releases may break it, and remove what was deprecated; the CHANGELOG lists each break with the change to make.
Public API
The promise covers:
- the
Corenamespace:Renderer,VersionAwareRendererand the renderers,Diagram,RenderOptions, theTheme,LayoutandFormatenums and the exceptions; D2SymfonyBundleand its configuration, thed2.rendererservice (autowired asRenderer) and thecache.d2pool;- the Twig
|d2and|d2_data_urifilters, thed2_file()function and the{% d2 %}tag; D2CommonMarkExtension(serviced2.commonmark.extension);- the
d2:downloadandd2:rendercommands and their options.
For these, a minor release never removes or renames a class, method, constant, enum case, configuration option, service, Twig name or command option, never changes their meaning, and never changes a signature in a way that breaks callers. Parameter names are covered too, since RenderOptions is meant to be built with named arguments. Adding optional parameters, options, enum cases or exception classes is not a break.
Classes are final: use them, don't extend them. The Renderer and VersionAwareRenderer interfaces can be implemented, and get no new method before the next major version. The exception interfaces (D2Exception, RendererUnavailableException) are for catch blocks.
Not covered
These may change in any release:
- classes and methods marked
@internal, and thed2.*service IDs not listed above; - the exact SVG, PNG and PDF output, which depends on d2: a minor release may update the d2 version installed by
d2:download(d2.binary.version) to a newer one tested with the bundle; - cache keys: after an upgrade, diagrams may be rendered again once;
- exception and log messages, the command output and the Web Profiler panel.
Support for a PHP or Symfony version that reached its end of life may be dropped in a minor release: Composer then keeps the previous version of the bundle on applications that still use it.
Deprecations
A feature to be removed is first deprecated in a minor release: it keeps working, is marked @deprecated, triggers a PHP deprecation (shown by the Symfony profiler and PHPUnit) and is listed under "Deprecated" in the CHANGELOG with its replacement. It is only removed in the next major release.
Before 1.0, minor releases (0.x) could break the API; these breaks are flagged BC break in the CHANGELOG.
Roadmap
| Milestone | Goal |
|---|---|
| v0.1.0 — Working core | Render a D2 diagram to SVG from Twig using a manually installed binary. |
| v0.2.0 — Caching & Twig ergonomics | Cached rendering, {% d2 %} tag, readable errors. |
| v0.3.0 — Frictionless installation | The d2 binary is downloaded automatically. |
| v0.4.0 — Kroki renderer | HTTP renderer for environments where binaries cannot run. |
| v0.5.0 — Developer experience | Profiler panel, rendering CLI, fully typed options. |
| v0.6.0 — Formats & integrations | PNG/PDF output, .d2 files, Markdown code blocks. |
| v0.7.0 — Hardening & feedback | Untrusted sources, production load, feedback before freezing the API. |
| v1.0.0 — Stabilization | Frozen API, complete documentation, release. |
Development
composer install composer ci # PHP-CS-Fixer + PHPStan + Deptrac + PHPUnit composer cs-fix # apply coding standards composer coverage # HTML coverage report in var/coverage/ (needs pcov or Xdebug)
Deptrac keeps src/Core isolated so it can become a standalone library: Core may only depend on symfony/process, symfony/http-client-contracts, psr/cache and psr/log, and never on the bundle code (composer deptrac).
Integration tests need the d2 binary on your PATH; they are skipped otherwise (set D2_REQUIRED=1 to make them fail instead).
CI runs PHPUnit against Symfony 6.4, 7.4 and 8.x on every PHP version each one supports (8.2 to 8.6) with the highest dependencies, plus a --prefer-lowest job for each Symfony version on its lowest PHP version. To test one Symfony version locally, restrict it with Symfony Flex:
composer global config allow-plugins.symfony/flex true && composer global require symfony/flex SYMFONY_REQUIRE='7.4.*' composer update # add --prefer-lowest for the lowest versions
A separate CI job measures the code coverage with the d2 binary installed, so integration tests count. It fails when less than 95 % of the lines of src/ are covered, writes a summary on the workflow run page and uploads the report to Codecov, which comments the coverage and its diff against main on pull requests.
To regenerate the README diagram after editing docs/example.d2:
d2 --pad=20 docs/example.d2 docs/images/example.svg
Changelog
The CHANGELOG follows Keep a Changelog. Every pull request with a user-facing change adds an entry under [Unreleased] (Added, Changed, Deprecated, Removed, Fixed or Security), with a link to its issue; BC breaks are flagged BC break and say what to change.
Releasing
-
Open a
chore: release X.Y.Zpull request that:- moves the
[Unreleased]entries to a new## [X.Y.Z] - YYYY-MM-DDsection, and updates the[Unreleased]and[X.Y.Z]compare links at the bottom of the file; - points the
dev-mainbranch alias ofcomposer.jsonto the next minor version (X.(Y+1).x-dev) when it changes.
- moves the
-
Once it is merged, tag
mainand push the tag:git switch main && git pull git tag -a vX.Y.Z -m "vX.Y.Z — <milestone name>" git push origin vX.Y.Z
-
The Release workflow then checks that the tag is on
mainand that the CHANGELOG has its section, publishes the GitHub release, named after thevX.Y.Z — …milestone, with the notes of that section and a link to the full changelog, and closes the milestone once its issues are closed. AvX.Y.Z-rc.Ntag, with its own[X.Y.Z-rc.N]section, publishes a pre-release and leaves the milestone open. Packagist picks the new tag up automatically.
Preview the notes before tagging with .github/scripts/release-notes.sh vX.Y.Z: it fails like the workflow when the section is missing. A failed run can be re-run from the Actions tab; it updates the release when it already exists. If the tag itself is wrong (e.g. pushed before the release pull request was merged), delete it right away (git push --delete origin vX.Y.Z, then git tag -d vX.Y.Z) and tag again: never move a tag once Packagist has published it.
License
MIT — see LICENSE.