Search by

adachsoft / dynamic-tables-report

Arkadiusz Adach

A configurable reporting engine for JSON-defined reports, dataset pipelines, and pluggable row sources.

Package info

gitlab.com/a.adach/dynamic-tables-report

Issues

pkg:composer/adachsoft/dynamic-tables-report

Statistics

Installs: 7

Dependents: 0

Suggesters: 0

Stars: 0

v0.1.0 2026-11-23 15:35 UTC

This package is auto-updated.

Last update: 2026-11-23 14:36:14 UTC


README

Configurable reports. A report is a JSON definition – parameters, datasets and sections – and running it returns values that are ready to be shown: nothing is left to calculate for whoever presents it.

The library knows nothing about any particular application and nothing about how data is stored. Rows come from a Source\RowSourceInterface (two methods: rows of a table, rows of a view), so it can sit on top of dynamic tables, SQL or anything else. HTTP is provided by adachsoft/dynamic-tables-symfony-bundle.

Namespace: AdachSoft\DynamicTablesReport

Requirements

  • PHP >= 8.3
  • adachsoft/rule-evaluator-contract ^0.2
  • Optional: adachsoft/rule-evaluator-expression-language ^0.2 for Symfony ExpressionLanguage support

Installation

Install the library with Composer:

composer require adachsoft/dynamic-tables-report

The expression-language adapter is optional. Install it when using Symfony ExpressionLanguage for report expressions:

composer require adachsoft/rule-evaluator-expression-language

Usage

$clock = new SystemClock('Europe/Warsaw');
$expressionEvaluator = new ExpressionEvaluator(
    (new ExpressionLanguageRuleEvaluatorFactory())->createExpressionEvaluator([
        new ReportFunctionProvider($clock),
    ]),
);
$stepRegistry = StepRegistry::withBuiltInSteps($expressionEvaluator, new ValueComparator('pl'));
$reportDefinitionParser = new ReportDefinitionParser($stepRegistry, $expressionEvaluator);
$reportRunner = new ReportRunner($rowSource, $stepRegistry, $expressionEvaluator, new ParameterResolver($expressionEvaluator));

$reportFacade = new ReportFacade(new JsonDirectoryReportDefinitionRepository('/var/reports'), $reportDefinitionParser, $reportRunner);

$reportFacade->save($definition);                                   // validates completely, then stores
$result = $reportFacade->run('stock', ['from' => '2026-11-01']);    // ReportResultDto
$json = (new ReportResultSerializer())->serialize($result);

Installer\ReportInstaller::installFromDirectory() installs the reports an application ships with (*.json, one definition per file). Existing reports are left alone unless replacing is requested.

Report definition

{
  "name": "stock",
  "title": "Stock",
  "description": "Quantity of every item in stock",
  "orientation": "portrait",
  "subtitle": "'As of ' ~ today()",
  "note": "Negative stock means an issue without a receipt.",
  "header": {"dataset": "company", "lines": ["name", "address"]},
  "parameters": [
    {"name": "from", "type": "date", "label": "From", "default": "startOfMonth(today())", "required": true}
  ],
  "datasets": {
    "company": {"source": {"table": "company"}},
    "received": {"source": {"table": "receipts"}, "steps": [
      {"type": "select", "fields": {"item": "item", "received": "number(packages) * number(content)", "issued": "0"}}
    ]},
    "issued": {"source": {"view": "issues"}, "steps": [
      {"type": "select", "fields": {"item": "i.item", "received": "0", "issued": "number(i.quantity)"}}
    ]},
    "stock": {"source": {"union": ["received", "issued"]}, "steps": [
      {"type": "group", "by": {"item": "item"}, "aggregates": {
        "received": {"function": "sum", "expression": "received"},
        "issued": {"function": "sum", "expression": "issued"}}},
      {"type": "derive", "fields": {"balance": "received - issued"}},
      {"type": "sort", "by": ["item"]}
    ]}
  },
  "sections": [
    {"type": "table", "title": "Items", "dataset": "stock",
     "columns": [
       {"field": "item", "label": "Item", "link": {"report": "item_card", "params": {"item": "item"}}},
       {"field": "balance", "label": "Balance", "format": "number", "highlight": "balance < 0"}
     ],
     "totals": {"balance": "sum"}, "totalsLabel": "Total", "emptyText": "Nothing in stock."}
  ]
}
KeyMeaning
nameIdentifier: lowercase letters, digits, underscores.
title, descriptionShown in lists and above the report.
orientationportrait (default) or landscape – a hint for printing.
subtitleExpression over the parameters, e.g. the period covered.
noteExplanation shown under the report.
headerLines above the report: expressions evaluated on the first row of a dataset.
parametersWhat the caller can pass; see below.
datasetsNamed row sets: a source and steps applied in order.
sectionsWhat is shown, top to bottom.

Unknown keys, step types, datasets, formats and invalid expressions are rejected when a definition is saved; the error names the path of the problem (report.datasets.stock.steps[1]: …).

