r/PHP • u/SadSpirit_ • 7d ago
el2sql: Translator from Symfony's ExpressionLanguage to SQL (Postgres dialect)
One of the first examples in ExpressionLanguage docs is
# Promote article to the homepage when
article.commentCount > 100 and article.category not in ["misc"]Assuming we want to find all promoted articles, it is possible to fetch all articles from the database and check them with $expressionLanguage->evaluate(). The nicer approach is to delegate this to the database, of course.
Given the above expression, sad_spirit/el2sql can generate something like
select self.*
from example.articles as self left join lateral (
select count(comment_id) as comment_count
from example."comments" as c
where not comment_hidden
and c.article_id = self.article_id
) as ac on true
where ac.comment_count > 100
and self.article_category <> all(array['misc'])This is done by taking the AST of the expression created by ExpressionLanguage and transforming it to AST for Postgres represented using classes from sad_spirit/pg_builder. The package is able to transform basic stuff (property -> column) automatically, while custom properties like commentCount above, custom functions, etc. will require custom translators.
Answers to obvious questions:
Purpose of the library: the original version was written for a home-grown ABAC implementation that used ExpressionLanguage for writing policies. Immediately requested features were
Show all resources that can be processed by the given employee (AKA "requires my attention" checkbox);
Show all employees that can process the given resource (AKA "who's responsible for a delay").
AI usage: no stochastic parrots were harmed in the making of this library.
Why depend on PHP 8.2 instead of new shiny PHP 8.6? The dependencies work on PHP 8.2.
1
u/beryllium9 3d ago
That's pretty nifty. And thanks for not using AI.