Parameters

KeyMeaning
nameRead in expressions as params.<name>.
typedate (YYYY-MM-DD), int, number, string, bool, entry (identifier of a record of table).
labelShown next to the input.
defaultExpression giving the value used when none is passed; it may use earlier parameters.
requiredWithout a value the report is returned with ready: false and no sections.
tableTable whose record is picked (entry only).
min, maxBounds of an int.

A missing, empty or invalid value falls back to the default. The result always tells which values were used.

Sources

{"table": "id"}, {"view": "name"}, {"dataset": "name"} (rows of another dataset) or {"union": ["a", "b"]} (rows of several datasets, one after another). Every dataset is calculated at most once per run; a dataset may not depend on itself.

Steps

TypeOptionsEffect
filterexpressionKeeps the rows for which the expression is true.
derivefields (name → expression)Adds calculated fields, in order.
selectfields (name → expression)Replaces every row with the listed fields.
groupby (name → expression), aggregates (name → {function, expression})One row per group. Functions: count, countDistinct, sum, avg, min, max, first, last; all ignore empty values. Without by there is a single group, also for no rows.
sortby (fields, - prefix for descending)Numbers numerically, text alphabetically for the locale, empty values first; equal rows keep their order.
runningfield, expression, partitionRunning total in the current order, optionally restarted per partition.
distinctby, keep (first / last)One row for every combination of the fields.
collectas, dataset, match (field → field of the other dataset), expression, separatorText built from the matching rows of another dataset (a label of a related record, a list of child rows).
limitcountKeeps the first rows.

Applications can add their own steps by implementing Step\StepInterface and passing them to StepRegistry. A step also describes itself – description() and options() (name, kind of value, whether required) – which is what lets an editor offer inputs for it without knowing it.

Expressions

Expressions use an engine implementing adachsoft/rule-evaluator-contract. The suggested adachsoft/rule-evaluator-expression-language adapter uses Symfony ExpressionLanguage syntax: arithmetic, comparisons, and / or / not, ~ (concatenation), condition ? a : b.

  • A field is read by its name; fields named alias.column (rows of join views) are read as written: v.visited_at.
  • Parameters are read as params.name. An unknown field is null.
  • Functions: today(), date(value), addDays(day, days), startOfMonth(day), endOfMonth(day), number(value), round(value, precision), text(value), empty(value), coalesce(a, b, …), join(separator, a, b, …), lower(text), upper(text), length(text).
  • Nothing else of PHP is reachable: definitions may come from users.

Sections

KeyMeaning
typetable (default), records (one block per row, with a heading) or summary (the first row as a list of figures).
titleHeading of the section.
datasetRows to show.
columnsfield, label, format (text, multiline, number, money, date, datetime, boolean), link, highlight.
totals, totalsLabelTotals row: column field → aggregate function.
emptyTextShown when there are no rows.
hideWhenEmptyLeaves the section out when there are no rows.
headingExpression giving the heading of each row (records).

A column link is {"report": name, "params": {name: expression}} or {"table": id, "entry": expression}. highlight is an expression; when true for a row, the cell should stand out. Values stay raw – format only says how they are meant to be shown.

Describing definitions to editors

ReportFacade::schema() (built by Schema\ReportSchemaProvider) returns everything an editor of definitions needs: parameter types, section types, column formats, aggregate functions, the functions available in expressions with their signatures, every registered step with its options, and the tables and views that can be read. The last part comes from an optional Schema\SourceCatalogInterface; without one, source names are typed by hand. ReportFacade::validate() checks a definition exactly as save() would, without storing it.

Result

ReportResultDto: name, title, description, orientation, subtitle, note, header (lines), parameters (with the values used), ready, sections. Each section has type, title, columns, rows (values, links, highlights, heading), totals, totalsLabel, emptyText.

Export

A calculated report can be written to a file. ReportExporterRegistry holds the available ReportExporterInterface implementations by format:

  • CsvReportExporter (csv) – UTF-8 text with a byte order mark and a configurable delimiter,
  • XlsxReportExporter (xlsx) – one sheet; numbers of numeric columns stay numbers (needs openspout/openspout),
  • PdfReportExporter (pdf) – laid out like the printed report, with the header lines and the note (needs dompdf/dompdf).

ReportValueFormatter decides the decimal separator and the words used for booleans. Table sections become a header row, the rows and the totals; sections of records become "label, value" rows under the heading of each record.

$content = $registry->find('xlsx')?->export($facade->run('sales', ['from' => '2026-11-01']));

Exceptions

InterfaceWhen
InvalidReportDefinitionExceptionInterfaceThe definition is malformed.
ReportNotFoundExceptionInterfaceNo report is stored under the name.
ReportExecutionExceptionInterfaceA valid definition cannot be run, e.g. a table it reads is gone.

Development

vendor/bin/phpunit --configuration phpunit.xml
vendor/bin/phpstan analyse --configuration=phpstan.neon src tests

License

MIT