diff --git a/.nix/fnox/wrappers.nix b/.nix/fnox/wrappers.nix index 206f98cf41..da36ace9f2 100644 --- a/.nix/fnox/wrappers.nix +++ b/.nix/fnox/wrappers.nix @@ -6,6 +6,7 @@ gh, blackfire, composer, + terraform, }: let @@ -36,4 +37,16 @@ in program = "${blackfire}/bin/blackfire"; secrets = [ "BLACKFIRE_CLIENT_ID" "BLACKFIRE_CLIENT_TOKEN" ]; }; + + terraform = with-secrets "terraform" { + program = "${terraform}/bin/terraform"; + secrets = [ + "CLOUDFLARE_API_TOKEN" + "TF_VAR_account_id" + "TF_VAR_zone_id" + "AWS_ACCESS_KEY_ID" + "AWS_SECRET_ACCESS_KEY" + "AWS_ENDPOINT_URL_S3" + ]; + }; } diff --git a/documentation/components/bridges/symfony-telemetry-bundle.md b/documentation/components/bridges/symfony-telemetry-bundle.md index 71b61e5b02..7b7be365df 100644 --- a/documentation/components/bridges/symfony-telemetry-bundle.md +++ b/documentation/components/bridges/symfony-telemetry-bundle.md @@ -9,6 +9,12 @@ instruments console commands, and sends data to OpenTelemetry-compatible backend [PACKAGE_NAV] +Guides that show the bundle at work, step by step: + +- [Symfony monitoring with OpenTelemetry: requests, commands and SQL queries](/guides/symfony-monitoring-with-opentelemetry/) +- [Find slow Doctrine queries in Symfony in production](/guides/find-slow-doctrine-queries-in-symfony/) +- [OpenTelemetry Collector for PHP: keep the PHP process light](/guides/opentelemetry-collector-for-php/) + [TOC] ## Installation @@ -26,8 +32,8 @@ Bridge](/documentation/components/bridges/telemetry-otlp-bridge.md). The bundle connects the Flow PHP Telemetry library to Symfony applications. It gives you: - Automatic resource detection: detects the service name, version, environment, OS, host, and process information -- 8 auto-instrumentation options: HTTP kernel, console, messenger, Twig, HTTP client, PSR-18 client, Doctrine DBAL, and - cache +- 9 auto-instrumentation options: HTTP kernel, security, console, messenger, Twig, HTTP client, PSR-18 client, Doctrine + DBAL, and cache - Context propagation: W3C TraceContext and Baggage support for distributed tracing - Configurable exporters: console, memory, void, or OTLP with multiple transport options - Full Symfony configuration: you configure everything through the Symfony configuration system @@ -74,8 +80,7 @@ flow_telemetry: enabled: true # Enable resource detectors (default: true) static: cache: - enabled: true # Cache static attributes (default: true) - path: null # Cache file path (default: sys_get_temp_dir()/flow_telemetry_resource_.cache) + enabled: true # Cache the os, host and git attributes (default: true) os: enabled: true # Detect os.type, os.name, os.version, os.description host: @@ -86,6 +91,10 @@ flow_telemetry: enabled: true # Detect deployment.environment.name from kernel environment environment: enabled: true # Read OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES + git: + enabled: false # Detect vcs.ref.head.* and vcs.repository.url.full with the git binary (default: false) + binary: git # Path to the git binary (default: resolved from $PATH) + working_directory: null # Directory to run git in (default: %kernel.project_dir%) dynamic: process: enabled: true # Detect process.pid, process.runtime.*, process.executable.* @@ -103,19 +112,22 @@ Detector types: | `host` | `HostDetector` | static | `host.name`, `host.arch`, `host.id` | | `service` | `ComposerDetector` | static | `service.name`, `service.version` (from composer.json) | | `deployment` | `SymfonyDeploymentDetector` | static | `deployment.environment.name` (from kernel environment) | -| `environment` | `EnvironmentDetector` | static | Reads `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES` env vars | +| `git` | `GitDetector` | static | `vcs.ref.head.*`, `vcs.repository.url.full` (off by default) | +| `environment` | `EnvironmentDetector` | dynamic | Reads `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES` env vars | | `process` | `ProcessDetector` | dynamic | `process.pid`, `process.runtime.*`, `process.executable.*` | -Static detectors are cached by default. Dynamic detectors run on every request and every command. +Only the two detections that cost something are cached: + +| Attributes | Cache file | Lifetime | +|------------------|-----------------------------------------------------------|---------------------------------------------| +| `os.*`, `host.*` | `sys_get_temp_dir()/flow_telemetry_resource_host.cache` | the host. All applications share the file | +| `vcs.*` (git) | `%kernel.cache_dir%/flow_telemetry_resource_git.cache` | the release. `cache:clear` removes the file | -The cache file is outside the Symfony cache lifecycle on purpose. A Symfony cache build (with `cache:warmup`) at image -build time otherwise freezes runtime attributes, such as `host.name` or `process.pid`, from the build container. The -default location, `sys_get_temp_dir()`, keeps one cache for each runtime and prevents this problem. The default filename -contains the kernel environment (`flow_telemetry_resource_.cache`). Thus, a change of `APP_ENV`, for example from -dev to prod, does not serve an old `deployment.environment.name`. To clear the cached values, delete the cache file or -restart the process. `cache:clear` does not touch the file. +Every other attribute is read in every process. A new `service.version`, a change of `resource.custom` or of an +`OTEL_*` variable applies at once. The host file is outside the Symfony cache on purpose: a cache build at image build +time (`cache:warmup`) does not freeze `host.name` from the build container. -Custom attributes override auto-detected values. +Custom attributes override detected values and the `OTEL_*` variables. ### Clock Configuration @@ -1193,9 +1205,9 @@ flow_telemetry: trace_controller_arguments: false # controller.get_arguments aggregate span (default OFF) trace_controller_argument_resolvers: false # per-resolver controller.argument_value_resolver spans (default OFF) exclude_paths: - - path: '/_profiler' - - path: '/_wdt' - - path: '/health' + - path: '#^/_profiler#' # Regex: /_profiler and everything below it + - path: '#^/_wdt#' + - path: '/health' # Exact path method: GET - path: '/^\/api\/internal\/.*/' # Regex pattern ``` @@ -1418,7 +1430,7 @@ flow_telemetry: trace_blocks: false # Trace block rendering trace_macros: false # Trace macro execution exclude_templates: - - '@WebProfiler' + - '/^@WebProfiler\//' - '/^@Debug\/.*/' ``` @@ -1491,7 +1503,7 @@ flow_telemetry: dbal: enabled: true max_sql_length: 1000 # Max db.query.text length (0 = no limit) - collect_metrics: true # Emit db.client.operation.duration + db.client.response.returned_rows + collect_metrics: true # Emit the db.client.operation.duration histogram include_parameters: false # Include bound statement parameters (security consideration) max_parameters: 10 # Max parameters to include when include_parameters is enabled max_parameter_length: 100 # Max length per included parameter value @@ -1503,6 +1515,9 @@ flow_telemetry: - 'cache_items' ``` +A statement that changes rows (`INSERT`, `UPDATE`, `DELETE`) gets the attribute `flow.db.response.affected_rows`. A +statement that returns a result set gets no row count: the rows are fetched after the span ends. + #### Cache Traces Symfony Cache operations. @@ -1558,10 +1573,10 @@ example `cache_items`. The cache instrumentation also emits hit and miss counters. To export them, configure a `meter_provider`: -| Metric | Instrument | Unit | Emitted | -|---------------------|------------|--------------|---------------------| -| `flow.cache.hits` | Counter | `operations` | once per cache hit | -| `flow.cache.misses` | Counter | `operations` | once per cache miss | +| Metric | Instrument | Unit | Emitted | +|---------------------|------------|---------------|---------------------| +| `flow.cache.hits` | Counter | `{operation}` | once per cache hit | +| `flow.cache.misses` | Counter | `{operation}` | once per cache miss | ### Web Profiler @@ -1659,7 +1674,8 @@ Behavior: a clear error. - When `framework_logger` is `null` and Symfony's `logger` service is the default `Symfony\Component\HttpKernel\Log\Logger`, the bundle automatically aliases `logger` to - `flow.telemetry.default.logger.psr3`. + `flow.telemetry.default.logger.psr3`. For this, `logger_provider` must have a processor other than `void`, or + `console_output` must be on. With the default `void` processor the Symfony logger stays, so no log record is lost. - When `framework_logger` is `null` and another bundle provides `logger` (for example, Monolog or a custom alias), the bundle does not change `logger`. @@ -1873,11 +1889,16 @@ final class OrderService { $tracer = $this->telemetry->tracer('order-service'); - $tracer->trace('process_order', function () use ($orderId) { + $span = $tracer->span('process_order'); + $span->setAttribute('order.id', $orderId); + $scope = $tracer->activate($span); + + try { // Your order processing logic - }, [ - 'order.id' => $orderId, - ]); + } finally { + $scope->detach(); + $tracer->complete($span); + } } } ``` @@ -2007,15 +2028,15 @@ final class CheckoutController extends AbstractController $meter = $this->telemetry->meter('business-metrics'); // Counter -$meter->counter('orders_processed') +$meter->createCounter('orders_processed') ->add(1, ['status' => 'completed']); // Histogram -$meter->histogram('order_value') +$meter->createHistogram('order_value') ->record(99.99, ['currency' => 'USD']); // Gauge -$meter->gauge('active_users') +$meter->createGauge('active_users') ->record(42); ``` @@ -2119,8 +2140,8 @@ flow_telemetry: http_kernel: enabled: true exclude_paths: - - path: '/_profiler' - - path: '/_wdt' + - path: '#^/_profiler#' + - path: '#^/_wdt#' - path: '/health' method: GET console: diff --git a/documentation/components/libs/telemetry.md b/documentation/components/libs/telemetry.md index cd8a796352..94354ad15f 100644 --- a/documentation/components/libs/telemetry.md +++ b/documentation/components/libs/telemetry.md @@ -30,6 +30,9 @@ signal type and gives access to Tracers, Meters, and Loggers. > clean contracts, and no magic. > > Our contracts are [here](/documentation/components/libs/telemetry/contracts.md). +> +> Flow Telemetry is not built on the official OpenTelemetry PHP SDK. The differences are +> [here](/documentation/components/libs/telemetry/opentelemetry-sdk.md). ### Basic Setup with Memory Providers (Testing) @@ -1003,14 +1006,29 @@ $resource = static_detector([ #### Caching Detection Results Resource detection can read files, for example `/etc/machine-id` for the host ID. Use `caching_detector()` to cache -the results and not detect again: +the results and not detect again. The cache file never expires, so wrap only the detectors whose values cannot change +on the host: ```php detect(); +$resource = resource_detector([ + caching_detector(chain_detector(os_detector(), host_detector())), + process_detector(), + composer_detector(), + environment_detector(), +])->detect(); ``` By default, the cache is in `sys_get_temp_dir()/flow_telemetry_resource.cache`. You can give a custom path as the diff --git a/documentation/components/libs/telemetry/opentelemetry-sdk.md b/documentation/components/libs/telemetry/opentelemetry-sdk.md new file mode 100644 index 0000000000..fe3cbd1854 --- /dev/null +++ b/documentation/components/libs/telemetry/opentelemetry-sdk.md @@ -0,0 +1,92 @@ +--- +seo_title: "Flow Telemetry and the OpenTelemetry PHP SDK: the differences" +seo_description: > + Flow Telemetry is an independent OpenTelemetry implementation for PHP with no C extension. How it differs from the + official OpenTelemetry PHP SDK, and what is the same. +--- + +# Flow Telemetry and the OpenTelemetry PHP SDK + +Flow Telemetry is an independent implementation of OpenTelemetry for PHP. It is not a wrapper around the official +SDK, and it does not use any of its packages. Both send the same OTLP data, so the same collectors and backends +accept it. + +[DOC_LINK:/documentation/components/libs/telemetry.md] + +[TOC] + +## No singletons, no implicit behavior + +- There is no global instance. You create a `Telemetry` object and pass it to the code that needs it. +- Composer loads the library and nothing runs. No span, no export and no configuration starts by itself. +- Nothing is read from the environment to build the pipeline. What the code says is what runs. +- Nothing is instrumented until you wrap it. A bridge takes your HTTP client, logger or kernel and returns one of + the same type that records telemetry. + +```php ignore + 'my-app']), + tracer_provider( + pass_through_span_processor(console_exporter()), + new SystemClock(), + memory_context_storage(), + ), +); + +$tracer = $telemetry->tracer('http-handler'); +$span = $tracer->span('handle-request'); +$tracer->complete($span); +``` + +To send the data to a collector, read the [OTLP Bridge](/documentation/components/bridges/telemetry-otlp-bridge.md). diff --git a/documentation/contributing/nix.md b/documentation/contributing/nix.md index ed7dc6b529..1165df8043 100644 --- a/documentation/contributing/nix.md +++ b/documentation/contributing/nix.md @@ -91,7 +91,7 @@ To configure blackfire, create a file `./.nix/php/lib/blackfire.ini` with your b ## Secrets -`gh`, `composer` and `blackfire` in the nix shell run through [fnox](https://fnox.jdx.dev). +`gh`, `composer`, `blackfire` and `terraform` in the nix shell run through [fnox](https://fnox.jdx.dev). fnox reads the secrets below from the provider that you choose. It gives them to the tool only. Nothing is exported to the shell. @@ -101,11 +101,17 @@ to the shell. | `GH_TOKEN` | `gh`, `composer` | `GH_TOKEN`, `COMPOSER_AUTH` | | `BLACKFIRE_CLIENT_ID` | `blackfire` | `BLACKFIRE_CLIENT_ID` | | `BLACKFIRE_CLIENT_TOKEN` | `blackfire` | `BLACKFIRE_CLIENT_TOKEN` | +| `CLOUDFLARE_API_TOKEN` | `terraform` | `CLOUDFLARE_API_TOKEN` | +| `TF_VAR_account_id` | `terraform` | `TF_VAR_account_id` | +| `TF_VAR_zone_id` | `terraform` | `TF_VAR_zone_id` | +| `AWS_ACCESS_KEY_ID` | `terraform` | `AWS_ACCESS_KEY_ID` | +| `AWS_SECRET_ACCESS_KEY` | `terraform` | `AWS_SECRET_ACCESS_KEY` | +| `AWS_ENDPOINT_URL_S3` | `terraform` | `AWS_ENDPOINT_URL_S3` | `fnox.toml` names the secrets. Your provider goes into `fnox.local.toml`, which git ignores. Without that file, the tools run without secrets. -To use them, add a `[providers]` section and the three secrets to `fnox.local.toml`. The +To use them, add a `[providers]` section and the secrets that you need to `fnox.local.toml`. The [fnox providers](https://fnox.jdx.dev/providers/overview) page shows the configuration of each provider. An example for 1Password, where each value is `item/field` in the vault: diff --git a/documentation/installation/packages/symfony-telemetry-bundle.md b/documentation/installation/packages/symfony-telemetry-bundle.md index 55f5412771..8290548ae8 100644 --- a/documentation/installation/packages/symfony-telemetry-bundle.md +++ b/documentation/installation/packages/symfony-telemetry-bundle.md @@ -32,6 +32,9 @@ composer require flow-php/symfony-telemetry-bundle:~--FLOW_PHP_VERSION-- - [flow-php/psr18-telemetry-bridge](/documentation/installation/packages/psr18-telemetry-bridge.md): for PSR-18 HTTP client tracing - [flow-php/telemetry-otlp-bridge](/documentation/installation/packages/telemetry-otlp-bridge.md): for OTLP exporter support - [symfony/messenger](https://packagist.org/packages/symfony/messenger): for Messenger tracing middleware +- [symfony/security-core](https://packagist.org/packages/symfony/security-core): for the authenticated user on the request span +- [symfony/security-http](https://packagist.org/packages/symfony/security-http): for logins that happen in the middle of a request +- [symfony/web-profiler-bundle](https://packagist.org/packages/symfony/web-profiler-bundle): for the Flow Telemetry panel of the web profiler in dev - [twig/twig](https://packagist.org/packages/twig/twig): for Twig template tracing ## Optional Dependencies diff --git a/documentation/upgrading.md b/documentation/upgrading.md index b45a093811..c63ca4a42e 100644 --- a/documentation/upgrading.md +++ b/documentation/upgrading.md @@ -152,6 +152,57 @@ to_parquet($path)->partitionBy(['date', 'country'], writeColumns: true); | `type_positive_integer()->cast("\f1")` throws | gives `1` | | a header cell `"\fid"` is named `"\fid"` | is named `id` | +### 14) `flow-php/symfony-telemetry-bundle` - only host and git resource attributes are cached + +| Attributes | Before | After | +|----------------------------------------------------------|-----------------------------------------------------------------|---------------------------------------------------------| +| `os.*`, `host.*` | `sys_get_temp_dir()/flow_telemetry_resource_.cache` | `sys_get_temp_dir()/flow_telemetry_resource_host.cache` | +| `vcs.*` (git detector) | the same file | `%kernel.cache_dir%/flow_telemetry_resource_git.cache` | +| `service.*`, `deployment.*`, `resource.custom`, `OTEL_*` | the same file, never refreshed | read in every process, not cached | +| `resource.detectors.static.cache.path` | a custom path for the file | removed | + +Remove `resource.detectors.static.cache.path` from the configuration. Delete the orphaned +`flow_telemetry_resource_.cache` files from the temp dir. + +### 15) `flow-php/symfony-telemetry-bundle` - `resource.custom` wins over `OTEL_RESOURCE_ATTRIBUTES` + +| Before | After | +|-------------------------------------------------------------------------------|---------------------------------------------------------------------------| +| `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES` override `resource.custom` | `resource.custom` overrides both, as the OpenTelemetry specification says | + +To let the environment decide a value, remove that key from `resource.custom`. + +### 16) `flow-php/symfony-telemetry-bundle` - DBAL spans report affected rows, not returned rows + +| Statement | Before | After | +|-----------------------------------|----------------------------------------------------------------|----------------------------------| +| returns a result set (`SELECT`) | `db.response.returned_rows` from `rowCount()`, wrong on SQLite | no row attribute | +| changes rows (`INSERT`, `UPDATE`) | `db.response.returned_rows` | `flow.db.response.affected_rows` | +| metric | `db.client.response.returned_rows` histogram | removed | + +### 17) `flow-php/symfony-telemetry-bundle` - the gRPC transport `timeout_ms` defaults to 250 + +| Before | After | +|-------------------------------------------------------|-------------------------------------| +| `transport.type: grpc` without `timeout_ms` gets 5000 | 250, the default of `GrpcTransport` | + +To keep the old deadline, set `timeout_ms: 5000`. + +### 18) `flow-php/symfony-telemetry-bundle` - the Symfony logger stays when logs have no destination + +| Before | After | +|-------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------| +| without MonologBundle, `logger` is replaced also with the `void` log processor, and every record is dropped | `logger` is replaced only with a log processor other than `void`, with `console_output`, or with `framework_logger` | + +### 19) `flow-php/telemetry` - the console exporter prints versions as reported and writes to `php://stdout` + +| Before | After | +|-------------------------------------------------|-------------------------------------------| +| `Scope: flow.symfony.http_kernel vv7.4.24` | `Scope: flow.symfony.http_kernel v7.4.24` | +| `Scope: flow.symfony.dbal v4.5.0` | `Scope: flow.symfony.dbal 4.5.0` | +| `Scope: my-tracer vunknown` | `Scope: my-tracer unknown` | +| the `STDOUT` constant, an error outside the CLI | the `php://stdout` stream | + --- ## Upgrading from 0.47.x to 0.48.x diff --git a/fnox.toml b/fnox.toml index 0eedf40a10..97d015656c 100644 --- a/fnox.toml +++ b/fnox.toml @@ -5,3 +5,9 @@ if_missing = "ignore" GH_TOKEN = { description = "GitHub token for gh and composer" } BLACKFIRE_CLIENT_ID = { description = "Blackfire client ID" } BLACKFIRE_CLIENT_TOKEN = { description = "Blackfire client token" } +CLOUDFLARE_API_TOKEN = { description = "Cloudflare API token for terraform" } +TF_VAR_account_id = { description = "Cloudflare account ID for terraform" } +TF_VAR_zone_id = { description = "Cloudflare zone ID for terraform" } +AWS_ACCESS_KEY_ID = { description = "R2 access key ID of the terraform state bucket" } +AWS_SECRET_ACCESS_KEY = { description = "R2 secret access key of the terraform state bucket" } +AWS_ENDPOINT_URL_S3 = { description = "R2 S3 endpoint of the terraform state bucket" } diff --git a/shell.nix b/shell.nix index b7237908ef..9117619fbb 100644 --- a/shell.nix +++ b/shell.nix @@ -145,7 +145,7 @@ pkgs.mkShell { pkgs.libxml2 pkgs.pkg-config ] - ++ pkgs.lib.optional with-terraform pkgs.terraform + ++ pkgs.lib.optional with-terraform fnox-wrappers.terraform ++ pkgs.lib.optionals with-c [ # C development tools for pg-query-ext extension development pkgs.gcc diff --git a/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/DependencyInjection/Compiler/FrameworkLoggerPass.php b/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/DependencyInjection/Compiler/FrameworkLoggerPass.php index 255b5f12c6..1300fae2bc 100644 --- a/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/DependencyInjection/Compiler/FrameworkLoggerPass.php +++ b/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/DependencyInjection/Compiler/FrameworkLoggerPass.php @@ -62,6 +62,13 @@ public function process(ContainerBuilder $container): void return; } + if ( + $container->hasParameter('flow.telemetry.logger_provider.has_destination') + && $container->getParameter('flow.telemetry.logger_provider.has_destination') !== true + ) { + return; + } + $container->setAlias('logger', 'flow.telemetry.default.logger.psr3')->setPublic(true); } } diff --git a/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/FlowTelemetryBundle.php b/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/FlowTelemetryBundle.php index 0f488a9ced..f0193f3092 100644 --- a/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/FlowTelemetryBundle.php +++ b/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/FlowTelemetryBundle.php @@ -164,11 +164,6 @@ final class FlowTelemetryBundle extends AbstractBundle private const string SECURITY_TOKEN_STORAGE_INTERFACE = 'Symfony\\Component\\Security\\Core\\Authentication\\Token\\Storage\\TokenStorageInterface'; - private const array TRANSPORT_TIMEOUT_DEFAULTS = [ - 'curl' => ['timeout_ms' => CurlTransportOptions::DEFAULT_TIMEOUT_MS], - 'async_curl' => ['connect_timeout_ms' => AsyncCurlTransportOptions::DEFAULT_CONNECT_TIMEOUT_MS], - ]; - private const string URL_GENERATOR_INTERFACE = 'Symfony\\Component\\Routing\\Generator\\UrlGeneratorInterface'; private const string WEB_PROFILER_BUNDLE = 'Symfony\\Bundle\\WebProfilerBundle\\WebProfilerBundle'; @@ -256,23 +251,19 @@ public function configure(DefinitionConfigurator $definition): void ->defaultTrue() ->end() ->arrayNode('static') - ->info('Static detectors - values that do not change between requests/commands (can be cached)') + ->info('Static detectors - values that do not change while a process runs') ->addDefaultsIfNotSet() ->children() ->arrayNode('cache') ->info( - 'File-based caching of static resource attributes. The cache file is intentionally outside Symfony\'s cache lifecycle so build-time cache:warmup does not freeze runtime-dependent attributes (host, process).', + 'File cache for the two detections that cost something. os and host are stored in sys_get_temp_dir()/flow_telemetry_resource_host.cache: they are the same for every application on a host. git is stored in %kernel.cache_dir%/flow_telemetry_resource_git.cache, which a release replaces. Every other attribute is read in every process.', ) ->addDefaultsIfNotSet() ->children() ->booleanNode('enabled') - ->info('Enable caching of static resource attributes') + ->info('Cache the os, host and git resource attributes') ->defaultTrue() ->end() - ->scalarNode('path') - ->info('Absolute path to the cache file. Default: sys_get_temp_dir()/flow_telemetry_resource_.cache (keyed by kernel environment so switching APP_ENV does not serve a stale deployment.environment.name).') - ->defaultNull() - ->end() ->end() ->end() ->arrayNode('os') @@ -768,7 +759,7 @@ public function configure(DefinitionConfigurator $definition): void ->min(0) ->end() ->booleanNode('collect_metrics') - ->info('Record db.client.operation.duration and db.client.response.returned_rows histograms') + ->info('Record the db.client.operation.duration histogram') ->defaultTrue() ->end() ->booleanNode('include_parameters') @@ -949,7 +940,7 @@ public function configure(DefinitionConfigurator $definition): void } /** - * @param array{enabled: bool, resource: array{detectors?: array{enabled?: bool, static?: array{cache?: array{enabled?: bool, path?: null|string}, os?: array{enabled?: bool}, host?: array{enabled?: bool}, service?: array{enabled?: bool}, deployment?: array{enabled?: bool}, git?: array{enabled?: bool, binary?: string, working_directory?: null|string}, environment?: array{enabled?: bool}}, dynamic?: array{process?: array{enabled?: bool}}}, custom?: array}, clock_service_id?: null|string, framework_logger?: null|string, capture_framework_channels?: bool, channel_attribute_target?: 'scope'|'signal'|'both', context_storage?: array{type?: string, service_id?: null|string}, propagator?: array{type?: string, service_id?: null|string}, exporters?: array>, error_handlers?: array>, tracer_provider?: array, meter_provider?: array, logger_provider?: array, instrumentation?: FlowTelemetryInstrumentationConfig, profiler?: array{enabled?: bool|null, capture_logs?: bool}, tracers?: array, signal?: array}}>, meters?: array, signal?: array}}>, loggers?: array, signal?: array}}>} $config + * @param array{enabled: bool, resource: array{detectors?: array{enabled?: bool, static?: array{cache?: array{enabled?: bool}, os?: array{enabled?: bool}, host?: array{enabled?: bool}, service?: array{enabled?: bool}, deployment?: array{enabled?: bool}, git?: array{enabled?: bool, binary?: string, working_directory?: null|string}, environment?: array{enabled?: bool}}, dynamic?: array{process?: array{enabled?: bool}}}, custom?: array}, clock_service_id?: null|string, framework_logger?: null|string, capture_framework_channels?: bool, channel_attribute_target?: 'scope'|'signal'|'both', context_storage?: array{type?: string, service_id?: null|string}, propagator?: array{type?: string, service_id?: null|string}, exporters?: array>, error_handlers?: array>, tracer_provider?: array, meter_provider?: array, logger_provider?: array, instrumentation?: FlowTelemetryInstrumentationConfig, profiler?: array{enabled?: bool|null, capture_logs?: bool}, tracers?: array, signal?: array}}>, meters?: array, signal?: array}}>, loggers?: array, signal?: array}}>} $config */ #[Override] public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void @@ -1011,8 +1002,6 @@ private function applyTransportSchema(ArrayNodeDefinition $node, bool $allowFail return $v; } - $v += self::TRANSPORT_TIMEOUT_DEFAULTS[$v['type'] ?? 'curl'] ?? []; - if (($v['type'] ?? null) === 'grpc' && array_key_exists('connect_timeout_ms', $v)) { throw new InvalidConfigurationException( 'The "connect_timeout_ms" parameter is not supported when transport.type is "grpc"; gRPC uses the per-call deadline (timeout_ms) for connection establishment too.', @@ -1128,8 +1117,7 @@ private function applyTransportSchema(ArrayNodeDefinition $node, bool $allowFail ->defaultTrue() ->end() ->integerNode('timeout_ms') - ->info('Per-request deadline in milliseconds (curl: total request, default 10000ms; async_curl/grpc: default 5000ms).') - ->defaultValue(5000) + ->info('Per-request deadline in milliseconds (curl: total request, default 10000ms; async_curl: default 5000ms; grpc: default 250ms).') ->min(1) ->end() ->arrayNode('headers') @@ -1141,19 +1129,16 @@ private function applyTransportSchema(ArrayNodeDefinition $node, bool $allowFail ->end() ->integerNode('connect_timeout_ms') ->info('Connection-establishment deadline in milliseconds (curl/async_curl only; curl default 250ms, async_curl default 1500ms).') - ->defaultValue(250) ->min(1) ->end() ->integerNode('pump_timeout_ms') ->info('Per-tick() bounded pump budget in milliseconds (async_curl only). 0 = single non-blocking exec round. Default 100ms.') - ->defaultValue(100) ->min(0) ->end() ->integerNode('shutdown_timeout_ms') ->info( 'Wall-clock budget in milliseconds for draining pending requests at shutdown (curl/grpc). Default 5000ms.', ) - ->defaultValue(5000) ->min(1) ->end() ->booleanNode('compression') @@ -1637,6 +1622,11 @@ private function buildLoggerProvider(array $config, ContainerBuilder $builder): $consoleOutputConfig = is_array($config['console_output'] ?? null) ? $config['console_output'] : []; + $builder->setParameter( + 'flow.telemetry.logger_provider.has_destination', + ($processorConfig['type'] ?? 'void') !== 'void' || (bool) ($consoleOutputConfig['enabled'] ?? false), + ); + if ((bool) ($consoleOutputConfig['enabled'] ?? false)) { $processorServiceId = $this->buildConsoleOutputLogging( $consoleOutputConfig, @@ -3632,7 +3622,7 @@ private function registerPropagator(array $config, ContainerBuilder $builder): v } /** - * @param array{detectors?: array{enabled?: bool, static?: array{cache?: array{enabled?: bool, path?: null|string}, os?: array{enabled?: bool}, host?: array{enabled?: bool}, service?: array{enabled?: bool}, deployment?: array{enabled?: bool}, git?: array{enabled?: bool, binary?: string, working_directory?: null|string}, environment?: array{enabled?: bool}}, dynamic?: array{process?: array{enabled?: bool}}}, custom?: array} $resourceConfig + * @param array{detectors?: array{enabled?: bool, static?: array{cache?: array{enabled?: bool}, os?: array{enabled?: bool}, host?: array{enabled?: bool}, service?: array{enabled?: bool}, deployment?: array{enabled?: bool}, git?: array{enabled?: bool, binary?: string, working_directory?: null|string}, environment?: array{enabled?: bool}}, dynamic?: array{process?: array{enabled?: bool}}}, custom?: array} $resourceConfig */ private function registerResource(array $resourceConfig, ContainerBuilder $builder): void { @@ -3653,30 +3643,45 @@ private function registerResource(array $resourceConfig, ContainerBuilder $build $dynamicConfig = $detectorsConfig['dynamic'] ?? []; $customAttributes = $resourceConfig['custom'] ?? []; - $staticDetectorRefs = []; + $cacheEnabled = $staticConfig['cache']['enabled'] ?? true; + $hostDetectorRefs = []; + $resourceDetectorRefs = []; if ($staticConfig['os']['enabled'] ?? true) { $builder->setDefinition('flow.telemetry.resource.detector.os', new Definition(OsDetector::class)); - $staticDetectorRefs[] = new Reference('flow.telemetry.resource.detector.os'); + $hostDetectorRefs[] = new Reference('flow.telemetry.resource.detector.os'); } if ($staticConfig['host']['enabled'] ?? true) { $builder->setDefinition('flow.telemetry.resource.detector.host', new Definition(HostDetector::class)); - $staticDetectorRefs[] = new Reference('flow.telemetry.resource.detector.host'); + $hostDetectorRefs[] = new Reference('flow.telemetry.resource.detector.host'); + } + + if ($cacheEnabled && count($hostDetectorRefs) > 0) { + $builder->setDefinition('flow.telemetry.resource.detector.host_cache', new Definition( + CachingDetector::class, + [ + new Definition(ChainDetector::class, $hostDetectorRefs), + sys_get_temp_dir() . '/flow_telemetry_resource_host.cache', + ], + )); + $resourceDetectorRefs[] = new Reference('flow.telemetry.resource.detector.host_cache'); + } else { + $resourceDetectorRefs = $hostDetectorRefs; } if ($staticConfig['service']['enabled'] ?? true) { $composerDefinition = new Definition(ComposerDetector::class); $composerDefinition->setArgument(0, '%kernel.project_dir%/composer.json'); $builder->setDefinition('flow.telemetry.resource.detector.service', $composerDefinition); - $staticDetectorRefs[] = new Reference('flow.telemetry.resource.detector.service'); + $resourceDetectorRefs[] = new Reference('flow.telemetry.resource.detector.service'); } if ($staticConfig['deployment']['enabled'] ?? true) { $deploymentDefinition = new Definition(SymfonyDeploymentDetector::class); $deploymentDefinition->setArgument(0, '%kernel.environment%'); $builder->setDefinition('flow.telemetry.resource.detector.deployment', $deploymentDefinition); - $staticDetectorRefs[] = new Reference('flow.telemetry.resource.detector.deployment'); + $resourceDetectorRefs[] = new Reference('flow.telemetry.resource.detector.deployment'); } if ($staticConfig['git']['enabled'] ?? false) { @@ -3688,14 +3693,19 @@ private function registerResource(array $resourceConfig, ContainerBuilder $build $gitDefinition->setArgument(0, $workingDirectory ?? '%kernel.project_dir%'); $gitDefinition->setArgument(1, $gitBinary); $builder->setDefinition('flow.telemetry.resource.detector.git', $gitDefinition); - $staticDetectorRefs[] = new Reference('flow.telemetry.resource.detector.git'); - } - if (count($customAttributes) > 0) { - $manualDefinition = new Definition(StaticDetector::class); - $manualDefinition->setArgument(0, $customAttributes); - $builder->setDefinition('flow.telemetry.resource.detector.custom', $manualDefinition); - $staticDetectorRefs[] = new Reference('flow.telemetry.resource.detector.custom'); + if ($cacheEnabled) { + $builder->setDefinition('flow.telemetry.resource.detector.git_cache', new Definition( + CachingDetector::class, + [ + new Reference('flow.telemetry.resource.detector.git'), + '%kernel.cache_dir%/flow_telemetry_resource_git.cache', + ], + )); + $resourceDetectorRefs[] = new Reference('flow.telemetry.resource.detector.git_cache'); + } else { + $resourceDetectorRefs[] = new Reference('flow.telemetry.resource.detector.git'); + } } if ($staticConfig['environment']['enabled'] ?? true) { @@ -3703,55 +3713,28 @@ private function registerResource(array $resourceConfig, ContainerBuilder $build 'flow.telemetry.resource.detector.environment', new Definition(EnvironmentDetector::class), ); - $staticDetectorRefs[] = new Reference('flow.telemetry.resource.detector.environment'); + $resourceDetectorRefs[] = new Reference('flow.telemetry.resource.detector.environment'); } - $staticChainDefinition = new Definition(ChainDetector::class); - $staticChainDefinition->setArguments($staticDetectorRefs); - $builder->setDefinition('flow.telemetry.resource.detector.static.chain', $staticChainDefinition); - - $cacheConfig = $staticConfig['cache'] ?? []; - $cacheEnabled = $cacheConfig['enabled'] ?? true; - - if ($cacheEnabled) { - $cachingDefinition = new Definition(CachingDetector::class); - $cachingDefinition->setArgument(0, new Reference('flow.telemetry.resource.detector.static.chain')); - $cachingDefinition->setArgument( - 1, - $cacheConfig['path'] ?? sys_get_temp_dir() . '/flow_telemetry_resource_%kernel.environment%.cache', - ); - $builder->setDefinition('flow.telemetry.resource.detector.static', $cachingDefinition); - } else { - $builder->setAlias( - 'flow.telemetry.resource.detector.static', - 'flow.telemetry.resource.detector.static.chain', - ); + if (count($customAttributes) > 0) { + $manualDefinition = new Definition(StaticDetector::class); + $manualDefinition->setArgument(0, $customAttributes); + $builder->setDefinition('flow.telemetry.resource.detector.custom', $manualDefinition); + $resourceDetectorRefs[] = new Reference('flow.telemetry.resource.detector.custom'); } - $dynamicDetectorRefs = []; - if ($dynamicConfig['process']['enabled'] ?? true) { $builder->setDefinition( 'flow.telemetry.resource.detector.process', new Definition(ProcessDetector::class), ); - $dynamicDetectorRefs[] = new Reference('flow.telemetry.resource.detector.process'); + $resourceDetectorRefs[] = new Reference('flow.telemetry.resource.detector.process'); } - if (count($dynamicDetectorRefs) > 0) { - $dynamicChainDefinition = new Definition(ChainDetector::class); - $dynamicChainDefinition->setArguments($dynamicDetectorRefs); - $builder->setDefinition('flow.telemetry.resource.detector.dynamic', $dynamicChainDefinition); - - $finalChainDefinition = new Definition(ChainDetector::class); - $finalChainDefinition->setArguments([ - new Reference('flow.telemetry.resource.detector.static'), - new Reference('flow.telemetry.resource.detector.dynamic'), - ]); - $builder->setDefinition('flow.telemetry.resource.detector', $finalChainDefinition); - } else { - $builder->setAlias('flow.telemetry.resource.detector', 'flow.telemetry.resource.detector.static'); - } + $builder->setDefinition('flow.telemetry.resource.detector', new Definition( + ChainDetector::class, + $resourceDetectorRefs, + )); $resourceDefinition = new Definition(Resource::class); $resourceDefinition->setFactory([new Reference('flow.telemetry.resource.detector'), 'detect']); diff --git a/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/Instrumentation/Doctrine/DBAL/DbAttributes.php b/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/Instrumentation/Doctrine/DBAL/DbAttributes.php index a2c74c31b8..25531b7d5c 100644 --- a/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/Instrumentation/Doctrine/DBAL/DbAttributes.php +++ b/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/Instrumentation/Doctrine/DBAL/DbAttributes.php @@ -13,5 +13,7 @@ final class DbAttributes { public const string DB_CONNECTION_NAME = 'flow.db.connection.name'; + public const string DB_RESPONSE_AFFECTED_ROWS = 'flow.db.response.affected_rows'; + public const string DB_TRANSACTION_NESTING_LEVEL = 'flow.db.transaction.nesting_level'; } diff --git a/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/Instrumentation/Doctrine/DBAL/QueryTracer.php b/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/Instrumentation/Doctrine/DBAL/QueryTracer.php index 257c37bf14..d49526cfe0 100644 --- a/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/Instrumentation/Doctrine/DBAL/QueryTracer.php +++ b/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/Instrumentation/Doctrine/DBAL/QueryTracer.php @@ -6,6 +6,7 @@ use DateTimeImmutable; use Doctrine\DBAL\Driver\Exception as DriverException; +use Doctrine\DBAL\Driver\Result; use Flow\Telemetry\Meter\Instrument\Histogram; use Flow\Telemetry\PackageVersion; use Flow\Telemetry\SemConvAttributes; @@ -29,8 +30,6 @@ final class QueryTracer { private ?Histogram $operationDuration = null; - private ?Histogram $returnedRows = null; - private readonly SqlAttributesExtractor $extractor; private readonly ParameterFormatter $parameterFormatter; @@ -58,12 +57,6 @@ public function __construct( 'Duration of database client operations', [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0], ); - $this->returnedRows = $meter->createHistogram( - SemConvMetrics::DB_CLIENT_RESPONSE_RETURNED_ROWS, - '{row}', - 'Number of rows returned by database operations', - [1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0], - ); } } @@ -136,21 +129,15 @@ public function recordError(Span $span, Throwable $exception): void $span->setStatus(SpanStatus::error($exception->getMessage())); } - public function recordQueryMetrics(int|float|false $startTime, ?int $rowCount, SqlAttributes $attributes): void + public function affectedRows(Result $result): ?int { - $metricAttributes = $this->metricAttributes($attributes); - $duration = $this->elapsed($startTime); - $operationDuration = $this->operationDuration; - - if ($operationDuration !== null && $duration !== null) { - $operationDuration->record($duration, $metricAttributes); - } - - $returnedRows = $this->returnedRows; + // DBAL defines rowCount() only for a statement that returns no result set. + return $result->columnCount() > 0 ? null : (int) $result->rowCount(); + } - if ($rowCount !== null && $returnedRows !== null) { - $returnedRows->record($rowCount, $metricAttributes); - } + public function recordQueryMetrics(int|float|false $startTime, SqlAttributes $attributes): void + { + $this->recordDuration($startTime, $this->metricAttributes($attributes)); } /** diff --git a/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/Instrumentation/Doctrine/DBAL/TracingConnection.php b/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/Instrumentation/Doctrine/DBAL/TracingConnection.php index b82c134553..c91a82b997 100644 --- a/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/Instrumentation/Doctrine/DBAL/TracingConnection.php +++ b/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/Instrumentation/Doctrine/DBAL/TracingConnection.php @@ -165,7 +165,7 @@ public function query(string $sql): Result return $this->traceQuery( $sql, fn() => parent::query($sql), - static fn(Result $result): int => (int) $result->rowCount(), + fn(Result $result): ?int => $this->queryTracer->affectedRows($result), ); } @@ -173,11 +173,11 @@ public function query(string $sql): Result * @template T * * @param \Closure(): T $execute - * @param \Closure(T): int $rowCount + * @param \Closure(T): ?int $affectedRows * * @return T */ - private function traceQuery(string $sql, Closure $execute, Closure $rowCount): mixed + private function traceQuery(string $sql, Closure $execute, Closure $affectedRows): mixed { $sqlAttributes = $this->queryTracer->extract($sql); $startTime = hrtime(true); @@ -191,14 +191,18 @@ private function traceQuery(string $sql, Closure $execute, Closure $rowCount): m try { $result = $execute(); - $rows = $rowCount($result); - $span->setAttribute(SemConvAttributes::DB_RESPONSE_RETURNED_ROWS, $rows); - $this->queryTracer->recordQueryMetrics($startTime, $rows, $sqlAttributes); + $rows = $affectedRows($result); + + if ($rows !== null) { + $span->setAttribute(DbAttributes::DB_RESPONSE_AFFECTED_ROWS, $rows); + } + + $this->queryTracer->recordQueryMetrics($startTime, $sqlAttributes); return $result; } catch (Throwable $exception) { $this->queryTracer->recordError($span, $exception); - $this->queryTracer->recordQueryMetrics($startTime, null, $sqlAttributes); + $this->queryTracer->recordQueryMetrics($startTime, $sqlAttributes); throw $exception; } finally { diff --git a/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/Instrumentation/Doctrine/DBAL/TracingStatement.php b/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/Instrumentation/Doctrine/DBAL/TracingStatement.php index e3ac54ed4d..a07ec9112b 100644 --- a/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/Instrumentation/Doctrine/DBAL/TracingStatement.php +++ b/src/bridge/symfony/telemetry-bundle/src/Flow/Bridge/Symfony/TelemetryBundle/Instrumentation/Doctrine/DBAL/TracingStatement.php @@ -8,7 +8,6 @@ use Doctrine\DBAL\Driver\Result; use Doctrine\DBAL\Driver\Statement as StatementInterface; use Doctrine\DBAL\ParameterType; -use Flow\Telemetry\SemConvAttributes; use Flow\Telemetry\Tracer\SpanKind; use Override; use Throwable; @@ -54,14 +53,18 @@ public function execute(): Result try { $result = parent::execute(); - $rows = (int) $result->rowCount(); - $span->setAttribute(SemConvAttributes::DB_RESPONSE_RETURNED_ROWS, $rows); - $this->queryTracer->recordQueryMetrics($startTime, $rows, $this->sqlAttributes); + $affectedRows = $this->queryTracer->affectedRows($result); + + if ($affectedRows !== null) { + $span->setAttribute(DbAttributes::DB_RESPONSE_AFFECTED_ROWS, $affectedRows); + } + + $this->queryTracer->recordQueryMetrics($startTime, $this->sqlAttributes); return $result; } catch (Throwable $exception) { $this->queryTracer->recordError($span, $exception); - $this->queryTracer->recordQueryMetrics($startTime, null, $this->sqlAttributes); + $this->queryTracer->recordQueryMetrics($startTime, $this->sqlAttributes); throw $exception; } finally { diff --git a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Context/SymfonyContext.php b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Context/SymfonyContext.php index e1318fb2fc..870695bbdb 100644 --- a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Context/SymfonyContext.php +++ b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Context/SymfonyContext.php @@ -4,6 +4,7 @@ namespace Flow\Bridge\Symfony\TelemetryBundle\Tests\Context; +use Composer\Autoload\ClassLoader; use Flow\Bridge\Symfony\TelemetryBundle\Tests\Fixtures\TestKernel; use Flow\Telemetry\Telemetry; use LogicException; @@ -14,8 +15,8 @@ use function dirname; use function Flow\Types\DSL\type_instance_of; use function is_callable; +use function spl_autoload_register; use function str_starts_with; -use function sys_get_temp_dir; final class SymfonyContext { @@ -129,6 +130,19 @@ public function makeFlowServicesPublic(ContainerBuilder $container): void } } + public function withoutOtlpBridge(): void + { + foreach (ClassLoader::getRegisteredLoaders() as $loader) { + $loader->unregister(); + + spl_autoload_register(static function (string $class) use ($loader): void { + if (!str_starts_with($class, 'Flow\\Bridge\\Telemetry\\OTLP\\')) { + $loader->loadClass($class); + } + }); + } + } + public function shutdown(): void { if ($this->kernel === null) { @@ -136,7 +150,6 @@ public function shutdown(): void } $runDir = dirname($this->kernel->getCacheDir()); - $environment = $this->kernel->getEnvironment(); $this->kernel->shutdown(); $this->kernel = null; @@ -146,11 +159,5 @@ public function shutdown(): void if ($filesystem->exists($runDir)) { $filesystem->remove($runDir); } - - $defaultResourceCache = sys_get_temp_dir() . '/flow_telemetry_resource_' . $environment . '.cache'; - - if ($filesystem->exists($defaultResourceCache)) { - $filesystem->remove($defaultResourceCache); - } } } diff --git a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Fixtures/Doctrine/ConnectionStub.php b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Fixtures/Doctrine/ConnectionStub.php new file mode 100644 index 0000000000..6f777d58c9 --- /dev/null +++ b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Fixtures/Doctrine/ConnectionStub.php @@ -0,0 +1,60 @@ +affectedRows; + } + + public function getNativeConnection(): object + { + return new stdClass(); + } + + public function getServerVersion(): string + { + return '8.0.0'; + } + + public function lastInsertId(): int + { + return 0; + } + + public function prepare(string $sql): Statement + { + throw new LogicException('ConnectionStub does not prepare statements.'); + } + + public function query(string $sql): Result + { + return $this->queryResult; + } + + public function quote(string $value): string + { + return $value; + } + + public function rollBack(): void {} +} diff --git a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Fixtures/Doctrine/ResultStub.php b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Fixtures/Doctrine/ResultStub.php new file mode 100644 index 0000000000..543a5d6465 --- /dev/null +++ b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Fixtures/Doctrine/ResultStub.php @@ -0,0 +1,67 @@ +columnCount; + } + + public function fetchAllAssociative(): array + { + return []; + } + + public function fetchAllNumeric(): array + { + return []; + } + + public function fetchAssociative(): array|false + { + return false; + } + + public function fetchFirstColumn(): array + { + return []; + } + + public function fetchNumeric(): array|false + { + return false; + } + + public function fetchOne(): mixed + { + return false; + } + + public function free(): void {} + + public function rowCount(): int + { + return $this->rowCount; + } +} diff --git a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Integration/ChannelLoggerPassTest.php b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Integration/ChannelLoggerPassTest.php index 770644f7de..cc982efd19 100644 --- a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Integration/ChannelLoggerPassTest.php +++ b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Integration/ChannelLoggerPassTest.php @@ -181,6 +181,8 @@ public function test_does_not_capture_framework_channels_when_disabled(): void 'config' => static function (TestKernel $kernel) use ($channelContext): void { $kernel->addTestExtensionConfig('flow_telemetry', [ 'resource' => [], + 'exporters' => ['memory' => ['memory' => null]], + 'logger_provider' => ['processor' => ['type' => 'memory', 'exporter' => 'memory']], 'capture_framework_channels' => false, ]); $kernel->addTestContainerConfigurator(static function (ContainerBuilder $container) use ( diff --git a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Integration/FlowTelemetryExtensionTest.php b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Integration/FlowTelemetryExtensionTest.php index b2ce7a4f2a..7a7fdb03f5 100644 --- a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Integration/FlowTelemetryExtensionTest.php +++ b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Integration/FlowTelemetryExtensionTest.php @@ -12,6 +12,7 @@ use Flow\Bridge\Symfony\TelemetryBundle\Instrumentation\Messenger\MessengerFlushSubscriber; use Flow\Bridge\Symfony\TelemetryBundle\Propagation\TraceContextProvider; use Flow\Bridge\Symfony\TelemetryBundle\Routing\TraceContextUrlGenerator; +use Flow\Bridge\Symfony\TelemetryBundle\Tests\Context\RuntimeEnvironment; use Flow\Bridge\Symfony\TelemetryBundle\Tests\Fixtures\CompiledIdCollectorPass; use Flow\Bridge\Symfony\TelemetryBundle\Tests\Fixtures\Telemetry\SpySpanProcessor; use Flow\Bridge\Symfony\TelemetryBundle\Tests\Fixtures\TestKernel; @@ -19,6 +20,7 @@ use Flow\Bridge\Telemetry\OTLP\Transport\AsyncCurlTransport; use Flow\Bridge\Telemetry\OTLP\Transport\AsyncCurlTransportOptions; use Flow\Bridge\Telemetry\OTLP\Transport\CurlTransport; +use Flow\Bridge\Telemetry\OTLP\Transport\CurlTransportOptions; use Flow\Bridge\Telemetry\OTLP\Transport\GrpcTransport; use Flow\Bridge\Telemetry\OTLP\Transport\StreamTransport; use Flow\Telemetry\ErrorHandler\CompositeErrorHandler; @@ -57,6 +59,7 @@ use Flow\Telemetry\Tracer\Sampler\TraceIdRatioBasedSampler; use Override; use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\RunInSeparateProcess; use PHPUnit\Framework\Attributes\TestWith; use Symfony\Bundle\FrameworkBundle\FrameworkBundle; use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; @@ -68,7 +71,9 @@ use Symfony\Component\Messenger\Middleware\MiddlewareInterface as MessengerMiddlewareInterface; use function bin2hex; +use function class_exists; use function extension_loaded; +use function Flow\Types\DSL\type_instance_of; use function interface_exists; use function is_file; use function random_bytes; @@ -89,12 +94,55 @@ protected function tearDown(): void parent::tearDown(); } + public function test_symfony_default_logger_stays_when_no_log_processor_is_configured(): void + { + $this->bootKernel([ + 'config' => static function (TestKernel $kernel): void { + $kernel->addTestExtensionConfig('flow_telemetry', [ + 'resource' => [], + ]); + $kernel->addTestContainerConfigurator(static function (ContainerBuilder $container): void { + $loggerDefinition = new Definition(SymfonyDefaultLogger::class); + $loggerDefinition->setPublic(true); + $container->setDefinition('logger', $loggerDefinition); + }); + }, + ]); + + static::assertInstanceOf(SymfonyDefaultLogger::class, $this->getContainer()->get('logger')); + } + + #[TestWith([['processor' => ['type' => 'void']], false])] + #[TestWith([['processor' => ['type' => 'void'], 'console_output' => ['enabled' => true]], true])] + #[TestWith([['processor' => ['type' => 'memory', 'exporter' => 'memory']], true])] + public function test_logs_have_a_destination_with_a_processor_or_console_output( + array $loggerProvider, + bool $expected, + ): void { + $this->bootKernel([ + 'config' => static function (TestKernel $kernel) use ($loggerProvider): void { + $kernel->addTestExtensionConfig('flow_telemetry', [ + 'resource' => [], + 'exporters' => ['memory' => ['memory' => null]], + 'logger_provider' => $loggerProvider, + ]); + }, + ]); + + static::assertSame( + $expected, + $this->getContainer()->getParameter('flow.telemetry.logger_provider.has_destination'), + ); + } + public function test_auto_alias_when_logger_service_is_symfony_default(): void { $this->bootKernel([ 'config' => static function (TestKernel $kernel): void { $kernel->addTestExtensionConfig('flow_telemetry', [ 'resource' => [], + 'exporters' => ['memory' => ['memory' => null]], + 'logger_provider' => ['processor' => ['type' => 'memory', 'exporter' => 'memory']], ]); $kernel->addTestContainerConfigurator(static function (ContainerBuilder $container): void { $loggerDefinition = new Definition(SymfonyDefaultLogger::class); @@ -109,75 +157,150 @@ public function test_auto_alias_when_logger_service_is_symfony_default(): void static::assertSame($container->get('flow.telemetry.default.logger.psr3'), $container->get('logger')); } - public function test_caching_detector_writes_to_configured_path(): void + #[RunInSeparateProcess] + public function test_boots_without_the_otlp_bridge(): void { - $cachePath = sys_get_temp_dir() . '/flow_telemetry_resource_' . uniqid() . '.cache'; + $this->symfonyContext()->withoutOtlpBridge(); - try { + static::assertFalse(class_exists(OTLPExporter::class)); + static::assertFalse(class_exists(CurlTransportOptions::class, false)); + + $this->bootKernel([ + 'config' => static function (TestKernel $kernel): void { + $kernel->addTestExtensionConfig('flow_telemetry', [ + 'resource' => [], + 'exporters' => ['terminal' => ['console' => null]], + 'tracer_provider' => ['processor' => ['type' => 'passthrough', 'exporter' => 'terminal']], + ]); + }, + ]); + + static::assertInstanceOf(Telemetry::class, $this->getContainer()->get('flow.telemetry')); + } + + #[TestWith(['curl', [10_000, 250]])] + #[TestWith(['async_curl', [5_000, 1_500]])] + public function test_otlp_transport_timeouts_default_to_the_bridge_values(string $type, array $expected): void + { + $this->bootKernel([ + 'config' => static function (TestKernel $kernel) use ($type): void { + $kernel->addTestExtensionConfig('flow_telemetry', [ + 'resource' => [], + 'exporters' => [ + 'otlp' => ['otlp' => ['transport' => ['type' => $type, 'endpoint' => 'http://localhost:4318']]], + ], + 'tracer_provider' => ['processor' => ['type' => 'passthrough', 'exporter' => 'otlp']], + ]); + }, + ]); + + $options = $this->getContainer()->get('flow.telemetry.exporter.otlp.transport.options'); + + static::assertSame($expected, match (true) { + $options instanceof CurlTransportOptions, $options instanceof AsyncCurlTransportOptions => [ + $options->timeoutMs(), + $options->connectTimeoutMs(), + ], + default => [], + }); + } + + public function test_changed_custom_attributes_are_not_served_from_a_cache(): void + { + $teams = []; + + foreach (['first', 'second'] as $team) { $this->bootKernel([ - 'config' => static function (TestKernel $kernel) use ($cachePath): void { - $kernel->addTestExtensionConfig('flow_telemetry', [ - 'resource' => [ - 'detectors' => [ - 'static' => [ - 'cache' => ['path' => $cachePath], - ], - ], - 'custom' => ['service.name' => 'cached-service'], - ], - ]); + 'config' => static function (TestKernel $kernel) use ($team): void { + $kernel->addTestExtensionConfig('flow_telemetry', ['resource' => ['custom' => ['team' => $team]]]); }, ]); - $container = $this->getContainer(); - $detector = $container->get('flow.telemetry.resource.detector.static'); - static::assertInstanceOf(CachingDetector::class, $detector); - - $resource = $container->get('flow.telemetry.resource'); - static::assertInstanceOf(Resource::class, $resource); - static::assertSame('cached-service', $resource->get('service.name')); - static::assertFileExists($cachePath); - } finally { - if (is_file($cachePath)) { - unlink($cachePath); - } + $teams[] = type_instance_of(Resource::class) + ->assert($this->getContainer()->get('flow.telemetry.resource')) + ->get('team'); } + + static::assertSame(['first', 'second'], $teams); } - public function test_caching_detector_default_path_is_keyed_by_kernel_environment(): void + public function test_changed_environment_variables_are_not_served_from_a_cache(): void { - $expectedPath = sys_get_temp_dir() . '/flow_telemetry_resource_test.cache'; + $serviceNames = []; + + foreach (['first', 'second'] as $serviceName) { + RuntimeEnvironment::with([], ['OTEL_SERVICE_NAME' => $serviceName], function () use (&$serviceNames): void { + $this->bootKernel([ + 'config' => static function (TestKernel $kernel): void { + $kernel->addTestExtensionConfig('flow_telemetry', ['resource' => []]); + }, + ]); - if (is_file($expectedPath)) { - unlink($expectedPath); + $serviceNames[] = type_instance_of(Resource::class) + ->assert($this->getContainer()->get('flow.telemetry.resource')) + ->get('service.name'); + }); } - try { + static::assertSame(['first', 'second'], $serviceNames); + } + + public function test_custom_attributes_win_over_otel_resource_attributes(): void + { + RuntimeEnvironment::with([], ['OTEL_RESOURCE_ATTRIBUTES' => 'team=environment'], function (): void { $this->bootKernel([ 'config' => static function (TestKernel $kernel): void { $kernel->addTestExtensionConfig('flow_telemetry', [ - 'resource' => [ - 'custom' => ['service.name' => 'env-keyed-service'], - ], + 'resource' => ['custom' => ['team' => 'configuration']], ]); }, ]); - $container = $this->getContainer(); - static::assertInstanceOf( - CachingDetector::class, - $container->get('flow.telemetry.resource.detector.static'), + static::assertSame( + 'configuration', + type_instance_of(Resource::class) + ->assert($this->getContainer()->get('flow.telemetry.resource')) + ->get('team'), ); + }); + } - $resource = $container->get('flow.telemetry.resource'); - static::assertInstanceOf(Resource::class, $resource); - static::assertSame('env-keyed-service', $resource->get('service.name')); - static::assertFileExists($expectedPath); - } finally { - if (is_file($expectedPath)) { - unlink($expectedPath); - } - } + public function test_host_attributes_are_cached_for_the_host_and_git_attributes_for_the_release(): void + { + $kernel = $this->bootKernel([ + 'config' => static function (TestKernel $kernel): void { + $kernel->addTestExtensionConfig('flow_telemetry', [ + 'resource' => ['detectors' => ['static' => ['git' => ['enabled' => true]]]], + ]); + }, + ]); + + $container = $this->getContainer(); + $container->get('flow.telemetry.resource'); + + static::assertInstanceOf( + CachingDetector::class, + $container->get('flow.telemetry.resource.detector.host_cache'), + ); + static::assertInstanceOf(CachingDetector::class, $container->get('flow.telemetry.resource.detector.git_cache')); + static::assertFileExists(sys_get_temp_dir() . '/flow_telemetry_resource_host.cache'); + static::assertFileExists($kernel->getCacheDir() . '/flow_telemetry_resource_git.cache'); + } + + public function test_nothing_is_cached_when_the_resource_cache_is_disabled(): void + { + $this->bootKernel([ + 'config' => static function (TestKernel $kernel): void { + $kernel->addTestExtensionConfig('flow_telemetry', [ + 'resource' => [ + 'detectors' => ['static' => ['cache' => ['enabled' => false], 'git' => ['enabled' => true]]], + ], + ]); + }, + ]); + + static::assertFalse($this->getContainer()->has('flow.telemetry.resource.detector.host_cache')); + static::assertFalse($this->getContainer()->has('flow.telemetry.resource.detector.git_cache')); } public function test_git_detector_is_not_registered_by_default(): void diff --git a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Integration/Instrumentation/Doctrine/DBAL/TracingMiddlewareTest.php b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Integration/Instrumentation/Doctrine/DBAL/TracingMiddlewareTest.php index 238c3f961b..b6eb615571 100644 --- a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Integration/Instrumentation/Doctrine/DBAL/TracingMiddlewareTest.php +++ b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Integration/Instrumentation/Doctrine/DBAL/TracingMiddlewareTest.php @@ -18,6 +18,7 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use function array_filter; +use function array_intersect_key; use function array_map; use function array_values; use function interface_exists; @@ -585,6 +586,52 @@ public function test_prepared_statement_creates_prepare_and_execute_spans(): voi } } + public function test_sqlite_reports_affected_rows_and_no_row_count_for_a_select(): void + { + $this->bootKernel([ + 'config' => static function (TestKernel $kernel): void { + $kernel->addTestContainerConfigurator(static function (ContainerBuilder $container): void { + $container->setParameter('doctrine.connections', ['default' => 'doctrine.dbal.default_connection']); + }); + + $kernel->addTestExtensionConfig('flow_telemetry', [ + 'resource' => [], + 'exporters' => ['memory' => ['memory' => null]], + 'tracer_provider' => ['processor' => ['type' => 'memory', 'exporter' => 'memory']], + 'instrumentation' => ['dbal' => ['enabled' => true]], + ]); + }, + ]); + + $container = $this->getContainer(); + + /** @var TracingMiddleware $middleware */ + $middleware = $container->get('flow.telemetry.dbal.middleware.default'); + + $configuration = new Configuration(); + $configuration->setMiddlewares([$middleware]); + + $connection = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true], $configuration); + $connection->executeStatement('CREATE TABLE test_table (id INTEGER PRIMARY KEY, name TEXT)'); + $connection->executeStatement('INSERT INTO test_table (name) VALUES (?)', ['first']); + $connection->fetchAllAssociative('SELECT * FROM test_table WHERE name = ?', ['first']); + + /** @var MemorySpanProcessor $processor */ + $processor = $container->get('flow.telemetry.tracer_provider.processor'); + + $rowAttributes = []; + + foreach ($processor->endedSpans() as $span) { + $rowAttributes[$span->name()][] = array_intersect_key($span->attributes(), [ + 'db.response.returned_rows' => true, + 'flow.db.response.affected_rows' => true, + ]); + } + + static::assertSame([[], []], $rowAttributes['SELECT test_table']); + static::assertContains(['flow.db.response.affected_rows' => 1], $rowAttributes['INSERT test_table']); + } + public function test_query_creates_span_with_sql_attribute(): void { $this->bootKernel([ diff --git a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/DependencyInjection/Compiler/FrameworkLoggerPassTest.php b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/DependencyInjection/Compiler/FrameworkLoggerPassTest.php index 32d62632cd..f51fef63c1 100644 --- a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/DependencyInjection/Compiler/FrameworkLoggerPassTest.php +++ b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/DependencyInjection/Compiler/FrameworkLoggerPassTest.php @@ -38,6 +38,42 @@ public function test_aliases_symfony_logger_when_telemetry_is_enabled(): void static::assertSame('flow.telemetry.default.logger.psr3', (string) $container->getAlias('logger')); } + public function test_symfony_logger_stays_when_logs_have_no_destination(): void + { + $container = new ContainerBuilder(); + $container->setParameter('flow.telemetry.logger_provider.has_destination', false); + $container->setDefinition('logger', new Definition(SymfonyDefaultLogger::class)); + + (new FrameworkLoggerPass())->process($container); + + static::assertFalse($container->hasAlias('logger')); + static::assertSame(SymfonyDefaultLogger::class, $container->getDefinition('logger')->getClass()); + } + + public function test_symfony_logger_is_aliased_when_logs_have_a_destination(): void + { + $container = new ContainerBuilder(); + $container->setParameter('flow.telemetry.logger_provider.has_destination', true); + $container->setDefinition('logger', new Definition(SymfonyDefaultLogger::class)); + + (new FrameworkLoggerPass())->process($container); + + static::assertSame('flow.telemetry.default.logger.psr3', (string) $container->getAlias('logger')); + } + + public function test_framework_logger_is_aliased_without_a_destination(): void + { + $container = new ContainerBuilder(); + $container->setParameter('flow.telemetry.framework_logger', 'default'); + $container->setParameter('flow.telemetry.logger_provider.has_destination', false); + $container->setDefinition('logger', new Definition(SymfonyDefaultLogger::class)); + $container->setDefinition('flow.telemetry.default.logger.psr3', new Definition(SymfonyDefaultLogger::class)); + + (new FrameworkLoggerPass())->process($container); + + static::assertSame('flow.telemetry.default.logger.psr3', (string) $container->getAlias('logger')); + } + public function test_aliases_symfony_logger_when_enabled_parameter_is_absent(): void { $container = new ContainerBuilder(); diff --git a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/DependencyInjection/ConfigurationTest.php b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/DependencyInjection/ConfigurationTest.php index 7a8e04acbd..6c337b1135 100644 --- a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/DependencyInjection/ConfigurationTest.php +++ b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/DependencyInjection/ConfigurationTest.php @@ -11,6 +11,7 @@ use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\Config\Definition\Exception\InvalidTypeException; +use function array_intersect_key; use function sprintf; final class ConfigurationTest extends TestCase @@ -330,20 +331,31 @@ public function test_async_curl_transport_is_accepted(): void static::assertSame(500, $config['exporters']['otlp']['otlp']['transport']['connect_timeout_ms']); } - public function test_async_curl_transport_defaults_connect_timeout_to_1500ms(): void + #[TestWith(['curl'])] + #[TestWith(['async_curl'])] + #[TestWith(['grpc'])] + public function test_timeouts_that_are_not_configured_are_left_to_the_transport(string $type): void { $config = $this->context->processConfig([ 'resource' => [], 'exporters' => [ 'otlp' => [ 'otlp' => [ - 'transport' => ['type' => 'async_curl', 'endpoint' => 'http://localhost:4318'], + 'transport' => ['type' => $type, 'endpoint' => 'http://localhost:4318'], ], ], ], ]); - static::assertSame(1500, $config['exporters']['otlp']['otlp']['transport']['connect_timeout_ms']); + static::assertSame( + [], + array_intersect_key($config['exporters']['otlp']['otlp']['transport'], [ + 'timeout_ms' => true, + 'connect_timeout_ms' => true, + 'pump_timeout_ms' => true, + 'shutdown_timeout_ms' => true, + ]), + ); } public function test_async_curl_transport_accepts_pump_timeout_ms(): void @@ -366,22 +378,6 @@ public function test_async_curl_transport_accepts_pump_timeout_ms(): void static::assertSame(50, $config['exporters']['otlp']['otlp']['transport']['pump_timeout_ms']); } - public function test_async_curl_transport_defaults_pump_timeout_to_100ms(): void - { - $config = $this->context->processConfig([ - 'resource' => [], - 'exporters' => [ - 'otlp' => [ - 'otlp' => [ - 'transport' => ['type' => 'async_curl', 'endpoint' => 'http://localhost:4318'], - ], - ], - ], - ]); - - static::assertSame(100, $config['exporters']['otlp']['otlp']['transport']['pump_timeout_ms']); - } - #[TestWith(['curl'])] #[TestWith(['grpc'])] #[TestWith(['stream'])] @@ -408,22 +404,6 @@ public function test_pump_timeout_ms_is_rejected_for_non_async_curl_transports(s ]); } - public function test_curl_transport_defaults_request_timeout_to_10000ms(): void - { - $config = $this->context->processConfig([ - 'resource' => [], - 'exporters' => [ - 'otlp' => [ - 'otlp' => [ - 'transport' => ['type' => 'curl', 'endpoint' => 'http://localhost:4318'], - ], - ], - ], - ]); - - static::assertSame(10000, $config['exporters']['otlp']['otlp']['transport']['timeout_ms']); - } - public function test_otlp_exporter_error_handler_defaults_to_default(): void { $config = $this->context->processConfig([ diff --git a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/Instrumentation/Doctrine/DBAL/QueryTracerTest.php b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/Instrumentation/Doctrine/DBAL/QueryTracerTest.php index 0e223d1449..fd08efdf28 100644 --- a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/Instrumentation/Doctrine/DBAL/QueryTracerTest.php +++ b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/Instrumentation/Doctrine/DBAL/QueryTracerTest.php @@ -7,6 +7,7 @@ use Doctrine\DBAL\Driver\Exception as DriverException; use Flow\Bridge\Symfony\TelemetryBundle\Instrumentation\Doctrine\DBAL\QueryTracer; use Flow\Bridge\Symfony\TelemetryBundle\Instrumentation\Doctrine\DBAL\SqlAttributes; +use Flow\Bridge\Symfony\TelemetryBundle\Tests\Fixtures\Doctrine\ResultStub; use Flow\Bridge\Symfony\TelemetryBundle\Tests\Mother\TelemetryMother; use Flow\Telemetry\PackageVersion; use Flow\Telemetry\Provider\Memory\MemoryExporter; @@ -163,6 +164,29 @@ public function test_record_error_sets_status_code_from_driver_exception(): void static::assertSame('23505', $span->attributes()['db.response.status_code']); } + #[TestWith([0])] + #[TestWith([3])] + public function test_a_result_set_has_no_affected_rows(int $driverRowCount): void + { + $queryTracer = $this->queryTracer(TelemetryMother::withSpanProcessor(new MemorySpanProcessor( + new MemoryExporter(), + ))); + + static::assertNull($queryTracer->affectedRows(ResultStub::resultSet($driverRowCount))); + } + + #[TestWith(['postgresql'])] + #[TestWith(['sqlite'])] + public function test_a_statement_without_a_result_set_reports_the_affected_rows(string $system): void + { + $queryTracer = $this->queryTracer( + TelemetryMother::withSpanProcessor(new MemorySpanProcessor(new MemoryExporter())), + baseAttributes: ['db.system.name' => $system], + ); + + static::assertSame(5, $queryTracer->affectedRows(ResultStub::affecting(5))); + } + public function test_record_query_metrics_uses_low_cardinality_attributes(): void { $metricProcessor = new MemoryMetricProcessor(new MemoryExporter()); @@ -173,7 +197,7 @@ public function test_record_query_metrics_uses_low_cardinality_attributes(): voi collectMetrics: true, ); - $queryTracer->recordQueryMetrics(hrtime(true), 5, new SqlAttributes('SELECT', 'users')); + $queryTracer->recordQueryMetrics(hrtime(true), new SqlAttributes('SELECT', 'users')); $this->collectMetrics($telemetry); $duration = $metricProcessor->metricsWithName('db.client.operation.duration'); @@ -181,8 +205,7 @@ public function test_record_query_metrics_uses_low_cardinality_attributes(): voi static::assertSame('SELECT', $duration[0]->attributes->get('db.operation.name')); static::assertSame('users', $duration[0]->attributes->get('db.collection.name')); static::assertFalse($duration[0]->attributes->has('db.query.text')); - - static::assertCount(1, $metricProcessor->metricsWithName('db.client.response.returned_rows')); + static::assertSame(1, $metricProcessor->countMetrics()); } public function test_record_query_metrics_noop_when_metrics_disabled(): void @@ -191,7 +214,7 @@ public function test_record_query_metrics_noop_when_metrics_disabled(): void $telemetry = TelemetryMother::withProcessors(new MemorySpanProcessor(new MemoryExporter()), $metricProcessor); $queryTracer = $this->queryTracer($telemetry, collectMetrics: false); - $queryTracer->recordQueryMetrics(hrtime(true), 5, new SqlAttributes('SELECT', 'users')); + $queryTracer->recordQueryMetrics(hrtime(true), new SqlAttributes('SELECT', 'users')); $this->collectMetrics($telemetry); static::assertSame(0, $metricProcessor->countMetrics()); diff --git a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/Instrumentation/Doctrine/DBAL/TracingConnectionTest.php b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/Instrumentation/Doctrine/DBAL/TracingConnectionTest.php index 13e100dde9..d72a13222c 100644 --- a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/Instrumentation/Doctrine/DBAL/TracingConnectionTest.php +++ b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/Instrumentation/Doctrine/DBAL/TracingConnectionTest.php @@ -12,6 +12,8 @@ use Flow\Bridge\Symfony\TelemetryBundle\Instrumentation\Doctrine\DBAL\TracingConnection; use Flow\Bridge\Symfony\TelemetryBundle\Instrumentation\Doctrine\DBAL\TracingStatement; use Flow\Bridge\Symfony\TelemetryBundle\Instrumentation\Doctrine\DBAL\TransactionSpanMode; +use Flow\Bridge\Symfony\TelemetryBundle\Tests\Fixtures\Doctrine\ConnectionStub; +use Flow\Bridge\Symfony\TelemetryBundle\Tests\Fixtures\Doctrine\ResultStub; use Flow\Bridge\Symfony\TelemetryBundle\Tests\Mother\TelemetryMother; use Flow\Telemetry\Context\Context; use Flow\Telemetry\Context\MemoryContextStorage; @@ -517,7 +519,35 @@ public function test_query_span_has_semantic_name_and_attributes(): void static::assertSame('SELECT', $attributes['db.operation.name']); static::assertSame('users', $attributes['db.collection.name']); static::assertSame('SELECT * FROM users WHERE id = 1', $attributes['db.query.text']); - static::assertArrayHasKey('db.response.returned_rows', $attributes); + } + + public function test_query_with_a_result_set_has_no_row_count(): void + { + $spanProcessor = new MemorySpanProcessor(new MemoryExporter()); + $tracing = $this->tracingConnection( + new ConnectionStub(ResultStub::resultSet(3), 0), + TelemetryMother::withSpanProcessor($spanProcessor), + ); + + $tracing->query('SELECT * FROM users'); + + $attributes = $spanProcessor->endedSpans()[0]->attributes(); + + static::assertArrayNotHasKey('db.response.returned_rows', $attributes); + static::assertArrayNotHasKey('flow.db.response.affected_rows', $attributes); + } + + public function test_exec_span_has_the_affected_rows(): void + { + $spanProcessor = new MemorySpanProcessor(new MemoryExporter()); + $tracing = $this->tracingConnection( + new ConnectionStub(ResultStub::resultSet(0), 5), + TelemetryMother::withSpanProcessor($spanProcessor), + ); + + $tracing->exec('DELETE FROM users'); + + static::assertSame(5, $spanProcessor->endedSpans()[0]->attributes()['flow.db.response.affected_rows']); } public function test_records_duration_and_row_metrics_with_low_cardinality_attributes(): void @@ -546,7 +576,7 @@ public function test_records_duration_and_row_metrics_with_low_cardinality_attri static::assertSame('SELECT', $duration[0]->attributes->get('db.operation.name')); static::assertSame('users', $duration[0]->attributes->get('db.collection.name')); - static::assertCount(1, $metricProcessor->metricsWithName('db.client.response.returned_rows')); + static::assertCount(0, $metricProcessor->metricsWithName('db.client.response.returned_rows')); } public function test_transaction_duration_metric_uses_operation_and_nesting_level(): void diff --git a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/Instrumentation/Doctrine/DBAL/TracingStatementTest.php b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/Instrumentation/Doctrine/DBAL/TracingStatementTest.php index 9b0d6c16d4..aa9b377006 100644 --- a/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/Instrumentation/Doctrine/DBAL/TracingStatementTest.php +++ b/src/bridge/symfony/telemetry-bundle/tests/Flow/Bridge/Symfony/TelemetryBundle/Tests/Unit/Instrumentation/Doctrine/DBAL/TracingStatementTest.php @@ -8,6 +8,7 @@ use Doctrine\DBAL\Driver\Statement as StatementInterface; use Flow\Bridge\Symfony\TelemetryBundle\Instrumentation\Doctrine\DBAL\QueryTracer; use Flow\Bridge\Symfony\TelemetryBundle\Instrumentation\Doctrine\DBAL\TracingStatement; +use Flow\Bridge\Symfony\TelemetryBundle\Tests\Fixtures\Doctrine\ResultStub; use Flow\Bridge\Symfony\TelemetryBundle\Tests\Mother\TelemetryMother; use Flow\Telemetry\Provider\Memory\MemoryExporter; use Flow\Telemetry\Provider\Memory\MemorySpanProcessor; @@ -37,6 +38,35 @@ public function test_traces_statement_execution(): void static::assertSame('SELECT * FROM users', $spans[0]->attributes()['db.query.text']); } + public function test_statement_with_a_result_set_has_no_row_count(): void + { + $spanProcessor = new MemorySpanProcessor(new MemoryExporter()); + $telemetry = TelemetryMother::withSpanProcessor($spanProcessor); + + $statement = $this->createStub(StatementInterface::class); + $statement->method('execute')->willReturn(ResultStub::resultSet(3)); + + $this->tracingStatement($statement, $telemetry, 'SELECT * FROM users')->execute(); + + $attributes = $spanProcessor->endedSpans()[0]->attributes(); + + static::assertArrayNotHasKey('db.response.returned_rows', $attributes); + static::assertArrayNotHasKey('flow.db.response.affected_rows', $attributes); + } + + public function test_statement_without_a_result_set_has_the_affected_rows(): void + { + $spanProcessor = new MemorySpanProcessor(new MemoryExporter()); + $telemetry = TelemetryMother::withSpanProcessor($spanProcessor); + + $statement = $this->createStub(StatementInterface::class); + $statement->method('execute')->willReturn(ResultStub::affecting(5)); + + $this->tracingStatement($statement, $telemetry, 'UPDATE users SET active = 1')->execute(); + + static::assertSame(5, $spanProcessor->endedSpans()[0]->attributes()['flow.db.response.affected_rows']); + } + public function test_records_exception_when_execution_fails(): void { $spanProcessor = new MemorySpanProcessor(new MemoryExporter()); diff --git a/src/lib/telemetry/src/Flow/Telemetry/Provider/Console/ConsoleExporter.php b/src/lib/telemetry/src/Flow/Telemetry/Provider/Console/ConsoleExporter.php index ef2831bfe0..14ce7d5bbb 100644 --- a/src/lib/telemetry/src/Flow/Telemetry/Provider/Console/ConsoleExporter.php +++ b/src/lib/telemetry/src/Flow/Telemetry/Provider/Console/ConsoleExporter.php @@ -52,7 +52,7 @@ /** * @param bool $colors Whether to use ANSI colors * @param null|int $maxLogBodyLength Maximum length for log body+attributes column (null = no limit) - * @param null|resource $outputStream Output stream (default: STDOUT) + * @param null|resource $outputStream Output stream (default: php://stdout) */ public function __construct( bool $colors = true, @@ -188,7 +188,7 @@ private function buildLogScopeLine(LogEntry $entry): ?string $scope = $entry->scope; - return 'Scope: ' . $this->output->dim($scope->name . ' v' . $scope->version); + return 'Scope: ' . $this->output->dim($scope->name . ' ' . $scope->version); } /** @@ -272,7 +272,7 @@ private function buildMetricScopeLine(Metric $metric): ?string $scope = $metric->scope; - return 'Scope: ' . $this->output->dim($scope->name . ' v' . $scope->version); + return 'Scope: ' . $this->output->dim($scope->name . ' ' . $scope->version); } /** @@ -290,7 +290,7 @@ private function buildShortResourceLines(TelemetryResource $resource): array $serviceVersion = $resource->get('service.version'); if (is_string($serviceVersion)) { - $parts[] = 'v' . $serviceVersion; + $parts[] = $serviceVersion; } if (count($parts) === 0) { @@ -479,7 +479,7 @@ private function buildSpanScopeLines(Span $span): array $scope = $span->scope(); - return ['Scope: ' . $this->output->dim($scope->name . ' v' . $scope->version)]; + return ['Scope: ' . $this->output->dim($scope->name . ' ' . $scope->version)]; } /** diff --git a/src/lib/telemetry/src/Flow/Telemetry/Provider/Console/ConsoleOutput.php b/src/lib/telemetry/src/Flow/Telemetry/Provider/Console/ConsoleOutput.php index 82f425d556..7a600c5a83 100644 --- a/src/lib/telemetry/src/Flow/Telemetry/Provider/Console/ConsoleOutput.php +++ b/src/lib/telemetry/src/Flow/Telemetry/Provider/Console/ConsoleOutput.php @@ -5,12 +5,16 @@ namespace Flow\Telemetry\Provider\Console; use DateTimeImmutable; +use Flow\Telemetry\Exception\RuntimeException; use JsonException; use function floor; +use function fopen; use function fwrite; +use function get_debug_type; use function is_array; use function is_bool; +use function is_resource; use function json_encode; use function mb_strlen; use function mb_substr; @@ -18,8 +22,6 @@ use function sprintf; use function str_repeat; -use const STDOUT; - final class ConsoleOutput { private const string BLUE = "\033[34m"; @@ -45,13 +47,23 @@ final class ConsoleOutput /** * @param bool $colors Whether to use ANSI colors - * @param null|resource $stream Output stream (default: STDOUT) + * @param null|resource $stream Output stream (default: php://stdout) */ public function __construct( private readonly bool $colors = true, $stream = null, ) { - $this->stream = $stream ?? STDOUT; + $stream ??= fopen('php://stdout', 'wb'); + + if (!is_resource($stream)) { + throw new RuntimeException( + 'Console output needs an open stream, for example fopen("php://stdout", "wb"), got ' + . get_debug_type($stream) + . '.', + ); + } + + $this->stream = $stream; } public function blue(string $text): string diff --git a/src/lib/telemetry/tests/Flow/Telemetry/Tests/Mother/LogEntryMother.php b/src/lib/telemetry/tests/Flow/Telemetry/Tests/Mother/LogEntryMother.php index 011f931e69..7a4651542f 100644 --- a/src/lib/telemetry/tests/Flow/Telemetry/Tests/Mother/LogEntryMother.php +++ b/src/lib/telemetry/tests/Flow/Telemetry/Tests/Mother/LogEntryMother.php @@ -5,13 +5,28 @@ namespace Flow\Telemetry\Tests\Mother; use DateTimeImmutable; +use Flow\Telemetry\InstrumentationScope; use Flow\Telemetry\Logger\LogEntry; use Flow\Telemetry\Logger\LogRecord; use Flow\Telemetry\Logger\Severity; +use Flow\Telemetry\Resource; use Flow\Telemetry\Tracer\SpanContext; final class LogEntryMother { + public static function scoped(InstrumentationScope $scope, Resource $resource): LogEntry + { + return new LogEntry( + (new LogRecord()) + ->setSeverity(Severity::INFO) + ->setBody('Hello world'), + $resource, + $scope, + new DateTimeImmutable('2024-01-15T10:30:00.000000+00:00'), + null, + ); + } + /** * @param array|bool|\DateTimeImmutable|float|int|string> $attributes */ diff --git a/src/lib/telemetry/tests/Flow/Telemetry/Tests/Mother/MetricMother.php b/src/lib/telemetry/tests/Flow/Telemetry/Tests/Mother/MetricMother.php index 8242e0d07c..20bff2d5c8 100644 --- a/src/lib/telemetry/tests/Flow/Telemetry/Tests/Mother/MetricMother.php +++ b/src/lib/telemetry/tests/Flow/Telemetry/Tests/Mother/MetricMother.php @@ -6,8 +6,10 @@ use DateTimeImmutable; use Flow\Telemetry\Attributes; +use Flow\Telemetry\InstrumentationScope; use Flow\Telemetry\Meter\Metric; use Flow\Telemetry\Meter\MetricType; +use Flow\Telemetry\Resource; final class MetricMother { @@ -68,6 +70,19 @@ public static function deterministicGauge( ); } + public static function scoped(InstrumentationScope $scope, Resource $resource): Metric + { + return new Metric( + name: 'requests.total', + type: MetricType::COUNTER, + value: 1, + attributes: Attributes::empty(), + timestamp: new DateTimeImmutable('2024-01-15T10:30:00.000000+00:00'), + resource: $resource, + scope: $scope, + ); + } + public static function counterWithAttributes(string $name, int|float $value, Attributes $attributes): Metric { return new Metric( diff --git a/src/lib/telemetry/tests/Flow/Telemetry/Tests/Mother/SpanMother.php b/src/lib/telemetry/tests/Flow/Telemetry/Tests/Mother/SpanMother.php index 55b7b8256a..7b89c13b8e 100644 --- a/src/lib/telemetry/tests/Flow/Telemetry/Tests/Mother/SpanMother.php +++ b/src/lib/telemetry/tests/Flow/Telemetry/Tests/Mother/SpanMother.php @@ -8,6 +8,7 @@ use Flow\Telemetry\Context\SpanId; use Flow\Telemetry\Context\TraceId; use Flow\Telemetry\InstrumentationScope; +use Flow\Telemetry\Resource; use Flow\Telemetry\Tracer\Span; use Flow\Telemetry\Tracer\SpanContext; use Flow\Telemetry\Tracer\SpanKind; @@ -48,6 +49,21 @@ public static function deterministic(string $name = 'test-operation', SpanKind $ ); } + public static function scoped(InstrumentationScope $scope, Resource $resource): Span + { + return new Span( + 'test-operation', + SpanContext::create( + TraceId::fromHex('0123456789abcdef0123456789abcdef'), + SpanId::fromHex('0123456789abcdef'), + ), + SpanKind::INTERNAL, + new DateTimeImmutable('2024-01-15T10:30:00.000000+00:00'), + $resource, + $scope, + ); + } + public static function withName(string $name): Span { return self::create($name); diff --git a/src/lib/telemetry/tests/Flow/Telemetry/Tests/Unit/Provider/Console/ConsoleExporterTest.php b/src/lib/telemetry/tests/Flow/Telemetry/Tests/Unit/Provider/Console/ConsoleExporterTest.php index 58c45f7288..93f90398db 100644 --- a/src/lib/telemetry/tests/Flow/Telemetry/Tests/Unit/Provider/Console/ConsoleExporterTest.php +++ b/src/lib/telemetry/tests/Flow/Telemetry/Tests/Unit/Provider/Console/ConsoleExporterTest.php @@ -11,18 +11,22 @@ use Flow\Telemetry\Meter\Metric; use Flow\Telemetry\Meter\MetricType; use Flow\Telemetry\Provider\Console\ConsoleExporter; +use Flow\Telemetry\Provider\Console\ConsoleLogOptions; use Flow\Telemetry\Signal\Signals; use Flow\Telemetry\Tests\Mother\InstrumentationScopeMother; use Flow\Telemetry\Tests\Mother\LogEntryMother; +use Flow\Telemetry\Tests\Mother\MetricMother; use Flow\Telemetry\Tests\Mother\ResourceMother; use Flow\Telemetry\Tests\Mother\SpanMother; use Flow\Telemetry\Tracer\SpanKind; use Flow\Telemetry\Tracer\SpanStatus; +use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\TestCase; use function fopen; use function rewind; use function stream_get_contents; +use function substr_count; final class ConsoleExporterTest extends TestCase { @@ -123,6 +127,35 @@ public function test_export_traces_writes_span_section(): void static::assertStringContainsString('SPAN: test-operation', $output); } + #[TestWith(['v7.4.24'])] + #[TestWith(['4.5.0'])] + #[TestWith(['unknown'])] + public function test_versions_are_printed_as_reported(string $version): void + { + $stream = fopen('php://memory', 'rwb'); + static::assertIsResource($stream); + + $scope = InstrumentationScopeMother::named('checkout', $version); + $resource = ResourceMother::with(['service.name' => 'shop', 'service.version' => $version]); + + $exporter = new ConsoleExporter( + colors: false, + outputStream: $stream, + logOptions: new ConsoleLogOptions(showResourceAttributes: false), + ); + $exporter->export(Signals::logs([LogEntryMother::scoped($scope, $resource)])); + $exporter->export(Signals::metrics([MetricMother::scoped($scope, $resource)])); + $exporter->export(Signals::traces([ + SpanMother::scoped($scope, $resource)->end(new DateTimeImmutable('2024-01-15T10:30:00.150000+00:00')), + ])); + + rewind($stream); + $output = (string) stream_get_contents($stream); + + static::assertSame(3, substr_count($output, 'Scope: checkout ' . $version)); + static::assertStringContainsString('shop ' . $version, $output); + } + public function test_implements_exporter(): void { $stream = fopen('php://memory', 'rwb'); diff --git a/src/lib/telemetry/tests/Flow/Telemetry/Tests/Unit/Provider/Console/ConsoleOutputTest.php b/src/lib/telemetry/tests/Flow/Telemetry/Tests/Unit/Provider/Console/ConsoleOutputTest.php index 6052a7ed26..9e2ebdddc1 100644 --- a/src/lib/telemetry/tests/Flow/Telemetry/Tests/Unit/Provider/Console/ConsoleOutputTest.php +++ b/src/lib/telemetry/tests/Flow/Telemetry/Tests/Unit/Provider/Console/ConsoleOutputTest.php @@ -5,6 +5,7 @@ namespace Flow\Telemetry\Tests\Unit\Provider\Console; use DateTimeImmutable; +use Flow\Telemetry\Exception\RuntimeException; use Flow\Telemetry\Provider\Console\ConsoleOutput; use PHPUnit\Framework\TestCase; @@ -40,6 +41,18 @@ public function test_color_enabled_wraps_text_with_ansi(): void static::assertStringContainsString('test', $output->red('test')); } + public function test_rejects_a_value_that_is_not_an_open_stream(): void + { + $stream = fopen('php://memory', 'rwb'); + static::assertIsResource($stream); + fclose($stream); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Console output needs an open stream'); + + new ConsoleOutput(stream: $stream); + } + public function test_format_duration_microseconds(): void { $output = new ConsoleOutput(); diff --git a/terraform/cloudflare/README.md b/terraform/cloudflare/README.md index 9b319a055f..5f5dd47573 100644 --- a/terraform/cloudflare/README.md +++ b/terraform/cloudflare/README.md @@ -1,15 +1,52 @@ # Cloudflare Terraform -Required Variables: +Terraform runs in the nix shell, from this directory: -``` -export CLOUDFLARE_API_TOKEN="xxx" -export TF_VAR_account_id="xxx" -export TF_VAR_zone_id="xxx" +```shell +nix-shell --arg with-terraform true +cd terraform/cloudflare +terraform init +terraform plan ``` -# Initialization +## State +The state is in the R2 bucket `flow-php-terraform-state`, under the key `cloudflare/terraform.tfstate`. Terraform +reads and writes it through the `s3` backend in `versions.tf`. A lock file next to the state stops two runs at the +same time. + +The bucket is not managed by this configuration. It was created by hand, with an R2 API token that has "Object Read +& Write" on this bucket only. + +## Credentials + +`terraform` in the nix shell runs through [fnox](https://fnox.jdx.dev). fnox reads the secrets below and gives them +to terraform only. Nothing is exported to the shell. + +| Secret | Terraform reads it as | +|-------------------------|-------------------------------------------| +| `CLOUDFLARE_API_TOKEN` | the token of the provider | +| `TF_VAR_account_id` | the variable `account_id` | +| `TF_VAR_zone_id` | the variable `zone_id` | +| `AWS_ACCESS_KEY_ID` | the access key ID of the state bucket | +| `AWS_SECRET_ACCESS_KEY` | the secret access key of the state bucket | +| `AWS_ENDPOINT_URL_S3` | the S3 endpoint of the account in R2 | + +`fnox.toml` in the repository root names the secrets. Your provider goes into `fnox.local.toml`, which git ignores. +An example for 1Password, where each value is `item/field` in the vault: + +```toml +[providers.op] +type = "1password" +vault = "my-vault" + +[secrets] +CLOUDFLARE_API_TOKEN = { provider = "op", value = "cloudflare-api-token/credential" } +TF_VAR_account_id = { provider = "op", value = "terraform-account-id/credential" } +TF_VAR_zone_id = { provider = "op", value = "terraform-zone-id/credential" } +AWS_ACCESS_KEY_ID = { provider = "op", value = "cloudflare-terraform-state-token/access_key_id" } +AWS_SECRET_ACCESS_KEY = { provider = "op", value = "cloudflare-terraform-state-token/secret_access_key" } +AWS_ENDPOINT_URL_S3 = { provider = "op", value = "cloudflare-terraform-state-token/s3_endpoint" } ``` -terraform init -``` + +The "Secrets" section of the [nix page](/documentation/contributing/nix.md) has the full setup. diff --git a/terraform/cloudflare/redirects.csv b/terraform/cloudflare/redirects.csv new file mode 100644 index 0000000000..f54771011b --- /dev/null +++ b/terraform/cloudflare/redirects.csv @@ -0,0 +1,103 @@ +source,target +/data_frame/,/examples/ +/join/,/examples/#Join +/filesystem/,/examples/#Store%20files +/data_reading/,/examples/#Read +/join/join/,/joins/join/ +/data_writing/,/examples/#Write +/aggregations/grouping/group_by/,/aggregations/group_by/group_by/ +/data_frame/data_reading/array/,/reading/array/ +/partitioning/,/examples/#Partition +/types/assertions/scalar/,/types/assert/ +/types/casting/boolean/,/types/cast/ +/data_reading/csv/,/reading/csv/ +/types/,/examples/#Cast +/transformations/,/examples/#Transform +/partitioning/partitioning/,/partitioning/partitioning/overwrite/ +/types/validation/uuid/,/types/is_valid/ +/schema/,/examples/#Validate +/data_writing/database_upsert/,/writing/dbal/upsert/ +/types/assertions/uuid/,/types/assert/ +/types/validation/enum/,/types/is_valid/ +/data_writing/parquet/,/writing/parquet/ +/data_reading/parquet/,/reading/parquet/ +/data_frame/data_reading/database/,/reading/dbal/limit_offset/ +/data_writing/jsonl/,/writing/jsonl/ +/data_frame/data_writing/database_upsert/,/writing/dbal/upsert/ +/data_frame/batch_by/,/batching/batch_by/ +/data_reading/database/,/reading/dbal/limit_offset/ +/data_frame/batch_size/,/batching/constant_size/ +/types/assertions/,/types/assert/ +/window_functions/,/examples/#Rank +/data_frame/batch_size/collect/,/batching/collect/ +/aggregations/,/examples/#Aggregate +/data_frame/data_writing/parquet/,/writing/parquet/ +/data_frame/data_writing/array/,/writing/array/ +/types/validation/array/,/types/is_valid/ +/types/casting/enum/,/types/cast/ +/types/assertions/instance_of/,/types/assert/ +/types/validation/boolean/,/types/is_valid/ +/types/casting/mixed/,/types/cast/ +/types/casting/scalar/,/types/cast/ +/types/validation/xml/,/types/is_valid/ +/data_frame/data_writing/database/,/writing/dbal/insert/ +/types/casting/constrained/,/types/cast/ +/data_reading/http_dynamic/,/reading/http/ +/join/join_each/,/joins/join_each/ +/data_frame/data_reading/jsonl/,/reading/jsonl/ +/types/casting/array/,/types/cast/ +/data_frame/data_reading/parquet/,/reading/parquet/ +/data_reading/jsonl/,/reading/jsonl/ +/types/assertions/array/,/types/assert/ +/data_frame/data_reading/http_dynamic/,/reading/http/ +/types/assertions/literal/,/types/assert/ +/data_reading/xml/,/reading/xml/ +/types/casting/class_string/,/types/cast/ +/data_frame/rename_columns/,/columns/rename/ +/data_frame/cache/,/caching/cache/ +/data_writing/csv/,/writing/csv/ +/types/casting/optional/,/types/cast/ +/data_frame/data_writing/database_delete/,/writing/dbal/delete/ +/data_frame/batch_size/constant_size/,/batching/constant_size/ +/aggregations/group_by/,/aggregations/group_by/group_by/ +/aggregations/aggregating_functions/sum/,/aggregations/functions/sum/ +/types/assertions/class_string/,/types/assert/ +/data_frame/columns/rename/,/columns/rename/ +/data_frame/data_reading/http_static/,/reading/http/ +/data_writing/elasticsearch/,/guides/index-database-table-in-elasticsearch-with-php/ +/data_frame/data_reading/xml/,/reading/xml/ +/data_frame/transformations/custom/,/transformations/custom/ +/data_frame/columns/create/,/columns/create/ +/types/validation/structure/,/types/is_valid/ +/data_writing/database/,/writing/dbal/insert/ +/data_frame/data_writing/excel/,/writing/excel/ +/data_frame/data_reading/json/,/reading/json/ +/types/casting/resource/,/types/cast/ +/data_reading/json/,/reading/json/ +/data_frame/data_reading/csv/,/reading/csv/ +/types/assertions/structure/,/types/assert/ +/data_frame/data_reading/excel/,/reading/excel/ +/types/casting/html/,/types/cast/ +/data_writing/database_delete/,/writing/dbal/delete/ +/transformations/array_unpack/,/transformations/array/unpack/ +/types/assertions/date/,/types/assert/ +/getting_started/,/examples/#Start +/reading/,/examples/#Read +/writing/,/examples/#Write +/columns/,/examples/#Select%20columns +/inspecting/,/examples/#Inspect +/joins/,/examples/#Join +/batching/,/examples/#Batch +/caching/,/examples/#Cache +/telemetry/,/examples/#Observe +/errors/,/examples/#Handle%20errors +/aggregations/functions/,/aggregations/functions/sum/ +/aggregations/pivot/,/aggregations/pivot/declared_values/ +/partitioning/reading/,/partitioning/reading/basic/ +/reading/dbal/,/reading/dbal/limit_offset/ +/reading/postgresql/,/reading/postgresql/limit_offset/ +/transformations/array/,/transformations/array/expand/ +/transformations/filtering/,/transformations/filtering/basic/ +/transformations/when/,/transformations/when/basic/ +/writing/dbal/,/writing/dbal/insert/ +/writing/postgresql/,/writing/postgresql/insert/ diff --git a/terraform/cloudflare/redirects.tf b/terraform/cloudflare/redirects.tf new file mode 100644 index 0000000000..b32ce26b38 --- /dev/null +++ b/terraform/cloudflare/redirects.tf @@ -0,0 +1,37 @@ +resource "cloudflare_list" "example_redirects" { + account_id = cloudflare_account.account.id + name = "example_redirects" + kind = "redirect" + description = "Old example addresses" + items = [ + for row in csvdecode(file("${path.module}/redirects.csv")) : { + redirect = { + source_url = "flow-php.com${row.source}" + target_url = "https://flow-php.com${row.target}" + status_code = 301 + preserve_query_string = true + } + } + ] +} + +resource "cloudflare_ruleset" "bulk_redirects" { + account_id = cloudflare_account.account.id + name = "Bulk redirects" + description = "Redirects old example addresses" + kind = "root" + phase = "http_request_redirect" + rules = [ + { + ref = "example_redirects" + description = "Old example addresses" + expression = "http.request.full_uri in $example_redirects" + action = "redirect" + action_parameters = { + from_list = { name = "example_redirects", key = "http.request.full_uri" } + } + enabled = true + } + ] + depends_on = [cloudflare_list.example_redirects] +} diff --git a/terraform/cloudflare/versions.tf b/terraform/cloudflare/versions.tf index 495f380043..e352b37884 100644 --- a/terraform/cloudflare/versions.tf +++ b/terraform/cloudflare/versions.tf @@ -1,5 +1,20 @@ terraform { - required_version = ">= 1.0" + required_version = ">= 1.10" + + backend "s3" { + bucket = "flow-php-terraform-state" + key = "cloudflare/terraform.tfstate" + region = "auto" + + use_lockfile = true + + skip_credentials_validation = true + skip_metadata_api_check = true + skip_region_validation = true + skip_requesting_account_id = true + skip_s3_checksum = true + use_path_style = true + } required_providers { cloudflare = { diff --git a/web/landing/assets/controllers/horizontal_scroll_controller.js b/web/landing/assets/controllers/horizontal_scroll_controller.js deleted file mode 100644 index bfd9e9bca2..0000000000 --- a/web/landing/assets/controllers/horizontal_scroll_controller.js +++ /dev/null @@ -1,51 +0,0 @@ -import { Controller } from "@hotwired/stimulus" - -export default class extends Controller { - static targets = ["container", "leftArrow", "rightArrow"] - - #scrollAmount = 200 - - connect() { - this.#updateArrowVisibility() - this.boundUpdateVisibility = this.#updateArrowVisibility.bind(this) - this.containerTarget.addEventListener('scroll', this.boundUpdateVisibility) - window.addEventListener('resize', this.boundUpdateVisibility) - } - - disconnect() { - this.containerTarget.removeEventListener('scroll', this.boundUpdateVisibility) - window.removeEventListener('resize', this.boundUpdateVisibility) - } - - scrollLeft(event) { - event.preventDefault() - this.containerTarget.scrollBy({ - left: -this.#scrollAmount, - behavior: 'smooth' - }) - } - - scrollRight(event) { - event.preventDefault() - this.containerTarget.scrollBy({ - left: this.#scrollAmount, - behavior: 'smooth' - }) - } - - #updateArrowVisibility() { - const container = this.containerTarget - const canScrollLeft = container.scrollLeft > 0 - const canScrollRight = container.scrollLeft < (container.scrollWidth - container.clientWidth - 1) - - if (this.hasLeftArrowTarget) { - this.leftArrowTarget.classList.toggle('opacity-0', !canScrollLeft) - this.leftArrowTarget.classList.toggle('pointer-events-none', !canScrollLeft) - } - - if (this.hasRightArrowTarget) { - this.rightArrowTarget.classList.toggle('opacity-0', !canScrollRight) - this.rightArrowTarget.classList.toggle('pointer-events-none', !canScrollRight) - } - } -} diff --git a/web/landing/assets/controllers/menu_close_controller.js b/web/landing/assets/controllers/menu_close_controller.js new file mode 100644 index 0000000000..bc63c3d9a8 --- /dev/null +++ b/web/landing/assets/controllers/menu_close_controller.js @@ -0,0 +1,20 @@ +import { Controller } from '@hotwired/stimulus'; + +export default class extends Controller { + static targets = ['menu']; + + closeOutside({ target }) { + this.#close(this.menuTargets.filter((menu) => !(target instanceof Node && menu.contains(target)))); + } + + closeAll() { + this.#close(this.menuTargets); + } + + #close(menus) { + menus + // On a phone the menus are sections of the page, not floating panels, and they stay open. + .filter((menu) => getComputedStyle(menu.lastElementChild).position === 'absolute') + .forEach((menu) => { menu.open = false; }); + } +} diff --git a/web/landing/assets/controllers/reading_progress_controller.js b/web/landing/assets/controllers/reading_progress_controller.js new file mode 100644 index 0000000000..9bf9a0548e --- /dev/null +++ b/web/landing/assets/controllers/reading_progress_controller.js @@ -0,0 +1,39 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + static targets = ["article", "bar"] + + connect() { + this.frame = null + this.resizes = new ResizeObserver(() => this.schedule()) + this.resizes.observe(this.articleTarget) + this.update() + } + + disconnect() { + this.resizes.disconnect() + cancelAnimationFrame(this.frame) + } + + schedule() { + if (this.frame !== null) { + return + } + + this.frame = requestAnimationFrame(() => { + this.frame = null + this.update() + }) + } + + update() { + const article = this.articleTarget.getBoundingClientRect() + const distance = article.height - window.innerHeight + + this.barTarget.hidden = distance <= 0 + this.barTarget.style.setProperty( + "--reading-progress", + distance <= 0 ? 0 : Math.min(1, Math.max(0, -article.top / distance)), + ) + } +} diff --git a/web/landing/assets/controllers/syntax_highlight_controller.js b/web/landing/assets/controllers/syntax_highlight_controller.js index c600d4ed15..4376801316 100644 --- a/web/landing/assets/controllers/syntax_highlight_controller.js +++ b/web/landing/assets/controllers/syntax_highlight_controller.js @@ -9,6 +9,7 @@ import 'prismjs/components/prism-bash.min.js'; import 'prismjs/components/prism-json.min.js'; import 'prismjs/components/prism-csv.min.js'; import 'prismjs/components/prism-yaml.min.js'; +import 'prismjs/components/prism-sql.min.js'; export default class extends Controller { diff --git a/web/landing/assets/controllers/tag_filter_controller.js b/web/landing/assets/controllers/tag_filter_controller.js new file mode 100644 index 0000000000..e19486f87c --- /dev/null +++ b/web/landing/assets/controllers/tag_filter_controller.js @@ -0,0 +1,66 @@ +import { Controller } from '@hotwired/stimulus'; + +export default class extends Controller { + static targets = ['button', 'card', 'featured', 'menu']; + static values = { hub: String }; + + #active = []; + + connect() { + this.#show(decodeURIComponent(window.location.hash.slice(1)).split(',').filter((tag) => tag !== '')); + } + + select({ currentTarget, params: { tag, kind } }) { + this.#show(this.#active.includes(tag) ? this.#active.filter((active) => active !== tag) : [...this.#active, tag]); + + window.posthog?.capture('site:filter_change', { + hub: this.hubValue, + filter: tag, + filter_kind: kind, + filter_selected: this.#active.includes(tag), + filter_source: currentTarget.closest('[data-tag-filter-card]') === null ? 'bar' : 'card', + active_filters: this.#active, + items_shown: this.cardTargets.filter((card) => !card.hidden).length, + }); + } + + #show(tags) { + const known = this.buttonTargets.map((button) => button.dataset.tagFilterTagParam); + + this.#active = tags.filter((tag) => known.includes(tag)); + + this.cardTargets.forEach((card) => { card.hidden = !this.#matches(card, this.#active); }); + + this.buttonTargets.forEach((button) => { + const tag = button.dataset.tagFilterTagParam; + const count = this.cardTargets.filter((card) => this.#matches(card, [...this.#active, tag])).length; + + button.setAttribute('aria-pressed', String(this.#active.includes(tag))); + button.disabled = count === 0; + button.querySelectorAll('[data-tag-filter-count]').forEach((element) => { element.textContent = String(count); }); + }); + + this.menuTargets.forEach((menu) => { + const selected = [...menu.querySelectorAll('button[aria-pressed="true"]')].map((button) => button.dataset.tagFilterTagParam); + + menu.querySelectorAll('[data-tag-filter-selected]').forEach((element) => { + element.textContent = selected.length === 0 ? element.dataset.placeholder : selected.join(', '); + element.toggleAttribute('data-active', selected.length > 0); + }); + }); + + this.featuredTargets.forEach((featured) => { featured.hidden = this.#active.length > 0; }); + + history.replaceState( + null, + '', + this.#active.length === 0 ? window.location.pathname : `#${this.#active.map(encodeURIComponent).join(',')}`, + ); + } + + #matches(card, tags) { + const own = JSON.parse(card.dataset.tags); + + return tags.every((tag) => own.includes(tag)); + } +} diff --git a/web/landing/assets/styles/app.css b/web/landing/assets/styles/app.css index 82d3389c9b..97a74405c8 100644 --- a/web/landing/assets/styles/app.css +++ b/web/landing/assets/styles/app.css @@ -64,6 +64,138 @@ html { tracking-[0.18em] text-blue-300 dark:text-blue-100; } +.tag-badge { + @apply inline-flex cursor-pointer items-center gap-2 rounded-md border border-slate-200 bg-slate-50 + px-2.5 py-1.5 font-mono text-sm font-semibold text-slate-700 transition-colors + hover:border-slate-500 hover:text-slate-900 + dark:border-white/10 dark:bg-white/5 dark:text-white/80 + dark:hover:border-white/40 dark:hover:text-white; +} + +.tag-badge[aria-pressed="true"] { + @apply border-slate-900 bg-slate-900/10 text-slate-900 + dark:border-white/70 dark:bg-white/10 dark:text-white; +} + +.tag-badge-action { + @apply border-blue-300/40 bg-blue-300/10 font-sans text-blue-300 + hover:border-blue-300 hover:text-blue-300 + dark:border-blue-100/30 dark:bg-blue-100/10 dark:text-blue-50 + dark:hover:border-blue-100 dark:hover:text-white; +} + +.tag-badge-action[aria-pressed="true"] { + @apply border-blue-300 bg-blue-300 text-white hover:text-white + dark:border-blue-50 dark:bg-blue-50 dark:text-black dark:hover:border-blue-50 dark:hover:text-black; +} + +.tag-badge:disabled { + @apply cursor-default opacity-30 hover:border-slate-200 hover:text-slate-700 + dark:hover:border-white/10 dark:hover:text-white/80; +} + +.tag-badge > svg { + @apply h-5 w-5; +} + +[data-controller~="tag-filter"] [hidden] { + display: none; +} + +.tag-filter-count { + @apply text-xs font-normal opacity-60; +} + +.tag-filter-menu { + @apply relative; +} + +.tag-filter-trigger { + @apply flex cursor-pointer list-none items-center gap-3 rounded-lg border border-slate-200 bg-white/60 + px-4 py-3 transition-colors hover:border-slate-300 + dark:border-white/10 dark:bg-white/[0.03] dark:hover:border-white/20; +} + +.tag-filter-trigger::-webkit-details-marker { + display: none; +} + +.tag-filter-menu[open] > .tag-filter-trigger { + @apply border-blue-300 dark:border-blue-100; +} + +.tag-filter-label { + @apply shrink-0 text-xs font-semibold uppercase tracking-[0.18em] text-slate-500 dark:text-white/55; +} + +.tag-filter-selected { + @apply min-w-0 flex-1 truncate text-sm text-slate-500 dark:text-white/55; +} + +.tag-filter-selected[data-active] { + @apply font-semibold text-blue-300 dark:text-blue-50; +} + +.tag-filter-chevron { + @apply h-4 w-4 shrink-0 text-slate-500 transition-transform dark:text-white/55; +} + +.tag-filter-menu[open] .tag-filter-chevron { + @apply rotate-180; +} + +.tag-filter-panel { + @apply mt-2 grid gap-1 rounded-lg border border-slate-200 bg-white p-2 + sm:absolute sm:left-0 sm:top-full sm:z-20 sm:min-w-full sm:shadow-xl + dark:border-white/10 dark:bg-slate-950; +} + +.tag-filter-panel-wide { + @apply sm:w-[28rem] sm:grid-cols-2; +} + +.tag-filter-option { + @apply flex w-full cursor-pointer items-center gap-2 rounded-md px-2.5 py-2 text-left text-sm font-semibold + text-slate-700 transition-colors hover:bg-slate-100 + dark:text-white/80 dark:hover:bg-white/10; +} + +.tag-filter-option[aria-pressed="true"], .tag-filter-option[aria-current="page"] { + @apply bg-blue-300/10 text-blue-300 dark:bg-blue-100/15 dark:text-blue-50; +} + +.tag-filter-option:disabled { + @apply cursor-default opacity-30 hover:bg-transparent dark:hover:bg-transparent; +} + +.tag-filter-option > svg { + @apply h-5 w-5 shrink-0; +} + +.tag-filter-option > .tag-filter-check { + @apply invisible h-4 w-4; +} + +.tag-filter-option[aria-pressed="true"] > .tag-filter-check, .tag-filter-option[aria-current="page"] > .tag-filter-check { + @apply visible; +} + +.tag-filter-menu-topic .tag-filter-selected[data-active] { + @apply text-slate-900 dark:text-white; +} + +.tag-filter-menu-topic .tag-filter-option[aria-pressed="true"], .tag-filter-menu-topic .tag-filter-option[aria-current="page"] { + @apply bg-slate-900/10 text-slate-900 dark:bg-white/10 dark:text-white; +} + +a.tag-filter-option { + text-decoration: none; +} + +.tag-filter-option-name { + @apply min-w-0 flex-1 truncate; +} + .section-title { @apply text-3xl sm:text-4xl font-bold tracking-tight; } @@ -281,6 +413,122 @@ code { @apply text-orange-300 dark:text-orange-100; } +.reading-progress { + @apply pointer-events-none fixed inset-x-0 top-16 z-50 h-[3px] origin-left bg-blue-300 dark:bg-blue-100; + transform: scaleX(var(--reading-progress, 0)); +} + +.guide-example { + @apply flex min-w-0 flex-col rounded-xl border border-slate-200 bg-white p-5 no-underline + transition-colors duration-150 hover:border-blue-300 + dark:border-white/10 dark:bg-white/[0.03] dark:hover:border-blue-100/60; + flex: 1 1 26rem; +} + +.guide-example-step { + @apply font-mono text-sm font-semibold text-slate-400 dark:text-white/35; +} + +.guide-example-chip { + @apply inline-flex items-center gap-1.5 rounded-md border border-slate-200 bg-slate-50 px-2 py-1 + font-mono text-xs font-semibold text-slate-700 + dark:border-white/10 dark:bg-white/5 dark:text-white/80; +} + +.guide-example-chip > svg { + @apply h-4 w-4; +} + +.guide-example-chip-action { + @apply border-blue-300/40 bg-blue-300/10 font-sans text-blue-300 + dark:border-blue-100/30 dark:bg-blue-100/10 dark:text-blue-50; +} + +.guide-example-title { + @apply mt-4 text-lg font-semibold tracking-tight text-slate-900 transition-colors duration-150 + group-hover:text-blue-300 dark:text-white dark:group-hover:text-blue-50; +} + +.guide-example-summary { + @apply mt-2 block text-sm leading-relaxed text-slate-600 dark:text-white/70; +} + +.example-guide { + @apply flex items-center gap-3 py-4 no-underline; +} + +li:last-child > .example-guide { + @apply pb-0; +} + +.example-guide-problem { + @apply block font-mono text-xs text-slate-500 dark:text-white/55; +} + +.example-guide-title { + @apply mt-1 block text-base font-semibold leading-snug text-slate-900 transition-colors duration-150 + group-hover:text-blue-300 dark:text-white dark:group-hover:text-blue-50; +} + +.example-guide-proof { + @apply mt-2 flex items-center gap-1.5 font-mono text-xs; +} + +.example-pager { + @apply flex items-center gap-4 rounded-xl border border-slate-200 bg-white px-4 py-3 no-underline + transition-colors duration-150 hover:border-blue-300 + dark:border-white/10 dark:bg-white/[0.03] dark:hover:border-blue-100/60; +} + +.example-pager-arrow { + @apply inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-slate-200 + text-slate-500 transition-colors duration-150 + group-hover:border-blue-300 group-hover:bg-blue-300 group-hover:text-white + dark:border-white/15 dark:text-white/60 + dark:group-hover:border-blue-100 dark:group-hover:bg-blue-100 dark:group-hover:text-black; +} + +.example-pager-label { + @apply block text-xs text-slate-500 dark:text-white/55; +} + +.example-pager-name { + @apply block truncate text-base font-semibold text-slate-900 dark:text-white; +} + +.example-docs p { + @apply text-sm leading-relaxed text-slate-600 dark:text-white/70; +} + +.example-docs ul { + @apply mt-3 list-none divide-y divide-slate-200 pl-0 dark:divide-white/10; +} + +.example-docs li a { + @apply flex items-center gap-3 py-3 text-base font-semibold text-slate-900 no-underline transition-colors duration-150 + hover:text-blue-300 dark:text-white dark:hover:text-blue-50; +} + +.example-docs li:last-child a { + @apply pb-0; +} + +.example-docs li a::before, +.example-docs li a::after { + content: ""; + @apply h-4 w-4 shrink-0 bg-current opacity-50; + mask: var(--example-docs-icon) center / contain no-repeat; +} + +.example-docs li a::before { + --example-docs-icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z'/%3E%3Cpath d='M14 2v5h6'/%3E%3Cpath d='M8 13h8'/%3E%3Cpath d='M8 17h6'/%3E%3C/svg%3E"); +} + +.example-docs li a::after { + --example-docs-icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m9 18 6-6-6-6'/%3E%3C/svg%3E"); + @apply ml-auto; +} + /* Documentation prose. Markdown → HTML renders into #documentation-page; the styles below replace the previous heavy borders/shadows with the lighter @@ -507,8 +755,6 @@ code { display: none; } -/* Utility: hide native horizontal scrollbar while keeping scroll functionality. - Used by topic-nav and the horizontal-scroll Stimulus controller's container. */ .scrollbar-hide { scrollbar-width: none; /* Firefox */ -ms-overflow-style: none; /* IE/Edge */ @@ -518,15 +764,6 @@ code { display: none; /* Chrome, Safari */ } -[data-controller="horizontal-scroll"] [data-horizontal-scroll-target="container"] { - scrollbar-width: none; - -ms-overflow-style: none; -} - -[data-controller="horizontal-scroll"] [data-horizontal-scroll-target="container"]::-webkit-scrollbar { - display: none; -} - /* Playground - unified with brand palette: orange-100 = primary accent (active states, CTAs), blue-100 = file-tree directories, white/* opacity = neutral surfaces. Output semantic colors (cyan/green/yellow/red) are diff --git a/web/landing/content/examples/topics/aggregations/_meta.yaml b/web/landing/content/examples/topics/aggregations/_meta.yaml index 76b24de0b7..51da2e463d 100644 --- a/web/landing/content/examples/topics/aggregations/_meta.yaml +++ b/web/landing/content/examples/topics/aggregations/_meta.yaml @@ -1,2 +1,3 @@ priority: 5 hidden: false +action: Aggregate diff --git a/web/landing/content/examples/topics/aggregations/functions/_meta.yaml b/web/landing/content/examples/topics/aggregations/functions/_meta.yaml index 372963400e..de83e62686 100644 --- a/web/landing/content/examples/topics/aggregations/functions/_meta.yaml +++ b/web/landing/content/examples/topics/aggregations/functions/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: 'Aggregate a column in PHP: sum, average, min, max' +summary: 'Reduce a column to one value with aggregate(): one variant each for sum, average, min, max, first and last.' diff --git a/web/landing/content/examples/topics/aggregations/functions/average/_meta.yaml b/web/landing/content/examples/topics/aggregations/functions/average/_meta.yaml index 372963400e..2f25278c2b 100644 --- a/web/landing/content/examples/topics/aggregations/functions/average/_meta.yaml +++ b/web/landing/content/examples/topics/aggregations/functions/average/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Calculate the average of a column in PHP +summary: 'Get the mean of a column with average() inside aggregate(): five rows go in and one row with the result comes out.' diff --git a/web/landing/content/examples/topics/aggregations/functions/first/_meta.yaml b/web/landing/content/examples/topics/aggregations/functions/first/_meta.yaml index 76b24de0b7..a9692ee6b5 100644 --- a/web/landing/content/examples/topics/aggregations/functions/first/_meta.yaml +++ b/web/landing/content/examples/topics/aggregations/functions/first/_meta.yaml @@ -1,2 +1,4 @@ priority: 5 hidden: false +title: Get the first value of a column in PHP +summary: 'Take the value of the first row with first() inside aggregate(). The result depends on the row order, so sort before you rely on it.' diff --git a/web/landing/content/examples/topics/aggregations/functions/last/_meta.yaml b/web/landing/content/examples/topics/aggregations/functions/last/_meta.yaml index 1cfff153ea..25a843ce78 100644 --- a/web/landing/content/examples/topics/aggregations/functions/last/_meta.yaml +++ b/web/landing/content/examples/topics/aggregations/functions/last/_meta.yaml @@ -1,2 +1,4 @@ priority: 6 hidden: false +title: Get the last value of a column in PHP +summary: 'Take the value of the last row with last() inside aggregate(). Like the first value, it follows the order in which rows are read.' diff --git a/web/landing/content/examples/topics/aggregations/functions/max/_meta.yaml b/web/landing/content/examples/topics/aggregations/functions/max/_meta.yaml index d3f9270d46..b271489f8c 100644 --- a/web/landing/content/examples/topics/aggregations/functions/max/_meta.yaml +++ b/web/landing/content/examples/topics/aggregations/functions/max/_meta.yaml @@ -1,2 +1,4 @@ priority: 4 hidden: false +title: Find the largest value of a column in PHP +summary: 'Get the highest value of a column with max() inside aggregate(), whatever order the rows arrive in.' diff --git a/web/landing/content/examples/topics/aggregations/functions/min/_meta.yaml b/web/landing/content/examples/topics/aggregations/functions/min/_meta.yaml index 8608dd76b4..d3044d93a6 100644 --- a/web/landing/content/examples/topics/aggregations/functions/min/_meta.yaml +++ b/web/landing/content/examples/topics/aggregations/functions/min/_meta.yaml @@ -1,2 +1,4 @@ priority: 3 hidden: false +title: Find the smallest value of a column in PHP +summary: 'Get the lowest value of a column with min() inside aggregate(). The order of the rows does not change the result.' diff --git a/web/landing/content/examples/topics/aggregations/functions/sum/_meta.yaml b/web/landing/content/examples/topics/aggregations/functions/sum/_meta.yaml index 0d96c143f9..3849d5edb7 100644 --- a/web/landing/content/examples/topics/aggregations/functions/sum/_meta.yaml +++ b/web/landing/content/examples/topics/aggregations/functions/sum/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Sum a column in PHP +summary: 'Add up every value of a column with sum() inside aggregate(). Without a group, the whole data set becomes one row.' diff --git a/web/landing/content/examples/topics/aggregations/group_by/_meta.yaml b/web/landing/content/examples/topics/aggregations/group_by/_meta.yaml index 0d96c143f9..ee2d58c4f9 100644 --- a/web/landing/content/examples/topics/aggregations/group_by/_meta.yaml +++ b/web/landing/content/examples/topics/aggregations/group_by/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Group rows by a column in PHP +summary: 'Group rows with groupBy() and aggregate each group: count the rows of a group, or sum one of its columns.' diff --git a/web/landing/content/examples/topics/aggregations/group_by/group_by/_meta.yaml b/web/landing/content/examples/topics/aggregations/group_by/group_by/_meta.yaml index 0d96c143f9..813e4e0d20 100644 --- a/web/landing/content/examples/topics/aggregations/group_by/group_by/_meta.yaml +++ b/web/landing/content/examples/topics/aggregations/group_by/group_by/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Group by a column and count rows in PHP +summary: 'Split rows into groups with groupBy() and count the rows of each group with count() inside aggregate().' diff --git a/web/landing/content/examples/topics/aggregations/group_by/group_by_sum/_meta.yaml b/web/landing/content/examples/topics/aggregations/group_by/group_by_sum/_meta.yaml index 372963400e..8d29067b67 100644 --- a/web/landing/content/examples/topics/aggregations/group_by/group_by_sum/_meta.yaml +++ b/web/landing/content/examples/topics/aggregations/group_by/group_by_sum/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Group by a column and sum values in PHP +summary: 'Group rows with groupBy() and add up a second column per group with sum(), instead of counting the rows.' diff --git a/web/landing/content/examples/topics/aggregations/pivot/_meta.yaml b/web/landing/content/examples/topics/aggregations/pivot/_meta.yaml index 8608dd76b4..083bfadbab 100644 --- a/web/landing/content/examples/topics/aggregations/pivot/_meta.yaml +++ b/web/landing/content/examples/topics/aggregations/pivot/_meta.yaml @@ -1,2 +1,4 @@ priority: 3 hidden: false +title: Pivot a table in PHP +summary: 'Turn the values of one column into columns with pivot(), with the values declared up front or discovered from the data.' diff --git a/web/landing/content/examples/topics/aggregations/pivot/declared_values/_meta.yaml b/web/landing/content/examples/topics/aggregations/pivot/declared_values/_meta.yaml index 0d96c143f9..1f6811df4e 100644 --- a/web/landing/content/examples/topics/aggregations/pivot/declared_values/_meta.yaml +++ b/web/landing/content/examples/topics/aggregations/pivot/declared_values/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Pivot rows into columns in PHP +summary: 'Turn the values of one column into columns with pivot() and pivot_values(). Declared values name the columns before a row is read.' diff --git a/web/landing/content/examples/topics/aggregations/pivot/discovered_values/_meta.yaml b/web/landing/content/examples/topics/aggregations/pivot/discovered_values/_meta.yaml index 372963400e..41e5826b4a 100644 --- a/web/landing/content/examples/topics/aggregations/pivot/discovered_values/_meta.yaml +++ b/web/landing/content/examples/topics/aggregations/pivot/discovered_values/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Pivot a table without knowing the values in PHP +summary: 'Let discover_pivot_values() find the pivot columns in the data. Same result as declared values, for one extra pass over the source.' diff --git a/web/landing/content/examples/topics/batching/_meta.yaml b/web/landing/content/examples/topics/batching/_meta.yaml index 066e3e5a89..57ca908da3 100644 --- a/web/landing/content/examples/topics/batching/_meta.yaml +++ b/web/landing/content/examples/topics/batching/_meta.yaml @@ -1,2 +1,3 @@ priority: 10 hidden: false +action: Batch diff --git a/web/landing/content/examples/topics/batching/batch_by/_meta.yaml b/web/landing/content/examples/topics/batching/batch_by/_meta.yaml index 0d96c143f9..a5317171b6 100644 --- a/web/landing/content/examples/topics/batching/batch_by/_meta.yaml +++ b/web/landing/content/examples/topics/batching/batch_by/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Batch rows by a column value in PHP +summary: 'Cut batches where a column value changes with batchBy(), so rows of one order stay together; constraint_sorted_by() guards the input order.' diff --git a/web/landing/content/examples/topics/batching/collect/_meta.yaml b/web/landing/content/examples/topics/batching/collect/_meta.yaml index 372963400e..2d39087e7d 100644 --- a/web/landing/content/examples/topics/batching/collect/_meta.yaml +++ b/web/landing/content/examples/topics/batching/collect/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Collect all rows into one batch in PHP +summary: 'Merge every batch into one with collect(), so the next step sees the whole data set at once. Memory grows with the data.' diff --git a/web/landing/content/examples/topics/batching/column_backend/_meta.yaml b/web/landing/content/examples/topics/batching/column_backend/_meta.yaml index d3f9270d46..86adceabeb 100644 --- a/web/landing/content/examples/topics/batching/column_backend/_meta.yaml +++ b/web/landing/content/examples/topics/batching/column_backend/_meta.yaml @@ -1,2 +1,4 @@ priority: 4 hidden: false +title: Set the column backend of a DataFrame in PHP +summary: 'Pass PhpBackend to config_builder()->backend() to opt out of the flow_php extension, then print the class and the values of each column.' diff --git a/web/landing/content/examples/topics/batching/constant_size/_meta.yaml b/web/landing/content/examples/topics/batching/constant_size/_meta.yaml index 8608dd76b4..90e671910c 100644 --- a/web/landing/content/examples/topics/batching/constant_size/_meta.yaml +++ b/web/landing/content/examples/topics/batching/constant_size/_meta.yaml @@ -1,2 +1,4 @@ priority: 3 hidden: false +title: Process rows in fixed-size batches in PHP +summary: 'Split a data set into batches of two rows with batchSize() and watch to_output() print each batch on its own.' diff --git a/web/landing/content/examples/topics/caching/_meta.yaml b/web/landing/content/examples/topics/caching/_meta.yaml index 54474545b3..f9f46430e1 100644 --- a/web/landing/content/examples/topics/caching/_meta.yaml +++ b/web/landing/content/examples/topics/caching/_meta.yaml @@ -1,2 +1,3 @@ priority: 11 hidden: false +action: Cache diff --git a/web/landing/content/examples/topics/caching/cache/_meta.yaml b/web/landing/content/examples/topics/caching/cache/_meta.yaml index b67e2094be..03d7f05b51 100644 --- a/web/landing/content/examples/topics/caching/cache/_meta.yaml +++ b/web/landing/content/examples/topics/caching/cache/_meta.yaml @@ -2,3 +2,6 @@ priority: 1 hidden: false run: skip: "reads the GitHub API over HTTP; the playground sandbox has no network" +title: Cache API responses on disk in PHP +summary: 'Read from_cache() with an HTTP extractor as the fallback and store the rows with cache(), so the next run skips the GitHub API call.' +tags: [REST API] diff --git a/web/landing/content/examples/topics/columns/_meta.yaml b/web/landing/content/examples/topics/columns/_meta.yaml index 8608dd76b4..83269134b9 100644 --- a/web/landing/content/examples/topics/columns/_meta.yaml +++ b/web/landing/content/examples/topics/columns/_meta.yaml @@ -1,2 +1,3 @@ priority: 3 hidden: false +action: Select columns diff --git a/web/landing/content/examples/topics/columns/create/_meta.yaml b/web/landing/content/examples/topics/columns/create/_meta.yaml index 0d96c143f9..d308ebaa05 100644 --- a/web/landing/content/examples/topics/columns/create/_meta.yaml +++ b/web/landing/content/examples/topics/columns/create/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Add a column to a data set in PHP +summary: 'Add or replace a column with withColumn(): compute it from another column with ref() or set a constant with lit().' diff --git a/web/landing/content/examples/topics/columns/rename/_meta.yaml b/web/landing/content/examples/topics/columns/rename/_meta.yaml index 8608dd76b4..ed4c3a5a25 100644 --- a/web/landing/content/examples/topics/columns/rename/_meta.yaml +++ b/web/landing/content/examples/topics/columns/rename/_meta.yaml @@ -1,2 +1,4 @@ priority: 3 hidden: false +title: Rename a column in PHP +summary: 'Change the name of one column with rename() and leave the other columns and the row order as they are.' diff --git a/web/landing/content/examples/topics/columns/rename_map/_meta.yaml b/web/landing/content/examples/topics/columns/rename_map/_meta.yaml index d3f9270d46..337ed4ce97 100644 --- a/web/landing/content/examples/topics/columns/rename_map/_meta.yaml +++ b/web/landing/content/examples/topics/columns/rename_map/_meta.yaml @@ -1,2 +1,4 @@ priority: 4 hidden: false +title: Rename several columns at once in PHP +summary: 'Rename many columns in one pass with renameEach() and rename_map(), an array of old name to new name.' diff --git a/web/landing/content/examples/topics/columns/rename_replace/_meta.yaml b/web/landing/content/examples/topics/columns/rename_replace/_meta.yaml index 76b24de0b7..0dd038b613 100644 --- a/web/landing/content/examples/topics/columns/rename_replace/_meta.yaml +++ b/web/landing/content/examples/topics/columns/rename_replace/_meta.yaml @@ -1,2 +1,4 @@ priority: 5 hidden: false +title: Remove a prefix from column names in PHP +summary: 'Strip or swap a part of every column name with rename_replace(): here the order_ prefix goes away.' diff --git a/web/landing/content/examples/topics/columns/rename_style/_meta.yaml b/web/landing/content/examples/topics/columns/rename_style/_meta.yaml index 1cfff153ea..145491ff58 100644 --- a/web/landing/content/examples/topics/columns/rename_style/_meta.yaml +++ b/web/landing/content/examples/topics/columns/rename_style/_meta.yaml @@ -1,2 +1,4 @@ priority: 6 hidden: false +title: Convert column names to snake_case in PHP +summary: 'Rewrite every column name into one naming style with rename_style(), here camelCase to snake_case, without listing the columns.' diff --git a/web/landing/content/examples/topics/columns/reorder/_meta.yaml b/web/landing/content/examples/topics/columns/reorder/_meta.yaml index 7141fd2295..03def93df7 100644 --- a/web/landing/content/examples/topics/columns/reorder/_meta.yaml +++ b/web/landing/content/examples/topics/columns/reorder/_meta.yaml @@ -1,2 +1,4 @@ priority: 7 hidden: false +title: Reorder columns of a data set in PHP +summary: 'Change the column order by sorting the schema: schema_sort_by_type_and_name() groups columns by type, then by name.' diff --git a/web/landing/content/examples/topics/columns/select/_meta.yaml b/web/landing/content/examples/topics/columns/select/_meta.yaml index 372963400e..bce444a01c 100644 --- a/web/landing/content/examples/topics/columns/select/_meta.yaml +++ b/web/landing/content/examples/topics/columns/select/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Select columns from a data set in PHP +summary: 'Keep only the columns you name with select() and drop the rest. Here it goes into the pipeline through with().' diff --git a/web/landing/content/examples/topics/errors/_meta.yaml b/web/landing/content/examples/topics/errors/_meta.yaml index 23fc71ba25..6f9a125406 100644 --- a/web/landing/content/examples/topics/errors/_meta.yaml +++ b/web/landing/content/examples/topics/errors/_meta.yaml @@ -1,2 +1,3 @@ priority: 15 hidden: false +action: Handle errors diff --git a/web/landing/content/examples/topics/errors/ignore/_meta.yaml b/web/landing/content/examples/topics/errors/ignore/_meta.yaml index 0d96c143f9..dffe550ac9 100644 --- a/web/landing/content/examples/topics/errors/ignore/_meta.yaml +++ b/web/landing/content/examples/topics/errors/ignore/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Ignore failed rows in a PHP data pipeline +summary: 'Drop the batch a transformation failed in with ignore_error_handler() and keep going; with batchSize(1) only the failing row is lost.' diff --git a/web/landing/content/examples/topics/errors/skip_rows/_meta.yaml b/web/landing/content/examples/topics/errors/skip_rows/_meta.yaml index 372963400e..3d620b46fb 100644 --- a/web/landing/content/examples/topics/errors/skip_rows/_meta.yaml +++ b/web/landing/content/examples/topics/errors/skip_rows/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Skip a failed batch in a PHP data pipeline +summary: 'See skip_rows_handler() drop the whole batch a failure landed in: with batchSize(2) the valid row beside the failing one goes too.' diff --git a/web/landing/content/examples/topics/errors/throw/_meta.yaml b/web/landing/content/examples/topics/errors/throw/_meta.yaml index 8608dd76b4..b8e1059e03 100644 --- a/web/landing/content/examples/topics/errors/throw/_meta.yaml +++ b/web/landing/content/examples/topics/errors/throw/_meta.yaml @@ -1,2 +1,4 @@ priority: 3 hidden: false +title: Stop a PHP data pipeline on the first error +summary: 'Stop the pipeline at the first failure with throw_error_handler(), the default, and catch the exception in the calling code.' diff --git a/web/landing/content/examples/topics/filesystem/_meta.yaml b/web/landing/content/examples/topics/filesystem/_meta.yaml index a1d79141df..aef3564cb1 100644 --- a/web/landing/content/examples/topics/filesystem/_meta.yaml +++ b/web/landing/content/examples/topics/filesystem/_meta.yaml @@ -1,2 +1,3 @@ priority: 12 hidden: false +action: Store files diff --git a/web/landing/content/examples/topics/filesystem/azure/_meta.yaml b/web/landing/content/examples/topics/filesystem/azure/_meta.yaml index daca8475b8..7ccfb8a697 100644 --- a/web/landing/content/examples/topics/filesystem/azure/_meta.yaml +++ b/web/landing/content/examples/topics/filesystem/azure/_meta.yaml @@ -2,3 +2,6 @@ priority: 4 hidden: false run: skip: "needs Azure Blob Storage credentials in a .env file" +title: Read and write Azure Blob Storage files in PHP +summary: 'Build azure_filesystem() from an account and a shared key, write a Parquet file to azure-blob:// with to_parquet() and read it back.' +tags: [Azure] diff --git a/web/landing/content/examples/topics/filesystem/local/_meta.yaml b/web/landing/content/examples/topics/filesystem/local/_meta.yaml index 0d96c143f9..270457ec2d 100644 --- a/web/landing/content/examples/topics/filesystem/local/_meta.yaml +++ b/web/landing/content/examples/topics/filesystem/local/_meta.yaml @@ -1,2 +1,5 @@ priority: 1 hidden: false +title: 'PHP filesystem: write, list and read local files' +summary: 'Get the local filesystem with fstab(), write files as streams, list them by a glob pattern and read one back.' +tags: [Local files] diff --git a/web/landing/content/examples/topics/filesystem/s3/_meta.yaml b/web/landing/content/examples/topics/filesystem/s3/_meta.yaml index 73720abf3b..5197b383d7 100644 --- a/web/landing/content/examples/topics/filesystem/s3/_meta.yaml +++ b/web/landing/content/examples/topics/filesystem/s3/_meta.yaml @@ -2,3 +2,7 @@ priority: 3 hidden: false run: skip: "needs AWS S3 credentials in a .env file" +title: Read and write files on AWS S3 in PHP +summary: 'Build aws_s3_filesystem() from a bucket and a client, write Parquet, CSV, XML, JSON and text files to aws-s3:// and read one back.' +label: S3 +tags: [S3] diff --git a/web/landing/content/examples/topics/filesystem/stdout/_meta.yaml b/web/landing/content/examples/topics/filesystem/stdout/_meta.yaml index 372963400e..edb0a7450f 100644 --- a/web/landing/content/examples/topics/filesystem/stdout/_meta.yaml +++ b/web/landing/content/examples/topics/filesystem/stdout/_meta.yaml @@ -1,2 +1,5 @@ priority: 2 hidden: false +title: Write to PHP stdout with the stdout:// filesystem +summary: 'Open a write stream on stdout:// with fstab() and append lines straight to the process output, with nothing held in memory. Write-only.' +label: stdout diff --git a/web/landing/content/examples/topics/getting_started/01_first_pipeline/_meta.yaml b/web/landing/content/examples/topics/getting_started/01_first_pipeline/_meta.yaml index 0d96c143f9..7a2e9368ad 100644 --- a/web/landing/content/examples/topics/getting_started/01_first_pipeline/_meta.yaml +++ b/web/landing/content/examples/topics/getting_started/01_first_pipeline/_meta.yaml @@ -1,2 +1,5 @@ priority: 1 hidden: false +title: First data pipeline with Flow PHP +summary: 'Build the smallest pipeline: from_array() yields the rows, to_output() prints them, and nothing happens before run().' +label: First pipeline diff --git a/web/landing/content/examples/topics/getting_started/02_print_schema/_meta.yaml b/web/landing/content/examples/topics/getting_started/02_print_schema/_meta.yaml index 372963400e..70501f7ba4 100644 --- a/web/landing/content/examples/topics/getting_started/02_print_schema/_meta.yaml +++ b/web/landing/content/examples/topics/getting_started/02_print_schema/_meta.yaml @@ -1,2 +1,5 @@ priority: 2 hidden: false +title: Print the schema of a DataFrame in PHP +summary: 'Call printSchema() on a DataFrame to see each column with its type; a ? marks a nullable column.' +label: Print schema diff --git a/web/landing/content/examples/topics/getting_started/03_inferred_or_declared/_meta.yaml b/web/landing/content/examples/topics/getting_started/03_inferred_or_declared/_meta.yaml index 8608dd76b4..c918e8bc35 100644 --- a/web/landing/content/examples/topics/getting_started/03_inferred_or_declared/_meta.yaml +++ b/web/landing/content/examples/topics/getting_started/03_inferred_or_declared/_meta.yaml @@ -1,2 +1,6 @@ priority: 3 hidden: false +title: Infer or declare a CSV schema in PHP +summary: 'Read the same CSV twice with from_csv(), once with an inferred schema and once with a declared one, and compare both with schema_to_ascii().' +label: Inferred or declared +tags: [CSV] diff --git a/web/landing/content/examples/topics/getting_started/04_schema_before_running/_meta.yaml b/web/landing/content/examples/topics/getting_started/04_schema_before_running/_meta.yaml index d3f9270d46..fee93434fe 100644 --- a/web/landing/content/examples/topics/getting_started/04_schema_before_running/_meta.yaml +++ b/web/landing/content/examples/topics/getting_started/04_schema_before_running/_meta.yaml @@ -1,2 +1,5 @@ priority: 4 hidden: false +title: Get a DataFrame schema without reading rows in PHP +summary: 'Filter a DataFrame, add a column, then ask schema() for the result: the answer comes from the plan and not one row is read.' +label: Schema before running diff --git a/web/landing/content/examples/topics/getting_started/05_reading_a_csv/_meta.yaml b/web/landing/content/examples/topics/getting_started/05_reading_a_csv/_meta.yaml index 76b24de0b7..937e5a6984 100644 --- a/web/landing/content/examples/topics/getting_started/05_reading_a_csv/_meta.yaml +++ b/web/landing/content/examples/topics/getting_started/05_reading_a_csv/_meta.yaml @@ -1,2 +1,6 @@ priority: 5 hidden: false +title: Read the first rows of a CSV file in PHP +summary: 'Read a CSV file with one argument to from_csv(), keep two columns with select() and stop after three rows with limit().' +label: Reading a CSV +tags: [CSV] diff --git a/web/landing/content/examples/topics/getting_started/_meta.yaml b/web/landing/content/examples/topics/getting_started/_meta.yaml index 7e24f38dd8..c0ce791609 100644 --- a/web/landing/content/examples/topics/getting_started/_meta.yaml +++ b/web/landing/content/examples/topics/getting_started/_meta.yaml @@ -1,2 +1,3 @@ priority: 0 hidden: false +action: Start diff --git a/web/landing/content/examples/topics/inspecting/_meta.yaml b/web/landing/content/examples/topics/inspecting/_meta.yaml index d3f9270d46..439d0a48c6 100644 --- a/web/landing/content/examples/topics/inspecting/_meta.yaml +++ b/web/landing/content/examples/topics/inspecting/_meta.yaml @@ -1,2 +1,3 @@ priority: 4 hidden: false +action: Inspect diff --git a/web/landing/content/examples/topics/inspecting/display/_meta.yaml b/web/landing/content/examples/topics/inspecting/display/_meta.yaml index 0d96c143f9..43a1534f73 100644 --- a/web/landing/content/examples/topics/inspecting/display/_meta.yaml +++ b/web/landing/content/examples/topics/inspecting/display/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Render a DataFrame as a text table in PHP +summary: 'Get the table back as a string with display() and a row limit, to log it, assert on it or embed it instead of printing it.' diff --git a/web/landing/content/examples/topics/inspecting/fetch/_meta.yaml b/web/landing/content/examples/topics/inspecting/fetch/_meta.yaml index 372963400e..038cc3255a 100644 --- a/web/landing/content/examples/topics/inspecting/fetch/_meta.yaml +++ b/web/landing/content/examples/topics/inspecting/fetch/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Fetch rows of a DataFrame into a PHP array +summary: 'Bring a few rows back into PHP with fetch(), read one value from a column and turn the rows into arrays with toArray().' diff --git a/web/landing/content/examples/topics/inspecting/for_each/_meta.yaml b/web/landing/content/examples/topics/inspecting/for_each/_meta.yaml index 8608dd76b4..0380f5ad7a 100644 --- a/web/landing/content/examples/topics/inspecting/for_each/_meta.yaml +++ b/web/landing/content/examples/topics/inspecting/for_each/_meta.yaml @@ -1,2 +1,4 @@ priority: 3 hidden: false +title: Run a callback on every batch of rows in PHP +summary: 'Run the pipeline with forEach() and get every batch in a callback; read a batch by column with column(''name'')->values().' diff --git a/web/landing/content/examples/topics/joins/_meta.yaml b/web/landing/content/examples/topics/joins/_meta.yaml index 7141fd2295..615af6d123 100644 --- a/web/landing/content/examples/topics/joins/_meta.yaml +++ b/web/landing/content/examples/topics/joins/_meta.yaml @@ -1,2 +1,3 @@ priority: 7 hidden: false +action: Join diff --git a/web/landing/content/examples/topics/joins/join/_meta.yaml b/web/landing/content/examples/topics/joins/join/_meta.yaml index 0d96c143f9..b5a178712f 100644 --- a/web/landing/content/examples/topics/joins/join/_meta.yaml +++ b/web/landing/content/examples/topics/joins/join/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Join two data sets in PHP +summary: 'Match rows of two data sets on a shared column with join(): inner, left, right and anti join in one call.' diff --git a/web/landing/content/examples/topics/joins/join_each/_meta.yaml b/web/landing/content/examples/topics/joins/join_each/_meta.yaml index 372963400e..bedf7f92e7 100644 --- a/web/landing/content/examples/topics/joins/join_each/_meta.yaml +++ b/web/landing/content/examples/topics/joins/join_each/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Join a large data set batch by batch in PHP +summary: 'Fetch the right side once per left batch with joinEach() and an ExtractorFactory, and keep only the unknown rows with JoinType::left_anti.' diff --git a/web/landing/content/examples/topics/joins/left_right_inner/_meta.yaml b/web/landing/content/examples/topics/joins/left_right_inner/_meta.yaml index 8608dd76b4..27035eed56 100644 --- a/web/landing/content/examples/topics/joins/left_right_inner/_meta.yaml +++ b/web/landing/content/examples/topics/joins/left_right_inner/_meta.yaml @@ -1,2 +1,4 @@ priority: 3 hidden: false +title: Inner, left and right join compared in PHP +summary: 'Join the same two data sets three times with JoinType::inner, left and right, and compare which rows each type keeps.' diff --git a/web/landing/content/examples/topics/partitioning/_meta.yaml b/web/landing/content/examples/topics/partitioning/_meta.yaml index 3c24b8b7fa..11a5eb2821 100644 --- a/web/landing/content/examples/topics/partitioning/_meta.yaml +++ b/web/landing/content/examples/topics/partitioning/_meta.yaml @@ -1,2 +1,3 @@ priority: 9 hidden: false +action: Partition diff --git a/web/landing/content/examples/topics/partitioning/partition_placeholders/_meta.yaml b/web/landing/content/examples/topics/partitioning/partition_placeholders/_meta.yaml index 372963400e..1586e30dc2 100644 --- a/web/landing/content/examples/topics/partitioning/partition_placeholders/_meta.yaml +++ b/web/landing/content/examples/topics/partitioning/partition_placeholders/_meta.yaml @@ -1,2 +1,5 @@ priority: 2 hidden: false +title: Name partition files with path placeholders in PHP +summary: 'Put {color} and {sku} in the to_csv() path to name directories and files after partition values, and read them back with the same pattern.' +tags: [CSV] diff --git a/web/landing/content/examples/topics/partitioning/partition_pruning/_meta.yaml b/web/landing/content/examples/topics/partitioning/partition_pruning/_meta.yaml index d3f9270d46..123f9bf576 100644 --- a/web/landing/content/examples/topics/partitioning/partition_pruning/_meta.yaml +++ b/web/landing/content/examples/topics/partitioning/partition_pruning/_meta.yaml @@ -1,2 +1,5 @@ priority: 4 hidden: false +title: Skip partitions when reading files in PHP +summary: 'Filter on a partition column with filter() and the reader never opens the directories that fail the condition, here color=green.' +tags: [CSV] diff --git a/web/landing/content/examples/topics/partitioning/partitioning/_meta.yaml b/web/landing/content/examples/topics/partitioning/partitioning/_meta.yaml index 0d96c143f9..285b8547a6 100644 --- a/web/landing/content/examples/topics/partitioning/partitioning/_meta.yaml +++ b/web/landing/content/examples/topics/partitioning/partitioning/_meta.yaml @@ -1,2 +1,5 @@ priority: 1 hidden: false +title: Write partitioned files in PHP +summary: 'Write one directory per column value with partitionBy(), and choose what happens when a partition exists: append, overwrite, ignore or fail.' +tags: [CSV] diff --git a/web/landing/content/examples/topics/partitioning/partitioning/append/_meta.yaml b/web/landing/content/examples/topics/partitioning/partitioning/append/_meta.yaml index 372963400e..d90f39eb28 100644 --- a/web/landing/content/examples/topics/partitioning/partitioning/append/_meta.yaml +++ b/web/landing/content/examples/topics/partitioning/partitioning/append/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Append data to partitioned files in PHP +summary: 'Add new files to existing partitions with the append() save mode. Each run writes a file with a random suffix and removes nothing.' diff --git a/web/landing/content/examples/topics/partitioning/partitioning/exception_if_exists/_meta.yaml b/web/landing/content/examples/topics/partitioning/partitioning/exception_if_exists/_meta.yaml index d3f9270d46..8206c56b1c 100644 --- a/web/landing/content/examples/topics/partitioning/partitioning/exception_if_exists/_meta.yaml +++ b/web/landing/content/examples/topics/partitioning/partitioning/exception_if_exists/_meta.yaml @@ -1,2 +1,4 @@ priority: 4 hidden: false +title: Fail when a partition file exists in PHP +summary: 'Protect partitioned data with exception_if_exists(), the default save mode: the write throws when a partition file is already there.' diff --git a/web/landing/content/examples/topics/partitioning/partitioning/ignore/_meta.yaml b/web/landing/content/examples/topics/partitioning/partitioning/ignore/_meta.yaml index 8608dd76b4..97e573b7c5 100644 --- a/web/landing/content/examples/topics/partitioning/partitioning/ignore/_meta.yaml +++ b/web/landing/content/examples/topics/partitioning/partitioning/ignore/_meta.yaml @@ -1,2 +1,4 @@ priority: 3 hidden: false +title: Skip existing partitions when writing in PHP +summary: 'Leave existing partition files alone with the ignore() save mode, so a second run of the pipeline does not duplicate data.' diff --git a/web/landing/content/examples/topics/partitioning/partitioning/overwrite/_meta.yaml b/web/landing/content/examples/topics/partitioning/partitioning/overwrite/_meta.yaml index 0d96c143f9..12887883ca 100644 --- a/web/landing/content/examples/topics/partitioning/partitioning/overwrite/_meta.yaml +++ b/web/landing/content/examples/topics/partitioning/partitioning/overwrite/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Write partitioned CSV files in PHP +summary: 'Split a data set into color= and sku= directories with partitionBy(). The overwrite() save mode replaces the files of each partition it writes.' diff --git a/web/landing/content/examples/topics/partitioning/path_partitions/_meta.yaml b/web/landing/content/examples/topics/partitioning/path_partitions/_meta.yaml index 76b24de0b7..0a3b9d5389 100644 --- a/web/landing/content/examples/topics/partitioning/path_partitions/_meta.yaml +++ b/web/landing/content/examples/topics/partitioning/path_partitions/_meta.yaml @@ -1,2 +1,5 @@ priority: 5 hidden: false +title: List partitioned files without reading them in PHP +summary: 'Get one row per file with from_path_partitions(): the path, the partitions map and a column for each partition value.' +tags: [Local files] diff --git a/web/landing/content/examples/topics/partitioning/reading/_meta.yaml b/web/landing/content/examples/topics/partitioning/reading/_meta.yaml index 8608dd76b4..2f1baae92e 100644 --- a/web/landing/content/examples/topics/partitioning/reading/_meta.yaml +++ b/web/landing/content/examples/topics/partitioning/reading/_meta.yaml @@ -1,2 +1,5 @@ priority: 3 hidden: false +title: Read partitioned files in PHP +summary: 'Read a partitioned directory with a glob path and get the partition columns back, also after append and overwrite.' +tags: [CSV] diff --git a/web/landing/content/examples/topics/partitioning/reading/after_append/_meta.yaml b/web/landing/content/examples/topics/partitioning/reading/after_append/_meta.yaml index 8608dd76b4..444284647e 100644 --- a/web/landing/content/examples/topics/partitioning/reading/after_append/_meta.yaml +++ b/web/landing/content/examples/topics/partitioning/reading/after_append/_meta.yaml @@ -1,2 +1,4 @@ priority: 3 hidden: false +title: Read partitions written with append in PHP +summary: 'Run append() twice, then read the partitions back: the glob color=*/*.csv picks up both files of every partition.' diff --git a/web/landing/content/examples/topics/partitioning/reading/after_overwrite/_meta.yaml b/web/landing/content/examples/topics/partitioning/reading/after_overwrite/_meta.yaml index 372963400e..119965a962 100644 --- a/web/landing/content/examples/topics/partitioning/reading/after_overwrite/_meta.yaml +++ b/web/landing/content/examples/topics/partitioning/reading/after_overwrite/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Read partitions written with overwrite in PHP +summary: 'Write with overwrite(), then read the partitions back: each one holds exactly one file with the data of the last run.' diff --git a/web/landing/content/examples/topics/partitioning/reading/basic/_meta.yaml b/web/landing/content/examples/topics/partitioning/reading/basic/_meta.yaml index 0d96c143f9..5f6c02a3b1 100644 --- a/web/landing/content/examples/topics/partitioning/reading/basic/_meta.yaml +++ b/web/landing/content/examples/topics/partitioning/reading/basic/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Read partitioned CSV files in PHP +summary: 'Read every partition with one from_csv() glob over color=*/sku=* directories. The partition values come back as columns.' diff --git a/web/landing/content/examples/topics/reading/_meta.yaml b/web/landing/content/examples/topics/reading/_meta.yaml index 0d96c143f9..1fdf2d4168 100644 --- a/web/landing/content/examples/topics/reading/_meta.yaml +++ b/web/landing/content/examples/topics/reading/_meta.yaml @@ -1,2 +1,3 @@ priority: 1 hidden: false +action: Read diff --git a/web/landing/content/examples/topics/reading/array/_meta.yaml b/web/landing/content/examples/topics/reading/array/_meta.yaml index 0d96c143f9..38e76f2eb4 100644 --- a/web/landing/content/examples/topics/reading/array/_meta.yaml +++ b/web/landing/content/examples/topics/reading/array/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Read a PHP array into a DataFrame +summary: 'Turn rows that are already in memory, like API responses or fixtures, into a DataFrame with from_array() and let it infer the types.' diff --git a/web/landing/content/examples/topics/reading/corrupted_records_routing/_meta.yaml b/web/landing/content/examples/topics/reading/corrupted_records_routing/_meta.yaml index 6d6ded0400..2041afd449 100644 --- a/web/landing/content/examples/topics/reading/corrupted_records_routing/_meta.yaml +++ b/web/landing/content/examples/topics/reading/corrupted_records_routing/_meta.yaml @@ -1,2 +1,5 @@ priority: 16 hidden: false +title: Skip invalid CSV rows in PHP +summary: 'Keep reading a CSV file past broken lines: withCorruptedRecords() writes each rejected record with its reason to a JSON Lines file.' +tags: [CSV] diff --git a/web/landing/content/examples/topics/reading/csv/_meta.yaml b/web/landing/content/examples/topics/reading/csv/_meta.yaml index 372963400e..4a584afda9 100644 --- a/web/landing/content/examples/topics/reading/csv/_meta.yaml +++ b/web/landing/content/examples/topics/reading/csv/_meta.yaml @@ -1,2 +1,6 @@ priority: 2 hidden: false +title: Read a CSV file in PHP +summary: 'Read a CSV file row by row with from_csv(), set the delimiter and header, and get typed columns back.' +label: CSV +tags: [CSV] diff --git a/web/landing/content/examples/topics/reading/csv_cells/_meta.yaml b/web/landing/content/examples/topics/reading/csv_cells/_meta.yaml index 3c24b8b7fa..9624b01e94 100644 --- a/web/landing/content/examples/topics/reading/csv_cells/_meta.yaml +++ b/web/landing/content/examples/topics/reading/csv_cells/_meta.yaml @@ -1,2 +1,6 @@ priority: 9 hidden: false +title: Handle empty and missing CSV cells in PHP +summary: 'See how from_csv() names blank header cells, pads short lines with withMissingColumnsAsNull() and treats empty cells.' +label: CSV cells +tags: [CSV] diff --git a/web/landing/content/examples/topics/reading/dbal/_meta.yaml b/web/landing/content/examples/topics/reading/dbal/_meta.yaml index 3c24b8b7fa..f76e781dcd 100644 --- a/web/landing/content/examples/topics/reading/dbal/_meta.yaml +++ b/web/landing/content/examples/topics/reading/dbal/_meta.yaml @@ -1,2 +1,6 @@ priority: 9 hidden: false +title: Read from a database with Doctrine DBAL in PHP +summary: 'Read query results through Doctrine DBAL: one query, many parameter sets, LIMIT and OFFSET pages or key set pagination.' +label: DBAL +tags: [Database] diff --git a/web/landing/content/examples/topics/reading/dbal/key_set/_meta.yaml b/web/landing/content/examples/topics/reading/dbal/key_set/_meta.yaml index 89ae9e74cd..b4ce585adc 100644 --- a/web/landing/content/examples/topics/reading/dbal/key_set/_meta.yaml +++ b/web/landing/content/examples/topics/reading/dbal/key_set/_meta.yaml @@ -2,3 +2,5 @@ priority: 2 hidden: false run: skip: "uses pdo_sqlite, which the playground PHP build does not include" +title: Paginate a Doctrine DBAL query by key in PHP +summary: 'Read a large table page by page with from_dbal_key_set_qb(): each page starts after the last key, so the cost stays flat.' diff --git a/web/landing/content/examples/topics/reading/dbal/limit_offset/_meta.yaml b/web/landing/content/examples/topics/reading/dbal/limit_offset/_meta.yaml index a450768fac..3836fe9b51 100644 --- a/web/landing/content/examples/topics/reading/dbal/limit_offset/_meta.yaml +++ b/web/landing/content/examples/topics/reading/dbal/limit_offset/_meta.yaml @@ -2,3 +2,5 @@ priority: 1 hidden: false run: skip: "uses pdo_sqlite, which the playground PHP build does not include" +title: Read a database table with LIMIT and OFFSET in PHP +summary: 'Walk a whole table page by page with from_dbal_limit_offset(), ordered by a column you choose: the simplest DBAL extractor.' diff --git a/web/landing/content/examples/topics/reading/dbal/queries/_meta.yaml b/web/landing/content/examples/topics/reading/dbal/queries/_meta.yaml index a1a2b907d1..924ec5a94a 100644 --- a/web/landing/content/examples/topics/reading/dbal/queries/_meta.yaml +++ b/web/landing/content/examples/topics/reading/dbal/queries/_meta.yaml @@ -2,3 +2,5 @@ priority: 4 hidden: false run: skip: "uses pdo_sqlite, which the playground PHP build does not include" +title: Run one SQL query with many parameter sets in PHP +summary: 'Run the same SQL statement once per parameter set with from_dbal_queries() and merge the results into one stream of rows.' diff --git a/web/landing/content/examples/topics/reading/dbal/query/_meta.yaml b/web/landing/content/examples/topics/reading/dbal/query/_meta.yaml index 817645f8ac..950498c93a 100644 --- a/web/landing/content/examples/topics/reading/dbal/query/_meta.yaml +++ b/web/landing/content/examples/topics/reading/dbal/query/_meta.yaml @@ -2,3 +2,5 @@ priority: 3 hidden: false run: skip: "uses pdo_sqlite, which the playground PHP build does not include" +title: Read the result of an SQL query in PHP +summary: 'Extract the result of your own SQL query with from_dbal_queries(), bind its parameters through ParametersSet and aggregate in the database.' diff --git a/web/landing/content/examples/topics/reading/excel/_meta.yaml b/web/landing/content/examples/topics/reading/excel/_meta.yaml index 7141fd2295..54679052cc 100644 --- a/web/landing/content/examples/topics/reading/excel/_meta.yaml +++ b/web/landing/content/examples/topics/reading/excel/_meta.yaml @@ -1,2 +1,5 @@ priority: 7 hidden: false +title: Read an Excel file in PHP +summary: 'Read an XLSX spreadsheet with from_excel(), rely on the default sheet and header handling, and select the columns you need.' +tags: [Excel] diff --git a/web/landing/content/examples/topics/reading/floe/_meta.yaml b/web/landing/content/examples/topics/reading/floe/_meta.yaml index 177f368d9d..918def727f 100644 --- a/web/landing/content/examples/topics/reading/floe/_meta.yaml +++ b/web/landing/content/examples/topics/reading/floe/_meta.yaml @@ -1,2 +1,5 @@ priority: 8 hidden: false +title: Read a Floe file in PHP +summary: 'Read Flow''s own binary format with from_floe(): the schema is stored in the file, so every type comes back exactly as written.' +tags: [Floe] diff --git a/web/landing/content/examples/topics/reading/http/_meta.yaml b/web/landing/content/examples/topics/reading/http/_meta.yaml index 066e3e5a89..bfd9181fef 100644 --- a/web/landing/content/examples/topics/reading/http/_meta.yaml +++ b/web/landing/content/examples/topics/reading/http/_meta.yaml @@ -1,2 +1,6 @@ priority: 10 hidden: false +title: Read a paginated REST API in PHP +summary: 'Walk every page of a JSON API with from_http_paginated() and http_pagination_page_number(), and stop when a page comes back empty.' +label: HTTP +tags: [REST API] diff --git a/web/landing/content/examples/topics/reading/json/_meta.yaml b/web/landing/content/examples/topics/reading/json/_meta.yaml index 8608dd76b4..1a00175d4e 100644 --- a/web/landing/content/examples/topics/reading/json/_meta.yaml +++ b/web/landing/content/examples/topics/reading/json/_meta.yaml @@ -1,2 +1,6 @@ priority: 3 hidden: false +title: Read a JSON file in PHP +summary: 'Read a JSON document that holds an array of objects with from_json(), one row per object, and select the columns you need.' +label: JSON +tags: [JSON] diff --git a/web/landing/content/examples/topics/reading/jsonl/_meta.yaml b/web/landing/content/examples/topics/reading/jsonl/_meta.yaml index d3f9270d46..33d9778862 100644 --- a/web/landing/content/examples/topics/reading/jsonl/_meta.yaml +++ b/web/landing/content/examples/topics/reading/jsonl/_meta.yaml @@ -1,2 +1,6 @@ priority: 4 hidden: false +title: Read a JSONL file in PHP +summary: 'Read JSON Lines with from_json_lines(), one object per line, so a large file never has to fit in memory.' +label: JSONL +tags: [JSON] diff --git a/web/landing/content/examples/topics/reading/parquet/_meta.yaml b/web/landing/content/examples/topics/reading/parquet/_meta.yaml index 1cfff153ea..4cc164c9a3 100644 --- a/web/landing/content/examples/topics/reading/parquet/_meta.yaml +++ b/web/landing/content/examples/topics/reading/parquet/_meta.yaml @@ -1,2 +1,5 @@ priority: 6 hidden: false +title: Read a Parquet file in PHP +summary: 'Read a columnar Parquet file with from_parquet(): the schema comes from the file, so no column type is guessed.' +tags: [Parquet] diff --git a/web/landing/content/examples/topics/reading/postgresql/_meta.yaml b/web/landing/content/examples/topics/reading/postgresql/_meta.yaml index 066e3e5a89..dabedb29ee 100644 --- a/web/landing/content/examples/topics/reading/postgresql/_meta.yaml +++ b/web/landing/content/examples/topics/reading/postgresql/_meta.yaml @@ -1,2 +1,6 @@ priority: 10 hidden: false +title: Read from PostgreSQL in PHP +summary: 'Read a PostgreSQL table through the native client: a server side cursor, LIMIT and OFFSET pages or key set pagination.' +label: PostgreSQL +tags: [PostgreSQL] diff --git a/web/landing/content/examples/topics/reading/postgresql/cursor/_meta.yaml b/web/landing/content/examples/topics/reading/postgresql/cursor/_meta.yaml index e7ca0a6712..948bdcc8dc 100644 --- a/web/landing/content/examples/topics/reading/postgresql/cursor/_meta.yaml +++ b/web/landing/content/examples/topics/reading/postgresql/cursor/_meta.yaml @@ -2,3 +2,5 @@ priority: 3 hidden: false run: skip: "needs a PostgreSQL server" +title: Read a large PostgreSQL table with a cursor in PHP +summary: 'Stream a query result through a server-side cursor with from_pgsql_cursor(): rows arrive in batches and memory stays flat.' diff --git a/web/landing/content/examples/topics/reading/postgresql/key_set/_meta.yaml b/web/landing/content/examples/topics/reading/postgresql/key_set/_meta.yaml index 3f6616d652..11c6193dec 100644 --- a/web/landing/content/examples/topics/reading/postgresql/key_set/_meta.yaml +++ b/web/landing/content/examples/topics/reading/postgresql/key_set/_meta.yaml @@ -2,3 +2,5 @@ priority: 2 hidden: false run: skip: "needs a PostgreSQL server" +title: Paginate a PostgreSQL query by key in PHP +summary: 'Page through a native PostgreSQL query with from_pgsql_key_set(); pgsql_pagination_key_set() names the columns of the cursor.' diff --git a/web/landing/content/examples/topics/reading/postgresql/limit_offset/_meta.yaml b/web/landing/content/examples/topics/reading/postgresql/limit_offset/_meta.yaml index f11de015b9..2aaa48e739 100644 --- a/web/landing/content/examples/topics/reading/postgresql/limit_offset/_meta.yaml +++ b/web/landing/content/examples/topics/reading/postgresql/limit_offset/_meta.yaml @@ -2,3 +2,5 @@ priority: 1 hidden: false run: skip: "needs a PostgreSQL server" +title: Read PostgreSQL with LIMIT and OFFSET in PHP +summary: 'Page through the result of your own query with from_pgsql_limit_offset() over a native ext-pgsql connection, with no Doctrine in between.' diff --git a/web/landing/content/examples/topics/reading/sequence_date/_meta.yaml b/web/landing/content/examples/topics/reading/sequence_date/_meta.yaml index b7792d1b73..034ea5b801 100644 --- a/web/landing/content/examples/topics/reading/sequence_date/_meta.yaml +++ b/web/landing/content/examples/topics/reading/sequence_date/_meta.yaml @@ -1,2 +1,4 @@ priority: 13 hidden: true +title: Generate a range of dates in PHP +summary: 'Generate one row per day between a start and an end date with from_sequence_date_period(); the end date itself is not included.' diff --git a/web/landing/content/examples/topics/reading/sequence_date_recurrences/_meta.yaml b/web/landing/content/examples/topics/reading/sequence_date_recurrences/_meta.yaml index dc990e1004..a341492842 100644 --- a/web/landing/content/examples/topics/reading/sequence_date_recurrences/_meta.yaml +++ b/web/landing/content/examples/topics/reading/sequence_date_recurrences/_meta.yaml @@ -1,2 +1,4 @@ priority: 14 hidden: true +title: Generate a fixed number of dates in PHP +summary: 'Generate a date sequence from a start date and a number of recurrences with from_sequence_date_period_recurrences(), with no end date.' diff --git a/web/landing/content/examples/topics/reading/sequence_number/_meta.yaml b/web/landing/content/examples/topics/reading/sequence_number/_meta.yaml index 56e60a31e4..8fc3ecde50 100644 --- a/web/landing/content/examples/topics/reading/sequence_number/_meta.yaml +++ b/web/landing/content/examples/topics/reading/sequence_number/_meta.yaml @@ -1,2 +1,4 @@ priority: 12 hidden: true +title: Generate a range of numbers in PHP +summary: 'Generate rows from a start number to an end number with a step using from_sequence_number(), with no file or table behind them.' diff --git a/web/landing/content/examples/topics/reading/xml/_meta.yaml b/web/landing/content/examples/topics/reading/xml/_meta.yaml index 76b24de0b7..48acf8391a 100644 --- a/web/landing/content/examples/topics/reading/xml/_meta.yaml +++ b/web/landing/content/examples/topics/reading/xml/_meta.yaml @@ -1,2 +1,6 @@ priority: 5 hidden: false +title: Read an XML file in PHP +summary: 'Read XML node by node with from_xml() and withXMLNodePath(), then pick values out of each node with xpath().' +label: XML +tags: [XML] diff --git a/web/landing/content/examples/topics/schema/_meta.yaml b/web/landing/content/examples/topics/schema/_meta.yaml index 177f368d9d..5fc840d2b6 100644 --- a/web/landing/content/examples/topics/schema/_meta.yaml +++ b/web/landing/content/examples/topics/schema/_meta.yaml @@ -1,2 +1,3 @@ priority: 8 hidden: false +action: Validate diff --git a/web/landing/content/examples/topics/schema/apply/_meta.yaml b/web/landing/content/examples/topics/schema/apply/_meta.yaml index 372963400e..75c595e466 100644 --- a/web/landing/content/examples/topics/schema/apply/_meta.yaml +++ b/web/landing/content/examples/topics/schema/apply/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Apply a schema to a data source in PHP +summary: 'Declare the column types on a reader with withSchema() instead of inferring them, so NOT NULL columns stay NOT NULL.' diff --git a/web/landing/content/examples/topics/schema/definitions/_meta.yaml b/web/landing/content/examples/topics/schema/definitions/_meta.yaml index 1cfff153ea..b2f15864f7 100644 --- a/web/landing/content/examples/topics/schema/definitions/_meta.yaml +++ b/web/landing/content/examples/topics/schema/definitions/_meta.yaml @@ -1,2 +1,4 @@ priority: 6 hidden: false +title: Define a schema with nested columns in PHP +summary: 'Build a schema from column definitions and nest fields with structure_schema() around type_structure(), then print it with schema_to_ascii().' diff --git a/web/landing/content/examples/topics/schema/display/_meta.yaml b/web/landing/content/examples/topics/schema/display/_meta.yaml index d3f9270d46..177b826660 100644 --- a/web/landing/content/examples/topics/schema/display/_meta.yaml +++ b/web/landing/content/examples/topics/schema/display/_meta.yaml @@ -1,2 +1,4 @@ priority: 4 hidden: false +title: Print an inferred schema as a tree in PHP +summary: 'Print the schema instead of the rows with to_output(output: Output::schema); a key that some rows lack becomes a nullable column.' diff --git a/web/landing/content/examples/topics/schema/inferring/_meta.yaml b/web/landing/content/examples/topics/schema/inferring/_meta.yaml index 0d96c143f9..a5cf17de13 100644 --- a/web/landing/content/examples/topics/schema/inferring/_meta.yaml +++ b/web/landing/content/examples/topics/schema/inferring/_meta.yaml @@ -1,2 +1,5 @@ priority: 1 hidden: false +title: Infer a CSV schema once and reuse it in PHP +summary: 'Infer a schema from 100 rows of a CSV file, save it with schema_to_json() and load it with schema_from_json(), so later reads skip inference.' +tags: [CSV] diff --git a/web/landing/content/examples/topics/schema/strict_or_evolving/_meta.yaml b/web/landing/content/examples/topics/schema/strict_or_evolving/_meta.yaml index 76b24de0b7..0dd488eb1e 100644 --- a/web/landing/content/examples/topics/schema/strict_or_evolving/_meta.yaml +++ b/web/landing/content/examples/topics/schema/strict_or_evolving/_meta.yaml @@ -1,2 +1,4 @@ priority: 5 hidden: false +title: Strict or evolving schema validation in PHP +summary: 'Match a row with an extra column against one schema twice: schema_evolving_validator() lets it through, schema_strict_validator() fails.' diff --git a/web/landing/content/examples/topics/schema/validate/_meta.yaml b/web/landing/content/examples/topics/schema/validate/_meta.yaml index 8608dd76b4..933655aa10 100644 --- a/web/landing/content/examples/topics/schema/validate/_meta.yaml +++ b/web/landing/content/examples/topics/schema/validate/_meta.yaml @@ -1,2 +1,4 @@ priority: 3 hidden: false +title: Validate data against a schema in PHP +summary: 'Check a DataFrame against a declared schema with match(), and give from_array() the same schema so NOT NULL declarations can match.' diff --git a/web/landing/content/examples/topics/telemetry/_meta.yaml b/web/landing/content/examples/topics/telemetry/_meta.yaml index fb1ad991ac..29fd91ba24 100644 --- a/web/landing/content/examples/topics/telemetry/_meta.yaml +++ b/web/landing/content/examples/topics/telemetry/_meta.yaml @@ -1,2 +1,3 @@ priority: 14 hidden: false +action: Observe diff --git a/web/landing/content/examples/topics/telemetry/combined/_meta.yaml b/web/landing/content/examples/topics/telemetry/combined/_meta.yaml index 1cfff153ea..3024c7af64 100644 --- a/web/landing/content/examples/topics/telemetry/combined/_meta.yaml +++ b/web/landing/content/examples/topics/telemetry/combined/_meta.yaml @@ -1,2 +1,5 @@ priority: 6 hidden: false +title: Traces, logs and metrics together in PHP +summary: 'Wire a tracer, a logger and a meter into one telemetry() instance, so the spans, logs and metrics of one order share a resource and a context.' +tags: [OpenTelemetry] diff --git a/web/landing/content/examples/topics/telemetry/logger/_meta.yaml b/web/landing/content/examples/topics/telemetry/logger/_meta.yaml index 8608dd76b4..7b5b0f9967 100644 --- a/web/landing/content/examples/topics/telemetry/logger/_meta.yaml +++ b/web/landing/content/examples/topics/telemetry/logger/_meta.yaml @@ -1,2 +1,5 @@ priority: 3 hidden: false +title: Write structured logs with severity levels in PHP +summary: 'Create a logger with logger_provider() and write info, debug, warn and error records, each with structured attributes.' +tags: [OpenTelemetry] diff --git a/web/landing/content/examples/topics/telemetry/meter/_meta.yaml b/web/landing/content/examples/topics/telemetry/meter/_meta.yaml index 372963400e..2c70a1c9e2 100644 --- a/web/landing/content/examples/topics/telemetry/meter/_meta.yaml +++ b/web/landing/content/examples/topics/telemetry/meter/_meta.yaml @@ -1,2 +1,5 @@ priority: 2 hidden: false +title: Record metrics with counters and histograms in PHP +summary: 'Create a meter with meter_provider() and record values on a counter, a histogram, an up-down counter and a gauge.' +tags: [OpenTelemetry] diff --git a/web/landing/content/examples/topics/telemetry/propagator/_meta.yaml b/web/landing/content/examples/topics/telemetry/propagator/_meta.yaml index 76b24de0b7..1fbc5e66a3 100644 --- a/web/landing/content/examples/topics/telemetry/propagator/_meta.yaml +++ b/web/landing/content/examples/topics/telemetry/propagator/_meta.yaml @@ -1,2 +1,5 @@ priority: 5 hidden: false +title: Propagate W3C trace context between PHP services +summary: 'Extract traceparent and baggage headers with composite_propagator(), start a child span from them and inject the context into outgoing headers.' +tags: [OpenTelemetry] diff --git a/web/landing/content/examples/topics/telemetry/resource/_meta.yaml b/web/landing/content/examples/topics/telemetry/resource/_meta.yaml index d3f9270d46..1b6d3c24fa 100644 --- a/web/landing/content/examples/topics/telemetry/resource/_meta.yaml +++ b/web/landing/content/examples/topics/telemetry/resource/_meta.yaml @@ -1,2 +1,5 @@ priority: 4 hidden: false +title: Set service resource attributes for PHP telemetry +summary: 'Detect host and process attributes with resource_detector(), merge custom ones from resource() over them and attach the result to every span.' +tags: [OpenTelemetry] diff --git a/web/landing/content/examples/topics/telemetry/tracer/_meta.yaml b/web/landing/content/examples/topics/telemetry/tracer/_meta.yaml index 0d96c143f9..dc25023554 100644 --- a/web/landing/content/examples/topics/telemetry/tracer/_meta.yaml +++ b/web/landing/content/examples/topics/telemetry/tracer/_meta.yaml @@ -1,2 +1,5 @@ priority: 1 hidden: false +title: Distributed tracing in PHP with spans +summary: 'Create a tracer with tracer_provider(), open a span with attributes, nest a child span in it and print both with console_exporter().' +tags: [OpenTelemetry] diff --git a/web/landing/content/examples/topics/transformations/_meta.yaml b/web/landing/content/examples/topics/transformations/_meta.yaml index d3f9270d46..b8700bc2f3 100644 --- a/web/landing/content/examples/topics/transformations/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/_meta.yaml @@ -1,2 +1,3 @@ priority: 4 hidden: false +action: Transform diff --git a/web/landing/content/examples/topics/transformations/array/_meta.yaml b/web/landing/content/examples/topics/transformations/array/_meta.yaml index 177f368d9d..f4d499741b 100644 --- a/web/landing/content/examples/topics/transformations/array/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/array/_meta.yaml @@ -1,2 +1,4 @@ priority: 8 hidden: false +title: Work with array columns in PHP +summary: 'Reshape a column that holds arrays: expand its elements into rows, or unpack its keys into separate columns.' diff --git a/web/landing/content/examples/topics/transformations/array/expand/_meta.yaml b/web/landing/content/examples/topics/transformations/array/expand/_meta.yaml index 0d96c143f9..57e3827651 100644 --- a/web/landing/content/examples/topics/transformations/array/expand/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/array/expand/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Expand a PHP array column into rows +summary: 'Turn each element of an array column into its own row with array_expand(), and keep the other columns.' diff --git a/web/landing/content/examples/topics/transformations/array/unpack/_meta.yaml b/web/landing/content/examples/topics/transformations/array/unpack/_meta.yaml index 372963400e..b7f5169d71 100644 --- a/web/landing/content/examples/topics/transformations/array/unpack/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/array/unpack/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Unpack an array column into columns in PHP +summary: 'Spread the keys of an array column into separate columns with unpack(), and describe those keys with a schema of typed entries.' diff --git a/web/landing/content/examples/topics/transformations/call/_meta.yaml b/web/landing/content/examples/topics/transformations/call/_meta.yaml index 76b24de0b7..f453d39ba0 100644 --- a/web/landing/content/examples/topics/transformations/call/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/call/_meta.yaml @@ -1,2 +1,4 @@ priority: 5 hidden: false +title: Call a PHP callable on a column +summary: 'Apply any PHP function to a column with call(): here explode splits a string into a list of integers, and you declare the result type.' diff --git a/web/landing/content/examples/topics/transformations/custom/_meta.yaml b/web/landing/content/examples/topics/transformations/custom/_meta.yaml index 7141fd2295..42fd5b58a4 100644 --- a/web/landing/content/examples/topics/transformations/custom/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/custom/_meta.yaml @@ -1,2 +1,4 @@ priority: 7 hidden: false +title: Write a custom transformation in PHP +summary: 'Pack several steps into one reusable class that implements Transformation, and add it to the pipeline with with().' diff --git a/web/landing/content/examples/topics/transformations/filtering/_meta.yaml b/web/landing/content/examples/topics/transformations/filtering/_meta.yaml index 3c24b8b7fa..082642b25c 100644 --- a/web/landing/content/examples/topics/transformations/filtering/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/filtering/_meta.yaml @@ -1,2 +1,4 @@ priority: 9 hidden: false +title: Filter rows in PHP +summary: 'Keep the rows that pass a condition with filter(): compare a column, a calculated value or the remainder of a division.' diff --git a/web/landing/content/examples/topics/transformations/filtering/basic/_meta.yaml b/web/landing/content/examples/topics/transformations/filtering/basic/_meta.yaml index 0d96c143f9..c9a1772b56 100644 --- a/web/landing/content/examples/topics/transformations/filtering/basic/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/filtering/basic/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Filter rows of a data set in PHP +summary: 'Keep only the rows where a condition is true with filter(): here isTrue() on a boolean column drops the inactive users.' diff --git a/web/landing/content/examples/topics/transformations/filtering/divide/_meta.yaml b/web/landing/content/examples/topics/transformations/filtering/divide/_meta.yaml index 372963400e..5d3afcdae3 100644 --- a/web/landing/content/examples/topics/transformations/filtering/divide/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/filtering/divide/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Filter rows by a calculated value in PHP +summary: 'Compare two columns after arithmetic inside filter(): divide() halves one column and equals() checks it against the other.' diff --git a/web/landing/content/examples/topics/transformations/filtering/mod/_meta.yaml b/web/landing/content/examples/topics/transformations/filtering/mod/_meta.yaml index 8608dd76b4..b273e2bab0 100644 --- a/web/landing/content/examples/topics/transformations/filtering/mod/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/filtering/mod/_meta.yaml @@ -1,2 +1,4 @@ priority: 3 hidden: false +title: Filter even or odd rows with modulo in PHP +summary: 'Keep the rows with an even value: mod() returns the remainder of a division and filter() compares it with zero.' diff --git a/web/landing/content/examples/topics/transformations/literals/_meta.yaml b/web/landing/content/examples/topics/transformations/literals/_meta.yaml index 0d96c143f9..ba125a9357 100644 --- a/web/landing/content/examples/topics/transformations/literals/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/literals/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Add a constant column to a data set in PHP +summary: 'Put the same value into every row with lit() and withColumn(), for a marker column or a default value.' diff --git a/web/landing/content/examples/topics/transformations/match/_meta.yaml b/web/landing/content/examples/topics/transformations/match/_meta.yaml index 1cfff153ea..178e6f9c41 100644 --- a/web/landing/content/examples/topics/transformations/match/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/match/_meta.yaml @@ -1,2 +1,4 @@ priority: 6 hidden: false +title: Match a column against conditions in PHP +summary: 'Clean mixed string values with match_cases(): each match_condition() pairs a test with a result, the first hit wins, and a default covers the rest.' diff --git a/web/landing/content/examples/topics/transformations/math/_meta.yaml b/web/landing/content/examples/topics/transformations/math/_meta.yaml index 372963400e..2668873acc 100644 --- a/web/landing/content/examples/topics/transformations/math/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/math/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Subtract one column from another in PHP +summary: 'Calculate a new column from two others with minus(), and keep both source columns in the row.' diff --git a/web/landing/content/examples/topics/transformations/size/_meta.yaml b/web/landing/content/examples/topics/transformations/size/_meta.yaml index 8608dd76b4..3917cb3bf8 100644 --- a/web/landing/content/examples/topics/transformations/size/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/size/_meta.yaml @@ -1,2 +1,4 @@ priority: 3 hidden: false +title: Count the elements of an array column in PHP +summary: 'Get the number of elements of a list or map column with size(), without unpacking the array.' diff --git a/web/landing/content/examples/topics/transformations/sort/_meta.yaml b/web/landing/content/examples/topics/transformations/sort/_meta.yaml index d3f9270d46..24f2fae26d 100644 --- a/web/landing/content/examples/topics/transformations/sort/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/sort/_meta.yaml @@ -1,2 +1,4 @@ priority: 4 hidden: false +title: Sort rows by a column in PHP +summary: 'Order a whole data set with sortBy() and reverse the direction with desc(). The sort has to see every row first.' diff --git a/web/landing/content/examples/topics/transformations/until/_meta.yaml b/web/landing/content/examples/topics/transformations/until/_meta.yaml index 54474545b3..c9482dd289 100644 --- a/web/landing/content/examples/topics/transformations/until/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/until/_meta.yaml @@ -1,2 +1,4 @@ priority: 11 hidden: false +title: Stop reading a data source early in PHP +summary: 'Stop the source as soon as a condition fails with until(), and see why filter() on the same condition still reads every row.' diff --git a/web/landing/content/examples/topics/transformations/when/_meta.yaml b/web/landing/content/examples/topics/transformations/when/_meta.yaml index 066e3e5a89..e7e08374f1 100644 --- a/web/landing/content/examples/topics/transformations/when/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/when/_meta.yaml @@ -1,2 +1,4 @@ priority: 10 hidden: false +title: Conditional column values in PHP +summary: 'Set a column from a condition with when(): if and else, a chain of conditions, a default for null, or an odd and even flag.' diff --git a/web/landing/content/examples/topics/transformations/when/basic/_meta.yaml b/web/landing/content/examples/topics/transformations/when/basic/_meta.yaml index 0d96c143f9..d445fffee3 100644 --- a/web/landing/content/examples/topics/transformations/when/basic/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/when/basic/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Write an if else condition on a column in PHP +summary: 'Set a column from a condition with when(): one test, one value when it is true and another when it is false, combined here with and().' diff --git a/web/landing/content/examples/topics/transformations/when/else_when/_meta.yaml b/web/landing/content/examples/topics/transformations/when/else_when/_meta.yaml index d3f9270d46..f0e5cc64cb 100644 --- a/web/landing/content/examples/topics/transformations/when/else_when/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/when/else_when/_meta.yaml @@ -1,2 +1,4 @@ priority: 4 hidden: false +title: Chain if, elseif and else on a column in PHP +summary: 'Nest when() calls to build an if, elseif, else chain: here a score turns into the grade A, B, C or F and the first match decides.' diff --git a/web/landing/content/examples/topics/transformations/when/null/_meta.yaml b/web/landing/content/examples/topics/transformations/when/null/_meta.yaml index 8608dd76b4..666384c3af 100644 --- a/web/landing/content/examples/topics/transformations/when/null/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/when/null/_meta.yaml @@ -1,2 +1,4 @@ priority: 3 hidden: false +title: Replace null values in a column in PHP +summary: 'Replace null with a default using when() and isNull(), and pass the column as else so the other rows keep their value.' diff --git a/web/landing/content/examples/topics/transformations/when/odd/_meta.yaml b/web/landing/content/examples/topics/transformations/when/odd/_meta.yaml index 372963400e..c430bac92e 100644 --- a/web/landing/content/examples/topics/transformations/when/odd/_meta.yaml +++ b/web/landing/content/examples/topics/transformations/when/odd/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Mark odd and even numbers in PHP +summary: 'Label each number of a sequence as odd or even with when() and isOdd(), using the named then and else arguments.' diff --git a/web/landing/content/examples/topics/types/_meta.yaml b/web/landing/content/examples/topics/types/_meta.yaml index 5c128501ed..154b24a666 100644 --- a/web/landing/content/examples/topics/types/_meta.yaml +++ b/web/landing/content/examples/topics/types/_meta.yaml @@ -1,2 +1,3 @@ priority: 13 hidden: false +action: Cast diff --git a/web/landing/content/examples/topics/types/assert/_meta.yaml b/web/landing/content/examples/topics/types/assert/_meta.yaml index 0d96c143f9..db7704652a 100644 --- a/web/landing/content/examples/topics/types/assert/_meta.yaml +++ b/web/landing/content/examples/topics/types/assert/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Assert the type of a value in PHP +summary: 'Narrow a value with type_integer()->assert(): it returns the value typed for static analysis and throws on the wrong type, with no coercion.' diff --git a/web/landing/content/examples/topics/types/cast/_meta.yaml b/web/landing/content/examples/topics/types/cast/_meta.yaml index 372963400e..566fb36af5 100644 --- a/web/landing/content/examples/topics/types/cast/_meta.yaml +++ b/web/landing/content/examples/topics/types/cast/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Cast a string to an integer or a date in PHP +summary: 'Convert a string to an integer and to a date with cast() on type_integer() and type_date(), and catch the CastingException for bad input.' diff --git a/web/landing/content/examples/topics/types/is_valid/_meta.yaml b/web/landing/content/examples/topics/types/is_valid/_meta.yaml index 8608dd76b4..e940f8590c 100644 --- a/web/landing/content/examples/topics/types/is_valid/_meta.yaml +++ b/web/landing/content/examples/topics/types/is_valid/_meta.yaml @@ -1,2 +1,4 @@ priority: 3 hidden: false +title: Check the type of a value without exceptions in PHP +summary: 'Ask isValid() on type_integer() and type_json() whether a value has the type, and get a boolean for a condition, not an exception.' diff --git a/web/landing/content/examples/topics/window_functions/_meta.yaml b/web/landing/content/examples/topics/window_functions/_meta.yaml index 1cfff153ea..11bba3df4e 100644 --- a/web/landing/content/examples/topics/window_functions/_meta.yaml +++ b/web/landing/content/examples/topics/window_functions/_meta.yaml @@ -1,2 +1,3 @@ priority: 6 hidden: false +action: Rank diff --git a/web/landing/content/examples/topics/window_functions/dense_rank/_meta.yaml b/web/landing/content/examples/topics/window_functions/dense_rank/_meta.yaml index 8608dd76b4..71a0b2dd5e 100644 --- a/web/landing/content/examples/topics/window_functions/dense_rank/_meta.yaml +++ b/web/landing/content/examples/topics/window_functions/dense_rank/_meta.yaml @@ -1,2 +1,4 @@ priority: 3 hidden: false +title: Rank rows without gaps with dense_rank() in PHP +summary: 'Rank salaries inside each department with dense_rank(): tied rows share a rank and the next rank follows with no gap.' diff --git a/web/landing/content/examples/topics/window_functions/frames/_meta.yaml b/web/landing/content/examples/topics/window_functions/frames/_meta.yaml index d3f9270d46..3298054cd1 100644 --- a/web/landing/content/examples/topics/window_functions/frames/_meta.yaml +++ b/web/landing/content/examples/topics/window_functions/frames/_meta.yaml @@ -1,2 +1,4 @@ priority: 4 hidden: false +title: Running total and moving average in PHP +summary: 'Limit the rows an aggregate sees with rowsBetween(): unbounded_preceding() gives a running total, preceding(1) a two-row moving average.' diff --git a/web/landing/content/examples/topics/window_functions/rank/_meta.yaml b/web/landing/content/examples/topics/window_functions/rank/_meta.yaml index 372963400e..1ba8b34486 100644 --- a/web/landing/content/examples/topics/window_functions/rank/_meta.yaml +++ b/web/landing/content/examples/topics/window_functions/rank/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Rank rows per group with rank() in PHP +summary: 'Rank salaries inside each department with rank() over a window: tied rows share a rank and the next rank skips ahead.' diff --git a/web/landing/content/examples/topics/window_functions/row_number/_meta.yaml b/web/landing/content/examples/topics/window_functions/row_number/_meta.yaml index 0d96c143f9..56dc2c2d6e 100644 --- a/web/landing/content/examples/topics/window_functions/row_number/_meta.yaml +++ b/web/landing/content/examples/topics/window_functions/row_number/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Number rows per group with row_number() in PHP +summary: 'Number the rows of each department 1, 2, 3 with row_number() over a window; tied salaries still get different numbers.' diff --git a/web/landing/content/examples/topics/writing/_meta.yaml b/web/landing/content/examples/topics/writing/_meta.yaml index 372963400e..805693d2bb 100644 --- a/web/landing/content/examples/topics/writing/_meta.yaml +++ b/web/landing/content/examples/topics/writing/_meta.yaml @@ -1,2 +1,3 @@ priority: 2 hidden: false +action: Write diff --git a/web/landing/content/examples/topics/writing/array/_meta.yaml b/web/landing/content/examples/topics/writing/array/_meta.yaml index 0d96c143f9..03958658c6 100644 --- a/web/landing/content/examples/topics/writing/array/_meta.yaml +++ b/web/landing/content/examples/topics/writing/array/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Write a DataFrame to a PHP array +summary: 'Collect every row into a PHP array passed by reference with to_array(), for tests or for code outside the pipeline.' diff --git a/web/landing/content/examples/topics/writing/branch/_meta.yaml b/web/landing/content/examples/topics/writing/branch/_meta.yaml index 066e3e5a89..9189ee9b5c 100644 --- a/web/landing/content/examples/topics/writing/branch/_meta.yaml +++ b/web/landing/content/examples/topics/writing/branch/_meta.yaml @@ -1,2 +1,5 @@ priority: 10 hidden: false +title: Split rows into two files by a condition in PHP +summary: 'Route rows to different loaders by a condition with to_branch(), so one pass over the data writes two CSV files.' +tags: [CSV] diff --git a/web/landing/content/examples/topics/writing/csv/_meta.yaml b/web/landing/content/examples/topics/writing/csv/_meta.yaml index 372963400e..9dec661f92 100644 --- a/web/landing/content/examples/topics/writing/csv/_meta.yaml +++ b/web/landing/content/examples/topics/writing/csv/_meta.yaml @@ -1,2 +1,6 @@ priority: 2 hidden: false +title: Write a CSV file in PHP +summary: 'Write rows to a CSV file with to_csv(); the header row and the order of the columns come from the schema.' +label: CSV +tags: [CSV] diff --git a/web/landing/content/examples/topics/writing/dbal/_meta.yaml b/web/landing/content/examples/topics/writing/dbal/_meta.yaml index 54474545b3..12f09261f0 100644 --- a/web/landing/content/examples/topics/writing/dbal/_meta.yaml +++ b/web/landing/content/examples/topics/writing/dbal/_meta.yaml @@ -1,2 +1,6 @@ priority: 11 hidden: false +title: Write to a database with Doctrine DBAL in PHP +summary: 'Send rows to a database table through Doctrine DBAL in bulk: insert them, upsert them on a key, or delete the matching rows.' +label: DBAL +tags: [Database] diff --git a/web/landing/content/examples/topics/writing/dbal/delete/_meta.yaml b/web/landing/content/examples/topics/writing/dbal/delete/_meta.yaml index 817645f8ac..c490c1b0ba 100644 --- a/web/landing/content/examples/topics/writing/dbal/delete/_meta.yaml +++ b/web/landing/content/examples/topics/writing/dbal/delete/_meta.yaml @@ -2,3 +2,5 @@ priority: 3 hidden: false run: skip: "uses pdo_sqlite, which the playground PHP build does not include" +title: Delete database rows from a DataFrame in PHP +summary: 'Delete the table rows that match each frame row on all its columns with to_dbal_table_delete() over Doctrine DBAL.' diff --git a/web/landing/content/examples/topics/writing/dbal/insert/_meta.yaml b/web/landing/content/examples/topics/writing/dbal/insert/_meta.yaml index a450768fac..394a408aec 100644 --- a/web/landing/content/examples/topics/writing/dbal/insert/_meta.yaml +++ b/web/landing/content/examples/topics/writing/dbal/insert/_meta.yaml @@ -2,3 +2,5 @@ priority: 1 hidden: false run: skip: "uses pdo_sqlite, which the playground PHP build does not include" +title: Insert rows into a database table in PHP +summary: 'Insert each batch of rows into a table through Doctrine DBAL with to_dbal_table_insert(), then read the table back.' diff --git a/web/landing/content/examples/topics/writing/dbal/upsert/_meta.yaml b/web/landing/content/examples/topics/writing/dbal/upsert/_meta.yaml index 89ae9e74cd..76d0f6247a 100644 --- a/web/landing/content/examples/topics/writing/dbal/upsert/_meta.yaml +++ b/web/landing/content/examples/topics/writing/dbal/upsert/_meta.yaml @@ -2,3 +2,5 @@ priority: 2 hidden: false run: skip: "uses pdo_sqlite, which the playground PHP build does not include" +title: Upsert rows with Doctrine DBAL in PHP +summary: 'Turn the insert into an upsert with sqlite_insert_options(), so writing the same ten orders twice updates them instead of failing.' diff --git a/web/landing/content/examples/topics/writing/excel/_meta.yaml b/web/landing/content/examples/topics/writing/excel/_meta.yaml index 1cfff153ea..1279bd7ab1 100644 --- a/web/landing/content/examples/topics/writing/excel/_meta.yaml +++ b/web/landing/content/examples/topics/writing/excel/_meta.yaml @@ -1,2 +1,5 @@ priority: 6 hidden: false +title: Write an Excel file in PHP +summary: 'Write rows to an XLSX spreadsheet with to_excel(), with a header row from the schema, and read the file back with from_excel().' +tags: [Excel] diff --git a/web/landing/content/examples/topics/writing/floe/_meta.yaml b/web/landing/content/examples/topics/writing/floe/_meta.yaml index 7141fd2295..802e570476 100644 --- a/web/landing/content/examples/topics/writing/floe/_meta.yaml +++ b/web/landing/content/examples/topics/writing/floe/_meta.yaml @@ -1,2 +1,5 @@ priority: 7 hidden: false +title: Write a Floe file in PHP +summary: 'Write Flow''s own binary format with to_floe(); the schema is stored in the file, so from_floe() reads every type back exactly.' +tags: [Floe] diff --git a/web/landing/content/examples/topics/writing/jsonl/_meta.yaml b/web/landing/content/examples/topics/writing/jsonl/_meta.yaml index 8608dd76b4..84eaad14a6 100644 --- a/web/landing/content/examples/topics/writing/jsonl/_meta.yaml +++ b/web/landing/content/examples/topics/writing/jsonl/_meta.yaml @@ -1,2 +1,6 @@ priority: 3 hidden: false +title: Write a JSONL file in PHP +summary: 'Write JSON Lines with to_json_lines(): one JSON object per row and one row per line, ready to be read back line by line.' +label: JSONL +tags: [JSON] diff --git a/web/landing/content/examples/topics/writing/overwrite/_meta.yaml b/web/landing/content/examples/topics/writing/overwrite/_meta.yaml index 3c24b8b7fa..cf0a19ca20 100644 --- a/web/landing/content/examples/topics/writing/overwrite/_meta.yaml +++ b/web/landing/content/examples/topics/writing/overwrite/_meta.yaml @@ -1,2 +1,5 @@ priority: 9 hidden: false +title: Overwrite an existing file in PHP +summary: 'Replace what is already at the destination with overwrite(): read a CSV file and write it back to the same path without one column.' +tags: [CSV] diff --git a/web/landing/content/examples/topics/writing/parquet/_meta.yaml b/web/landing/content/examples/topics/writing/parquet/_meta.yaml index 76b24de0b7..9783ac5eef 100644 --- a/web/landing/content/examples/topics/writing/parquet/_meta.yaml +++ b/web/landing/content/examples/topics/writing/parquet/_meta.yaml @@ -1,2 +1,5 @@ priority: 5 hidden: false +title: Write a Parquet file in PHP +summary: 'Write a columnar, compressed Parquet file with to_parquet() using the schema of the frame, then read it back with from_parquet().' +tags: [Parquet] diff --git a/web/landing/content/examples/topics/writing/postgresql/_meta.yaml b/web/landing/content/examples/topics/writing/postgresql/_meta.yaml index a1d79141df..2a590d2231 100644 --- a/web/landing/content/examples/topics/writing/postgresql/_meta.yaml +++ b/web/landing/content/examples/topics/writing/postgresql/_meta.yaml @@ -1,2 +1,6 @@ priority: 12 hidden: false +title: Write to PostgreSQL in PHP +summary: 'Write rows to PostgreSQL through the native client: bulk insert, upsert on conflict, or several tables in one transaction.' +label: PostgreSQL +tags: [PostgreSQL] diff --git a/web/landing/content/examples/topics/writing/postgresql/insert/_meta.yaml b/web/landing/content/examples/topics/writing/postgresql/insert/_meta.yaml index f11de015b9..f088d17c5a 100644 --- a/web/landing/content/examples/topics/writing/postgresql/insert/_meta.yaml +++ b/web/landing/content/examples/topics/writing/postgresql/insert/_meta.yaml @@ -2,3 +2,5 @@ priority: 1 hidden: false run: skip: "needs a PostgreSQL server" +title: Insert rows into PostgreSQL in PHP +summary: 'Insert rows over a native ext-pgsql connection with to_pgsql_table(), batched into multi-row statements as the DataFrame streams.' diff --git a/web/landing/content/examples/topics/writing/postgresql/transaction/_meta.yaml b/web/landing/content/examples/topics/writing/postgresql/transaction/_meta.yaml index e7ca0a6712..787818c102 100644 --- a/web/landing/content/examples/topics/writing/postgresql/transaction/_meta.yaml +++ b/web/landing/content/examples/topics/writing/postgresql/transaction/_meta.yaml @@ -2,3 +2,5 @@ priority: 3 hidden: false run: skip: "needs a PostgreSQL server" +title: Write to PostgreSQL in a transaction in PHP +summary: 'Group writes to two tables with to_pgsql_transaction(), so each batch commits together and rolls back if any write fails.' diff --git a/web/landing/content/examples/topics/writing/postgresql/upsert/_meta.yaml b/web/landing/content/examples/topics/writing/postgresql/upsert/_meta.yaml index 3f6616d652..e1205144c6 100644 --- a/web/landing/content/examples/topics/writing/postgresql/upsert/_meta.yaml +++ b/web/landing/content/examples/topics/writing/postgresql/upsert/_meta.yaml @@ -2,3 +2,5 @@ priority: 2 hidden: false run: skip: "needs a PostgreSQL server" +title: Upsert rows into PostgreSQL in PHP +summary: 'Insert or update in one statement with pgsql_insert_options(): ON CONFLICT DO UPDATE, so loading the same rows twice gives no error.' diff --git a/web/landing/content/examples/topics/writing/text/_meta.yaml b/web/landing/content/examples/topics/writing/text/_meta.yaml index 177f368d9d..e642e85bc9 100644 --- a/web/landing/content/examples/topics/writing/text/_meta.yaml +++ b/web/landing/content/examples/topics/writing/text/_meta.yaml @@ -1,2 +1,5 @@ priority: 8 hidden: false +title: Write a text file line by line in PHP +summary: 'Reduce each row to one column with concat_ws() and write it with to_text(), one line of the file per row.' +tags: [Text] diff --git a/web/landing/content/examples/topics/writing/xml/_meta.yaml b/web/landing/content/examples/topics/writing/xml/_meta.yaml index d3f9270d46..6e43e417e0 100644 --- a/web/landing/content/examples/topics/writing/xml/_meta.yaml +++ b/web/landing/content/examples/topics/writing/xml/_meta.yaml @@ -1,2 +1,6 @@ priority: 4 hidden: false +title: Write an XML file in PHP +summary: 'Write rows to an XML file with to_xml(), then echo the file back to see the nesting the writer produced.' +label: XML +tags: [XML] diff --git a/web/landing/content/guides/distributed-tracing-in-php.md b/web/landing/content/guides/distributed-tracing-in-php.md new file mode 100644 index 0000000000..eb00139d71 --- /dev/null +++ b/web/landing/content/guides/distributed-tracing-in-php.md @@ -0,0 +1,213 @@ +--- +seo_title: Distributed tracing in PHP - pass traceparent from one service to the next +seo_description: 'Connect the traces of two PHP services into one: send the W3C traceparent header with the request and use it as the parent span in the next service.' +group: Observability +actions: [Observe] +tags: [OpenTelemetry, REST API] +problem: 'Two services, two traces, and nothing connects them' +proof_label: 'Traces for one checkout' +proof_before: '2' +proof_after: '1' +published: '2026-12-01' +updated: '2026-12-01' +examples: [telemetry/propagator, telemetry/tracer] +--- + +# Distributed tracing in PHP: pass traceparent from one service to the next + +Let's say our checkout calls a second service to ask if a product is in stock. Both services have tracing. +A customer complains about a slow checkout, and we find two traces: one in each service, with no way to tell that they belong together. + +Doesn't look like a complicated task, right? + +## Trace two PHP services separately + +The first idea is always to trace each service on its own. The script plays both of them: `stock()` stands for the second service, and the array is the HTTP headers that travel between them. + +```php + $name]), + tracer_provider(void_span_processor(), clock(), memory_context_storage()), + ); +} + +function stock(array $headers): string +{ + $span = service('stock')->tracer('http')->span('GET /stock'); + + return 'stock trace ' . $span->context()->traceId->toHex(); +} + +$span = service('checkout')->tracer('http')->span('POST /checkout'); + +echo 'checkout trace ', $span->context()->traceId->toHex(), "\n"; +echo stock(headers: []), "\n"; +``` + +```text +checkout trace c670645b3589cf4d76c06f05f8703630 +stock trace a0f647c13833ac7278f1e9022dc5752c +``` + +It works, and each service sees its own part. + +## Why two traces are not enough + +The two ids have nothing in common. A trace id is made when the first span of a process starts, and the stock service doesn't know that somebody already made one. + +To find the stock request of one slow checkout, we compare timestamps by hand. With ten checkouts a second that stops working. + +The services have to agree on one id. The W3C standard for that is one HTTP header, `traceparent`: + +```text +00-faedc55bb8bcc470f0813f7f9522bfd7-5bbe8a0c8e3d45a7-01 +``` + +It has four parts: a version, the trace id, the id of the span that makes the call, and a flag that says the trace is sampled. + +## Pass the trace context with traceparent + +flow-php/telemetry is an independent implementation of OpenTelemetry, written in PHP. It needs PHP 8.3 or newer, no extension, and it is [not a wrapper around the official SDK](/documentation/components/libs/telemetry/opentelemetry-sdk). + +```bash +composer require flow-php/telemetry flow-php/etl +``` + +```php + $name]), + tracer_provider(void_span_processor(), clock(), memory_context_storage()), + ); +} + +function stock(array $headers): string +{ + $caller = w3c_trace_context()->extract(array_carrier($headers))->spanContext; + + $span = service('stock')->tracer('http')->span( + 'GET /stock', + SpanKind::SERVER, + parent: $caller === null ? null : Context::root()->withActiveSpan($caller), + ); + + return 'stock trace ' . $span->context()->traceId->toHex() . ' parent ' . $span->context()->parentSpanId?->toHex(); +} + +$span = service('checkout')->tracer('http')->span('POST /checkout', SpanKind::CLIENT); + +$headers = array_carrier(); +w3c_trace_context()->inject(propagation_context($span->context()), $headers); + +echo 'checkout trace ', $span->context()->traceId->toHex(), ' span ', $span->context()->spanId->toHex(), "\n"; +echo 'header ', $headers->unwrap()['traceparent'], "\n"; +echo stock($headers->unwrap()), "\n"; +``` + +```text +checkout trace faedc55bb8bcc470f0813f7f9522bfd7 span 5bbe8a0c8e3d45a7 +header 00-faedc55bb8bcc470f0813f7f9522bfd7-5bbe8a0c8e3d45a7-01 +stock trace faedc55bb8bcc470f0813f7f9522bfd7 parent 5bbe8a0c8e3d45a7 +``` + +Now both services have the same trace id, and the span of the stock service is a child of the checkout span. + +Two calls do the work: + +- [`w3c_trace_context`](/documentation/dsl/telemetry/w3c-trace-context)`()->inject()` writes the header on the side that calls. +- `extract()` reads it on the side that answers, and the new span gets it as its `parent`. Without a header `extract` gives no span context, and the service starts its own trace as before. + +## The same with real HTTP requests + +> These two scripts need two web servers and a collector, so they run only on your machine, not in the playground. + +In a real service the array is the HTTP request. The checkout adds the header to its call, with any HTTP client: + +```php ignore +$tracer = $telemetry->tracer('http'); + +echo $tracer->trace('POST /checkout', static function () use ($tracer): string { + return $tracer->trace('GET stock', static function () use ($tracer): string { + $headers = array_carrier(); + w3c_trace_context()->inject(propagation_context($tracer->activeSpan()), $headers); + + return (string) file_get_contents('http://localhost:8002/', context: stream_context_create([ + 'http' => ['header' => 'traceparent: ' . $headers->unwrap()['traceparent']], + ])); + }, SpanKind::CLIENT); +}, SpanKind::SERVER); +``` + +The stock service reads the header from the request. [`superglobal_carrier`](/documentation/dsl/telemetry/superglobal-carrier) finds it in `$_SERVER`: + +```php ignore +$caller = w3c_trace_context()->extract(superglobal_carrier())->spanContext; + +echo $telemetry->tracer('http')->trace( + 'GET /stock', + static fn (): string => "3 in stock\n", + SpanKind::SERVER, + $caller === null ? null : Context::root()->withActiveSpan($caller), +); +``` + +Both services send their spans to the same collector, and it shows one trace from two services: + +```text +service.name=stock +GET /stock 28094e1b42436657d5912fa3b1d373c6 cd9fcb66ae4e8983 +service.name=checkout +GET stock 28094e1b42436657d5912fa3b1d373c6 c4e19ff8b5eb8a3d +POST /checkout 28094e1b42436657d5912fa3b1d373c6 935c0c2f0c27a3cd +``` + +Three spans, one trace id. A monitoring tool draws them as one timeline, and the slow part of the checkout is visible, whichever service it is in. + +## What to know before you trust a traceparent + +- The header comes from outside. A stranger can send one too, and then our spans join a trace we don't know. On a public endpoint, read it only from callers we trust. +- The last part of the header says if the caller keeps the trace. The default sampler follows that choice, so one checkout is kept or dropped in both services together. +- A queue works the same way. The header goes into the message, and the worker reads it from there. + +## Where to go from here + +The spans themselves are in the guide about [tracing in PHP](/guides/trace-php-script-with-opentelemetry). +How the spans of both services reach one place is in [send PHP traces over OTLP](/guides/send-php-traces-over-otlp). +In Symfony the bundle reads the header of every request for us, with `flow-php/symfony-http-foundation-telemetry-bridge` installed: see [Symfony monitoring with OpenTelemetry](/guides/symfony-monitoring-with-opentelemetry). +The log lines of both services get the same id too: see [PHP logs with a trace id](/guides/php-logs-with-trace-id). diff --git a/web/landing/content/guides/export-database-to-excel-in-php.md b/web/landing/content/guides/export-database-to-excel-in-php.md index 4cc689f3be..4e60bcaeac 100644 --- a/web/landing/content/guides/export-database-to-excel-in-php.md +++ b/web/landing/content/guides/export-database-to-excel-in-php.md @@ -1,13 +1,16 @@ --- -seo_title: 'PhpSpreadsheet out of memory: export a database table to Excel in PHP' +seo_title: Export a database table to Excel in PHP without running out of memory seo_description: 'PhpSpreadsheet keeps the whole workbook in memory, so a big export ends with "Allowed memory size exhausted". Why it happens, and how to export a million rows to XLSX in 28Mb.' group: Writing files +actions: [Export] +tags: [Excel, Database] problem: 'PhpSpreadsheet runs out of memory' proof_label: 'A million orders to XLSX' proof_before: '3663Mb' proof_after: '28Mb' published: '2026-11-18' updated: '2026-11-18' +examples: [reading/dbal/key_set, writing/excel, reading/excel] --- # Export a database table to Excel in PHP without running out of memory @@ -59,10 +62,6 @@ orders.sqlite: 1000000 rows The first thing that comes to mind is PhpSpreadsheet. We don't load the whole table. We fetch the orders one by one and add every order to the sheet. -```bash -composer require phpoffice/phpspreadsheet -``` - ```php ignore These steps need a Symfony application and a collector, so they run only on your machine, not in the playground. + +## Log slow queries in Symfony with a timer + +The first idea is always a timer around the query, and a line in the log when it took too long. + +```php ignore +#[Route('/prices', name: 'prices', methods: ['GET'])] +public function prices(Connection $connection, LoggerInterface $logger): Response +{ + $start = hrtime(true); + + $prices = $connection->fetchAllAssociative( + 'SELECT category_id, AVG(price) AS average FROM product GROUP BY category_id ORDER BY average DESC', + ); + + $milliseconds = (hrtime(true) - $start) / 1e6; + + if ($milliseconds > 100) { + $logger->warning('slow query', ['route' => 'prices', 'duration' => $milliseconds]); + } + + return $this->json($prices); +} +``` + +It works, for this one query. + +## Why a timer in the controller is not enough + +We put the timer where we already suspect the problem. The slow query is usually somewhere else. + +- Most queries are not in a controller. The ORM writes them, in a repository, a listener or a lazy relation in a template. +- A page that loads twenty products and then one category for each of them has no slow query. It has twenty-one fast ones, and no timer sees that. +- The slow query log of the database knows the query, but not the page that asked for it. + +We want every query measured, without touching the code that runs it, and connected to its request. + +## Trace every Doctrine query in Symfony + +flow-php/telemetry is an independent implementation of OpenTelemetry, written in PHP, and it is [not a wrapper around the official SDK](/documentation/components/libs/telemetry/opentelemetry-sdk). +The bundle needs PHP 8.3 or newer, Symfony 6.4, 7.4 or 8.0 and DoctrineBundle. The only PHP extension it needs is curl. + +```bash +composer require flow-php/symfony-telemetry-bundle flow-php/telemetry-otlp-bridge +``` + +The guide about [Symfony monitoring with OpenTelemetry](/guides/symfony-monitoring-with-opentelemetry) shows the installation step by step. This is the whole configuration: + +```yaml +# config/packages/flow_telemetry.yaml +flow_telemetry: + resource: + custom: + service.name: shop + + exporters: + collector: + otlp: + transport: + type: curl + endpoint: 'http://localhost:4318' + timeout_ms: 200 + connect_timeout_ms: 50 + + tracer_provider: + processor: + type: batching + exporter: collector + + meter_provider: + processor: + type: batching + exporter: collector + + instrumentation: + http_kernel: + enabled: true + dbal: + enabled: true +``` + +`dbal` puts itself between Doctrine and the database driver. Every query of the DBAL and of the ORM becomes a span with its SQL and its duration, inside the trace of its request. +We remove the timer from the controller. No code of the application changes. + +The SQL is recorded with `?` in place of the values, so no data of a customer leaves the database. + +## Show only the slow queries + +The spans go to an OpenTelemetry Collector on the same machine. The guide about the [collector for PHP](/guides/opentelemetry-collector-for-php) shows how to start one in Docker. +We tell it to drop every span that is not a query, and every query faster than 100ms: + +```yaml +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + +processors: + filter/slow-queries: + error_mode: ignore + traces: + span: + - 'attributes["db.query.text"] == nil' + - 'end_time_unix_nano - start_time_unix_nano < 100000000' + +exporters: + debug: + verbosity: normal + +service: + pipelines: + traces: + receivers: [otlp] + processors: [filter/slow-queries] + exporters: [debug] +``` + +Now we open three pages of the shop: the product list, the search and the price page. Together they run 39 queries. The collector prints one line: + +```text +ScopeTraces #0 flow.symfony.dbal@4.6.0 +SELECT product 2a69ccff0e69681fa58541211bbbacbe 5a988c30b722ff39 db.system.name=sqlite db.namespace=default server.address=localhost db.operation.name=SELECT db.collection.name=product db.query.text=SELECT category_id, AVG(price) AS average FROM product GROUP BY category_id ORDER BY average DESC +``` + +That's the query of the price page: an average over the whole `product` table, on every page view. +The second value in the line is the trace id. In a monitoring tool the same id opens the whole request, with the route and the controller. + +100ms is `100000000` in the filter, because the collector counts in nanoseconds. + +## Find a page with too many queries + +The other half of the problem has no slow query at all. For that the bundle counts: with `meter_provider` in the configuration, every query adds to a histogram named `db.client.operation.duration`. + +We add `metrics` to the collector, with no filter: + +```yaml +service: + pipelines: + metrics: + receivers: [otlp] + exporters: [debug] +``` + +This is what one view of the product list sends, with the long lines cut: + +```text +db.client.operation.duration{db.operation.name=SELECT,db.collection.name=product} count=1 sum=0.000163042 +db.client.operation.duration{db.operation.name=SELECT,db.collection.name=category} count=20 sum=0.000539291 +``` + +One query for twenty products, and then twenty queries for their categories, one by one. Every one of them is fast, and together they are the classic N+1 problem. +The price page looks different in the same metric: + +```text +db.client.operation.duration{db.operation.name=SELECT,db.collection.name=product} count=1 sum=0.261899958 +``` + +One query, 0.26 seconds. The sum is in seconds. + +A monitoring tool draws both as a chart for each table: how many queries, and how long they take. A new release that doubles one of them is visible the same day. + +## What to set for Doctrine tracing + +All of these are options of `dbal`, and none is needed to start: + +| Option | Default | What it does | +|----------------------|-----------|-------------------------------------------------------------------| +| `max_sql_length` | `1000` | Cuts the SQL text in the span | +| `include_parameters` | `false` | Adds the bound values. They can be personal data, so leave it off | +| `transaction_spans` | `grouped` | One span for a whole transaction, or `per_operation`, or `off` | +| `exclude_tables` | none | Queries of these tables are not traced | +| `collect_metrics` | `true` | The histogram from the section above | + +## Where to go from here + +The same bundle traces requests, console commands and more: see [Symfony monitoring with OpenTelemetry](/guides/symfony-monitoring-with-opentelemetry). +To keep whole traces of slow requests and drop the rest, read about tail sampling in the [OpenTelemetry Collector for PHP](/guides/opentelemetry-collector-for-php). +All the options are in the [bundle documentation](/documentation/components/bridges/symfony-telemetry-bundle). +Without Doctrine, the PostgreSQL client of Flow traces its own queries: see [trace SQL queries in PHP](/guides/trace-sql-queries-in-php). diff --git a/web/landing/content/guides/find-slow-phpunit-tests.md b/web/landing/content/guides/find-slow-phpunit-tests.md new file mode 100644 index 0000000000..ee7c9a6ab1 --- /dev/null +++ b/web/landing/content/guides/find-slow-phpunit-tests.md @@ -0,0 +1,165 @@ +--- +seo_title: Find slow PHPUnit tests with OpenTelemetry +seo_description: 'Find the slow tests of a PHPUnit suite on every run, also in CI: one extension in phpunit.xml sends a span for each test, with duration and memory.' +group: Observability +actions: [Observe] +tags: [OpenTelemetry] +problem: 'The test suite gets slower, and nobody knows which tests do it' +proof_label: 'Tests to read after one run' +proof_before: '4' +proof_after: '1' +published: '2026-12-01' +updated: '2026-12-01' +--- + +# Find slow PHPUnit tests with OpenTelemetry + +Let's say our test suite took two minutes last spring and takes nine now. Nobody added a slow test on purpose. +It happened one test at a time, and each of them looked fine in its pull request. + +> These steps need a collector, so they run only on your machine or in CI, not in the playground. + +## Find slow tests with the JUnit log of PHPUnit + +The first idea is the report PHPUnit can already write. + +```bash +vendor/bin/phpunit --log-junit junit.xml +``` + +```text + + + + + + +``` + +We run the suite as always: + +```bash +vendor/bin/phpunit +``` + +```text +.... 4 / 4 (100%) + +Time: 00:00.497, Memory: 50.50 MB + +OK (4 tests, 4 assertions) +``` + +Nothing looks different, and no test changed. At the end of the run the extension sent one trace to the collector: a span for the run, one for each test class and one for each test. + +```text +Test Suite Run + shop + Shop\Tests\OrderImportTest + test_imports_one_order + test_imports_a_full_file + Shop\Tests\PriceCalculatorTest + test_adds_tax + test_rounds_to_cents +``` + +Every test span has its duration, the result (`test.case.result.status=passed`), and the memory it used (`flow.phpunit.test.memory.peak`). + +## Show only the slow tests + +The spans go to an OpenTelemetry Collector. The guide about the [collector for PHP](/guides/opentelemetry-collector-for-php) shows how to start one in Docker. +We tell it to drop every span that is not a test, and every test faster than 100ms: + +```yaml +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + +processors: + filter/slow-tests: + error_mode: ignore + traces: + span: + - 'attributes["test.case.name"] == nil' + - 'end_time_unix_nano - start_time_unix_nano < 100000000' + +exporters: + debug: + verbosity: normal + +service: + pipelines: + traces: + receivers: [otlp] + processors: [filter/slow-tests] + exporters: [debug] +``` + +We run the four tests again, and the collector prints one line, with the long attributes cut: + +```text +test_imports_a_full_file 9846d920ea0f27322718e52774f5bcfb cdd86f0f36b631d4 flow.phpunit.test.id=Shop\Tests\OrderImportTest::test_imports_a_full_file test.case.result.status=passed flow.phpunit.test.memory.peak=37305016 +``` + +That's the test that imports a whole file, with its class and its peak memory in bytes. +100ms is `100000000` in the filter, because the collector counts in nanoseconds. + +## See the test suite get slower over time + +One slow test is a finding. The trend is what we came for, and the extension sends it as metrics with every run: + +```text +flow.phpunit.test.duration{test.case.result.status=passed} count=4 sum=0.48274 max=0.45617 +flow.phpunit.suite.duration{test.suite.name=Shop\Tests\OrderImportTest} count=1 sum=0.482965 +flow.phpunit.suite.duration{test.suite.name=Shop\Tests\PriceCalculatorTest} count=1 sum=0.001313 +``` + +A monitoring tool draws `flow.phpunit.suite.duration` as one line for each test class, run after run. The day a class doubles its time is visible on the chart, with the commit of that day next to it. + +## Send the results from CI + +In CI the address of the collector and the name of the service come from the environment, so `phpunit.xml` stays the same for everybody: + +```bash +FLOW_PHPUNIT_OTEL_ENDPOINT=https://otlp.example.com:4318 \ +FLOW_PHPUNIT_OTEL_SERVICE_NAME=shop-tests \ +vendor/bin/phpunit +``` + +On a machine with no collector the tests run and pass as before. The extension writes the reason to the PHP error log, and the result of the suite doesn't change. + +## Where to go from here + +All the parameters, the headers for a hosted service and the file transport are in the [bridge documentation](/documentation/components/bridges/phpunit-telemetry-bridge). +What a span and a trace are is in the guide about [tracing in PHP](/guides/trace-php-script-with-opentelemetry). diff --git a/web/landing/content/guides/import-csv-file-into-mysql-or-postgresql-in-php.md b/web/landing/content/guides/import-csv-file-into-mysql-or-postgresql-in-php.md index d715d9223c..2dee540115 100644 --- a/web/landing/content/guides/import-csv-file-into-mysql-or-postgresql-in-php.md +++ b/web/landing/content/guides/import-csv-file-into-mysql-or-postgresql-in-php.md @@ -2,6 +2,8 @@ seo_title: 'Import a CSV file into MySQL or PostgreSQL in PHP, with upsert' seo_description: 'Import a CSV file into a MySQL or PostgreSQL table in PHP, a hundred thousand rows in under three seconds, and update the rows that are already there with an upsert.' group: Importing data +actions: [Import] +tags: [CSV, MySQL, PostgreSQL] problem: 'One INSERT per row takes minutes' proof_label: '100,000 rows into MySQL' proof_before: '264s' @@ -9,6 +11,7 @@ proof_after: '2.3s' featured: true published: '2026-11-18' updated: '2026-11-18' +examples: [writing/postgresql/upsert, writing/dbal/upsert, writing/dbal/insert, writing/postgresql/insert, reading/corrupted_records_routing] --- # Import a CSV file into MySQL or PostgreSQL in PHP @@ -283,3 +286,9 @@ PHP 8.3, a hundred thousand orders with five columns, the databases in Docker: | Flow with Doctrine, the second night | 1.9s | 2.7s | | Flow PostgreSQL | - | 2.3s | | Flow PostgreSQL, the second night | - | 2.5s | + +## Where to go from here + +When the file is too big for the memory limit, read [read a large CSV file in PHP](/guides/read-large-csv-file-in-php) first. +The same import from other sources is in [import a large Excel file](/guides/import-large-excel-file-in-php) and [import data from a REST API](/guides/import-data-from-rest-api-in-php). +To make the imported rows searchable, see [index a database table in Elasticsearch](/guides/index-database-table-in-elasticsearch-with-php). diff --git a/web/landing/content/guides/import-data-from-rest-api-in-php.md b/web/landing/content/guides/import-data-from-rest-api-in-php.md index f65a9bf00b..f6bb886d89 100644 --- a/web/landing/content/guides/import-data-from-rest-api-in-php.md +++ b/web/landing/content/guides/import-data-from-rest-api-in-php.md @@ -2,9 +2,12 @@ seo_title: 'Consume a paginated REST API in PHP and keep the raw responses' seo_description: 'Import data from a paginated REST API into a database in PHP without a pagination loop, and store every raw response, so we always know what the API sent.' group: Importing data +actions: [Import] +tags: [REST API, Database] problem: 'Nobody knows what the API sent' published: '2026-11-18' updated: '2026-11-18' +examples: [reading/http, writing/branch, caching/cache, transformations/array/expand, writing/jsonl] --- # Import data from a REST API in PHP and keep the raw responses @@ -55,38 +58,20 @@ php -S 127.0.0.1:8080 api.php The `orders` table is the same as in [Import a CSV file into MySQL or PostgreSQL](/guides/import-csv-file-into-mysql-or-postgresql-in-php#the-table). -## Call a REST API in PHP with Guzzle +## Call a paginated REST API in PHP in a loop The first thing that comes to mind is a loop: ask for a page, decode it, insert the orders, ask for the next one. - -```bash -composer require guzzlehttp/guzzle -``` +With a PSR-18 client in `$client`, a PSR-17 factory in `$requests` and a prepared `INSERT` in `$insert`, it's a dozen lines: ```php ignore - 'http://127.0.0.1:8080', - 'headers' => ['Authorization' => 'Bearer secret-token'], -]); - -$database = new PDO('mysql:host=127.0.0.1;dbname=shop', 'shop', 'secret'); -$insert = $database->prepare( - 'INSERT INTO orders (id, email, country, amount, created_at) VALUES (?, ?, ?, ?, ?) - ON DUPLICATE KEY UPDATE email = VALUES(email), country = VALUES(country), amount = VALUES(amount), created_at = VALUES(created_at)' -); - $page = 1; do { - $response = $api->get('/orders', ['query' => ['page' => $page]]); + $response = $client->sendRequest( + $requests + ->createRequest('GET', 'http://127.0.0.1:8080/orders?page=' . $page) + ->withHeader('Authorization', 'Bearer secret-token'), + ); $orders = json_decode((string) $response->getBody(), true)['data']; foreach ($orders as $order) { @@ -97,7 +82,7 @@ do { } while ($orders !== []); ``` -It works, all 250 orders are in the table. +The orders are in the table, and everything the API sent is gone. ## Three weeks later an amount is wrong @@ -107,7 +92,7 @@ Was it the API, or our code? We can't tell. The response went through `json_decode` and five array keys into an `INSERT`, and after that it was gone. The API shows today's version of the order, not the one it sent us three weeks ago. -With an SDK in place of Guzzle it's the same, only with objects between the response and the table. +With an SDK in place of the HTTP client it's the same, only with objects between the response and the table. So the import needs to keep what the API said. That means more code in the loop: a file to write to, the status code, the failed requests. And the loop itself has to change for every API, because every API paginates in its own way. @@ -217,7 +202,7 @@ A `write` in the middle doesn't end anything. The same rows go on to the next st The second `write` is a branch. [`to_branch`](/documentation/dsl/core/to-branch) takes a condition, and only the responses that match it go to its file. -With a wrong token the API answers 401. Guzzle throws an exception. Flow stops asking, and the response is in `failed-2026-11-18.jsonl`: +With a wrong token the API answers 401. Flow stops asking, and the response is in `failed-2026-11-18.jsonl`: ```text {"request_uri":"http:\/\/127.0.0.1:8080\/orders?page=1","response_status_code":401,"response_body":"{\"error\":\"invalid token\"}"} @@ -259,3 +244,8 @@ http_pagination_cursor('meta.next_cursor', http_request_option_query('cursor')) ```php ignore tab="Link header" http_pagination_link_header('next') ``` + +## Where to go from here + +When the API gives one big file and not pages, read [read a large JSON file in PHP](/guides/read-large-json-file-in-php). +To follow one request through the API and our own code, see [distributed tracing in PHP](/guides/distributed-tracing-in-php). diff --git a/web/landing/content/guides/import-large-excel-file-in-php.md b/web/landing/content/guides/import-large-excel-file-in-php.md index a3935412f4..91bea3f57d 100644 --- a/web/landing/content/guides/import-large-excel-file-in-php.md +++ b/web/landing/content/guides/import-large-excel-file-in-php.md @@ -2,12 +2,15 @@ seo_title: 'PhpSpreadsheet out of memory: import a large Excel file in PHP' seo_description: 'PhpSpreadsheet builds an object for every cell, so a 3Mb Excel file runs out of memory. Why it happens, and how to read a million rows from XLSX in PHP with 26Mb.' group: Importing data +actions: [Read, Import] +tags: [Excel] problem: 'A 3Mb Excel file does not fit in 128Mb' proof_label: 'Reading a 2.6Mb Excel file' proof_before: '430Mb' proof_after: '26Mb' published: '2026-11-18' updated: '2026-11-18' +examples: [reading/excel, writing/excel, aggregations/group_by/group_by_sum, transformations/sort] --- # Import a large Excel file in PHP without running out of memory @@ -61,10 +64,6 @@ The first thing that comes to mind is PhpSpreadsheet: load the file and take the > PhpSpreadsheet is not available in the playground, so this script runs only on your machine. -```bash -composer require phpoffice/phpspreadsheet -``` - ```php ignore write(to_seal_delete($engine, 'products')) ->run(); ``` + +## Where to go from here + +To fill the table first, read [import a CSV file into MySQL or PostgreSQL](/guides/import-csv-file-into-mysql-or-postgresql-in-php). +To find the slow query behind a slow index run, see [trace SQL queries in PHP](/guides/trace-sql-queries-in-php). diff --git a/web/landing/content/guides/opentelemetry-collector-for-php.md b/web/landing/content/guides/opentelemetry-collector-for-php.md new file mode 100644 index 0000000000..d44b154879 --- /dev/null +++ b/web/landing/content/guides/opentelemetry-collector-for-php.md @@ -0,0 +1,257 @@ +--- +seo_title: OpenTelemetry Collector for PHP - keep the PHP process light +seo_description: 'A PHP process lives for one request. Send every span to an OpenTelemetry Collector on the same host and let it batch, retry and sample.' +group: Observability +actions: [Observe] +tags: [OpenTelemetry] +problem: 'A PHP request cannot wait for a monitoring service' +proof_label: 'Traces kept out of 4 requests' +proof_before: '4' +proof_after: '2' +published: '2026-12-01' +updated: '2026-12-01' +--- + +# OpenTelemetry Collector for PHP: keep the PHP process light + +Let's say our shop sends its traces straight to a monitoring service on the other side of the internet. +It works, until that service has a slow afternoon. Then every request of the shop waits for it too. + +> These scripts need a collector, so they run only on your machine, not in the playground. + +## Send traces from PHP straight to the backend + +This is where most of us start: the exporter gets the address of the service. + +```php ignore +$exporter = otlp_exporter(otlp_curl_transport( + endpoint: 'https://otlp.example.com:4318', + options: otlp_curl_options()->withHeader('Authorization', 'Bearer ' . $_ENV['OTLP_TOKEN']), +)); +``` + +It needs nothing else to run, and that's why it's the first thing we try. + +## Why PHP is the wrong place for the heavy work + +A PHP process lives for one request. Everything telemetry does inside it, the visitor waits for. + +- **The export.** A request to another continent with TLS takes time on a good day. On a bad day the request of the visitor waits for the timeout. +- **Retries.** When the service is down, somebody has to keep the data and try again. A PHP process that ends in 50ms can't. +- **Batching.** One request makes a few spans. A real batch needs the spans of many requests, and they live in different processes. +- **Sampling.** To keep only the slow and the failed requests, somebody has to see the whole trace first. The PHP process decides at the start, when it knows nothing yet. + +An OpenTelemetry Collector is a small program that runs next to PHP and never ends. It takes everything PHP sends, and it has all the time PHP doesn't have. + +## Send everything from PHP to a collector on the same host + +flow-php/telemetry is an independent implementation of OpenTelemetry, written in PHP. It needs PHP 8.3 or newer and the curl extension, and it is [not a wrapper around the official SDK](/documentation/components/libs/telemetry/opentelemetry-sdk). + +```bash +composer require flow-php/telemetry flow-php/telemetry-otlp-bridge flow-php/etl +``` + +```php ignore +withTimeout(200)->withConnectTimeout(50), +)); + +$telemetry = telemetry( + resource(['service.name' => 'shop']), + tracer_provider( + batching_span_processor($exporter), + clock(), + memory_context_storage(), + sampler: always_on_sampler(), + ), +)->registerShutdownFunction(); + +$tracer = $telemetry->tracer('http'); + +$requests = [ + 'GET /products' => 10_000, + 'GET /cart' => 15_000, + 'GET /search' => 400_000, + 'POST /checkout' => null, +]; + +foreach ($requests as $name => $microseconds) { + try { + $tracer->trace($name, static function () use ($microseconds): void { + if ($microseconds === null) { + throw new RuntimeException('Payment provider did not answer'); + } + + usleep($microseconds); + }); + } catch (RuntimeException) { + } +} +``` + +The script plays four requests: two fast ones, a slow search and a checkout that fails. + +On the PHP side there is nothing clever, and that's the point: + +- The address is `localhost`. No TLS, no token, no trip over the internet. +- The timeouts are 50ms to connect and 200ms for the request. A collector that doesn't answer costs a request at most that. +- [`always_on_sampler`](/documentation/dsl/telemetry/always-on-sampler) keeps every span. PHP doesn't decide what is interesting. +- The token of the monitoring service is not in the PHP application anymore. The collector has it. + +## Tail sampling in the OpenTelemetry Collector + +Now the collector. It's one program and one file. We use the `contrib` build, because tail sampling is a part of it. + +```yaml +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 256 + tail_sampling: + decision_wait: 5s + policies: + - name: errors + type: status_code + status_code: + status_codes: [ERROR] + - name: slow + type: latency + latency: + threshold_ms: 300 + - name: one-in-ten + type: probabilistic + probabilistic: + sampling_percentage: 10 + batch: + timeout: 5s + send_batch_size: 1024 + +exporters: + debug: + verbosity: normal + +service: + pipelines: + traces: + receivers: [otlp] + processors: [memory_limiter, tail_sampling, batch] + exporters: [debug] +``` + +## Run the OpenTelemetry Collector in Docker + +We save that file as `collector.yaml` and start the collector next to it. +One command is enough to try it, and the Compose service is what stays in the project. + +```bash tab="docker run" +docker run --rm -p 4318:4318 \ + -v "$PWD/collector.yaml:/etc/otelcol-contrib/config.yaml:ro" \ + otel/opentelemetry-collector-contrib:0.153.0 +``` + +```yaml tab="Docker Compose" +services: + otel-collector: + image: otel/opentelemetry-collector-contrib:0.153.0 + volumes: + - ./collector.yaml:/etc/otelcol-contrib/config.yaml:ro + ports: + - "4318:4318" +``` + +With Compose we start it with `docker compose up -d` and read its output with `docker compose logs -f otel-collector`. +When PHP runs in a container of the same Compose file, the address in the script is `http://otel-collector:4318`, not `localhost`. + +We run the PHP script, and a few seconds later the collector prints what it kept: + +```text +ScopeTraces #0 http +GET /search 47edec50aa6189bc6b4488c644fb4d45 1684acc2fe006947 +ResourceTraces #1 service.name=shop +ScopeTraces #1 http +POST /checkout 3d76b1b2ae1695e7a0a900a179a678fc 04fd71faef9b77db error.type=RuntimeException +``` + +Four requests went in, two came out: the slow search and the failed checkout. + +`tail_sampling` waits five seconds for all spans of a trace and then asks its three policies. A trace with an error stays. A trace longer than 300ms stays. From the rest, one in ten stays, so we still see what a normal request looks like. +In this run both fast requests were dropped. In another run one of them can stay. + +PHP couldn't make this choice. When `GET /search` started, nobody knew it would be slow. + +## What else moves to the collector + +- **Batching and compression.** `batch` collects the spans of all PHP processes for five seconds and sends them in one request. +- **Retries.** The exporter of the collector keeps the data in a queue and tries again when the service is back. With a queue on disk it also survives a restart. +- **The address and the token.** To send the data to a real service, replace `debug` with an `otlp_http` exporter. PHP doesn't change and doesn't restart. +- **Protection.** `memory_limiter` makes the collector refuse data before it runs out of memory, so a flood of spans doesn't take the server down. + +## No network at all: write to a file + +There is one step lighter. PHP appends the spans to a file, and the collector reads the file. + +```php ignore +use function Flow\Bridge\Telemetry\OTLP\DSL\{otlp_exporter, otlp_stream_transport}; + +$exporter = otlp_exporter(otlp_stream_transport('/var/otel/traces.jsonl')); +``` + +Every batch is one line of JSON in the OTLP format. The collector picks it up with the `otlpjsonfile` receiver: + +```yaml +receivers: + otlpjsonfile: + include: + - /var/otel/*.jsonl +``` + +Now a collector that is down costs PHP nothing, and it reads what it missed when it starts again. +It needs no curl extension either. Somebody has to rotate the file. + +## When to sample in PHP + +Tail sampling sees everything, so PHP sends everything. On a very busy application that is a lot of spans, even to `localhost`. +Then PHP can drop a part of the traces at the start, and the collector chooses among the rest: + +```php ignore +use function Flow\Telemetry\DSL\trace_id_ratio_based_sampler; + +tracer_provider( + batching_span_processor($exporter), + clock(), + memory_context_storage(), + sampler: trace_id_ratio_based_sampler(0.25), +); +``` + +One trace in four leaves PHP. The price is that three of four slow requests and errors are gone before the collector can see them. Start without it. + +## Where to go from here + +The spans themselves are in the guide about [tracing in PHP](/guides/trace-php-script-with-opentelemetry). +The ports, the timeouts and gRPC are in [send PHP traces over OTLP](/guides/send-php-traces-over-otlp). +The same collector can show only the slow tests of a suite: see [find slow PHPUnit tests](/guides/find-slow-phpunit-tests). diff --git a/web/landing/content/guides/parse-sql-query-in-php.md b/web/landing/content/guides/parse-sql-query-in-php.md index a53c00ee51..6a10efecc6 100644 --- a/web/landing/content/guides/parse-sql-query-in-php.md +++ b/web/landing/content/guides/parse-sql-query-in-php.md @@ -1,7 +1,9 @@ --- seo_title: Parse a SQL query in PHP with the PostgreSQL parser -seo_description: 'A regex finds seven tables in a query that reads four. Parse SQL in PHP with libpg_query, the parser of PostgreSQL: list the tables, allow only one SELECT, add LIMIT and count.' +seo_description: 'A regex finds seven tables in a query that reads four. Parse SQL in PHP with libpg_query, the parser of PostgreSQL: list the tables, allow only one SELECT, add LIMIT and OFFSET.' group: SQL +actions: [Parse] +tags: [SQL, PostgreSQL] problem: 'A regex finds tables that are not there' proof_label: 'Tables found in one query' proof_before: '7, 3 wrong' @@ -10,12 +12,12 @@ published: '2026-11-30' updated: '2026-11-30' --- -# Parse a SQL query in PHP +# Parse a SQL query in PHP with the PostgreSQL parser Let's say our application has a report builder. Analysts save their own SQL, and we run it on a PostgreSQL replica. Before we run a query, we want to know which tables it reads, and that it's one `SELECT` and nothing else. -> These scripts need the `pg_query` extension, so they run only on your machine, not in the playground. +> The parser reads the PostgreSQL dialect. The scripts need the `pg_query` extension, so they run only on your machine, not in the playground. ## The query @@ -184,7 +186,7 @@ echo sql_format(sql_to_paginated_query($sql, limit: 25, offset: 50)), "\n\n"; echo sql_format(sql_to_count_query($sql)), "\n"; ``` -```text +```sql SELECT c.email, sum(o.amount) AS revenue FROM customers c @@ -209,47 +211,6 @@ FROM [`sql_to_count_query`](/documentation/dsl/pg_query/sql-to-count-query) wraps the query and drops the `ORDER BY`, because the order doesn't change the count. [`sql_format`](/documentation/dsl/pg_query/sql-format) is there only to make the output readable. -## Group the same queries from a log - -The replica gets slow, and the log has thousands of queries that differ only by an id. - -```php ignore - $group) { - printf("%s %d calls %s\n", $fingerprint, $group['calls'], $group['query']); -} -``` - -```text -0500a4d40cb83d75 3 calls SELECT * FROM orders WHERE customer_id = $1 AND status = $2 -00b9f719a46da6e3 1 calls SELECT * FROM customers WHERE id = $1 -``` - -[`sql_fingerprint`](/documentation/dsl/pg_query/sql-fingerprint) gives the same value to queries with the same shape. The values, the letter case and the line breaks don't count. -[`sql_normalize`](/documentation/dsl/pg_query/sql-normalize) replaces the values with `$1` and `$2`, so we can print one query for the whole group. - ## Parse MySQL queries in PHP The parser comes from PostgreSQL, so it reads the PostgreSQL dialect. @@ -263,16 +224,9 @@ For a MySQL application this guide ends here. A parser of one database can't che ## How fast is a SQL parser in PHP -PHP 8.3 with the `protobuf` extension, the report from the beginning, ten thousand times: +PHP 8.3 with the `protobuf` extension: `sql_parse` and `sql_query_tables` on the report from the beginning, ten thousand times, take 2.4s. -| Code | Time | -|------------------------------------|--------| -| The regex | 0.007s | -| `sql_parse` and `sql_query_tables` | 2.4s | -| `sql_fingerprint` | 0.2s | - -The regex is much faster, and it's wrong. -One parse with the list of tables takes a quarter of a millisecond. +One parse with the list of tables takes a quarter of a millisecond, so a check before every report costs nothing we can notice. To check it on your machine, put the call in a loop: @@ -285,3 +239,8 @@ for ($i = 0; $i < 10_000; $i++) { printf("%.2fs\n", (hrtime(true) - $start) / 1e9); ``` + +## Where to go from here + +To see which queries an application runs, and how long they take, read [trace SQL queries in PHP](/guides/trace-sql-queries-in-php). +In a Symfony application, see [find slow Doctrine queries in Symfony](/guides/find-slow-doctrine-queries-in-symfony). diff --git a/web/landing/content/guides/php-logs-with-trace-id.md b/web/landing/content/guides/php-logs-with-trace-id.md new file mode 100644 index 0000000000..fd332eab87 --- /dev/null +++ b/web/landing/content/guides/php-logs-with-trace-id.md @@ -0,0 +1,195 @@ +--- +seo_title: PHP logs with a trace id - connect Monolog and OpenTelemetry +seo_description: 'Give every PHP log line the trace id of the work it belongs to: log through OpenTelemetry, or keep Monolog and add one handler.' +group: Observability +actions: [Observe] +tags: [OpenTelemetry] +problem: 'Which log lines belong to the request that failed?' +published: '2026-12-01' +updated: '2026-12-01' +examples: [telemetry/logger, telemetry/combined] +--- + +# PHP logs with a trace id: connect Monolog and OpenTelemetry + +Let's say our nightly import writes a log line for every order it loads, and one line when something goes wrong. +In the morning we find an error in the log, and we want every other line of the same order. + +Doesn't look like a complicated task, right? + +## Log lines without a trace id + +The first idea is always to put the order id into every line. + +```php + 'nightly-import']), + tracer_provider(pass_through_span_processor($exporter), clock(), $context), + loggerProvider: logger_provider(pass_through_log_processor($exporter), clock(), $context), +); + +$tracer = $telemetry->tracer('import'); +$logger = $telemetry->logger('import'); + +foreach ([1001, 1002] as $orderId) { + $tracer->trace('import-order', static function () use ($logger, $orderId): void { + $logger->info('order loaded', ['order.id' => $orderId]); + + if ($orderId === 1002) { + $logger->error('payment missing', ['order.id' => $orderId]); + } + }); +} +``` + +The log lines of the output, without the frames around them: + +```text +| Timestamp | Level | Message | Trace | +| 2026-12-01 21:37:52.677542 | INFO | order loaded {order.id: 1001} | e726e4e1/41edf58d | +| 2026-12-01 21:37:52.677834 | INFO | order loaded {order.id: 1002} | 481163f1/17468f32 | +| 2026-12-01 21:37:52.677856 | ERROR | payment missing {order.id: 1002} | 481163f1/17468f32 | +``` + +The last column is new. It is the start of the trace id and of the span id, and we never passed either of them to the logger. +The error and the line before it have the same trace id, `481163f1`. The first order has another one. + +It works because the tracer and the logger share one `memory_context_storage()`. `trace` puts its span there, and the logger reads it when a line is written. Code deep inside the import gets the same id, with no argument for it. + +The script also prints the span of each order: + +```text +| SPAN: import-order +| Trace: 481163f1f459eb639ff7497d3809fe0f Span: 17468f32427553a0 +``` + +So the id in the log line leads to a trace, with the duration and the steps of exactly that run. + +## Keep Monolog and add the trace id + +> This script needs Monolog, so it runs only on your machine, not in the playground. + +Most applications already log through Monolog, and nobody wants to rewrite every log call. We don't have to: one more handler sends each Monolog record to the telemetry logger. + +```bash +composer require flow-php/monolog-telemetry-bridge monolog/monolog +``` + +```php ignore + 'nightly-import']), + tracer_provider(void_span_processor(), clock(), $context), + loggerProvider: logger_provider(pass_through_log_processor(console_exporter(colors: false)), clock(), $context), +); + +$logger = new Logger('import', [ + new StreamHandler('php://stderr'), + telemetry_handler($telemetry->logger('import')), +]); + +$telemetry->tracer('import')->trace('import-order', static function () use ($logger): void { + $logger->error('payment missing', ['order_id' => 1002]); +}); +``` + +```text +[2026-12-01T21:38:03.769914+00:00] import.ERROR: payment missing {"order_id":1002} [] + +| Level | Message | Trace | +| ERROR | payment missing {monolog.channel: import, monolog.level_name: Error, context.order_id: 1002} | b69e7a69/a312a9bc | +``` + +The first line is Monolog as before, written by the old handler. The second one is the same record on the telemetry side, with the trace id, the channel and the context of Monolog as attributes. +The log calls of the application didn't change. + +## Where to go from here + +The console is for our machine. On a server the records go over OTLP to a collector, next to the spans, and a monitoring tool shows the lines of one trace under its timeline. +Only the exporter changes: see [send PHP traces over OTLP](/guides/send-php-traces-over-otlp). + +The guide about [tracing in PHP](/guides/trace-php-script-with-opentelemetry) shows where the trace id comes from. +When a request goes through more than one service, [distributed tracing](/guides/distributed-tracing-in-php) keeps one id for all of them, and so for all of their log lines. +In a Symfony application the bundle does the wiring: see [add a trace id to Symfony logs](/guides/symfony-logs-with-trace-id). diff --git a/web/landing/content/guides/php-metrics-with-opentelemetry.md b/web/landing/content/guides/php-metrics-with-opentelemetry.md new file mode 100644 index 0000000000..8c4b1a4bbe --- /dev/null +++ b/web/landing/content/guides/php-metrics-with-opentelemetry.md @@ -0,0 +1,193 @@ +--- +seo_title: PHP metrics with OpenTelemetry - counters, histograms and cardinality +seo_description: 'Count things in PHP with OpenTelemetry metrics: counters, histograms, gauges, and what happens when an attribute has too many values. With code that runs.' +group: Observability +actions: [Observe] +tags: [OpenTelemetry] +problem: 'A log line per order is not a number' +proof_label: 'Series for 500 order ids, limit 3' +proof_before: '500' +proof_after: '4' +published: '2026-12-01' +updated: '2026-12-01' +examples: [telemetry/meter, telemetry/combined] +--- + +# PHP metrics with OpenTelemetry: counters, histograms and cardinality + +Let's say the nightly import of orders works, and now somebody asks two questions. +How many orders did we import per country last night? And how long does it take to save one? + +Doesn't look like a complicated task, right? + +## Count things in PHP with a log line + +The first idea is always a log line for every order. + +```php + [12, 18, 15], 'US' => [22, 140], 'DE' => [9]] as $country => $timings) { + foreach ($timings as $milliseconds) { + echo "order saved country={$country} duration={$milliseconds}ms\n"; + } +} +``` + +```text output +order saved country=PL duration=12ms +order saved country=PL duration=18ms +order saved country=PL duration=15ms +order saved country=US duration=22ms +order saved country=US duration=140ms +order saved country=DE duration=9ms +``` + +It works, and the answer to both questions is in there somewhere. + +## Why log lines are not metrics + +To get "three orders from Poland" we have to read every line and count. With six orders that's fine. With a million orders a night it's a million lines that somebody stores, parses and pays for, only to get a few numbers. + +A metric is the number itself. The script adds to it while it runs, and at the end it sends one value per country, not one line per order. +OpenTelemetry has four kinds of them: + +| Instrument | What it holds | Example | +|-----------------|---------------------------------------|----------------------------| +| Counter | A number that only grows | Orders imported | +| Up-down counter | A number that grows and shrinks | Messages in a queue | +| Gauge | The value right now | Memory in use | +| Histogram | How many values fell into each range | Time to save one order | + +## Count and time things with OpenTelemetry metrics + +flow-php/telemetry is an independent implementation of OpenTelemetry, written in PHP. It needs PHP 8.3 or newer, no extension, and it is [not a wrapper around the official SDK](/documentation/components/libs/telemetry/opentelemetry-sdk). + +```bash +composer require flow-php/telemetry flow-php/etl +``` + +```php + 'nightly-import']), + meterProvider: meter_provider(memory_metric_processor(console_exporter(colors: false)), clock()), +); + +$meter = $telemetry->meter('import'); + +$processed = $meter->createCounter('orders.processed', 'orders', 'Orders saved by the import'); +$duration = $meter->createHistogram('orders.save.duration', 'ms', 'Time to save one order'); + +foreach (['PL' => [12, 18, 15], 'US' => [22, 140], 'DE' => [9]] as $country => $timings) { + foreach ($timings as $milliseconds) { + $processed->add(1, ['country' => $country]); + $duration->record($milliseconds, ['country' => $country]); + } +} + +$telemetry->flush(); +``` + +The output, with the long histogram lines cut: + +```text +| ^ orders.processed 3 [orders] // Orders saved by the import {country=PL} +| ^ orders.processed 2 [orders] // Orders saved by the import {country=US} +| ^ orders.processed 1 [orders] // Orders saved by the import {country=DE} +| # orders.save.duration 45.00 [ms] // Time to save one order {country=PL, histogram.count=3, histogram.sum=45, histogram.min=12, histogram.max=18, ... +| # orders.save.duration 162.00 [ms] // Time to save one order {country=US, histogram.count=2, histogram.sum=162, histogram.min=22, histogram.max=140, ... +| # orders.save.duration 9.00 [ms] // Time to save one order {country=DE, histogram.count=1, histogram.sum=9, histogram.min=9, histogram.max=9, ... +``` + +Six orders became six numbers, and a million orders would become the same six. + +The counter answers the first question: three, two and one. +The histogram answers the second one. For every country it keeps the count, the sum, the smallest and the biggest value, and how many values fell into each range. A slow save of 140ms in the US is visible as `max=140`, and an average would hide it. + +`flush` sends what the script collected. [`console_exporter`](/documentation/dsl/telemetry/console-exporter) prints it, and it's the only line that changes when the numbers go to a real tool. + +## Why a metric with an id in it explodes + +Every different set of attributes is its own number. Three countries are three numbers. That's the whole idea, and it's also the trap. + +Let's say we add the order id, to find a single order later. + +```php + 'nightly-import']), + meterProvider: meter_provider( + memory_metric_processor(console_exporter(colors: false)), + clock(), + limits: metric_limits(cardinalityLimit: 3), + ), +); + +$processed = $telemetry->meter('import')->createCounter('orders.processed', 'orders'); + +for ($orderId = 1; $orderId <= 500; $orderId++) { + $processed->add(1, ['order.id' => $orderId]); +} + +$telemetry->flush(); +``` + +```text output ++-------------------------------------------------------------+ +| METRICS | ++-------------------------------------------------------------+ +| Resource: | +| service.name = nightly-import | +| Scope: import unknown | ++-------------------------------------------------------------+ +| ^ orders.processed 1 [orders] {order.id=1} | +| ^ orders.processed 1 [orders] {order.id=2} | +| ^ orders.processed 1 [orders] {order.id=3} | +| ^ orders.processed 497 [orders] {otel.metric.overflow=1} | ++-------------------------------------------------------------+ +``` + +Five hundred ids would be five hundred numbers, each of them `1`. That's the log line again, only more expensive: a monitoring tool stores every one of them as its own series. + +The number of different attribute sets of one metric is its cardinality. +[`metric_limits`](/documentation/dsl/telemetry/metric-limits) sets how many one instrument can have. We set three to see it happen, and the default is 2000. +Past the limit nothing is lost: the other 497 orders are counted in one number with `otel.metric.overflow`. The total is still 500. + +## Which attributes to put on a metric + +- Values from a short, fixed list: a country, a status, a queue name, an HTTP method. +- Never an id, an email, a full URL or a timestamp. Those belong to a span or a log line. +- If a metric shows `otel.metric.overflow`, it has an attribute with too many values. Remove the attribute, don't raise the limit. + +## Where to go from here + +The console is for our machine. On a server the same numbers go to a collector or a monitoring tool over OTLP, the protocol of OpenTelemetry. +Only the exporter changes, and it comes from [flow-php/telemetry-otlp-bridge](/documentation/components/bridges/telemetry-otlp-bridge). + +The guide about [tracing in PHP](/guides/trace-php-script-with-opentelemetry) shows the other half: where the time of one run goes. diff --git a/web/landing/content/guides/read-and-write-parquet-files-in-php.md b/web/landing/content/guides/read-and-write-parquet-files-in-php.md index 5e15af979c..ac31c7cd4a 100644 --- a/web/landing/content/guides/read-and-write-parquet-files-in-php.md +++ b/web/landing/content/guides/read-and-write-parquet-files-in-php.md @@ -2,12 +2,15 @@ seo_title: Read and write Parquet files in PHP seo_description: 'Write a Parquet file in PHP: a million orders take 2.2Mb, not 62Mb as CSV. Read two columns of it and find three orders out of a million in 0.03s. With code that runs.' group: Writing files +actions: [Read, Write] +tags: [Parquet] problem: 'A CSV file stores every value as text' proof_label: 'A million orders on disk' proof_before: '62Mb' proof_after: '2.2Mb' published: '2026-11-30' updated: '2026-11-30' +examples: [reading/parquet, writing/parquet, aggregations/group_by/group_by_sum, transformations/sort] --- # Read and write Parquet files in PHP @@ -371,15 +374,13 @@ PHP 8.3, `memory_limit=128M`, a million orders, the 2.2Mb Parquet file from abov |---------------------|---------------------------------------------|-------------|-------| | Write the file | flow-php/parquet | 18Mb | 9.5s | | Write the file | flow-php/parquet with the `arrow` extension | 12Mb | 2.3s | -| Revenue per country | `fgetcsv` loop over the CSV file | 2Mb | 1.2s | | Revenue per country | flow-php/parquet | 6Mb | 1.8s | | Revenue per country | flow-php/parquet with the `arrow` extension | 6Mb | 0.3s | | Last three orders | `fgetcsv` loop over the CSV file | 2Mb | 1.1s | | Last three orders | flow-php/parquet | 6Mb | 0.03s | | Last three orders | flow-php/parquet with the `arrow` extension | 6Mb | 0.02s | -A plain `fgetcsv` loop reads the whole CSV file faster than PHP reads two columns of the Parquet file. -When we don't need the whole file, Parquet wins. +To find three orders, the `fgetcsv` loop reads a million rows. The Parquet reader skips almost all of them, and it's 36 times faster. [arrow](/documentation/components/extensions/arrow-ext) is an optional PHP extension. The scripts stay the same, without a single change. @@ -388,3 +389,8 @@ To check it on your machine, add this line at the end of any of the scripts abov ```php ignore printf("peak memory: %.1f MB\n", memory_get_peak_usage(true) / 1024 / 1024); ``` + +## Where to go from here + +The row format that Parquet replaces is in [read a large CSV file in PHP](/guides/read-large-csv-file-in-php). +Parquet files often live in a bucket: see [read a large file from S3](/guides/read-large-file-from-s3-in-php). diff --git a/web/landing/content/guides/read-large-csv-file-in-php.md b/web/landing/content/guides/read-large-csv-file-in-php.md index 454b1e7bea..781cbf492b 100644 --- a/web/landing/content/guides/read-large-csv-file-in-php.md +++ b/web/landing/content/guides/read-large-csv-file-in-php.md @@ -1,13 +1,16 @@ --- seo_title: Read a large CSV file in PHP without running out of memory -seo_description: 'A CSV file bigger than the memory limit ends with "Allowed memory size exhausted". Why file() fails, how fgetcsv fixes it and what Flow adds, with code that runs.' +seo_description: 'A CSV file bigger than the memory limit ends with "Allowed memory size exhausted". Why file() and usort() fail, and how Flow reads and sorts it.' group: Reading files +actions: [Read] +tags: [CSV] problem: 'file() and usort() run out of memory' proof_label: 'Sorting a million rows' proof_before: '624Mb' proof_after: '98Mb' published: '2026-11-18' updated: '2026-11-18' +examples: [reading/csv, aggregations/group_by/group_by_sum, transformations/sort, writing/csv, reading/corrupted_records_routing] --- # Read a large CSV file in PHP without running out of memory @@ -97,39 +100,8 @@ We could raise `memory_limit`, but that only moves the problem to the next, bigg ## Read the CSV file line by line with fgetcsv -`fgetcsv` reads one row at a time, so it doesn't matter how big the file is. - -```php - $total) { - printf("%s %.2f\n", $country, $total); -} -``` - -```text output -GB 10030.00 -FR 10010.00 -DE 9990.00 -US 9970.00 -PL 9950.00 -``` - -That's 2Mb of memory for a million rows. Reading a big file was never the hard part. +`fgetcsv` reads one row at a time, so a sum for each country fits in a short loop and a few megabytes of memory. +Reading a big file was never the hard part. ## Now sort it @@ -271,7 +243,6 @@ PHP 8.3, `memory_limit=128M`, a million rows, 62Mb: | Task | Code | Peak memory | Time | |---------------------|-------------------------------------|--------------------------|------| | Revenue per country | `file()` | fatal error, needs 172Mb | - | -| Revenue per country | `fgetcsv` loop | 2Mb | 1.6s | | Revenue per country | Flow | 44Mb | 4.9s | | Revenue per country | Flow with the `flow_php` extension | 16Mb | 0.6s | | Sort by amount | `fgetcsv` and `usort` | fatal error, needs 624Mb | - | @@ -287,3 +258,9 @@ To check it on your machine, add this line at the end of any of the scripts abov ```php ignore printf("peak memory: %.1f MB\n", memory_get_peak_usage(true) / 1024 / 1024); ``` + +## Where to go from here + +To put the rows into a database, read [import a CSV file into MySQL or PostgreSQL](/guides/import-csv-file-into-mysql-or-postgresql-in-php). +The same problem with other formats is in [read a large JSON file](/guides/read-large-json-file-in-php) and [read and write Parquet files](/guides/read-and-write-parquet-files-in-php). +When the file is not on the local disk, see [read a large file from S3](/guides/read-large-file-from-s3-in-php). diff --git a/web/landing/content/guides/read-large-file-from-s3-in-php.md b/web/landing/content/guides/read-large-file-from-s3-in-php.md new file mode 100644 index 0000000000..dac57d69a8 --- /dev/null +++ b/web/landing/content/guides/read-large-file-from-s3-in-php.md @@ -0,0 +1,359 @@ +--- +seo_title: Read a large file from S3 in PHP without running out of memory +seo_description: 'getObject() needs 1052Mb to read a 1Gb file from S3. Read it line by line in PHP with 10Mb. Read a part of it, list files by pattern, copy them to SFTP or Azure.' +group: Reading files +actions: [Read] +tags: [S3, Azure, SFTP] +problem: 'getObject() loads the whole file into memory' +proof_label: 'Reading a 1Gb file from S3' +proof_before: '1052Mb' +proof_after: '10Mb' +published: '2026-12-01' +updated: '2026-12-01' +examples: [filesystem/s3, filesystem/azure, filesystem/local] +--- + +# Read a large file from S3 in PHP without running out of memory + +Let's say a nightly job puts all our orders into an S3 bucket: one CSV file, 16 million rows, about 1Gb. +We need the revenue per country, and our PHP process runs with the default `memory_limit` of 128Mb. + +Doesn't look like a complicated task, right? + +> These scripts need a bucket, so they run only on your machine, not in the playground. + +## The file + +We need `exports/orders.csv` in a bucket named `orders-exports`. +The guide about [uploading a large file to S3](/guides/upload-large-file-to-s3-in-php) has the script that generates the file and the one that sends it to the bucket. + +## Read a file from S3 with getObject + +The first answer we find is `getObject` from the AWS SDK for PHP. + +```php ignore + 'latest', 'region' => 'eu-west-1']); + +$body = (string) $client->getObject(['Bucket' => 'orders-exports', 'Key' => 'exports/orders.csv'])['Body']; +$revenue = []; + +foreach (explode("\n", trim($body)) as $number => $line) { + if ($number === 0) { + continue; + } + + $row = str_getcsv($line, escape: ''); + $revenue[$row[2]] = ($revenue[$row[2]] ?? 0.0) + (float) $row[3]; +} + +arsort($revenue); + +foreach ($revenue as $country => $total) { + printf("%s %.2f\n", $country, $total); +} +``` + +```text +GB 10030.00 +FR 10010.00 +DE 9990.00 +US 9970.00 +PL 9950.00 +``` + +With a thousand rows it works. With a 100Mb file it still works, with 122Mb of memory, 6Mb below the limit. +With the 1Gb file it ends like this: + +```text +Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 1080197120 bytes) +``` + +## Why getObject runs out of memory + +`getObject` downloads the file in one request, and `(string)` turns the whole answer into one string. +For our file that is 1052Mb before we read the first line, and we have 128Mb. + +The script that passed every test with a small file fails on the first big export. +We could raise `memory_limit`, but that only moves the problem to the next, bigger file. + +## Read a large file from S3 line by line + +Flow reads the file in pieces and hands us one line at a time. It needs PHP 8.3 or newer. +Its S3 filesystem uses [AsyncAws](https://async-aws.com/), so the AWS SDK is not needed. +The same code works with Azure Blob Storage and with an SFTP server, so every example has a tab for each of them. + +```bash tab="S3" +composer require flow-php/filesystem flow-php/filesystem-async-aws-bridge +``` + +```bash tab="Azure Blob Storage" +composer require flow-php/filesystem flow-php/filesystem-azure-bridge nyholm/psr7 +``` + +```bash tab="SFTP" +composer require flow-php/filesystem flow-php/filesystem-sftp-bridge +``` + +And this is the whole report: + +```php ignore tab="S3" + 'eu-west-1', + 'accessKeyId' => $_ENV['AWS_S3_KEY'], + 'accessKeySecret' => $_ENV['AWS_S3_SECRET'], +]); + +$revenue = []; + +foreach ($storage->readFrom(path('aws-s3://exports/orders.csv'))->readLines() as $number => $line) { + if ($number === 0) { + continue; + } + + $row = str_getcsv($line, escape: ''); + $revenue[$row[2]] = ($revenue[$row[2]] ?? 0.0) + (float) $row[3]; +} + +arsort($revenue); + +foreach ($revenue as $country => $total) { + printf("%s %.2f\n", $country, $total); +} +``` + +```php ignore tab="Azure Blob Storage" + $_ENV['AZURE_ACCOUNT'], + 'container' => 'orders-exports', + 'shared_key' => $_ENV['AZURE_SHARED_KEY'], +]); + +$revenue = []; + +foreach ($storage->readFrom(path('azure-blob://exports/orders.csv'))->readLines() as $number => $line) { + if ($number === 0) { + continue; + } + + $row = str_getcsv($line, escape: ''); + $revenue[$row[2]] = ($revenue[$row[2]] ?? 0.0) + (float) $row[3]; +} + +arsort($revenue); + +foreach ($revenue as $country => $total) { + printf("%s %.2f\n", $country, $total); +} +``` + +```php ignore tab="SFTP" + $_ENV['SFTP_HOST'], + 'user' => $_ENV['SFTP_USER'], + 'password' => $_ENV['SFTP_PASSWORD'], +]); + +$revenue = []; + +foreach ($storage->readFrom(path('sftp://upload/exports/orders.csv'))->readLines() as $number => $line) { + if ($number === 0) { + continue; + } + + $row = str_getcsv($line, escape: ''); + $revenue[$row[2]] = ($revenue[$row[2]] ?? 0.0) + (float) $row[3]; +} + +arsort($revenue); + +foreach ($revenue as $country => $total) { + printf("%s %.2f\n", $country, $total); +} +``` + +```text +GB 10030.00 +FR 10010.00 +DE 9990.00 +US 9970.00 +PL 9950.00 +``` + +That's 10Mb of memory for 16 million lines on S3, and it doesn't grow with the file. +`readFrom` asks S3 for the file in ranges of 9Mb, and `readLines` cuts every range into lines while it arrives. + +## Read a part of an S3 file + +Sometimes we don't need the whole file. To check that the export is complete, the last rows are enough. +`$storage` is the filesystem from the script above. + +```php ignore tab="S3" +$stream = $storage->readFrom(path('aws-s3://exports/orders.csv')); + +echo $stream->read(200, $stream->size() - 200); +``` + +```php ignore tab="Azure Blob Storage" +$stream = $storage->readFrom(path('azure-blob://exports/orders.csv')); + +echo $stream->read(200, $stream->size() - 200); +``` + +```php ignore tab="SFTP" +$stream = $storage->readFrom(path('sftp://upload/exports/orders.csv')); + +echo $stream->read(200, $stream->size() - 200); +``` + +```text +"2023-11-15 14:50:20" +998,customer998@example.com,FR,99.80,"2023-11-15 14:51:20" +999,customer999@example.com,GB,99.90,"2023-11-15 14:52:20" +1000,customer1000@example.com,PL,0.00,"2023-11-15 14:53:20" +``` + +`read` takes the length first, then the offset. The storage sends only these 200 bytes, the rest of the file stays where it is. +Reading 1Mb from the middle of the 1Gb file takes two requests and 0.02s. + +## List files in an S3 bucket by pattern + +After a few nights there is more than one export in the bucket. `list` takes a pattern: `*` matches inside one folder, `**` goes through all of them. + +```php ignore tab="S3" +foreach ($storage->list(path('aws-s3://exports/**/*.csv')) as $file) { + echo $file->path->uri(), ' ', $file->size, "\n"; +} +``` + +```php ignore tab="Azure Blob Storage" +foreach ($storage->list(path('azure-blob://exports/**/*.csv')) as $file) { + echo $file->path->uri(), ' ', $file->size, "\n"; +} +``` + +```php ignore tab="SFTP" +foreach ($storage->list(path('sftp://upload/exports/**/*.csv')) as $file) { + echo $file->path->uri(), ' ', $file->size, "\n"; +} +``` + +Every file comes back with its full path and its size: + +```text tab="S3" +aws-s3://exports/orders-generated.csv 56721 +aws-s3://exports/orders.csv 58721 +``` + +```text tab="Azure Blob Storage" +azure-blob://exports/orders-generated.csv 56721 +azure-blob://exports/orders.csv 58721 +``` + +```text tab="SFTP" +sftp://upload/exports/orders-generated.csv 56721 +sftp://upload/exports/orders.csv 58721 +``` + +## Copy a file from S3 to SFTP, Azure or the disk + +One day a partner wants the same export on their SFTP server, and the data team wants it in Azure. +For Flow all of them are filesystems, and `file_copy` moves a file between any two of them. + +```php ignore + 'eu-west-1', + 'accessKeyId' => $_ENV['AWS_S3_KEY'], + 'accessKeySecret' => $_ENV['AWS_S3_SECRET'], + ]), + azure_filesystem([ + 'account_name' => $_ENV['AZURE_ACCOUNT'], + 'container' => 'orders-exports', + 'shared_key' => $_ENV['AZURE_SHARED_KEY'], + ]), + sftp_filesystem([ + 'host' => $_ENV['SFTP_HOST'], + 'user' => $_ENV['SFTP_USER'], + 'password' => $_ENV['SFTP_PASSWORD'], + ]), +); + +$export = path('aws-s3://exports/orders.csv'); + +file_copy($files)->execute($export, path('sftp://upload/exports/orders.csv')); +file_copy($files)->execute($export, path('azure-blob://exports/orders.csv')); +file_copy($files)->execute($export, path(__DIR__ . '/orders-copy.csv')); +``` + +[`fstab`](/documentation/components/libs/filesystem) keeps the filesystems, and the scheme of a path picks the one to use. +The file goes from S3 to the other side in pieces of 8Mb. There is no copy of it in memory. + +All the options of each filesystem are in the documentation of the [S3](/documentation/components/bridges/filesystem-async-aws-bridge), [Azure](/documentation/components/bridges/filesystem-azure-bridge) and [SFTP](/documentation/components/bridges/filesystem-sftp-bridge) bridges. + +## How much memory does reading a file from S3 take in PHP + +PHP 8.3, `memory_limit=128M`, a 1Gb file with 16 million rows, aws/aws-sdk-php 3.409. Each number is one run. +The S3 server runs on the same machine, so the times have no network in them. + +| Task | Code | Peak memory | Time | +|---------------------|-------------------------|---------------------------|-------| +| Revenue per country | `getObject` as a string | fatal error, needs 1052Mb | - | +| Revenue per country | Flow `readLines` | 10Mb | 3.5s | +| 1Mb from the middle | Flow `read` | 10Mb | 0.02s | +| Copy to the disk | Flow `file_copy` | 32Mb | 2.7s | + +The numbers that matter are the ones that don't change. With a 100Mb file `readLines` takes 12Mb. +Only `getObject` grows with the file: 122Mb for 100Mb, 1052Mb for 1Gb. + +To check it on your machine, add this line at the end of any of the scripts above: + +```php ignore +printf("peak memory: %.1f MB\n", memory_get_peak_usage(true) / 1024 / 1024); +``` diff --git a/web/landing/content/guides/read-large-json-file-in-php.md b/web/landing/content/guides/read-large-json-file-in-php.md index 68d35d56d5..db4a316437 100644 --- a/web/landing/content/guides/read-large-json-file-in-php.md +++ b/web/landing/content/guides/read-large-json-file-in-php.md @@ -2,12 +2,15 @@ seo_title: Read a large JSON file in PHP without running out of memory seo_description: 'json_decode needs the whole file in memory, so a big JSON file ends with "Allowed memory size exhausted". Why it happens, and how to read a 110Mb JSON file in PHP with 22Mb.' group: Reading files +actions: [Read] +tags: [JSON] problem: 'json_decode() needs 778Mb for a 110Mb file' proof_label: 'Reading a 110Mb file' proof_before: '778Mb' proof_after: '22Mb' published: '2026-11-18' updated: '2026-11-18' +examples: [reading/json, aggregations/group_by/group_by_sum, transformations/sort] --- # Read a large JSON file in PHP without running out of memory @@ -160,3 +163,8 @@ To check it on your machine, add this line at the end of any of the scripts abov ```php ignore printf("peak memory: %.1f MB\n", memory_get_peak_usage(true) / 1024 / 1024); ``` + +## Where to go from here + +The same problem with CSV is in [read a large CSV file in PHP](/guides/read-large-csv-file-in-php). +When the JSON comes from an API and not from a file, see [import data from a REST API](/guides/import-data-from-rest-api-in-php). diff --git a/web/landing/content/guides/send-php-traces-over-otlp.md b/web/landing/content/guides/send-php-traces-over-otlp.md new file mode 100644 index 0000000000..87f6af8da1 --- /dev/null +++ b/web/landing/content/guides/send-php-traces-over-otlp.md @@ -0,0 +1,147 @@ +--- +seo_title: Send PHP traces over OTLP - endpoint, ports 4317 and 4318, HTTP or gRPC +seo_description: 'Send traces from PHP to an OpenTelemetry collector over OTLP: which endpoint and port to use, HTTP or gRPC, timeouts, and what happens when the collector is down.' +group: Observability +actions: [Observe] +tags: [OpenTelemetry] +problem: 'Port 4317 or 4318, HTTP or gRPC?' +published: '2026-12-01' +updated: '2026-12-01' +--- + +# Send PHP traces over OTLP: endpoint, ports, HTTP or gRPC + +Let's say our nightly import already creates spans, and they are printed to the console. +Now we want them in a real tool, with a timeline, where we can look at last night's run. + +> These scripts need a collector, so they run only on your machine, not in the playground. + +## OTLP ports 4317 and 4318 + +OTLP is the protocol of OpenTelemetry. Every collector and every monitoring tool that supports OpenTelemetry accepts it, in two flavors: + +| Flavor | Default port | Address we give | In PHP it needs | +|-----------|--------------|----------------------------------------|--------------------| +| OTLP/HTTP | 4318 | `http://localhost:4318` | the curl extension | +| OTLP/gRPC | 4317 | `localhost:4317` | the grpc extension | + +Over HTTP every kind of data has its own path: `/v1/traces`, `/v1/metrics` and `/v1/logs`. We give only the address, and the transport adds the path. + +## Send traces from PHP over OTLP/HTTP + +flow-php/telemetry is an independent implementation of OpenTelemetry, written in PHP. It needs PHP 8.3 or newer and the curl extension, and it is [not a wrapper around the official SDK](/documentation/components/libs/telemetry/opentelemetry-sdk). + +```bash +composer require flow-php/telemetry flow-php/telemetry-otlp-bridge flow-php/etl +``` + +```php ignore +withTimeout(2000)->withConnectTimeout(500), +)); + +$telemetry = telemetry( + resource(['service.name' => 'nightly-import']), + tracer_provider(batching_span_processor($exporter), clock(), memory_context_storage()), +)->registerShutdownFunction(); + +$tracer = $telemetry->tracer('import'); + +$tracer->trace('import-orders', static function () use ($tracer): void { + $tracer->trace('download', static fn () => usleep(120_000)); + $tracer->trace('save', static fn () => usleep(250_000)); +}); + +echo "import finished\n"; +``` + +```text +import finished +``` + +The script prints nothing else, and the collector has one trace named `import-orders` with three spans, 0.38s long. + +Three lines do the work: + +- [`otlp_curl_transport`](/documentation/dsl/telemetry_otlp/otlp-curl-transport) sends the data as JSON. No protobuf package is needed. +- [`batching_span_processor`](/documentation/dsl/telemetry/batching-span-processor) keeps the spans and sends them together, 512 at a time. Three spans are one request, not three. +- `registerShutdownFunction` sends what is left when the script ends. Without it the last spans stay in memory and are lost. + +## The wrong OTLP port + +The mistake everybody makes once is the gRPC port with the HTTP transport. + +```php ignore +$exporter = otlp_exporter(otlp_curl_transport(endpoint: 'http://localhost:4317')); +``` + +```text +import finished +[flow-telemetry] Flow\Bridge\Telemetry\OTLP\Transport\TransportException: curl error 1 (Unsupported protocol) for http://localhost:4317/v1/traces; elapsed connect=0ms total=10ms (configured connect_timeout=500ms, timeout=2000ms) +``` + +`Unsupported protocol` on port 4317 means HTTP was sent to the gRPC port. Change the port to 4318. + +## What happens when the collector is down + +A monitoring tool must never break the thing it monitors. Let's stop the collector and run the import again. + +```text +import finished +[flow-telemetry] Flow\Bridge\Telemetry\OTLP\Transport\TransportException: curl error 7 (Could not connect to server) for http://localhost:4318/v1/traces; elapsed connect=0ms total=1ms (configured connect_timeout=500ms, timeout=2000ms) +``` + +The import finished. The spans of this run are lost, and the reason is in the PHP error log, with the address and the timeouts. + +The two timeouts are the most a failed export can cost: half a second to connect, two seconds for the whole request. They are in milliseconds. +With a collector on the same machine they can be much smaller. + +## Send traces to a monitoring service + +A hosted service gives us an address and a token. Both go into the transport: + +```php ignore +$exporter = otlp_exporter(otlp_curl_transport( + endpoint: 'https://otlp.example.com:4318', + options: otlp_curl_options() + ->withHeader('Authorization', 'Bearer ' . $_ENV['OTLP_TOKEN']) + ->withCompression(), +)); +``` + +## OTLP over HTTP or gRPC in PHP + +Use HTTP. It needs only the curl extension, which almost every PHP has, and JSON can be read with any tool when something goes wrong. + +gRPC needs the `grpc` extension, which has to be compiled or installed for every PHP version on every server. Take it when the collector accepts nothing else: + +```php ignore +use function Flow\Bridge\Telemetry\OTLP\DSL\otlp_grpc_transport; + +$exporter = otlp_exporter(otlp_grpc_transport(endpoint: 'localhost:4317')); +``` + +The rest of the script doesn't change. The gRPC address has no `http://` in front. + +## Where to go from here + +The spans themselves, with attributes and errors, are in the guide about [tracing in PHP](/guides/trace-php-script-with-opentelemetry). +Metrics go the same way, with `/v1/metrics` as the path: see [PHP metrics with OpenTelemetry](/guides/php-metrics-with-opentelemetry). +All the options of the transports are in the [OTLP bridge documentation](/documentation/components/bridges/telemetry-otlp-bridge). diff --git a/web/landing/content/guides/stream-large-csv-download-in-symfony.md b/web/landing/content/guides/stream-large-csv-download-in-symfony.md index 43d639af33..5f6b005c42 100644 --- a/web/landing/content/guides/stream-large-csv-download-in-symfony.md +++ b/web/landing/content/guides/stream-large-csv-download-in-symfony.md @@ -2,12 +2,15 @@ seo_title: 'Export a large CSV file in PHP: stream the download in Symfony' seo_description: 'A Symfony StreamedResponse still loads the whole query result and runs out of memory. How to stream a million rows as CSV, JSON, XML or Parquet in 20Mb.' group: Writing files +actions: [Export] +tags: [CSV, Symfony] problem: 'StreamedResponse still runs out of memory' proof_label: 'A million orders as a download' proof_before: '91Mb' proof_after: '20Mb' published: '2026-11-18' updated: '2026-11-20' +examples: [reading/dbal/key_set] --- # Stream a large CSV download in Symfony without running out of memory @@ -82,57 +85,7 @@ So the download works on our machine, works for the first year in production, an ## Then somebody asks for JSON or XML The next request is always the same: "can we get it as JSON?". -There is nothing to reuse from the CSV controller. Every format is its own code: - -```php ignore tab="JSON" -return new StreamedResponse(function (): void { - $orders = $this->database->executeQuery('SELECT id, email, country, amount, created_at FROM orders ORDER BY id'); - $first = true; - - echo '['; - - while ($order = $orders->fetchAssociative()) { - $order['amount'] = (float) $order['amount']; - - echo $first ? '' : ',', json_encode($order, JSON_THROW_ON_ERROR); - $first = false; - } - - echo ']'; -}, 200, [ - 'Content-Type' => 'application/json', - 'Content-Disposition' => 'attachment; filename="orders.json"', -]); -``` - -```php ignore tab="XML" -return new StreamedResponse(function (): void { - $orders = $this->database->executeQuery('SELECT id, email, country, amount, created_at FROM orders ORDER BY id'); - - $xml = new XMLWriter(); - $xml->openUri('php://output'); - $xml->startDocument('1.0', 'UTF-8'); - $xml->startElement('rows'); - - while ($order = $orders->fetchAssociative()) { - $xml->startElement('row'); - - foreach ($order as $column => $value) { - $xml->writeElement($column, (string) $value); - } - - $xml->endElement(); - $xml->flush(); - } - - $xml->endElement(); - $xml->endDocument(); - $xml->flush(); -}, 200, [ - 'Content-Type' => 'application/xml', - 'Content-Disposition' => 'attachment; filename="orders.xml"', -]); -``` +There is nothing to reuse from the CSV controller. Every format is its own code. For JSON we write the brackets and the commas ourselves, and we cast the amount, because the database gives it to us as a string. For XML we need `XMLWriter`, and we have to flush it after every order, or the whole document waits in memory. @@ -256,16 +209,21 @@ Now the JSON and the XML version. With Flow it's the last two lines of the contr PHP 8.3, `memory_limit=128M`, a million orders in MySQL. Every controller masks the emails and formats the dates, so they all send the same file: -| Format | `StreamedResponse` by hand | Flow | Flow with the `flow_php` extension | -|---------|----------------------------|-------------|------------------------------------| -| CSV | 91Mb, 3.2s | 20Mb, 5.8s | 18Mb, 3.5s | -| JSON | 91Mb, 4.1s | 20Mb, 5.9s | 18Mb, 3.5s | -| XML | 91Mb, 4.5s | 20Mb, 5.9s | 20Mb, 4.5s | -| Parquet | - | 42Mb, 8.6s | 20Mb, 3.5s | +| Format | Flow | Flow with the `flow_php` extension | +|---------|-------------|------------------------------------| +| CSV | 20Mb, 5.8s | 18Mb, 3.5s | +| JSON | 20Mb, 5.9s | 18Mb, 3.5s | +| XML | 20Mb, 5.9s | 20Mb, 4.5s | +| Parquet | 42Mb, 8.6s | 20Mb, 3.5s | -With the extension Flow is faster than the controller written by hand for JSON, as fast for XML, and close to it for CSV. Without it they are faster. +The controllers written by hand take 91Mb for every format, because they read the whole query result first. But they are three different pieces of code, and their memory grows with the table. The Flow controller is one piece of code with one line changed. With half of the orders or with all of them it never takes more than 20Mb. [flow_php](/documentation/components/extensions/flow-php-ext) is an optional PHP extension. The controller stays the same, without a single change. + +## Where to go from here + +For a real Excel file in place of CSV, read [export a database table to Excel](/guides/export-database-to-excel-in-php). +To see what the controller does in production, see [Symfony monitoring with OpenTelemetry](/guides/symfony-monitoring-with-opentelemetry). diff --git a/web/landing/content/guides/symfony-logs-with-trace-id.md b/web/landing/content/guides/symfony-logs-with-trace-id.md new file mode 100644 index 0000000000..06393d41af --- /dev/null +++ b/web/landing/content/guides/symfony-logs-with-trace-id.md @@ -0,0 +1,173 @@ +--- +seo_title: Add a trace id to Symfony logs with Monolog and OpenTelemetry +seo_description: 'Give every Monolog record of a Symfony application the trace id of its request, so each log line opens the trace that wrote it.' +group: Observability +actions: [Observe] +tags: [Symfony, OpenTelemetry] +problem: 'A warning in the log, and no way to open its request' +published: '2026-12-01' +updated: '2026-12-01' +--- + +# Add a trace id to Symfony logs with Monolog and OpenTelemetry + +Let's say our Symfony shop logs a warning when a query is slow. In the morning the log has forty of them. +We want to open one and see the whole request: the route, the other queries, the time each step took. + +> These steps need a Symfony application and a collector, so they run only on your machine, not in the playground. + +## Add a request id to Monolog by hand + +The first idea is always a Monolog processor that puts a random id on every record of one request. + +```php ignore +requestId = bin2hex(random_bytes(4)); + } + + public function __invoke(LogRecord $record): LogRecord + { + $record->extra['request_id'] = $this->requestId; + + return $record; + } +} +``` + +```text +[2026-12-01T21:43:36.280622+00:00] app.WARNING: slow query {"route":"prices","duration":279.918708} {"request_id":"fad06b4d"} +``` + +It works: all lines of one request have the same id, and we can search for it. + +## Why a request id is not enough + +The id connects log lines with other log lines, and with nothing else. + +- It doesn't lead to the timeline of the request, because the trace has another id. +- A worker that handles a message of this request makes its own id. +- The next service we call knows nothing about it. + +Tracing already has an id for one piece of work, and it travels to workers and to other services. The log lines only have to use that one. + +## Send Monolog records to OpenTelemetry + +flow-php/telemetry is an independent implementation of OpenTelemetry, written in PHP, and it is [not a wrapper around the official SDK](/documentation/components/libs/telemetry/opentelemetry-sdk). +The bundle needs PHP 8.3 or newer and Symfony 6.4, 7.4 or 8.0. The only PHP extension it needs is curl. + +```bash +composer require flow-php/symfony-telemetry-bundle flow-php/telemetry-otlp-bridge flow-php/monolog-telemetry-bridge +``` + +The guide about [Symfony monitoring with OpenTelemetry](/guides/symfony-monitoring-with-opentelemetry) shows the installation of the bundle step by step. For logs it gets a `logger_provider`: + +```yaml +# config/packages/flow_telemetry.yaml +flow_telemetry: + resource: + custom: + service.name: shop + + exporters: + collector: + otlp: + transport: + type: curl + endpoint: 'http://localhost:4318' + timeout_ms: 200 + connect_timeout_ms: 50 + + tracer_provider: + processor: + type: batching + exporter: collector + + logger_provider: + processor: + type: batching + exporter: collector + + instrumentation: + http_kernel: + enabled: true + dbal: + enabled: true +``` + +Monolog stays the logger of the application. We give it one more handler, which passes each record to the telemetry logger: + +```yaml +# config/services.yaml +services: + app.telemetry_logger: + class: Flow\Telemetry\Logger\Logger + factory: ['@Flow\Telemetry\Telemetry', 'logger'] + arguments: ['app'] + + Flow\Bridge\Monolog\Telemetry\TelemetryHandler: + arguments: ['@app.telemetry_logger'] +``` + +```yaml +# config/packages/monolog.yaml +monolog: + handlers: + telemetry: + type: service + id: Flow\Bridge\Monolog\Telemetry\TelemetryHandler + channels: ["app"] +``` + +We remove `RequestIdProcessor`. The controllers and services keep their `LoggerInterface`, and no log call changes. + +## One log line, one trace + +We open the slow page again. The log file has its line as before, and the collector gets the same record with two more fields: + +```text +LogRecord #0 +SeverityText: WARN +Body: Str(slow query) + -> monolog.channel: Str(app) + -> monolog.level_name: Str(Warning) + -> context.route: Str(prices) + -> context.duration: Double(260.913792) +Trace ID: f1a96ab0d6ac300d22f4fa6af33a71b8 +Span ID: b2ae0eb0620a5192 +``` + +`Trace ID` is the id of the request that wrote the line, and `Span ID` is the step that was running at that moment. +Nobody passed these ids to the logger. The handler found the span that was open when the line was written. + +In a monitoring tool we click the warning and land in the trace of its request, with the route, the SQL query of 260ms and everything around it. From the trace we see all its log lines under the timeline. + +The context of Monolog is kept: `route` and `duration` are attributes of the record, so we can filter on them. + +## Which Monolog channels to send + +`channels: ["app"]` sends the records of our own code. That is a good start, because the channels of the framework are loud. + +- To add a channel, put it into the list: `["app", "security"]`. +- To send only warnings and errors, give the handler a level, the same way as for every Monolog handler. +- The file handler stays as it is. When the collector is down, the lines are still in the file. + +## Where to go from here + +A message handled by a worker keeps the connection to its request: see [Symfony Messenger monitoring](/guides/symfony-messenger-monitoring). +The same idea without Symfony is in [PHP logs with a trace id](/guides/php-logs-with-trace-id). +All the options of the logger provider are in the [bundle documentation](/documentation/components/bridges/symfony-telemetry-bundle). diff --git a/web/landing/content/guides/symfony-messenger-monitoring.md b/web/landing/content/guides/symfony-messenger-monitoring.md new file mode 100644 index 0000000000..31dad3c829 --- /dev/null +++ b/web/landing/content/guides/symfony-messenger-monitoring.md @@ -0,0 +1,178 @@ +--- +seo_title: Symfony Messenger monitoring - connect the worker to the request +seo_description: 'Monitor Symfony Messenger with OpenTelemetry: a span for each message sent and handled, a link between the two, and metrics. No change in handlers.' +group: Observability +actions: [Observe] +tags: [Symfony, OpenTelemetry] +problem: 'The worker did something, and nobody knows for which request' +published: '2026-12-01' +updated: '2026-12-01' +--- + +# Symfony Messenger monitoring: connect the worker to the request + +Let's say our checkout answers the customer at once and sends the receipt later: the controller dispatches a message, and a worker handles it. +A customer says the receipt never came. We know the request, and we have to find what the worker did with it. + +> These steps need a Symfony application, a queue and a collector, so they run only on your machine, not in the playground. + +## Monitor a Messenger handler with a log line + +The first idea is always a log line at the end of the handler. + +```php ignore +logger->info('receipt sent', ['order' => $message->orderId]); + } +} +``` + +It works: every receipt leaves a line in the log of the worker, when the handler gets to its last line. + +## Why a log line in the handler is not enough + +- A message that was never handled writes nothing. The log can't tell "not handled yet" from "lost". +- The line doesn't say how long the handler took, or how long the message waited in the queue. +- The line is in the log of the worker, and the request is in the log of the web server. Nothing connects the two, so we search by order id and hope it is in both. +- Every new handler needs its own line, and somebody forgets it. + +We want Messenger itself to tell us, for every message: who sent it, when it was handled, and how that went. + +## Trace Symfony Messenger with OpenTelemetry + +flow-php/telemetry is an independent implementation of OpenTelemetry, written in PHP, and it is [not a wrapper around the official SDK](/documentation/components/libs/telemetry/opentelemetry-sdk). +The bundle needs PHP 8.3 or newer and Symfony 6.4, 7.4 or 8.0. The only PHP extension it needs is curl. + +```bash +composer require flow-php/symfony-telemetry-bundle flow-php/telemetry-otlp-bridge +``` + +The guide about [Symfony monitoring with OpenTelemetry](/guides/symfony-monitoring-with-opentelemetry) shows the installation step by step. For Messenger we turn on one more line: + +```yaml +# config/packages/flow_telemetry.yaml +flow_telemetry: + resource: + custom: + service.name: shop + + exporters: + collector: + otlp: + transport: + type: curl + endpoint: 'http://localhost:4318' + timeout_ms: 200 + connect_timeout_ms: 50 + + tracer_provider: + processor: + type: batching + exporter: collector + + meter_provider: + processor: + type: batching + exporter: collector + + instrumentation: + http_kernel: + enabled: true + messenger: + enabled: true +``` + +The controller and the handler stay as they are. The bundle adds itself to every message bus. + +## What the request sends + +We post one checkout. The collector gets the trace of the request, here with only the names and ids: + +```text +Trace ID 07ced0cc1a3584be11025543741da7a1 + +POST /checkout Kind: Server ID: ec125274fdb858b4 + App\Controller\CheckoutController::__invoke Kind: Internal ID: eef20d1f4829042b + send async Kind: Producer ID: 4a6bd57021797cb1 + flow.messenger.message.class = App\Message\SendReceipt + messaging.destination.name = async + messaging.message.id = 1 +``` + +`send async` is new. It says that this request put a `SendReceipt` message on the `async` transport, and it has the id of the message. + +## What the worker sends + +Now we start the worker: + +```bash +php bin/console messenger:consume async +``` + +```text +Trace ID a423844581b2eb396beed59f2692a045 + +process async Kind: Consumer ID: da4ea95eb2275fdb + flow.messenger.message.class = App\Message\SendReceipt + messaging.message.id = 1 + Link -> Trace ID: 07ced0cc1a3584be11025543741da7a1 Span ID: 4a6bd57021797cb1 +``` + +The worker has its own trace, and the last line is the answer to our customer: a link to the trace and the span that sent the message. +A monitoring tool shows the link on both sides. From the request we jump to the work of the worker, and from a failed handler back to the request that asked for it. + +It is a link and not one long trace on purpose. A message can wait for hours, and a batch of a thousand messages has a thousand different senders. A trace that waits that long is hard to read, and a link has none of these problems. + +The bundle carries the ids for us: it puts them into a stamp on the envelope when the message is sent, and the worker reads the stamp. It works with every transport that keeps stamps, and we never touch a header. + +When the handler throws, the `process` span has the status `ERROR` and the exception, so "the receipt never came" has a place to look. + +## Count the messages + +With `meter_provider` in the configuration the bundle also counts: + +| Metric | What it holds | +|--------------------------------------|--------------------------------------------| +| `messaging.client.sent.messages` | Messages sent, for each transport | +| `messaging.client.consumed.messages` | Messages handled, for each transport | +| `messaging.process.duration` | How long the handlers take, as a histogram | + +A monitoring tool draws sent against consumed. When the first line grows faster than the second one, the queue fills up, and we see it before a customer does. + +## What to set for Messenger tracing + +All of these are options of `messenger`, and none is needed to start: + +| Option | Default | What it does | +|-----------------------|-------------|----------------------------------------------------------------------| +| `context_propagation` | `true` | Carries the trace ids in the message | +| `trace` | `true` | The `send` and `process` spans | +| `metrics` | `true` | The three metrics above | +| `span_naming` | `transport` | Names spans by the transport, or by `message_name` or `message_fqcn` | + +## Where to go from here + +To keep only the failed and the slow messages, read about tail sampling in the [OpenTelemetry Collector for PHP](/guides/opentelemetry-collector-for-php). +The same bundle shows the SQL queries of a handler: see [find slow Doctrine queries in Symfony](/guides/find-slow-doctrine-queries-in-symfony). +All the options are in the [bundle documentation](/documentation/components/bridges/symfony-telemetry-bundle). +The log lines of a handler carry the trace id of the worker: see [add a trace id to Symfony logs](/guides/symfony-logs-with-trace-id). diff --git a/web/landing/content/guides/symfony-monitoring-with-opentelemetry.md b/web/landing/content/guides/symfony-monitoring-with-opentelemetry.md new file mode 100644 index 0000000000..d90bd572de --- /dev/null +++ b/web/landing/content/guides/symfony-monitoring-with-opentelemetry.md @@ -0,0 +1,247 @@ +--- +seo_title: Symfony monitoring with OpenTelemetry - requests, commands and SQL queries +seo_description: 'Monitor a Symfony application in production with OpenTelemetry: one bundle and one YAML file trace every request, command and Doctrine query.' +group: Observability +actions: [Observe] +tags: [Symfony, OpenTelemetry] +problem: 'The web profiler stays in dev, and production is blind' +published: '2026-12-01' +updated: '2026-12-01' +examples: [telemetry/meter] +--- + +# Symfony monitoring with OpenTelemetry: requests, commands and SQL queries + +Let's say our shop runs on Symfony. On our machine the web profiler shows every query and every millisecond of a request. +In production somebody says "the price page is slow since Monday", and we have nothing to look at. + +> These steps need a Symfony application and a collector, so they run only on your machine, not in the playground. + +## The Symfony profiler in production + +The profiler is the first thing we think of, and its own configuration says where it lives: + +```yaml +# config/packages/web_profiler.yaml +when@dev: + web_profiler: + toolbar: true + + framework: + profiler: + collect_serializer_data: true +``` + +`when@dev` is there for a reason. The profiler stores everything about every request, and it shows the whole application to anybody who finds its address. +It also knows only the last requests of one server. + +## What we need in production + +- Something that is always on and costs almost nothing. +- One record for every request and every console command: how long it took, and what happened inside. +- The record leaves the server, so we can read it later, from all servers in one place. + +That record is a trace, and the standard for it is OpenTelemetry. Every monitoring tool reads it. + +## Add OpenTelemetry to a Symfony application + +flow-php/telemetry is an independent implementation of OpenTelemetry, written in PHP, and it is [not a wrapper around the official SDK](/documentation/components/libs/telemetry/opentelemetry-sdk). +The bundle needs PHP 8.3 or newer and Symfony 6.4, 7.4 or 8.0. The only PHP extension it needs is curl. + +```bash +composer require flow-php/symfony-telemetry-bundle flow-php/telemetry-otlp-bridge +``` + +The bundle has no Flex recipe, so we add it to the list ourselves: + +```php ignore +// config/bundles.php +return [ + // ... + Flow\Bridge\Symfony\TelemetryBundle\FlowTelemetryBundle::class => ['all' => true], +]; +``` + +After the installation nothing is recorded yet. We turn on each part we want, so the first configuration has three parts: where the spans go, how they get there, and what is traced. + +```yaml +# config/packages/flow_telemetry.yaml +flow_telemetry: + resource: + custom: + service.name: shop + + exporters: + terminal: + console: ~ + + tracer_provider: + processor: + type: passthrough + exporter: terminal + + instrumentation: + console: + enabled: true + dbal: + enabled: true +``` + +## Trace a Symfony console command + +The `console` exporter prints to the terminal, so we start with a command. The shop has one that prints the three most expensive categories. + +```bash +php bin/console app:price-report +``` + +Between the lines of the command we now see its spans. These are two of them, with the long lines cut: + +```text +| SPAN: SELECT product +| Trace: 805ffb8ac2a9bdabe5dec5ff854453b7 Span: b4a5ce6e23cd8f33 Parent: 9914660346568e80 +| Kind: CLIENT Status: UNSET Duration: 244.26ms +| db.query.text = SELECT category_id, AVG(price) AS average FROM product GROUP BY category_id ORDER BY average DESC LIMIT 3 + +category 50: 2524.00 +category 49: 2523.00 +category 48: 2522.00 + +| SPAN: app:price-report +| Trace: 805ffb8ac2a9bdabe5dec5ff854453b7 Span: 9914660346568e80 +| Kind: INTERNAL Status: UNSET Duration: 248.65ms +| flow.symfony.command.name = app:price-report +| process.exit.code = 0 +``` + +We didn't change the command. The command took 248ms, and 244ms of it is one SQL query, with its text. +The query is a child of the command: its parent is the span id of `app:price-report`. + +## Trace Symfony requests and Doctrine queries + +A request has no terminal, so the spans have to leave the server. They go over OTLP, the protocol of OpenTelemetry, to a collector on the same machine. +The guide about the [OpenTelemetry Collector for PHP](/guides/opentelemetry-collector-for-php) shows how to start one in Docker, and why it is the right place to send to. + +We replace the exporter and turn on `http_kernel`: + +```yaml +# config/packages/flow_telemetry.yaml +flow_telemetry: + resource: + custom: + service.name: shop + + exporters: + collector: + otlp: + transport: + type: curl + endpoint: 'http://localhost:4318' + timeout_ms: 200 + connect_timeout_ms: 50 + + tracer_provider: + processor: + type: batching + exporter: collector + + meter_provider: + processor: + type: batching + exporter: collector + + instrumentation: + http_kernel: + enabled: true + console: + enabled: true + dbal: + enabled: true +``` + +Now we open the price page, and the collector prints what it got. Again with the long lines cut: + +```text +ScopeTraces #0 flow.symfony.dbal@4.6.0 +doctrine.dbal.connection 3c8c4614e380df92919fd4954975696d 03052d8b27b00295 db.system.name=sqlite +SELECT product 3c8c4614e380df92919fd4954975696d 3b023f33295ebdef db.operation.name=SELECT db.collection.name=product db.query.text=SELECT category_id, AVG(price) AS average FROM product GROUP BY category_id ORDER BY average DESC +ScopeTraces #0 flow.symfony.http_kernel@v7.4.25 +App\Controller\ProductController::prices 3c8c4614e380df92919fd4954975696d 19297a7024039a87 http.route=prices +GET /prices 3c8c4614e380df92919fd4954975696d b69eab7a3a4971eb http.request.method=GET url.path=/prices http.route=/prices http.response.status_code=200 +``` + +One request is one trace with four spans: the request, the controller, the connection to the database and the query. +The controller is the same as before, and it works with the ORM too: Doctrine sends every query through the same connection. + +Three things in the configuration keep the request fast: + +- `batching` keeps the spans in memory and sends them once, after the response went out to the visitor. +- The two timeouts are in milliseconds. A collector that doesn't answer costs at most that, and never an error page. +- `dbal` records the SQL with `?` in place of the values. The data of our customers doesn't leave the database. + +## Add your own span and metric + +The bundle knows Symfony, and only we know the shop. `Telemetry` is a service, so we ask for it in the controller. + +```php ignore +meter('shop')->createCounter('reports.built', 'reports')->add(1, ['report' => 'price']); + + return $telemetry->tracer('shop')->trace('build-price-report', fn (): Response => $this->json( + $connection->fetchAllAssociative( + 'SELECT category_id, AVG(price) AS average FROM product GROUP BY category_id ORDER BY average DESC', + ), + )); + } +} +``` + +The collector shows two new lines for this request: + +```text +ScopeTraces #0 shop +build-price-report cfe93d89156c7eed0e579cc6961dde63 8dfdcce05d73ef93 + +ScopeMetrics #0 shop +reports.built{report=price} 1 +``` + +`build-price-report` has the same trace id as the request around it and the query inside it. We didn't connect anything, the tracer knows which span is open. +The guides about [tracing in PHP](/guides/trace-php-script-with-opentelemetry) and [PHP metrics](/guides/php-metrics-with-opentelemetry) show what else a span and a metric can carry. + +## What else the bundle can trace + +Each line is one more `enabled: true` under `instrumentation`: + +| Key | What we get | +|----------------|--------------------------------------------------------------| +| `messenger` | A span for every message that is sent and every one handled | +| `twig` | A span for every rendered template | +| `http_client` | A span for every request of the Symfony HTTP client | +| `psr18_client` | The same for PSR-18 clients | +| `cache` | Spans for cache writes, and counters for hits and misses | +| `security` | The id of the user on the span of the request | + +All the options are in the [bundle documentation](/documentation/components/bridges/symfony-telemetry-bundle). + +## Where to go from here + +The collector decides what is kept and where it goes: see the [OpenTelemetry Collector for PHP](/guides/opentelemetry-collector-for-php). +To find the query that makes a page slow, read [find slow Doctrine queries in Symfony in production](/guides/find-slow-doctrine-queries-in-symfony). +For the queue and the logs, read [Symfony Messenger monitoring](/guides/symfony-messenger-monitoring) and [add a trace id to Symfony logs](/guides/symfony-logs-with-trace-id). diff --git a/web/landing/content/guides/trace-php-script-with-opentelemetry.md b/web/landing/content/guides/trace-php-script-with-opentelemetry.md new file mode 100644 index 0000000000..1a0546e1f9 --- /dev/null +++ b/web/landing/content/guides/trace-php-script-with-opentelemetry.md @@ -0,0 +1,262 @@ +--- +seo_title: Tracing in PHP with OpenTelemetry - spans, attributes and errors +seo_description: 'Trace a PHP script with OpenTelemetry: nested spans show where the time goes, attributes say why, and errors keep their exception.' +group: Observability +actions: [Observe] +tags: [OpenTelemetry] +problem: 'microtime() tells how long, not where and why' +published: '2026-12-01' +updated: '2026-12-01' +examples: [telemetry/tracer, telemetry/resource, telemetry/combined] +--- + +# Tracing in PHP with OpenTelemetry: spans, attributes and errors + +Let's say a nightly script imports orders: it downloads a file, validates the rows and saves them. +Most nights it takes a few seconds. Some nights it takes ten minutes, and nobody knows which step is slow. + +Doesn't look like a complicated task, right? + +## Measure a PHP script with hrtime + +The first idea is always a timer around every step. + +```php + 'nightly-import']), + tracer_provider( + pass_through_span_processor(console_exporter(colors: false)), + clock(), + memory_context_storage(), + ), +); + +$tracer = $telemetry->tracer('import'); + +$tracer->trace('import-orders', static function () use ($tracer): void { + $orders = $tracer->trace('download', download(...)); + $orders = $tracer->trace('validate', static fn (): array => validate($orders)); + + $tracer->trace('save', static fn () => save($orders)); +}); +``` + +The script prints four spans. This is the first one, and the last one: + +```text ++-------------------------------------------------------------------------------------------+ +| SPAN: download | ++-------------------------------------------------------------------------------------------+ +| Trace: 7f54bdacc35e3e6f4cd87a31a805e3b9 Span: 38a57c917b46d260 Parent: 88febcef4ffc57db | +| Kind: INTERNAL Status: UNSET Duration: 125.06ms | +| Start: 2026-12-01 18:18:44.243811 | ++-------------------------------------------------------------------------------------------+ +| Resource: | +| service.name = nightly-import | +| Scope: import unknown | ++-------------------------------------------------------------------------------------------+ ++-----------------------------------------------------------------+ +| SPAN: import-orders | ++-----------------------------------------------------------------+ +| Trace: 7f54bdacc35e3e6f4cd87a31a805e3b9 Span: 88febcef4ffc57db | +| Kind: INTERNAL Status: UNSET Duration: 408.56ms | +| Start: 2026-12-01 18:18:44.243102 | ++-----------------------------------------------------------------+ +| Resource: | +| service.name = nightly-import | +| Scope: import unknown | ++-----------------------------------------------------------------+ +``` + +Every span has the same trace id, so the four of them belong to one run, and no other run can mix into it. +`download` has a parent, and that parent is the id of `import-orders`. We didn't indent anything, the tracer knows which span is open. + +`trace` starts a span, calls our function, and ends the span when the function returns or throws. +[`console_exporter`](/documentation/dsl/telemetry/console-exporter) prints the spans. It's the place we change later to send them to a real tool, the rest of the script stays. + +## Add details and errors to a span + +A duration says how long. To know why, a span carries attributes, and it remembers the exception that ended it. + +```php + 'nightly-import']), + tracer_provider( + pass_through_span_processor(console_exporter(colors: false)), + clock(), + memory_context_storage(), + ), +); + +$tracer = $telemetry->tracer('import'); + +$span = $tracer->span('save'); +$span->setAttribute('orders.count', 500); +$span->setAttribute('db.table', 'orders'); +$scope = $tracer->activate($span); + +try { + $tracer->trace('insert-batch', static function (): void { + throw new RuntimeException('Connection to the database was lost'); + }); +} catch (RuntimeException $exception) { + echo 'import failed: ', $exception->getMessage(), "\n"; +} finally { + $scope->detach(); + $tracer->complete($span); +} +``` + +The span of the failed step, with the long lines cut: + +```text +| SPAN: insert-batch +| Trace: 91bd69444627a2919048e391e19929ba Span: 578034676f8823ee Parent: 16f0f032bee8d2b3 +| Kind: INTERNAL Status: ERROR (Connection to the database was lost) Duration: 287.00us +| Attributes: +| error.type = RuntimeException +| Events (1): +| 18:18:54.815543 exception {"exception.type":"RuntimeException","exception.message":"Connection to the database was lost", ... +``` + +And its parent: + +```text +| SPAN: save +| Trace: 91bd69444627a2919048e391e19929ba Span: 16f0f032bee8d2b3 +| Kind: INTERNAL Status: UNSET Duration: 1.10ms +| Attributes: +| orders.count = 500 +| db.table = orders +``` + +`trace` caught the exception and wrote its class, its message and its stack trace into the span. +Then it set the status to `ERROR` and threw the exception again, so our `catch` works as before. + +`span` and `complete` are the long form of `trace`. We use them when a span needs attributes, or when it doesn't fit into one function. +A new span is not a parent until we `activate` it, and we `detach` it before we complete it. + +## What to name spans and attributes + +- A span name is the step, not the data: `save`, not `save 500 orders`. The number goes into an attribute. +- Attribute names use dots and small letters: `orders.count`, `db.table`. OpenTelemetry has a [list of standard names](https://opentelemetry.io/docs/specs/semconv/), and tools understand them. +- `service.name` in the resource is the name of the whole application. Every span of this script carries it. + +## Where to go from here + +The console is for our machine. On a server the same spans go to a collector or a monitoring tool over OTLP, the protocol of OpenTelemetry. +Only the exporter changes, and it comes from [flow-php/telemetry-otlp-bridge](/documentation/components/bridges/telemetry-otlp-bridge). The spans, the attributes and the tracer stay as they are in this guide. +The next steps are [PHP metrics with OpenTelemetry](/guides/php-metrics-with-opentelemetry), [PHP logs with a trace id](/guides/php-logs-with-trace-id) and [distributed tracing in PHP](/guides/distributed-tracing-in-php). +To send the spans to a real tool, read [send PHP traces over OTLP](/guides/send-php-traces-over-otlp). diff --git a/web/landing/content/guides/trace-sql-queries-in-php.md b/web/landing/content/guides/trace-sql-queries-in-php.md new file mode 100644 index 0000000000..3a611458aa --- /dev/null +++ b/web/landing/content/guides/trace-sql-queries-in-php.md @@ -0,0 +1,145 @@ +--- +seo_title: Trace SQL queries in PHP - find the slow PostgreSQL query of a script +seo_description: 'Trace every SQL query of a PHP script with OpenTelemetry: one wrapper around the PostgreSQL client gives a span for each query and transaction.' +group: Observability +actions: [Observe] +tags: [PostgreSQL, OpenTelemetry] +problem: 'The script is slow, and one of its queries is the reason' +published: '2026-12-01' +updated: '2026-12-01' +examples: [telemetry/tracer] +--- + +# Trace SQL queries in PHP: find the slow PostgreSQL query of a script + +Let's say a nightly script builds a sales report: it reads a customer, sums up the orders of the country, and saves the result in a transaction. +The script got slower every month, and now somebody asks which query it is. + +> These scripts need a PostgreSQL database, so they run only on your machine, not in the playground. + +## Time SQL queries in PHP by hand + +The first idea is always a timer around the query we suspect. + +```php ignore +fetchOne('SELECT country FROM customers WHERE id = $1', [42]); +printf("customer: %.1fms\n", (hrtime(true) - $start) / 1e6); +``` + +```text +customer: 1.8ms +``` + +It works, for the one query we wrapped. + +## Why timers around queries are not enough + +The script has four queries, so it needs four timers, and the next query somebody adds has none. +A timer also knows nothing about the transaction around the queries, and it says nothing when a query fails. + +We want every query measured in the place where all of them pass: the database client. + +## Trace every query of the PostgreSQL client + +flow-php/telemetry is an independent implementation of OpenTelemetry, written in PHP, and it is [not a wrapper around the official SDK](/documentation/components/libs/telemetry/opentelemetry-sdk). +The client needs PHP 8.3 or newer and the `pgsql` extension. + +```bash +composer require flow-php/postgresql flow-php/telemetry flow-php/etl +``` + +```php ignore + 'nightly-report']), + tracer_provider(pass_through_span_processor(console_exporter(colors: false)), clock(), memory_context_storage()), +); + +$client = traceable_postgresql_client( + pgsql_client(pgsql_connection('host=localhost port=5432 dbname=shop user=postgres password=postgres')), + postgresql_telemetry_config($telemetry, clock()), +); + +$telemetry->tracer('report')->trace('nightly-report', static function () use ($client): void { + $country = $client->fetchOne('SELECT country FROM customers WHERE id = $1', [42]); + $total = $client->fetchScalar('SELECT SUM(amount) FROM orders WHERE country = $1', [$country['country']]); + + $client->transaction(static function () use ($client, $country, $total): void { + $client->execute('DELETE FROM report WHERE country = $1', [$country['country']]); + $client->execute('INSERT INTO report (country, total) VALUES ($1, $2)', [$country['country'], $total]); + }); +}); +``` + +The script prints six spans. These are the lines that matter, with the rest cut: + +```text +| SPAN: SELECT customers Duration: 8.38ms +| db.query.text = SELECT country FROM customers WHERE id = $1 +| SPAN: SELECT orders Duration: 50.27ms +| db.query.text = SELECT SUM(amount) FROM orders WHERE country = $1 +| SPAN: DELETE report Duration: 1.04ms +| db.query.text = DELETE FROM report WHERE country = $1 +| SPAN: INSERT report Duration: 402.00us +| db.query.text = INSERT INTO report (country, total) VALUES ($1, $2) +| SPAN: BEGIN TRANSACTION Duration: 5.41ms +| SPAN: nightly-report Duration: 72.37ms +``` + +The script took 72ms, and 50ms of it is the sum over the `orders` table. That's our query. + +The code of the report has no timer. One line changed: [`traceable_postgresql_client`](/documentation/dsl/pg_query/traceable-postgresql-client) wraps the client, and every method of the client is traced, also for queries that somebody adds next month. + +## What a query span tells us + +- **The name** is the operation and the table, `SELECT orders`. It has no values in it, so a monitoring tool can group all runs of one query. +- **The SQL** is there with `$1` in place of the values. The data of our customers doesn't leave the database. +- **The transaction** is one span, `BEGIN TRANSACTION`, and the two queries inside are its children. We see how long the transaction was open, not only how long its queries took. +- **An error** sets the status of the span, with the SQLSTATE code of PostgreSQL. + +All spans have the trace id of `nightly-report`, because the client found that span open. In a web application the same happens with the span of the request. + +## What to set for query tracing + +[`postgresql_telemetry_options`](/documentation/dsl/pg_query/postgresql-telemetry-options) is the third argument of the config, and none of it is needed to start: + +| Option | Default | What it does | +|---------------------|-----------|----------------------------------------------------------------------| +| `maxQueryLength` | `1000` | Cuts the SQL text in the span | +| `includeParameters` | `false` | Adds the bound values. They can be personal data, so leave it off | +| `transactionSpans` | `GROUPED` | One span for a whole transaction, or `PER_OPERATION`, or `OFF` | +| `collectMetrics` | `true` | A histogram of query durations, when a meter provider is configured | +| `logQueries` | `false` | Writes each query to the telemetry logger | + +## Where to go from here + +The console is for our machine. On a server the spans go to a collector: see [send PHP traces over OTLP](/guides/send-php-traces-over-otlp). +With Doctrine in a Symfony application the same idea needs no code at all: see [find slow Doctrine queries in Symfony](/guides/find-slow-doctrine-queries-in-symfony). +The basics of spans are in the guide about [tracing in PHP](/guides/trace-php-script-with-opentelemetry). diff --git a/web/landing/content/guides/upload-large-file-to-s3-in-php.md b/web/landing/content/guides/upload-large-file-to-s3-in-php.md new file mode 100644 index 0000000000..ec49f352d6 --- /dev/null +++ b/web/landing/content/guides/upload-large-file-to-s3-in-php.md @@ -0,0 +1,258 @@ +--- +seo_title: Upload a large file to S3 in PHP with a multipart upload +seo_description: 'putObject() with file_get_contents() needs 1089Mb for a 1Gb file. How an S3 multipart upload fixes it with Flow in 6Mb, also when PHP generates the data.' +group: Writing files +actions: [Write] +tags: [S3, Azure, SFTP] +problem: 'putObject() with file_get_contents() runs out of memory' +proof_label: 'Uploading a 1Gb file to S3' +proof_before: '1089Mb' +proof_after: '6Mb' +published: '2026-12-01' +updated: '2026-12-01' +examples: [filesystem/s3, filesystem/local, filesystem/azure] +--- + +# Upload a large file to S3 in PHP with a multipart upload + +Let's say a nightly job exports all our orders to one CSV file, about 1Gb, and puts it into an S3 bucket. +Our PHP process runs with the default `memory_limit` of 128Mb. + +Doesn't look like a complicated task, right? + +> The scripts that talk to S3 need a bucket, so they don't run in the playground. Run them on your machine. + +## The file + +First we need a file to work with, so let's generate one. +Set `$rows` to `16_500_000` to get the 1Gb version. + +```php + 'latest', 'region' => 'eu-west-1']); + +$client->putObject([ + 'Bucket' => 'orders-exports', + 'Key' => 'exports/orders.csv', + 'Body' => file_get_contents(__DIR__ . '/orders.csv'), +]); +``` + +With a thousand rows it works. With a 100Mb file it still works, with 126Mb of memory, 2Mb below the limit. +With the 1Gb file it ends like this: + +```text +Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 1114636288 bytes) +``` + +## Why putObject runs out of memory + +`file_get_contents` reads the whole file into one string, and `putObject` sends that string in one request. +For our file that is 1089Mb, and we have 128Mb. + +The script that passed every test with a small file fails on the first big export. +We could raise `memory_limit`, but that only moves the problem to the next, bigger file. + +## S3 multipart upload in PHP + +A multipart upload cuts the file into parts and sends each part in its own request. S3 puts them together at the end. +Only one part is in memory at a time, so it doesn't matter how big the file is. + +By hand that is three kinds of requests: one that opens the upload, one for every part, and one that closes it with the list of all parts. +We also have to cut the file and keep the number of every part. + +## Upload a large file to S3 with Flow + +Flow does all of that for us. It needs PHP 8.3 or newer. +Its S3 filesystem uses [AsyncAws](https://async-aws.com/), so the AWS SDK is not needed. +The same code works with Azure Blob Storage and with an SFTP server, so from here every example has a tab for each of them. + +```bash tab="S3" +composer require flow-php/filesystem flow-php/filesystem-async-aws-bridge +``` + +```bash tab="Azure Blob Storage" +composer require flow-php/filesystem flow-php/filesystem-azure-bridge nyholm/psr7 +``` + +```bash tab="SFTP" +composer require flow-php/filesystem flow-php/filesystem-sftp-bridge +``` + +And this is the whole upload: + +```php ignore tab="S3" + 'eu-west-1', + 'accessKeyId' => $_ENV['AWS_S3_KEY'], + 'accessKeySecret' => $_ENV['AWS_S3_SECRET'], +]); + +$storage->writeTo(path('aws-s3://exports/orders.csv')) + ->fromResource(fopen(__DIR__ . '/orders.csv', 'rb')) + ->close(); +``` + +```php ignore tab="Azure Blob Storage" + $_ENV['AZURE_ACCOUNT'], + 'container' => 'orders-exports', + 'shared_key' => $_ENV['AZURE_SHARED_KEY'], +]); + +$storage->writeTo(path('azure-blob://exports/orders.csv')) + ->fromResource(fopen(__DIR__ . '/orders.csv', 'rb')) + ->close(); +``` + +```php ignore tab="SFTP" + $_ENV['SFTP_HOST'], + 'user' => $_ENV['SFTP_USER'], + 'password' => $_ENV['SFTP_PASSWORD'], +]); + +$storage->writeTo(path('sftp://upload/exports/orders.csv')) + ->fromResource(fopen(__DIR__ . '/orders.csv', 'rb')) + ->close(); +``` + +On S3, `writeTo` opens a multipart upload. Every time 5Mb of data is ready, Flow sends it as one part, and `close` finishes the upload. +The 1Gb file goes up in 215 requests, with 6Mb of memory. +Azure Blob Storage gets the file the same way, in blocks of 4Mb. + +Only the first lines of the script know which storage it is. + +## Write to S3 while PHP generates the data + +Our job writes `orders.csv` to the disk only to upload it a moment later. +The stream that `writeTo` gives us takes data piece by piece, so we can skip the file. +`$storage` is the filesystem from the script above. + +```php ignore tab="S3" +$stream = $storage->writeTo(path('aws-s3://exports/orders-generated.csv')); +``` + +```php ignore tab="Azure Blob Storage" +$stream = $storage->writeTo(path('azure-blob://exports/orders-generated.csv')); +``` + +```php ignore tab="SFTP" +$stream = $storage->writeTo(path('sftp://upload/exports/orders-generated.csv')); +``` + +```php ignore +$rows = 1_000; +$lines = "id,email,country,amount,created_at\n"; + +for ($id = 1; $id <= $rows; $id++) { + $lines .= implode(',', [ + $id, + "customer{$id}@example.com", + ['PL', 'US', 'DE', 'FR', 'GB'][$id % 5], + number_format(($id % 1000) / 10, 2, '.', ''), + gmdate('Y-m-d H:i:s', 1_700_000_000 + $id * 60), + ]) . "\n"; + + if ($id % 10_000 === 0) { + $stream->append($lines); + $lines = ''; + } +} + +$stream->append($lines)->close(); +``` + +We collect ten thousand lines and `append` them at once, because one `append` per line is three times slower. +16.5 million orders go to S3 with 6Mb of memory, and `orders.csv` never touches our disk. + +The next job reads the export back. That's the guide about [reading a large file from S3](/guides/read-large-file-from-s3-in-php), with the copy to SFTP and Azure at its end. + +All the options of each filesystem are in the documentation of the [S3](/documentation/components/bridges/filesystem-async-aws-bridge), [Azure](/documentation/components/bridges/filesystem-azure-bridge) and [SFTP](/documentation/components/bridges/filesystem-sftp-bridge) bridges. + +## How much memory does an S3 upload take in PHP + +PHP 8.3, `memory_limit=128M`, a 1Gb file, aws/aws-sdk-php 3.409. Each number is one run. +The S3 server runs on the same machine, so the times have no network in them. + +| Task | Code | Peak memory | Time | +|-------------------|---------------------------------------|---------------------------|-------| +| Upload | `putObject` with `file_get_contents` | fatal error, needs 1089Mb | - | +| Upload | Flow `fromResource` | 6Mb | 17.5s | +| Generate and send | Flow `append` | 6Mb | 26.2s | + +The numbers that matter are the ones that don't change. With a 100Mb file every Flow row takes the same memory as with 1Gb. +Only `putObject` with a string grows with the file: 126Mb for 100Mb, 1089Mb for 1Gb. + +To check it on your machine, add this line at the end of any of the scripts above: + +```php ignore +printf("peak memory: %.1f MB\n", memory_get_peak_usage(true) / 1024 / 1024); +``` diff --git a/web/landing/importmap.php b/web/landing/importmap.php index 34c57c0dfe..544116d478 100644 --- a/web/landing/importmap.php +++ b/web/landing/importmap.php @@ -159,4 +159,7 @@ '@polar-sh/checkout/embed' => [ 'version' => '0.3.0', ], + 'prismjs/components/prism-sql.min.js' => [ + 'version' => '1.30.0', + ], ]; diff --git a/web/landing/src/Flow/Website/Controller/ExamplesController.php b/web/landing/src/Flow/Website/Controller/ExamplesController.php index b65b1b87c5..036f896ec4 100644 --- a/web/landing/src/Flow/Website/Controller/ExamplesController.php +++ b/web/landing/src/Flow/Website/Controller/ExamplesController.php @@ -4,19 +4,30 @@ namespace Flow\Website\Controller; +use Flow\Website\Model\Documentation\Page; +use Flow\Website\Model\TagCounts; +use Flow\Website\Service\Documentation\Pages; use Flow\Website\Service\Examples; +use Flow\Website\Service\Examples\ExampleNotFound; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; +use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Attribute\Route; use function array_filter; +use function array_values; use function file_exists; +use function implode; +use function in_array; +use function usort; final class ExamplesController extends AbstractController { public function __construct( private readonly Examples $examples, + #[Autowire(service: 'guides.pages')] + private readonly Pages $guides, ) {} #[Route( @@ -39,73 +50,108 @@ public function data(string $topic, string $example, string $path): Response #[Route('/{topic}/{example}/', name: 'example', priority: -140)] public function example(string $topic, string $example): Response { - $firstOption = $this->examples->firstOption($topic, $example); - - return $this->render('example/index.html.twig', [ - 'topicsNavigation' => $this->examples->topicsNavigation(), - 'examplesNavigation' => $this->examples->examplesNavigation($topic), - 'optionsNavigation' => $this->examples->optionsNavigation($topic, $example), - 'currentTopic' => $topic, - 'currentExample' => $example, - 'currentOption' => null, - 'description' => $this->examples->description($topic, $example, $firstOption), - 'documentation' => $this->examples->documentation($topic, $example, $firstOption), - 'code' => $this->examples->code($topic, $example, $firstOption), - 'playgroundUrl' => $this->examples->playgroundUrl($topic, $example, $firstOption), + try { + $firstOption = $this->examples->firstOption($topic, $example); + + return $this->render('example/index.html.twig', [ + 'topicsNavigation' => $this->examples->topicsNavigation(), + 'examplesNavigation' => $this->examples->examplesNavigation($topic), + 'optionsNavigation' => $this->examples->optionsNavigation($topic, $example), + 'currentTopic' => $topic, + 'currentExample' => $example, + 'currentOption' => null, + 'topicMeta' => $this->examples->meta($topic), + 'pageMeta' => $this->examples->meta($topic, $example, $firstOption), + 'description' => $this->examples->description($topic, $example, $firstOption), + 'documentation' => $this->examples->documentation($topic, $example, $firstOption), + 'code' => $this->examples->code($topic, $example, $firstOption), + 'playgroundUrl' => $this->examples->playgroundUrl($topic, $example, $firstOption), + 'guides' => $this->guidesUsing(implode('/', array_filter([$topic, $example, $firstOption]))), + ]); + } catch (ExampleNotFound) { + throw $this->createNotFoundException(); + } + } + + #[Route('/examples/', name: 'examples', options: ['sitemap' => true], priority: 10)] + public function index(): Response + { + $cards = $this->examples->cards(); + $counts = TagCounts::fromCards($cards); + + return $this->render('example/hub.html.twig', [ + 'cards' => $cards, + 'actions' => $counts->actions(), + 'tags' => $counts->tags(), ]); } #[Route('/playground/{topic}/{example}/{option}/', name: 'example_option_playground', priority: 10)] public function exampleOptionPlayground(string $topic, string $example, string $option): Response { - return $this->render('example/playground.html.twig', [ - 'topic' => $topic, - 'example' => $example, - 'option' => $option, - 'code' => $this->examples->code($topic, $example, $option), - 'data_files' => $this->examples->dataFiles($topic, $example, $option), - 'backUrl' => $this->generateUrl('example_option', [ + try { + return $this->render('example/playground.html.twig', [ 'topic' => $topic, 'example' => $example, 'option' => $option, - ]), - ]); + 'code' => $this->examples->code($topic, $example, $option), + 'data_files' => $this->examples->dataFiles($topic, $example, $option), + 'backUrl' => $this->generateUrl('example_option', [ + 'topic' => $topic, + 'example' => $example, + 'option' => $option, + ]), + ]); + } catch (ExampleNotFound) { + throw $this->createNotFoundException(); + } } #[Route('/playground/{topic}/{example}/', name: 'example_playground', priority: 5)] public function examplePlayground(string $topic, string $example): Response { - $firstOption = $this->examples->firstOption($topic, $example); - - return $this->render('example/playground.html.twig', [ - 'topic' => $topic, - 'example' => $example, - 'option' => $firstOption, - 'code' => $this->examples->code($topic, $example, $firstOption), - 'data_files' => $this->examples->dataFiles($topic, $example, $firstOption), - 'backUrl' => $this->generateUrl($firstOption ? 'example_option' : 'example', array_filter([ + try { + $firstOption = $this->examples->firstOption($topic, $example); + + return $this->render('example/playground.html.twig', [ 'topic' => $topic, 'example' => $example, 'option' => $firstOption, - ])), - ]); + 'code' => $this->examples->code($topic, $example, $firstOption), + 'data_files' => $this->examples->dataFiles($topic, $example, $firstOption), + 'backUrl' => $this->generateUrl($firstOption ? 'example_option' : 'example', array_filter([ + 'topic' => $topic, + 'example' => $example, + 'option' => $firstOption, + ])), + ]); + } catch (ExampleNotFound) { + throw $this->createNotFoundException(); + } } #[Route('/{topic}/{example}/{option}/', name: 'example_option', priority: -150)] public function option(string $topic, string $example, string $option): Response { - return $this->render('example/index.html.twig', [ - 'topicsNavigation' => $this->examples->topicsNavigation(), - 'examplesNavigation' => $this->examples->examplesNavigation($topic), - 'optionsNavigation' => $this->examples->optionsNavigation($topic, $example), - 'currentTopic' => $topic, - 'currentExample' => $example, - 'currentOption' => $option, - 'description' => $this->examples->description($topic, $example, $option), - 'documentation' => $this->examples->documentation($topic, $example, $option), - 'code' => $this->examples->code($topic, $example, $option), - 'playgroundUrl' => $this->examples->playgroundUrl($topic, $example, $option), - ]); + try { + return $this->render('example/index.html.twig', [ + 'topicsNavigation' => $this->examples->topicsNavigation(), + 'examplesNavigation' => $this->examples->examplesNavigation($topic), + 'optionsNavigation' => $this->examples->optionsNavigation($topic, $example), + 'currentTopic' => $topic, + 'currentExample' => $example, + 'currentOption' => $option, + 'topicMeta' => $this->examples->meta($topic), + 'pageMeta' => $this->examples->meta($topic, $example, $option), + 'description' => $this->examples->description($topic, $example, $option), + 'documentation' => $this->examples->documentation($topic, $example, $option), + 'code' => $this->examples->code($topic, $example, $option), + 'playgroundUrl' => $this->examples->playgroundUrl($topic, $example, $option), + 'guides' => $this->guidesUsing($topic . '/' . $example . '/' . $option), + ]); + } catch (ExampleNotFound) { + throw $this->createNotFoundException(); + } } #[Route( @@ -125,23 +171,19 @@ public function optionData(string $topic, string $example, string $option, strin return new BinaryFileResponse($filePath); } - #[Route('/{topic}/', name: 'topic', priority: -120)] - public function topic(string $topic): Response + /** + * @return list + */ + private function guidesUsing(string $examplePath): array { - $firstExample = $this->examples->firstExample($topic); - $firstOption = $this->examples->firstOption($topic, $firstExample); - - return $this->render('example/index.html.twig', [ - 'topicsNavigation' => $this->examples->topicsNavigation(), - 'examplesNavigation' => $this->examples->examplesNavigation($topic), - 'optionsNavigation' => $this->examples->optionsNavigation($topic, $firstExample), - 'currentTopic' => $topic, - 'currentExample' => $firstExample, - 'currentOption' => $firstOption, - 'description' => $this->examples->description($topic, $firstExample, $firstOption), - 'documentation' => $this->examples->documentation($topic, $firstExample, $firstOption), - 'code' => $this->examples->code($topic, $firstExample, $firstOption), - 'playgroundUrl' => $this->examples->playgroundUrl($topic, $firstExample, $firstOption), - ]); + $guides = array_values(array_filter($this->guides->all(), static fn(Page $guide): bool => in_array( + $examplePath, + $guide->examples(), + true, + ))); + + usort($guides, static fn(Page $left, Page $right): int => $left->path <=> $right->path); + + return $guides; } } diff --git a/web/landing/src/Flow/Website/Controller/GuidesController.php b/web/landing/src/Flow/Website/Controller/GuidesController.php index c7537f59be..dca3111285 100644 --- a/web/landing/src/Flow/Website/Controller/GuidesController.php +++ b/web/landing/src/Flow/Website/Controller/GuidesController.php @@ -5,7 +5,9 @@ namespace Flow\Website\Controller; use Flow\Website\Model\Documentation\Page; +use Flow\Website\Model\TagCounts; use Flow\Website\Service\Documentation\Pages; +use Flow\Website\Service\Examples; use Flow\Website\SocialCard\Guides\CardGenerator; use RuntimeException; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; @@ -13,30 +15,24 @@ use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Attribute\Route; +use function array_combine; use function array_filter; -use function array_keys; +use function array_map; use function array_slice; -use function ksort; -use function uksort; +use function count; +use function explode; +use function uasort; use function usort; final class GuidesController extends AbstractController { - private const array GROUP_POSITIONS = [ - 'Reading files' => 1, - 'Writing files' => 2, - 'Importing data' => 3, - 'Search' => 4, - 'SQL' => 5, - ]; - public function __construct( #[Autowire(service: 'guides.pages')] private readonly Pages $guides, ) {} #[Route('/guides/{slug}/', name: 'guides_guide')] - public function guide(string $slug, CardGenerator $socialCards): Response + public function guide(string $slug, CardGenerator $socialCards, Examples $examples): Response { try { $guide = $this->guides->get($slug); @@ -61,37 +57,53 @@ public function guide(string $slug, CardGenerator $socialCards): Response 'slug' => $slug, 'social_image' => $socialCards->generate($guide, $slug), 'related' => array_slice($others, offset: 0, length: 3), + 'examples' => array_map(static function (string $path) use ($examples): array { + $segments = explode('/', $path); + + return [ + 'route' => count($segments) === 3 ? 'example_option' : 'example', + 'arguments' => array_combine( + array_slice(['topic', 'example', 'option'], 0, count($segments)), + $segments, + ), + 'meta' => $examples->meta(...$segments), + 'action' => $examples->meta($segments[0])->action, + ]; + }, $guide->examples()), ]); } #[Route('/guides/', name: 'guides', options: ['sitemap' => true])] public function index(): Response { - $groups = []; + $guides = []; $featured = []; foreach ($this->guides->all() as $guide) { - $groups[$guide->group()][$guide->path] = $guide; + $guides[$guide->path] = $guide; if ($guide->card()['featured']) { $featured[$guide->path] = $guide; } } - uksort( - $groups, - static fn(string $left, string $right): int => ( - [self::GROUP_POSITIONS[$left] ?? PHP_INT_MAX, $left] <=> [ - self::GROUP_POSITIONS[$right] ?? PHP_INT_MAX, - $right, - ] + uasort( + $guides, + static fn(Page $left, Page $right): int => ( + [$right->published(), $left->path] <=> [$left->published(), $right->path] ), ); - foreach (array_keys($groups) as $group) { - ksort($groups[$group]); - } + $counts = TagCounts::fromCards(array_map( + static fn(Page $guide): array => $guide->card(), + $this->guides->all(), + )); - return $this->render('guides/index.html.twig', ['groups' => $groups, 'featured' => $featured]); + return $this->render('guides/index.html.twig', [ + 'guides' => $guides, + 'featured' => $featured, + 'actions' => $counts->actions(), + 'tags' => $counts->tags(), + ]); } } diff --git a/web/landing/src/Flow/Website/EventListener/SitemapSubscriber.php b/web/landing/src/Flow/Website/EventListener/SitemapSubscriber.php index b84516e994..2c44e20136 100644 --- a/web/landing/src/Flow/Website/EventListener/SitemapSubscriber.php +++ b/web/landing/src/Flow/Website/EventListener/SitemapSubscriber.php @@ -14,6 +14,7 @@ use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; +use function array_map; use function mb_strtolower; final readonly class SitemapSubscriber implements EventSubscriberInterface @@ -110,35 +111,29 @@ private function populateDocumentation(SitemapPopulateEvent $event): void private function populateExamples(SitemapPopulateEvent $event): void { - $topics = $this->examples->topics(); - - foreach ($topics as $topic) { - $event->getUrlContainer()->addUrl( - new UrlConcrete( - $event->getUrlGenerator()->generate( - 'topic', - ['topic' => $topic], - UrlGeneratorInterface::ABSOLUTE_URL, - ), - changefreq: 'weekly', - ), - 'examples', - ); - - $examples = $this->examples->examples($topic); - - foreach ($examples as $example) { - $event->getUrlContainer()->addUrl( - new UrlConcrete( - $event->getUrlGenerator()->generate( - 'example', - ['topic' => $topic, 'example' => $example], - UrlGeneratorInterface::ABSOLUTE_URL, + foreach ($this->examples->topics() as $topic) { + foreach ($this->examples->examples($topic) as $example) { + $options = $this->examples->options($topic, $example); + $pages = $options === [] + ? [['example', ['topic' => $topic, 'example' => $example]]] + : array_map(static fn(string $option): array => [ + 'example_option', + ['topic' => $topic, 'example' => $example, 'option' => $option], + ], $options); + + foreach ($pages as [$route, $arguments]) { + $event->getUrlContainer()->addUrl( + new UrlConcrete( + $event->getUrlGenerator()->generate( + $route, + $arguments, + UrlGeneratorInterface::ABSOLUTE_URL, + ), + changefreq: 'weekly', ), - changefreq: 'weekly', - ), - 'examples', - ); + 'examples', + ); + } } } } diff --git a/web/landing/src/Flow/Website/Model/Documentation/Page.php b/web/landing/src/Flow/Website/Model/Documentation/Page.php index 16e08a586b..fd0ac043ed 100644 --- a/web/landing/src/Flow/Website/Model/Documentation/Page.php +++ b/web/landing/src/Flow/Website/Model/Documentation/Page.php @@ -7,6 +7,7 @@ use League\CommonMark\Extension\FrontMatter\Data\SymfonyYamlFrontMatterParser; use League\CommonMark\Extension\FrontMatter\FrontMatterParser; +use function Flow\Types\DSL\type_list; use function Flow\Types\DSL\type_map; use function Flow\Types\DSL\type_mixed; use function Flow\Types\DSL\type_null; @@ -21,7 +22,7 @@ public function __construct( ) {} /** - * @return array{problem: ?string, proof_label: ?string, proof_before: ?string, proof_after: ?string, featured: bool} + * @return array{problem: ?string, proof_label: ?string, proof_before: ?string, proof_after: ?string, featured: bool, tags: list, actions: list} */ public function card(): array { @@ -33,6 +34,8 @@ public function card(): array 'proof_before' => type_union(type_string(), type_null())->assert($frontMatter['proof_before'] ?? null), 'proof_after' => type_union(type_string(), type_null())->assert($frontMatter['proof_after'] ?? null), 'featured' => ($frontMatter['featured'] ?? false) === true, + 'tags' => type_list(type_string())->assert($frontMatter['tags'] ?? []), + 'actions' => type_list(type_string())->assert($frontMatter['actions'] ?? []), ]; } @@ -50,6 +53,14 @@ public function editOnGitHubUrl(): string return 'https://github.com/flow-php/flow/edit/1.x/documentation/' . ltrim($this->path, '/'); } + /** + * @return list + */ + public function examples(): array + { + return type_list(type_string())->assert($this->frontMatter()['examples'] ?? []); + } + public function group(): string { return type_string()->assert($this->frontMatter()['group'] ?? null); diff --git a/web/landing/src/Flow/Website/Model/TagCounts.php b/web/landing/src/Flow/Website/Model/TagCounts.php new file mode 100644 index 0000000000..ecfba4b212 --- /dev/null +++ b/web/landing/src/Flow/Website/Model/TagCounts.php @@ -0,0 +1,61 @@ + $actions + * @param array $tags + */ + private function __construct( + private array $actions, + private array $tags, + ) {} + + /** + * @param iterable, tags: list, ...}> $cards + */ + public static function fromCards(iterable $cards): self + { + $actions = []; + $tags = []; + + foreach ($cards as $card) { + foreach ($card['actions'] as $action) { + $actions[$action] = ($actions[$action] ?? 0) + 1; + } + + foreach ($card['tags'] as $tag) { + $tags[$tag] = ($tags[$tag] ?? 0) + 1; + } + } + + ksort($actions); + arsort($actions); + ksort($tags); + + return new self($actions, $tags); + } + + /** + * @return array + */ + public function actions(): array + { + return $this->actions; + } + + /** + * @return array + */ + public function tags(): array + { + return $this->tags; + } +} diff --git a/web/landing/src/Flow/Website/Service/Examples.php b/web/landing/src/Flow/Website/Service/Examples.php index 528aa0ace9..076d579138 100644 --- a/web/landing/src/Flow/Website/Service/Examples.php +++ b/web/landing/src/Flow/Website/Service/Examples.php @@ -6,6 +6,7 @@ use FilesystemIterator; use Flow\Website\Service\Examples\ExampleMeta; +use Flow\Website\Service\Examples\ExampleNotFound; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use RuntimeException; @@ -13,6 +14,7 @@ use function array_diff; use function array_keys; +use function array_map; use function array_values; use function asort; use function count; @@ -36,6 +38,53 @@ public function __construct( private string $examplesPath, ) {} + /** + * @throws ExampleNotFound + * + * @return list}, title: string, summary: string, actions: list, tags: list, variants: list}}>}> + */ + public function cards(): array + { + $cards = []; + + foreach ($this->topics() as $topic) { + $topicMeta = $this->meta($topic); + + foreach ($this->examples($topic) as $example) { + $exampleMeta = $this->meta($topic, $example); + $variants = array_values(array_map( + fn(string $option): array => [ + 'option' => $option, + 'label' => $this->meta($topic, $example, $option)->label, + 'route' => [ + 'name' => 'example_option', + 'arguments' => ['topic' => $topic, 'example' => $example, 'option' => $option], + ], + ], + $this->options($topic, $example), + )); + + $cards[] = [ + 'topic' => $topic, + 'example' => $example, + 'route' => $variants === [] + ? ['name' => 'example', 'arguments' => ['topic' => $topic, 'example' => $example]] + : $variants[0]['route'], + 'title' => type_string()->assert($exampleMeta->title), + 'summary' => type_string()->assert($exampleMeta->summary), + 'actions' => [type_string()->assert($topicMeta->action)], + 'tags' => $exampleMeta->tags, + 'variants' => $variants, + ]; + } + } + + return $cards; + } + + /** + * @throws ExampleNotFound + */ public function code(string $topic, string $example, ?string $option = null): string { if ($option !== null) { @@ -44,11 +93,7 @@ public function code(string $topic, string $example, ?string $option = null): st $options = $this->options($topic, $example); if (0 === count($options)) { - throw new RuntimeException(sprintf( - 'Example "%s" in topic "%s" has no valid options.', - $example, - $topic, - )); + throw ExampleNotFound::example($topic, $example); } $firstOption = current($options); $path = sprintf( @@ -63,10 +108,9 @@ public function code(string $topic, string $example, ?string $option = null): st } if (false === file_exists($path)) { - throw new RuntimeException(sprintf( - 'Code example doesn\'t exists, it should be located in path: "%s".', - $path, - )); + throw $option !== null + ? ExampleNotFound::option($topic, $example, $option) + : ExampleNotFound::example($topic, $example); } return type_string()->assert(file_get_contents($path)); @@ -192,6 +236,8 @@ public function documentation(string $topic, string $example, ?string $option = } /** + * @throws ExampleNotFound + * * @return array */ public function examples(string $topic): array @@ -199,11 +245,7 @@ public function examples(string $topic): array $path = sprintf('%s/topics/%s', realpath($this->examplesPath), $topic); if (false === file_exists($path)) { - throw new RuntimeException(sprintf( - 'Topic "%s" doesn\'t exists, it should be located in path: "%s".', - $topic, - $path, - )); + throw ExampleNotFound::topic($topic); } // an example is always a directory; a loose file beside them (a topic-level description.md, @@ -224,16 +266,13 @@ public function examples(string $topic): array $priorities = []; foreach ($examples as $example) { - $meta = $this->readMeta(sprintf('%s/topics/%s/%s', realpath($this->examplesPath), $topic, $example)); - $priorities[$example] = $meta['priority']; + $priorities[$example] = $this->meta($topic, $example)->priority; } asort($priorities); foreach (array_keys($priorities) as $example) { - $meta = $this->readMeta(sprintf('%s/topics/%s/%s', realpath($this->examplesPath), $topic, $example)); - - if ($meta['hidden']) { + if ($this->meta($topic, $example)->hidden) { unset($priorities[$example]); } } @@ -242,7 +281,7 @@ public function examples(string $topic): array } /** - * @return array}> + * @return array, label: ?string, tags: list}> */ public function examplesNavigation(string $topic): array { @@ -257,17 +296,22 @@ public function examplesNavigation(string $topic): array foreach ($examples as $nextExample) { $options = $this->options($nextTopic, $nextExample); + $meta = $this->meta($nextTopic, $nextExample); if (count($options) > 0) { $firstOption = type_string()->assert(reset($options)); $navigation[$nextExample] = [ 'name' => 'example_option', 'arguments' => ['topic' => $nextTopic, 'example' => $nextExample, 'option' => $firstOption], + 'label' => $meta->label, + 'tags' => $meta->tags, ]; } else { $navigation[$nextExample] = [ 'name' => 'example', 'arguments' => ['topic' => $nextTopic, 'example' => $nextExample], + 'label' => $meta->label, + 'tags' => $meta->tags, ]; } } @@ -276,24 +320,48 @@ public function examplesNavigation(string $topic): array return $navigation; } - public function firstExample(string $topic): string + /** + * @throws ExampleNotFound + */ + public function firstOption(string $topic, string $example): ?string { - $examples = $this->examples($topic); + $options = $this->options($topic, $example); - return type_string()->assert(reset($examples)); + return count($options) > 0 ? type_string()->assert(reset($options)) : null; } - public function firstOption(string $topic, string $example): ?string + /** + * @throws ExampleNotFound + */ + public function meta(string $topic, ?string $example = null, ?string $option = null): ExampleMeta { - $options = $this->options($topic, $example); + $path = sprintf('%s/topics/%s', realpath($this->examplesPath), $topic); - return count($options) > 0 ? type_string()->assert(reset($options)) : null; + if ($example !== null) { + $path .= '/' . $example; + } + + if ($option !== null) { + $path .= '/' . $option; + } + + if (!is_dir($path)) { + throw match (true) { + $example === null => ExampleNotFound::topic($topic), + $option === null => ExampleNotFound::example($topic, $example), + default => ExampleNotFound::option($topic, $example, $option), + }; + } + + return ExampleMeta::fromDirectory($path); } /** * Returns all visible options for a given example, sorted by priority. * Returns empty array if example is standalone (2-level structure). * + * @throws ExampleNotFound + * * @return array */ public function options(string $topic, string $example): array @@ -301,12 +369,7 @@ public function options(string $topic, string $example): array $path = sprintf('%s/topics/%s/%s', realpath($this->examplesPath), $topic, $example); if (false === file_exists($path)) { - throw new RuntimeException(sprintf( - 'Example "%s" in topic "%s" doesn\'t exist, it should be located in path: "%s".', - $example, - $topic, - $path, - )); + throw ExampleNotFound::example($topic, $example); } if (file_exists(sprintf('%s/code.php', $path))) { @@ -336,16 +399,13 @@ public function options(string $topic, string $example): array $priorities = []; foreach ($options as $option) { - $meta = $this->readMeta(sprintf('%s/%s', $path, $option)); - $priorities[$option] = $meta['priority']; + $priorities[$option] = $this->meta($topic, $example, $option)->priority; } asort($priorities); foreach (array_keys($priorities) as $option) { - $meta = $this->readMeta(sprintf('%s/%s', $path, $option)); - - if ($meta['hidden']) { + if ($this->meta($topic, $example, $option)->hidden) { unset($priorities[$option]); } } @@ -354,7 +414,7 @@ public function options(string $topic, string $example): array } /** - * @return array}> + * @return array, label: ?string}> */ public function optionsNavigation(string $topic, string $example): array { @@ -378,6 +438,7 @@ public function optionsNavigation(string $topic, string $example): array $navigation[$nextOption] = [ 'name' => 'example_option', 'arguments' => ['topic' => $nextTopic, 'example' => $example, 'option' => $nextOption], + 'label' => $this->meta($nextTopic, $example, $nextOption)->label, ]; } } @@ -437,16 +498,13 @@ public function topics(): array $priorities = []; foreach ($topics as $topic) { - $meta = $this->readMeta(sprintf('%s/topics/%s', realpath($this->examplesPath), $topic)); - $priorities[$topic] = $meta['priority']; + $priorities[$topic] = $this->meta($topic)->priority; } asort($priorities); foreach (array_keys($priorities) as $topic) { - $meta = $this->readMeta(sprintf('%s/topics/%s', realpath($this->examplesPath), $topic)); - - if ($meta['hidden']) { + if ($this->meta($topic)->hidden) { unset($priorities[$topic]); } } @@ -455,7 +513,7 @@ public function topics(): array } /** - * @return array}> + * @return array, label: ?string, count: int}> */ public function topicsNavigation(): array { @@ -472,11 +530,15 @@ public function topicsNavigation(): array $navigation[$topic] = [ 'name' => 'example_option', 'arguments' => ['topic' => $topic, 'example' => $firstExample, 'option' => $firstOption], + 'label' => $this->meta($topic)->action, + 'count' => count($examples), ]; } else { $navigation[$topic] = [ 'name' => 'example', 'arguments' => ['topic' => $topic, 'example' => $firstExample], + 'label' => $this->meta($topic)->action, + 'count' => count($examples), ]; } } @@ -494,11 +556,7 @@ private function examplePath(string $topic, string $example, ?string $option = n $options = $this->options($topic, $example); if (0 === count($options)) { - throw new RuntimeException(sprintf( - 'Example "%s" in topic "%s" has no valid options.', - $example, - $topic, - )); + throw ExampleNotFound::example($topic, $example); } $firstOption = current($options); @@ -539,16 +597,4 @@ private function hasOptions(string $topic, string $example): bool return false; } - - /** - * Read _meta.yaml file and return priority and hidden values. - * - * @return array{priority: int, hidden: bool} - */ - private function readMeta(string $path): array - { - $meta = ExampleMeta::fromDirectory($path); - - return ['priority' => $meta->priority, 'hidden' => $meta->hidden]; - } } diff --git a/web/landing/src/Flow/Website/Service/Examples/ExampleMeta.php b/web/landing/src/Flow/Website/Service/Examples/ExampleMeta.php index 398a79668c..483643902a 100644 --- a/web/landing/src/Flow/Website/Service/Examples/ExampleMeta.php +++ b/web/landing/src/Flow/Website/Service/Examples/ExampleMeta.php @@ -6,6 +6,7 @@ use Symfony\Component\Yaml\Yaml; +use function array_is_list; use function array_key_exists; use function file_exists; use function file_get_contents; @@ -13,20 +14,40 @@ use function in_array; use function is_array; use function is_string; +use function mb_strlen; +use function sprintf; use function trim; final readonly class ExampleMeta { - private const TOP_LEVEL = ['priority', 'hidden', 'run']; + private const TOP_LEVEL = ['priority', 'hidden', 'run', 'action', 'title', 'summary', 'tags', 'label']; private const RUN = ['skip']; private const DEFAULT_PRIORITY = 99; + private const ACTION_MAX = 20; + + private const TITLE_MAX = 60; + + private const LABEL_MAX = 30; + + private const SUMMARY_MIN = 70; + + private const SUMMARY_MAX = 155; + + /** + * @param list $tags + */ public function __construct( public int $priority, public bool $hidden, public ?string $skipReason, + public ?string $action = null, + public ?string $title = null, + public ?string $summary = null, + public array $tags = [], + public ?string $label = null, ) {} /** @@ -57,7 +78,39 @@ public static function fromDirectory(string $directory): self } } - return new self(self::priorityOf($path, $meta), self::hiddenOf($path, $meta), self::skipReasonOf($path, $meta)); + return new self( + self::priorityOf($path, $meta), + self::hiddenOf($path, $meta), + self::skipReasonOf($path, $meta), + self::actionOf($path, $meta), + self::titleOf($path, $meta), + self::summaryOf($path, $meta), + self::tagsOf($path, $meta), + self::labelOf($path, $meta), + ); + } + + /** + * @param array $meta + */ + private static function actionOf(string $path, array $meta): ?string + { + /** @var mixed $action */ + $action = $meta['action'] ?? null; + + if ($action === null) { + return null; + } + + if (!is_string($action) || trim($action) === '' || mb_strlen($action) > self::ACTION_MAX) { + throw InvalidExampleMetaException::badValue( + $path, + 'action', + sprintf('a non-empty string of at most %d characters', self::ACTION_MAX), + ); + } + + return $action; } /** @@ -75,6 +128,29 @@ private static function hiddenOf(string $path, array $meta): bool return $hidden; } + /** + * @param array $meta + */ + private static function labelOf(string $path, array $meta): ?string + { + /** @var mixed $label */ + $label = $meta['label'] ?? null; + + if ($label === null) { + return null; + } + + if (!is_string($label) || trim($label) === '' || mb_strlen($label) > self::LABEL_MAX) { + throw InvalidExampleMetaException::badValue( + $path, + 'label', + sprintf('a non-empty string of at most %d characters', self::LABEL_MAX), + ); + } + + return $label; + } + /** * 99 is the fallback for an example with no _meta.yaml, so leaving it there means the example * sorts alphabetically by accident rather than in the order a reader should meet it. @@ -128,4 +204,82 @@ private static function skipReasonOf(string $path, array $meta): ?string return $skip; } + + /** + * @param array $meta + */ + private static function summaryOf(string $path, array $meta): ?string + { + /** @var mixed $summary */ + $summary = $meta['summary'] ?? null; + + if ($summary === null) { + return null; + } + + if ( + !is_string($summary) + || mb_strlen($summary) < self::SUMMARY_MIN + || mb_strlen($summary) > self::SUMMARY_MAX + ) { + throw InvalidExampleMetaException::badValue( + $path, + 'summary', + sprintf('a string of %d to %d characters', self::SUMMARY_MIN, self::SUMMARY_MAX), + ); + } + + return $summary; + } + + /** + * @param array $meta + * + * @return list + */ + private static function tagsOf(string $path, array $meta): array + { + /** @var mixed $tags */ + $tags = $meta['tags'] ?? []; + + if (!is_array($tags) || !array_is_list($tags)) { + throw InvalidExampleMetaException::badValue($path, 'tags', 'a list of distinct non-empty strings'); + } + + $strings = []; + + /** @var mixed $tag */ + foreach ($tags as $tag) { + if (!is_string($tag) || trim($tag) === '' || in_array($tag, $strings, true)) { + throw InvalidExampleMetaException::badValue($path, 'tags', 'a list of distinct non-empty strings'); + } + + $strings[] = $tag; + } + + return $strings; + } + + /** + * @param array $meta + */ + private static function titleOf(string $path, array $meta): ?string + { + /** @var mixed $title */ + $title = $meta['title'] ?? null; + + if ($title === null) { + return null; + } + + if (!is_string($title) || trim($title) === '' || mb_strlen($title) > self::TITLE_MAX) { + throw InvalidExampleMetaException::badValue( + $path, + 'title', + sprintf('a non-empty string of at most %d characters', self::TITLE_MAX), + ); + } + + return $title; + } } diff --git a/web/landing/src/Flow/Website/Service/Examples/ExampleNotFound.php b/web/landing/src/Flow/Website/Service/Examples/ExampleNotFound.php new file mode 100644 index 0000000000..988acce1b2 --- /dev/null +++ b/web/landing/src/Flow/Website/Service/Examples/ExampleNotFound.php @@ -0,0 +1,27 @@ + DSL stands for Domain Specific Language. In Flow, the DSL is a set of small functions that wrap object construction so pipelines read top-to-bottom. - See the examples + See the examples for usage in context.

diff --git a/web/landing/templates/example/hub.html.twig b/web/landing/templates/example/hub.html.twig new file mode 100644 index 0000000000..ca2ea419fc --- /dev/null +++ b/web/landing/templates/example/hub.html.twig @@ -0,0 +1,78 @@ +{% extends 'base.html.twig' %} + +{%- block title -%} + PHP data processing examples | Flow PHP +{%- endblock -%} + +{%- block description -%} + {{ cards|length }} short PHP examples for reading, writing, joining and aggregating data with Flow. Filter by task and format. +{%- endblock -%} + +{%- block hero -%}{%- endblock -%} + +{% block main %} +
+
+
+ + + Examples + +

PHP data processing examples

+

+ Short programs, one function each, that you can run in the playground. +

+
+ +
    +
  • + + Runs in the playground +
  • +
  • + + One function per example +
  • +
  • + + Linked to the docs +
  • +
+
+ +
+
+ {% include 'partials/tag_filter/_menus.html.twig' with {actions: actions, tags: tags} %} +
+ +
+ {% for card in cards %} + {% set url = path(card.route.name, card.route.arguments) ~ '#example' %} + + {% endfor %} +
+
+
+{% endblock %} diff --git a/web/landing/templates/example/index.html.twig b/web/landing/templates/example/index.html.twig index 09507e9b3b..9d7dec407a 100644 --- a/web/landing/templates/example/index.html.twig +++ b/web/landing/templates/example/index.html.twig @@ -1,142 +1,164 @@ {% extends 'base.html.twig' %} {%- block title -%} - Flow PHP - {{ currentTopic|humanize }} - {{ currentExample|humanize }} - Example + {{ pageMeta.title }} | Flow PHP {%- endblock -%} {%- block description -%} - Code example showing {{ currentExample|humanize|lower }} {{ currentTopic|humanize|lower }}. + {{ pageMeta.summary }} {%- endblock -%} {%- block hero -%}{%- endblock -%} {% block main %}
- - - Examples - -

{{ currentTopic|humanize }}

- - {% include 'partials/topic_nav.html.twig' with {topicsNavigation: topicsNavigation, currentTopic: currentTopic} %} - -
- + +

{{ pageMeta.title }}

+

{{ pageMeta.summary }}

+
+ {% include 'partials/example_nav/_menu.html.twig' with {label: 'I want to', selected: topicsNavigation[currentTopic].label ?? currentTopic|humanize, items: topicsNavigation, current: currentTopic} only %} + {% include 'partials/example_nav/_menu.html.twig' with {label: 'Example', selected: examplesNavigation[currentExample].label ?? currentExample|humanize, items: examplesNavigation, current: currentExample, modifier: 'tag-filter-menu-topic'} only %} {% if optionsNavigation|length > 0 %} - + {% set currentVariant = currentOption ?? optionsNavigation|keys|first %} + {% include 'partials/example_nav/_menu.html.twig' with {label: 'Variant', selected: optionsNavigation[currentVariant].label ?? currentVariant|humanize, items: optionsNavigation, current: currentVariant, modifier: 'tag-filter-menu-topic'} only %} {% endif %} +
-
- {% if description %} -

Description

-
- {{ description|markdown_to_html }} -
- {% endif %} - - {% if documentation %} -

Documentation

-
- {{ documentation|markdown_to_html }} -
- {% endif %} - +
+
{% apply spaceless %} -

Code

-
-
- - - -
-
+                    
                         
                             {{- code | escape('html') -}}
                         
                     
{% endapply %} +
-
- -
+ +
+ +
+
+ + {% endblock %} diff --git a/web/landing/templates/guides/guide.html.twig b/web/landing/templates/guides/guide.html.twig index c508c73cef..af2de8ebe0 100644 --- a/web/landing/templates/guides/guide.html.twig +++ b/web/landing/templates/guides/guide.html.twig @@ -24,7 +24,9 @@ {%- block contributors -%}{%- endblock -%} {% block main %} -
+
+ +
{% endblock %} diff --git a/web/landing/templates/main/not_found.html.twig b/web/landing/templates/main/not_found.html.twig index f91dbe107c..92b4e58404 100644 --- a/web/landing/templates/main/not_found.html.twig +++ b/web/landing/templates/main/not_found.html.twig @@ -43,7 +43,7 @@ class="btn btn-secondary px-4 py-2 no-underline"> Documentation - Examples diff --git a/web/landing/templates/partials/example_nav/_menu.html.twig b/web/landing/templates/partials/example_nav/_menu.html.twig new file mode 100644 index 0000000000..dbbeeef8b0 --- /dev/null +++ b/web/landing/templates/partials/example_nav/_menu.html.twig @@ -0,0 +1,25 @@ +
+ + {{ label }} + {{ selected }} + + + +
diff --git a/web/landing/templates/partials/footer.html.twig b/web/landing/templates/partials/footer.html.twig index 9ba41db159..8adfb14d99 100644 --- a/web/landing/templates/partials/footer.html.twig +++ b/web/landing/templates/partials/footer.html.twig @@ -17,7 +17,7 @@
  • Docs
  • Guides
  • Playground
  • -
  • Examples
  • +
  • Examples
  • Changelog
  • diff --git a/web/landing/templates/partials/header.html.twig b/web/landing/templates/partials/header.html.twig index dcdc0592f9..99acea7089 100644 --- a/web/landing/templates/partials/header.html.twig +++ b/web/landing/templates/partials/header.html.twig @@ -18,7 +18,7 @@ {label: 'Docs', href: path('documentation'), route: 'documentation'}, {label: 'Guides', href: path('guides'), route: 'guides'}, {label: 'Playground', href: path('playground'), route: 'playground'}, - {label: 'Examples', href: path('example', {topic: 'reading', example: 'array', _fragment: 'example'}), route: 'example'}, + {label: 'Examples', href: path('examples'), route: 'example'}, {label: 'Work-Shop', href: path('work_shop'), route: 'work_shop', glow: true}, {label: 'Blog', href: path('blog'), route: 'blog'}, ] %} @@ -79,7 +79,7 @@ {label: 'Docs', href: path('documentation'), icon: 'checklist'}, {label: 'Guides', href: path('guides'), icon: 'file'}, {label: 'Playground', href: path('playground'), icon: 'play'}, - {label: 'Examples', href: path('example', {topic: 'reading', example: 'array', _fragment: 'example'}), icon: 'code'}, + {label: 'Examples', href: path('examples'), icon: 'code'}, {label: 'Work-Shop', href: path('work_shop'), icon: 'cart', glow: true}, {label: 'Blog', href: path('blog'), icon: 'pencil'}, {label: 'Sponsor', href: path('sponsor'), icon: 'heart'}, diff --git a/web/landing/templates/partials/tag_filter/_badges.html.twig b/web/landing/templates/partials/tag_filter/_badges.html.twig new file mode 100644 index 0000000000..b72525cc00 --- /dev/null +++ b/web/landing/templates/partials/tag_filter/_badges.html.twig @@ -0,0 +1,19 @@ +{% if actions or tags %} +
      + {% for action in actions %} +
    • + +
    • + {% endfor %} + {% for tag in tags %} +
    • + +
    • + {% endfor %} +
    +{% endif %} diff --git a/web/landing/templates/partials/tag_filter/_menus.html.twig b/web/landing/templates/partials/tag_filter/_menus.html.twig new file mode 100644 index 0000000000..535beee95c --- /dev/null +++ b/web/landing/templates/partials/tag_filter/_menus.html.twig @@ -0,0 +1,33 @@ +
    + + I want to + do anything + + +
    + {% for action, count in actions %} + + {% endfor %} +
    +
    +
    + + Working with + anything + + +
    + {% for tag, count in tags %} + + {% endfor %} +
    +
    diff --git a/web/landing/templates/partials/topic_nav.html.twig b/web/landing/templates/partials/topic_nav.html.twig index 6a519adee5..69f82e039c 100644 --- a/web/landing/templates/partials/topic_nav.html.twig +++ b/web/landing/templates/partials/topic_nav.html.twig @@ -1,4 +1,4 @@ -{# Shared topic navigation. Used on home and on the examples page so they stay visually identical. +{# Topic navigation of the home page. Params: topicsNavigation: dict currentTopic: string|null @@ -10,7 +10,7 @@
  • {{ topic|humanize }} diff --git a/web/landing/templates/tag_icons/azure.svg b/web/landing/templates/tag_icons/azure.svg new file mode 100644 index 0000000000..54840d0639 --- /dev/null +++ b/web/landing/templates/tag_icons/azure.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/csv.svg b/web/landing/templates/tag_icons/csv.svg new file mode 100644 index 0000000000..baecec35e1 --- /dev/null +++ b/web/landing/templates/tag_icons/csv.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/database.svg b/web/landing/templates/tag_icons/database.svg new file mode 100644 index 0000000000..a192c27477 --- /dev/null +++ b/web/landing/templates/tag_icons/database.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/elasticsearch.svg b/web/landing/templates/tag_icons/elasticsearch.svg new file mode 100644 index 0000000000..37e2baacbd --- /dev/null +++ b/web/landing/templates/tag_icons/elasticsearch.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/excel.svg b/web/landing/templates/tag_icons/excel.svg new file mode 100644 index 0000000000..423d3c3045 --- /dev/null +++ b/web/landing/templates/tag_icons/excel.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/floe.svg b/web/landing/templates/tag_icons/floe.svg new file mode 100644 index 0000000000..ed45f2ecf5 --- /dev/null +++ b/web/landing/templates/tag_icons/floe.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/json.svg b/web/landing/templates/tag_icons/json.svg new file mode 100644 index 0000000000..9a772ba116 --- /dev/null +++ b/web/landing/templates/tag_icons/json.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/local-files.svg b/web/landing/templates/tag_icons/local-files.svg new file mode 100644 index 0000000000..aefb0e28e1 --- /dev/null +++ b/web/landing/templates/tag_icons/local-files.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/mysql.svg b/web/landing/templates/tag_icons/mysql.svg new file mode 100644 index 0000000000..dd50b15a03 --- /dev/null +++ b/web/landing/templates/tag_icons/mysql.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/opentelemetry.svg b/web/landing/templates/tag_icons/opentelemetry.svg new file mode 100644 index 0000000000..c80f362b2f --- /dev/null +++ b/web/landing/templates/tag_icons/opentelemetry.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/parquet.svg b/web/landing/templates/tag_icons/parquet.svg new file mode 100644 index 0000000000..ed53a36dbf --- /dev/null +++ b/web/landing/templates/tag_icons/parquet.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/postgresql.svg b/web/landing/templates/tag_icons/postgresql.svg new file mode 100644 index 0000000000..71e26be52e --- /dev/null +++ b/web/landing/templates/tag_icons/postgresql.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/rest-api.svg b/web/landing/templates/tag_icons/rest-api.svg new file mode 100644 index 0000000000..2019377f5a --- /dev/null +++ b/web/landing/templates/tag_icons/rest-api.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/s3.svg b/web/landing/templates/tag_icons/s3.svg new file mode 100644 index 0000000000..876c71bee5 --- /dev/null +++ b/web/landing/templates/tag_icons/s3.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/sftp.svg b/web/landing/templates/tag_icons/sftp.svg new file mode 100644 index 0000000000..7032b47ee1 --- /dev/null +++ b/web/landing/templates/tag_icons/sftp.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/sql.svg b/web/landing/templates/tag_icons/sql.svg new file mode 100644 index 0000000000..fd5c22e19f --- /dev/null +++ b/web/landing/templates/tag_icons/sql.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/symfony.svg b/web/landing/templates/tag_icons/symfony.svg new file mode 100644 index 0000000000..e23d12cb12 --- /dev/null +++ b/web/landing/templates/tag_icons/symfony.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/text.svg b/web/landing/templates/tag_icons/text.svg new file mode 100644 index 0000000000..28c8b95915 --- /dev/null +++ b/web/landing/templates/tag_icons/text.svg @@ -0,0 +1 @@ + diff --git a/web/landing/templates/tag_icons/xml.svg b/web/landing/templates/tag_icons/xml.svg new file mode 100644 index 0000000000..08b57b9f33 --- /dev/null +++ b/web/landing/templates/tag_icons/xml.svg @@ -0,0 +1 @@ + diff --git a/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_1/_meta.yaml b/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_1/_meta.yaml index 0d96c143f9..1fdf2d4168 100644 --- a/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_1/_meta.yaml +++ b/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_1/_meta.yaml @@ -1,2 +1,3 @@ priority: 1 hidden: false +action: Read diff --git a/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_1/example_1/_meta.yaml b/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_1/example_1/_meta.yaml index 0d96c143f9..5c494257cc 100644 --- a/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_1/example_1/_meta.yaml +++ b/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_1/example_1/_meta.yaml @@ -1,2 +1,5 @@ priority: 1 hidden: false +title: Fixture topic 1 example 1 +summary: 'The fixture example 1 of topic 1, used to test the order of the cards on the examples hub.' +tags: [CSV] diff --git a/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_1/example_2/_meta.yaml b/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_1/example_2/_meta.yaml index 372963400e..9852a6156d 100644 --- a/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_1/example_2/_meta.yaml +++ b/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_1/example_2/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Fixture topic 1 example 2 +summary: 'The fixture example 2 of topic 1, used to test the order of the cards on the examples hub.' diff --git a/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_2/_meta.yaml b/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_2/_meta.yaml index 372963400e..805693d2bb 100644 --- a/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_2/_meta.yaml +++ b/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_2/_meta.yaml @@ -1,2 +1,3 @@ priority: 2 hidden: false +action: Write diff --git a/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_2/example_1/_meta.yaml b/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_2/example_1/_meta.yaml index 0d96c143f9..bce901f2a3 100644 --- a/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_2/example_1/_meta.yaml +++ b/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_2/example_1/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Fixture topic 2 example 1 +summary: 'The fixture example 1 of topic 2, used to test the order of the cards on the examples hub.' diff --git a/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_2/example_2/_meta.yaml b/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_2/example_2/_meta.yaml index 372963400e..c3f710492f 100644 --- a/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_2/example_2/_meta.yaml +++ b/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_2/example_2/_meta.yaml @@ -1,2 +1,4 @@ priority: 2 hidden: false +title: Fixture topic 2 example 2 +summary: 'The fixture example 2 of topic 2, used to test the order of the cards on the examples hub.' diff --git a/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_3/_meta.yaml b/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_3/_meta.yaml index 8608dd76b4..89417dda45 100644 --- a/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_3/_meta.yaml +++ b/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_3/_meta.yaml @@ -1,2 +1,3 @@ priority: 3 hidden: false +action: Join diff --git a/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_3/example_1/_meta.yaml b/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_3/example_1/_meta.yaml index 0d96c143f9..f24509e033 100644 --- a/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_3/example_1/_meta.yaml +++ b/web/landing/tests/Flow/Website/Tests/Fixtures/Valid/topics/topic_3/example_1/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Fixture topic 3 example 1 +summary: 'The fixture example 1 of topic 3, used to test the order of the cards on the examples hub.' diff --git a/web/landing/tests/Flow/Website/Tests/Fixtures/WithDataFiles/topics/data_topic/_meta.yaml b/web/landing/tests/Flow/Website/Tests/Fixtures/WithDataFiles/topics/data_topic/_meta.yaml index 0d96c143f9..1fdf2d4168 100644 --- a/web/landing/tests/Flow/Website/Tests/Fixtures/WithDataFiles/topics/data_topic/_meta.yaml +++ b/web/landing/tests/Flow/Website/Tests/Fixtures/WithDataFiles/topics/data_topic/_meta.yaml @@ -1,2 +1,3 @@ priority: 1 hidden: false +action: Read diff --git a/web/landing/tests/Flow/Website/Tests/Fixtures/WithDataFiles/topics/data_topic/option_example/_meta.yaml b/web/landing/tests/Flow/Website/Tests/Fixtures/WithDataFiles/topics/data_topic/option_example/_meta.yaml index 372963400e..112ac854b0 100644 --- a/web/landing/tests/Flow/Website/Tests/Fixtures/WithDataFiles/topics/data_topic/option_example/_meta.yaml +++ b/web/landing/tests/Flow/Website/Tests/Fixtures/WithDataFiles/topics/data_topic/option_example/_meta.yaml @@ -1,2 +1,6 @@ priority: 2 hidden: false +title: Fixture example with options +summary: 'A fixture example with one option, used to test the variants of a card on the examples hub.' +label: With options +tags: [CSV] diff --git a/web/landing/tests/Flow/Website/Tests/Fixtures/WithDataFiles/topics/data_topic/option_example/option_1/_meta.yaml b/web/landing/tests/Flow/Website/Tests/Fixtures/WithDataFiles/topics/data_topic/option_example/option_1/_meta.yaml index 0d96c143f9..f4842c649d 100644 --- a/web/landing/tests/Flow/Website/Tests/Fixtures/WithDataFiles/topics/data_topic/option_example/option_1/_meta.yaml +++ b/web/landing/tests/Flow/Website/Tests/Fixtures/WithDataFiles/topics/data_topic/option_example/option_1/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Fixture option 1 +summary: 'The only option of the fixture example with options, read by the variants and the meta tests.' diff --git a/web/landing/tests/Flow/Website/Tests/Fixtures/WithDataFiles/topics/data_topic/plain_example/_meta.yaml b/web/landing/tests/Flow/Website/Tests/Fixtures/WithDataFiles/topics/data_topic/plain_example/_meta.yaml index 0d96c143f9..591bbce01a 100644 --- a/web/landing/tests/Flow/Website/Tests/Fixtures/WithDataFiles/topics/data_topic/plain_example/_meta.yaml +++ b/web/landing/tests/Flow/Website/Tests/Fixtures/WithDataFiles/topics/data_topic/plain_example/_meta.yaml @@ -1,2 +1,4 @@ priority: 1 hidden: false +title: Fixture example without options +summary: 'A fixture example without options and with input data files, served by the playground data route.' diff --git a/web/landing/tests/Flow/Website/Tests/Functional/ExamplesControllerTest.php b/web/landing/tests/Flow/Website/Tests/Functional/ExamplesControllerTest.php index 402cb16caa..07f32b1c35 100644 --- a/web/landing/tests/Flow/Website/Tests/Functional/ExamplesControllerTest.php +++ b/web/landing/tests/Flow/Website/Tests/Functional/ExamplesControllerTest.php @@ -5,10 +5,14 @@ namespace Flow\Website\Tests\Functional; use Flow\Website\Kernel; +use Flow\Website\Service\Examples\ExampleMeta; use Override; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; +use Symfony\Component\DomCrawler\Crawler; +use function dirname; use function Flow\Types\DSL\type_string; +use function json_decode; final class ExamplesControllerTest extends WebTestCase { @@ -47,6 +51,182 @@ public function test_code_is_displayed_on_example_page(): void static::assertStringContainsString('text()); } + public function test_examples_hub_marks_examples_active_in_the_header(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/examples/'); + + self::assertResponseIsSuccessful(); + static::assertGreaterThan(0, $crawler->filter('header a[href="/examples/"][aria-current="page"]')->count()); + } + + public function test_topic_root_is_not_found(): void + { + self::createClient()->request('GET', '/reading/'); + + self::assertResponseStatusCodeSame(404); + } + + public function test_example_menu_prints_the_label(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/reading/dbal/limit_offset/'); + + self::assertResponseIsSuccessful(); + $menus = $crawler->filter('details.tag-filter-menu'); + $exampleMenu = $menus->reduce( + static fn(Crawler $menu): bool => $menu->filter('.tag-filter-label')->text() === 'Example', + ); + $variantMenu = $menus->reduce( + static fn(Crawler $menu): bool => $menu->filter('.tag-filter-label')->text() === 'Variant', + ); + + static::assertSame('DBAL', $exampleMenu->filter('.tag-filter-selected')->text()); + static::assertSame('DBAL', $exampleMenu->filter('a[aria-current="page"] .tag-filter-option-name')->text()); + static::assertSame('Limit offset', $variantMenu->filter('.tag-filter-selected')->text()); + } + + public function test_topic_menu_selected_text_matches_its_current_item(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/reading/dbal/limit_offset/'); + + self::assertResponseIsSuccessful(); + $topicMenu = $crawler + ->filter('details.tag-filter-menu') + ->reduce(static fn(Crawler $menu): bool => $menu->filter('.tag-filter-label')->text() === 'I want to'); + + static::assertSame('Read', $topicMenu->filter('.tag-filter-selected')->text()); + static::assertSame('Read', $topicMenu->filter('a[aria-current="page"] .tag-filter-option-name')->text()); + static::assertSame('13', $topicMenu->filter('a[aria-current="page"] .tag-filter-count')->text()); + } + + public function test_example_page_describes_its_breadcrumb_to_search_engines(): void + { + $client = self::createClient(); + + foreach ([ + '/reading/csv/' => 'Read a CSV file in PHP', + '/reading/dbal/limit_offset/' => 'Read a database table with LIMIT and OFFSET in PHP', + ] as $path => $title) { + $crawler = $client->request('GET', $path); + + self::assertResponseIsSuccessful(); + static::assertSame( + [ + '@context' => 'https://schema.org', + '@type' => 'BreadcrumbList', + 'itemListElement' => [ + [ + '@type' => 'ListItem', + 'position' => 1, + 'name' => 'Examples', + 'item' => 'http://localhost/examples/', + ], + [ + '@type' => 'ListItem', + 'position' => 2, + 'name' => $title, + 'item' => 'http://localhost' . $path, + ], + ], + ], + json_decode( + $crawler->filter('script[type="application/ld+json"]')->text(), + true, + flags: JSON_THROW_ON_ERROR, + ), + ); + } + } + + public function test_example_page_marks_where_its_links_are(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/transformations/sort/'); + + self::assertResponseIsSuccessful(); + + foreach ([ + '[data-ph-capture-attribute-link-location="example_menu"] details.tag-filter-menu a', + '[data-ph-capture-attribute-link-location="example_pager"] a[rel="next"]', + '[data-ph-capture-attribute-link-location="example_docs"] a', + '[data-ph-capture-attribute-link-location="example_guides"] a[href="/guides/read-large-csv-file-in-php/"]', + ] as $link) { + static::assertGreaterThan(0, $crawler->filter($link)->count(), $link); + } + } + + public function test_example_menu_shows_the_icon_of_the_format(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/reading/dbal/limit_offset/'); + + self::assertResponseIsSuccessful(); + $exampleMenu = $crawler + ->filter('details.tag-filter-menu') + ->reduce(static fn(Crawler $menu): bool => $menu->filter('.tag-filter-label')->text() === 'Example'); + + static::assertCount(2, $exampleMenu->filter('a[href="/reading/csv/#example"] > svg')); + static::assertCount(1, $exampleMenu->filter('a[href="/reading/array/#example"] > svg')); + } + + public function test_hub_variant_links_print_the_label_or_the_folder_name(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/examples/'); + + self::assertResponseIsSuccessful(); + static::assertCount( + 1, + $crawler + ->filter('[data-tag-filter-card="reading/dbal"] [data-example-variants] a') + ->reduce(static fn(Crawler $link): bool => $link->text() === 'Limit offset'), + ); + } + + public function test_examples_hub_counts_actions_and_tags(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/examples/'); + + self::assertResponseIsSuccessful(); + static::assertSame( + '3', + $crawler + ->filter('[data-tag-filter-actions] button[data-tag-filter-tag-param="Join"] [data-tag-filter-count]') + ->text(), + ); + } + + public function test_examples_hub_links_variants(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/examples/'); + + self::assertResponseIsSuccessful(); + static::assertCount( + 1, + $crawler->filter( + '[data-tag-filter-card="transformations/array"] [data-example-variants] a[href="/transformations/array/expand/#example"]', + ), + ); + } + + public function test_examples_hub_lists_every_visible_example(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/examples/'); + + self::assertResponseIsSuccessful(); + static::assertCount(93, $crawler->filter('[data-tag-filter-card]')); + static::assertSame( + ExampleMeta::fromDirectory(dirname(__DIR__, 5) . '/content/examples/topics/joins/join')->title, + $crawler->filter('[data-tag-filter-card="joins/join"] h3')->text(), + ); + static::assertCount(0, $crawler->filter('[data-tag-filter-target="featured"]')); + } + public function test_example_option_page_returns_200(): void { $client = self::createClient(); @@ -71,8 +251,65 @@ public function test_example_page_displays_correct_title(): void $client->request('GET', '/caching/cache/'); self::assertResponseIsSuccessful(); - self::assertSelectorTextContains('title', 'Flow PHP'); - self::assertSelectorTextContains('title', 'Cache'); + self::assertSelectorTextSame( + 'title', + type_string()->assert(ExampleMeta::fromDirectory( + dirname(__DIR__, 5) . '/content/examples/topics/caching/cache', + )->title) + . ' | Flow PHP', + ); + } + + public function test_example_page_has_breadcrumb_and_three_menus(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/transformations/array/expand/'); + + self::assertResponseIsSuccessful(); + static::assertCount(1, $crawler->filter('nav[aria-label="Breadcrumb"] a[href="/examples/#Transform"]')); + static::assertCount(3, $crawler->filter('details.tag-filter-menu')); + static::assertCount( + 1, + $crawler + ->filter('details.tag-filter-menu') + ->reduce(static fn(Crawler $menu): bool => $menu->filter('.tag-filter-label')->text() === 'Variant') + ->filter('a[aria-current="page"][href="/transformations/array/expand/#example"]'), + ); + } + + public function test_example_page_head_uses_the_example_texts(): void + { + $meta = ExampleMeta::fromDirectory(dirname(__DIR__, 5) . '/content/examples/topics/joins/join'); + $client = self::createClient(); + $crawler = $client->request('GET', '/joins/join/'); + + self::assertResponseIsSuccessful(); + static::assertSame($meta->title, $crawler->filter('main h1')->text()); + static::assertSame(type_string()->assert($meta->title) . ' | Flow PHP', $crawler->filter('title')->text()); + static::assertSame($meta->summary, $crawler->filter('meta[name="description"]')->attr('content')); + } + + public function test_example_without_options_has_no_variant_menu(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/joins/join/'); + + self::assertResponseIsSuccessful(); + static::assertCount(2, $crawler->filter('details.tag-filter-menu')); + } + + public function test_option_page_head_uses_the_option_texts(): void + { + $meta = ExampleMeta::fromDirectory( + dirname(__DIR__, 5) . '/content/examples/topics/transformations/array/expand', + ); + $client = self::createClient(); + $crawler = $client->request('GET', '/transformations/array/expand/'); + + self::assertResponseIsSuccessful(); + static::assertSame($meta->title, $crawler->filter('main h1')->text()); + static::assertSame(type_string()->assert($meta->title) . ' | Flow PHP', $crawler->filter('title')->text()); + static::assertSame($meta->summary, $crawler->filter('meta[name="description"]')->attr('content')); } public function test_example_page_returns_200(): void @@ -97,11 +334,104 @@ public function test_example_playground_page_returns_200(): void public function test_options_navigation_shows_on_example_with_options(): void { $client = self::createClient(); - $crawler = $client->request('GET', '/reading/'); + $crawler = $client->request('GET', '/reading/dbal/limit_offset/'); self::assertResponseIsSuccessful(); - $options = $crawler->filter('a:contains("Csv")'); - static::assertGreaterThan(0, $options->count()); + $variantMenu = $crawler + ->filter('details.tag-filter-menu') + ->reduce(static fn(Crawler $menu): bool => $menu->filter('.tag-filter-label')->text() === 'Variant'); + static::assertCount(1, $variantMenu); + static::assertCount(1, $variantMenu->filter('a[href="/reading/dbal/key_set/#example"]')); + } + + public function test_example_page_links_the_previous_and_the_next_example_of_the_topic(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/reading/csv/'); + + self::assertResponseIsSuccessful(); + static::assertSame( + ['/reading/array/', '/reading/json/'], + $crawler + ->filter('nav[aria-label="More examples"] a') + ->each(static fn(Crawler $link): ?string => $link->attr('href')), + ); + static::assertCount( + 1, + $crawler->filter('nav[aria-label="More examples"] a[rel="prev"][href="/reading/array/"]'), + ); + static::assertCount( + 1, + $crawler->filter('nav[aria-label="More examples"] a[rel="next"][href="/reading/json/"]'), + ); + + $crawler = $client->request('GET', '/reading/array/'); + + static::assertCount(0, $crawler->filter('nav[aria-label="More examples"] a[rel="prev"]')); + static::assertCount(1, $crawler->filter('nav[aria-label="More examples"] a[rel="next"]')); + } + + public function test_example_page_links_the_guides_that_use_it(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/transformations/sort/'); + + self::assertResponseIsSuccessful(); + static::assertSame( + [ + '/guides/import-large-excel-file-in-php/', + '/guides/read-and-write-parquet-files-in-php/', + '/guides/read-large-csv-file-in-php/', + '/guides/read-large-json-file-in-php/', + ], + $crawler + ->filterXPath('//aside//section[h2="Guides"]//a') + ->each(static fn(Crawler $link): ?string => $link->attr('href')), + ); + } + + public function test_example_option_page_links_the_guides_that_use_it(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/reading/dbal/key_set/'); + + self::assertResponseIsSuccessful(); + static::assertSame( + [ + '/guides/export-database-to-excel-in-php/', + '/guides/index-database-table-in-elasticsearch-with-php/', + '/guides/stream-large-csv-download-in-symfony/', + ], + $crawler + ->filterXPath('//aside//section[h2="Guides"]//a') + ->each(static fn(Crawler $link): ?string => $link->attr('href')), + ); + } + + public function test_example_page_without_guides_has_no_guides_section(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/joins/join/'); + + self::assertResponseIsSuccessful(); + static::assertNotContains('Guides', $crawler + ->filter('aside h2') + ->each(static fn(Crawler $heading): string => $heading->text())); + } + + public function test_example_page_shows_the_description_and_the_related_docs_next_to_the_code(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/reading/dbal/limit_offset/'); + + self::assertResponseIsSuccessful(); + static::assertSame( + ['About', 'Related docs'], + $crawler->filter('aside h2')->each(static fn(Crawler $heading): string => $heading->text()), + ); + static::assertCount(1, $crawler->filter('aside #example-description')); + static::assertCount(1, $crawler->filter('aside a[href="/documentation/components/adapters/doctrine/"]')); + static::assertSame('code.php', $crawler->filter('#code [data-code-file]')->text()); } public function test_try_it_in_playground_link_exists_on_example_page(): void @@ -110,11 +440,43 @@ public function test_try_it_in_playground_link_exists_on_example_page(): void $crawler = $client->request('GET', '/caching/cache/'); self::assertResponseIsSuccessful(); - $link = $crawler->filter('a[title="Try in Playground"]'); + $link = $crawler->filter('aside a:contains("Run in Playground")'); static::assertCount(1, $link); static::assertStringContainsString('/playground/', type_string()->assert($link->attr('href'))); } + public function test_unknown_example_is_not_found(): void + { + $client = self::createClient(); + $client->request('GET', '/join/join/'); + + self::assertResponseStatusCodeSame(404); + } + + public function test_unknown_example_playground_is_not_found(): void + { + $client = self::createClient(); + $client->request('GET', '/playground/join/join/'); + + self::assertResponseStatusCodeSame(404); + } + + public function test_unknown_option_is_not_found(): void + { + $client = self::createClient(); + $client->request('GET', '/reading/dbal/none/'); + + self::assertResponseStatusCodeSame(404); + } + + public function test_unknown_topic_is_not_found(): void + { + $client = self::createClient(); + $client->request('GET', '/data_reading/'); + + self::assertResponseStatusCodeSame(404); + } + #[Override] protected static function getKernelClass(): string { diff --git a/web/landing/tests/Flow/Website/Tests/Functional/ExamplesHubFilterTest.php b/web/landing/tests/Flow/Website/Tests/Functional/ExamplesHubFilterTest.php new file mode 100644 index 0000000000..a757ae23da --- /dev/null +++ b/web/landing/tests/Flow/Website/Tests/Functional/ExamplesHubFilterTest.php @@ -0,0 +1,57 @@ + $card['topic'] . '/' . $card['example'], + array_filter( + (new Examples(dirname(__DIR__, 5) . '/content/examples'))->cards(), + static fn(array $card): bool => $card['topic'] === 'reading' && in_array('CSV', $card['tags'], true), + ), + )); + + $this->recordPostHog($browser = $this->playwrightBrowser()); + $browser->visit('/examples/'); + $page = $this->pageOf($browser); + $page->waitForSelector('[data-tag-filter-selected]'); + + $page->click('details:has([data-tag-filter-actions]):not([open]) > summary'); + $page->click('[data-tag-filter-actions] button[data-tag-filter-tag-param="Read"]'); + $page->click('details:has([data-tag-filter-bar]):not([open]) > summary'); + $page->click('[data-tag-filter-bar] button[data-tag-filter-tag-param="CSV"]'); + + static::assertNotSame([], $expected); + static::assertSame('#Read,CSV', $page->evaluate('() => window.location.hash')); + static::assertSame( + $expected, + $page->evaluate( + '() => [...document.querySelectorAll("[data-tag-filter-card]")].filter((card) => card.offsetParent !== null).map((card) => card.dataset.tagFilterCard)', + ), + ); + static::assertSame( + [ + ['site:filter_change', 'examples', 'Read'], + ['site:filter_change', 'examples', 'CSV'], + ], + array_map(static fn(array $event): array => [ + $event['name'], + $event['properties']['hub'] ?? null, + $event['properties']['filter'] ?? null, + ], $this->capturedEvents($browser)), + ); + } +} diff --git a/web/landing/tests/Flow/Website/Tests/Functional/ExamplesSitemapTest.php b/web/landing/tests/Flow/Website/Tests/Functional/ExamplesSitemapTest.php new file mode 100644 index 0000000000..58f5f14ade --- /dev/null +++ b/web/landing/tests/Flow/Website/Tests/Functional/ExamplesSitemapTest.php @@ -0,0 +1,46 @@ +request('GET', '/sitemap.default.xml'); + + self::assertResponseIsSuccessful(); + static::assertStringContainsString( + '/examples/', + type_string()->assert($client->getResponse()->getContent()), + ); + } + + public function test_examples_sitemap_lists_every_built_page_and_no_root(): void + { + $client = self::createClient(); + $client->request('GET', '/sitemap.examples.xml'); + + self::assertResponseIsSuccessful(); + $sitemap = type_string()->assert($client->getResponse()->getContent()); + static::assertSame(120, substr_count($sitemap, '')); + static::assertStringContainsString('/transformations/array/expand/', $sitemap); + static::assertStringNotContainsString('/transformations/array/', $sitemap); + static::assertStringNotContainsString('/reading/', $sitemap); + } + + #[Override] + protected static function getKernelClass(): string + { + return Kernel::class; + } +} diff --git a/web/landing/tests/Flow/Website/Tests/Functional/GuideFilterTest.php b/web/landing/tests/Flow/Website/Tests/Functional/GuideFilterTest.php new file mode 100644 index 0000000000..8ece7f9db5 --- /dev/null +++ b/web/landing/tests/Flow/Website/Tests/Functional/GuideFilterTest.php @@ -0,0 +1,145 @@ + [...document.querySelectorAll("[data-tag-filter-card]")].filter((card) => card.offsetParent !== null).map((card) => card.dataset.tagFilterCard)'; + + public function test_an_open_menu_closes_on_escape_and_on_an_outside_click(): void + { + $browser = $this->playwrightBrowser(); + $browser->visit('/guides/'); + $page = $this->pageOf($browser); + $page->waitForSelector('[data-tag-filter-selected]'); + + $page->click('details:has([data-tag-filter-actions]):not([open]) > summary'); + $page->keyboard()->press('Escape'); + + static::assertSame(0, $page->evaluate('() => document.querySelectorAll("details[open]").length')); + + $page->click('details:has([data-tag-filter-actions]):not([open]) > summary'); + $page->click('h1'); + + static::assertSame(0, $page->evaluate('() => document.querySelectorAll("details[open]").length')); + } + + public function test_every_click_on_a_badge_reports_the_filter(): void + { + $this->recordPostHog($browser = $this->playwrightBrowser()); + $browser->visit('/guides/'); + $page = $this->pageOf($browser); + $page->waitForSelector('[data-tag-filter-selected]'); + + $page->click('details:has([data-tag-filter-actions]):not([open]) > summary'); + $page->click('[data-tag-filter-actions] button[data-tag-filter-tag-param="Read"]'); + $page->click('[data-tag-filter-card="read-large-csv-file-in-php"] button[data-tag-filter-tag-param="CSV"]'); + $page->click('details:has([data-tag-filter-actions]):not([open]) > summary'); + $page->click('[data-tag-filter-actions] button[data-tag-filter-tag-param="Read"]'); + + static::assertSame( + [ + [ + 'name' => 'site:filter_change', + 'properties' => [ + 'hub' => 'guides', + 'filter' => 'Read', + 'filter_kind' => 'action', + 'filter_selected' => true, + 'filter_source' => 'bar', + 'active_filters' => ['Read'], + 'items_shown' => 5, + ], + ], + [ + 'name' => 'site:filter_change', + 'properties' => [ + 'hub' => 'guides', + 'filter' => 'CSV', + 'filter_kind' => 'topic', + 'filter_selected' => true, + 'filter_source' => 'card', + 'active_filters' => ['Read', 'CSV'], + 'items_shown' => 1, + ], + ], + [ + 'name' => 'site:filter_change', + 'properties' => [ + 'hub' => 'guides', + 'filter' => 'Read', + 'filter_kind' => 'action', + 'filter_selected' => false, + 'filter_source' => 'bar', + 'active_filters' => ['CSV'], + 'items_shown' => 3, + ], + ], + ], + $this->capturedEvents($browser), + ); + } + + public function test_selected_tags_narrow_the_guides_and_a_second_click_brings_them_back(): void + { + $browser = $this->playwrightBrowser(); + $browser->visit('/guides/'); + $page = $this->pageOf($browser); + $page->waitForSelector('[data-tag-filter-selected]'); + + $page->click('details:has([data-tag-filter-bar]):not([open]) > summary'); + $page->click('[data-tag-filter-bar] button[data-tag-filter-tag-param="CSV"]'); + + static::assertSame( + [ + 'import-csv-file-into-mysql-or-postgresql-in-php', + 'read-large-csv-file-in-php', + 'stream-large-csv-download-in-symfony', + ], + $page->evaluate(self::VISIBLE_CARDS), + ); + static::assertTrue($page->evaluate( + '() => document.querySelector(\'[data-tag-filter-bar] button[data-tag-filter-tag-param="JSON"]\').disabled', + )); + static::assertFalse($page->evaluate( + '() => document.querySelector("[data-guide-featured]").offsetParent !== null', + )); + + $page->click( + '[data-tag-filter-card="stream-large-csv-download-in-symfony"] button[data-tag-filter-tag-param="Symfony"]', + ); + + static::assertSame(['stream-large-csv-download-in-symfony'], $page->evaluate(self::VISIBLE_CARDS)); + static::assertSame('#CSV,Symfony', $page->evaluate('() => window.location.hash')); + + $page->click('details:has([data-tag-filter-bar]):not([open]) > summary'); + $page->click('[data-tag-filter-bar] button[data-tag-filter-tag-param="CSV"]'); + $page->click('[data-tag-filter-bar] button[data-tag-filter-tag-param="Symfony"]'); + + static::assertTrue($page->evaluate( + '() => [...document.querySelectorAll("[data-tag-filter-card]")].every((card) => card.offsetParent !== null)', + )); + static::assertSame('', $page->evaluate('() => window.location.hash')); + } + + public function test_tags_from_the_address_are_selected_when_the_page_opens(): void + { + $browser = $this->playwrightBrowser(); + $browser->visit('/guides/#S3,Azure'); + $page = $this->pageOf($browser); + $page->waitForSelector('[data-tag-filter-selected][data-active]'); + + static::assertSame( + ['read-large-file-from-s3-in-php', 'upload-large-file-to-s3-in-php'], + $page->evaluate(self::VISIBLE_CARDS), + ); + + $page->click('details:has([data-tag-filter-actions]):not([open]) > summary'); + $page->click('[data-tag-filter-actions] button[data-tag-filter-tag-param="Write"]'); + + static::assertSame(['upload-large-file-to-s3-in-php'], $page->evaluate(self::VISIBLE_CARDS)); + static::assertSame('#S3,Azure,Write', $page->evaluate('() => window.location.hash')); + } +} diff --git a/web/landing/tests/Flow/Website/Tests/Functional/GuideReadingProgressTest.php b/web/landing/tests/Flow/Website/Tests/Functional/GuideReadingProgressTest.php new file mode 100644 index 0000000000..c341ad52d5 --- /dev/null +++ b/web/landing/tests/Flow/Website/Tests/Functional/GuideReadingProgressTest.php @@ -0,0 +1,39 @@ + { + const article = document.querySelector('[data-reading-progress-target="article"]'); + const top = article.getBoundingClientRect().top + window.scrollY; + + window.scrollTo({top: top + (article.offsetHeight - window.innerHeight) * position, behavior: 'instant'}); + await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); + + return Math.round( + parseFloat( + document + .querySelector('[data-reading-progress-target="bar"]') + .style.getPropertyValue('--reading-progress'), + ) * 100, + ); + } + JS; + + public function test_the_bar_follows_the_position_in_the_guide_and_not_in_the_page(): void + { + $browser = $this->playwrightBrowser(); + $browser->visit('/guides/read-large-csv-file-in-php/'); + $page = $this->pageOf($browser); + $page->waitForSelector('[data-reading-progress-target="bar"][aria-hidden="true"]', ['state' => 'attached']); + + static::assertSame(0, $page->evaluate(self::PROGRESS_AT, 0)); + static::assertSame(50, $page->evaluate(self::PROGRESS_AT, 0.5)); + static::assertSame(100, $page->evaluate(self::PROGRESS_AT, 1)); + static::assertSame(100, $page->evaluate(self::PROGRESS_AT, 1.2)); + } +} diff --git a/web/landing/tests/Flow/Website/Tests/Functional/GuidesControllerTest.php b/web/landing/tests/Flow/Website/Tests/Functional/GuidesControllerTest.php index fc74890e05..553145a440 100644 --- a/web/landing/tests/Flow/Website/Tests/Functional/GuidesControllerTest.php +++ b/web/landing/tests/Flow/Website/Tests/Functional/GuidesControllerTest.php @@ -38,6 +38,8 @@ public function test_guide_page(): void 'meta[property="og:image"][content="http://localhost/images/guides/social/read-large-csv-file-in-php.png"]', 'meta[name="twitter:image"][content="http://localhost/images/guides/social/read-large-csv-file-in-php.png"]', 'header nav a[href="/guides/"][aria-current="page"]', + '[data-guide-examples][data-ph-capture-attribute-link-location="guide_examples"]', + '[data-guide-related][data-ph-capture-attribute-link-location="guide_related"]', 'a[href="https://github.com/flow-php/flow/edit/1.x/web/landing/content/guides/read-large-csv-file-in-php.md"]', ] as $element) { static::assertCount(1, $crawler->filter($element), $element); @@ -49,14 +51,24 @@ public function test_guide_page(): void ); static::assertSame( [ + '/guides/read-large-file-from-s3-in-php/', '/guides/read-large-json-file-in-php/', - '/guides/export-database-to-excel-in-php/', - '/guides/import-csv-file-into-mysql-or-postgresql-in-php/', + '/guides/distributed-tracing-in-php/', ], $crawler ->filter('[data-guide-related] h3 a') ->each(static fn(Crawler $link): ?string => $link->attr('href')), ); + static::assertSame( + [ + '/guides/read-large-file-from-s3-in-php/', + '/guides/read-large-json-file-in-php/', + '/guides/distributed-tracing-in-php/', + ], + $crawler + ->filter('[data-guide-related] a[aria-label^="Read the guide: "]') + ->each(static fn(Crawler $link): ?string => $link->attr('href')), + ); static::assertSame( [ @@ -96,6 +108,33 @@ public function test_guide_page(): void ); } + public function test_guide_page_links_the_examples_it_uses(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/guides/read-large-csv-file-in-php/'); + + self::assertResponseIsSuccessful(); + static::assertSame( + [ + '/reading/csv/', + '/aggregations/group_by/group_by_sum/', + '/transformations/sort/', + '/writing/csv/', + '/reading/corrupted_records_routing/', + ], + $crawler->filter('[data-guide-examples] a')->each(static fn(Crawler $link): ?string => $link->attr('href')), + ); + } + + public function test_guide_page_without_examples_has_no_examples_block(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/guides/parse-sql-query-in-php/'); + + self::assertResponseIsSuccessful(); + static::assertCount(0, $crawler->filter('[data-guide-examples]')); + } + public function test_hub_lists_guides_by_group(): void { $client = self::createClient(); @@ -108,8 +147,21 @@ public function test_hub_lists_guides_by_group(): void ); static::assertSame('Data processing in PHP', $crawler->filter('main h1')->text()); static::assertSame( - ['Reading files', 'Writing files', 'Importing data', 'Search', 'SQL'], - $crawler->filter('main h2.uppercase')->each(static fn(Crawler $group): string => $group->text()), + ['Observe 12', 'Read 5', 'Import 3', 'Export 2', 'Write 2', 'Parse 1', 'Search 1'], + $crawler + ->filter('[data-tag-filter-actions] button') + ->each(static fn(Crawler $action): string => $action->text()), + ); + static::assertSame( + [ + 'distributed-tracing-in-php', + 'find-slow-doctrine-queries-in-symfony', + 'find-slow-phpunit-tests', + ], + $crawler + ->filter('[data-tag-filter-card]') + ->slice(0, 3) + ->each(static fn(Crawler $card): ?string => $card->attr('data-tag-filter-card')), ); static::assertSame( 'Import a CSV file into MySQL or PostgreSQL in PHP, with upsert', @@ -117,11 +169,11 @@ public function test_hub_lists_guides_by_group(): void ); static::assertSame( '624Mb 98Mb Sorting a million rows', - $crawler->filter('[data-guide-card="read-large-csv-file-in-php"] [data-guide-proof]')->text(), + $crawler->filter('[data-tag-filter-card="read-large-csv-file-in-php"] [data-guide-proof]')->text(), ); static::assertCount( 0, - $crawler->filter('[data-guide-card="import-data-from-rest-api-in-php"] [data-guide-proof]'), + $crawler->filter('[data-tag-filter-card="import-data-from-rest-api-in-php"] [data-guide-proof]'), ); static::assertSame( 'Read a large CSV file in PHP without running out of memory', diff --git a/web/landing/tests/Flow/Website/Tests/Functional/HomeControllerTest.php b/web/landing/tests/Flow/Website/Tests/Functional/HomeControllerTest.php index f7cfd6d6c7..cac8f0900b 100644 --- a/web/landing/tests/Flow/Website/Tests/Functional/HomeControllerTest.php +++ b/web/landing/tests/Flow/Website/Tests/Functional/HomeControllerTest.php @@ -91,6 +91,16 @@ public function test_homepage_topic_link_works(): void self::assertResponseIsSuccessful(); } + public function test_header_and_footer_link_to_the_examples_hub(): void + { + $client = self::createClient(); + $crawler = $client->request('GET', '/'); + + self::assertResponseIsSuccessful(); + static::assertGreaterThan(0, $crawler->filter('header a[href="/examples/"]')->count()); + static::assertGreaterThan(0, $crawler->filter('footer a[href="/examples/"]')->count()); + } + public function test_not_found_page_links_to_docs_examples_and_search(): void { $client = self::createClient(); @@ -98,7 +108,7 @@ public function test_not_found_page_links_to_docs_examples_and_search(): void self::assertResponseIsSuccessful(); static::assertGreaterThan(0, $crawler->filter('main a[href="/documentation/"]')->count()); - static::assertGreaterThan(0, $crawler->filter('main a[href^="/reading/array/"]')->count()); + static::assertGreaterThan(0, $crawler->filter('main a[href="/examples/"]')->count()); static::assertGreaterThan(0, $crawler->filter('main button[popovertarget="search-modal"]')->count()); static::assertCount(1, $crawler ->filter('script') diff --git a/web/landing/tests/Flow/Website/Tests/Functional/RedirectTargetsTest.php b/web/landing/tests/Flow/Website/Tests/Functional/RedirectTargetsTest.php new file mode 100644 index 0000000000..4972f6a34f --- /dev/null +++ b/web/landing/tests/Flow/Website/Tests/Functional/RedirectTargetsTest.php @@ -0,0 +1,116 @@ + $examples->meta($topic)->action, $examples->topics()); + $targets = array_map( + static fn(string $line): string => explode(',', $line, 2)[1], + array_slice(file(self::MAP, FILE_IGNORE_NEW_LINES) ?: [], 1), + ); + $fragments = array_map(static fn(string $target): string => rawurldecode( + explode('#', $target, 2)[1], + ), array_values(array_filter($targets, static fn(string $target): bool => str_contains($target, '#')))); + + static::assertNotSame([], $fragments); + static::assertSame( + [], + array_values(array_filter( + $fragments, + static fn(string $fragment): bool => !in_array($fragment, $actions, true), + )), + ); + } + + public function test_every_redirect_target_is_a_built_page(): void + { + $client = self::createClient(); + $built = []; + + foreach (['/sitemap.examples.xml', '/sitemap.default.xml', '/sitemap.guides.xml'] as $sitemap) { + $client->request('GET', $sitemap); + preg_match_all('#([^<]+)#', type_string()->assert($client->getResponse()->getContent()), $locs); + $built = [ + ...$built, + ...array_map(static fn(string $loc): string => (string) parse_url($loc, PHP_URL_PATH), $locs[1]), + ]; + } + + $paths = array_map( + static fn(string $line): string => explode('#', explode(',', $line, 2)[1], 2)[0], + array_slice(file(self::MAP, FILE_IGNORE_NEW_LINES) ?: [], 1), + ); + + static::assertSame( + [], + array_values(array_filter($paths, static fn(string $path): bool => !in_array($path, $built, true))), + ); + } + + public function test_sources_are_unique_and_not_built(): void + { + $client = self::createClient(); + $built = []; + + foreach (['/sitemap.examples.xml', '/sitemap.default.xml', '/sitemap.guides.xml'] as $sitemap) { + $client->request('GET', $sitemap); + preg_match_all('#([^<]+)#', type_string()->assert($client->getResponse()->getContent()), $locs); + $built = [ + ...$built, + ...array_map(static fn(string $loc): string => (string) parse_url($loc, PHP_URL_PATH), $locs[1]), + ]; + } + + $sources = array_map( + static fn(string $line): string => explode(',', $line, 2)[0], + array_slice(file(self::MAP, FILE_IGNORE_NEW_LINES) ?: [], 1), + ); + + static::assertSame( + [], + array_keys(array_filter(array_count_values($sources), static fn(int $count): bool => $count > 1)), + ); + static::assertSame([], array_values(array_intersect($sources, $built))); + } + + public function test_the_map_has_102_rows(): void + { + static::assertCount(102, array_slice(file(self::MAP, FILE_IGNORE_NEW_LINES) ?: [], 1)); + } + + #[Override] + protected static function getKernelClass(): string + { + return Kernel::class; + } +} diff --git a/web/landing/tests/Flow/Website/Tests/Integration/ExampleCorpusMetaTest.php b/web/landing/tests/Flow/Website/Tests/Integration/ExampleCorpusMetaTest.php index f8daef3b3c..79ff1d3a32 100644 --- a/web/landing/tests/Flow/Website/Tests/Integration/ExampleCorpusMetaTest.php +++ b/web/landing/tests/Flow/Website/Tests/Integration/ExampleCorpusMetaTest.php @@ -13,7 +13,13 @@ use RecursiveIteratorIterator; use SplFileInfo; +use function array_filter; +use function array_map; +use function array_unique; use function dirname; +use function file_exists; +use function glob; +use function iterator_to_array; use function mb_strlen; use function mb_substr; @@ -34,9 +40,99 @@ public static function example_directories(): Generator } } + /** + * @return Generator + */ + public static function example_folders(): Generator + { + foreach (self::topic_folders() as [$topic]) { + foreach (glob($topic . '/*', GLOB_ONLYDIR) ?: [] as $example) { + yield mb_substr($example, mb_strlen(dirname($topic)) + 1) => [$example]; + } + } + } + + /** + * @return Generator + */ + public static function option_folders(): Generator + { + foreach (self::example_folders() as $name => [$example]) { + if (file_exists($example . '/code.php')) { + continue; + } + + foreach (glob($example . '/*/code.php') ?: [] as $code) { + yield $name . '/' . mb_substr(dirname($code), mb_strlen($example) + 1) => [dirname($code)]; + } + } + } + + /** + * @return Generator + */ + public static function topic_folders(): Generator + { + $root = dirname(__DIR__, 5) . '/content/examples/topics'; + + foreach (glob($root . '/*', GLOB_ONLYDIR) ?: [] as $topic) { + yield mb_substr($topic, mb_strlen($root) + 1) => [$topic]; + } + } + + #[DataProvider('example_folders')] + public function test_every_example_has_title_and_summary(string $directory): void + { + $meta = ExampleMeta::fromDirectory($directory); + + static::assertNotNull($meta->title); + static::assertNotNull($meta->summary); + } + #[DataProvider('example_directories')] public function test_every_meta_file_in_the_corpus_is_valid(string $directory): void { static::assertNotSame(99, ExampleMeta::fromDirectory($directory)->priority); } + + #[DataProvider('option_folders')] + public function test_every_option_has_title_and_summary(string $directory): void + { + $meta = ExampleMeta::fromDirectory($directory); + + static::assertNotNull($meta->title); + static::assertNotNull($meta->summary); + } + + #[DataProvider('topic_folders')] + public function test_every_topic_has_an_action(string $directory): void + { + static::assertNotNull(ExampleMeta::fromDirectory($directory)->action); + } + + #[DataProvider('option_folders')] + public function test_options_have_no_tags(string $directory): void + { + static::assertSame([], ExampleMeta::fromDirectory($directory)->tags); + } + + public function test_summaries_are_unique(): void + { + $summaries = array_filter(array_map( + static fn(array $folder): ?string => ExampleMeta::fromDirectory($folder[0])->summary, + [...iterator_to_array(self::example_folders()), ...iterator_to_array(self::option_folders())], + )); + + static::assertSame($summaries, array_unique($summaries)); + } + + public function test_titles_are_unique(): void + { + $titles = array_filter(array_map( + static fn(array $folder): ?string => ExampleMeta::fromDirectory($folder[0])->title, + [...iterator_to_array(self::example_folders()), ...iterator_to_array(self::option_folders())], + )); + + static::assertSame($titles, array_unique($titles)); + } } diff --git a/web/landing/tests/Flow/Website/Tests/Integration/ExamplesTest.php b/web/landing/tests/Flow/Website/Tests/Integration/ExamplesTest.php index 70a432ec72..95fcbb9fdc 100644 --- a/web/landing/tests/Flow/Website/Tests/Integration/ExamplesTest.php +++ b/web/landing/tests/Flow/Website/Tests/Integration/ExamplesTest.php @@ -5,9 +5,12 @@ namespace Flow\Website\Tests\Integration; use Flow\Website\Service\Examples; +use Flow\Website\Service\Examples\ExampleNotFound; use PHPUnit\Framework\TestCase; use RuntimeException; +use function array_map; + final class ExamplesTest extends TestCase { public function test_description_merges_example_and_option_levels(): void @@ -112,8 +115,8 @@ public function test_throw_exception_when_example_code_does_not_exists(): void $path = __DIR__ . '/../Fixtures/InvalidCode'; $service = new Examples($path); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessageMatches('/Code example doesn\'t exists, it should be located in path: ".*"./'); + $this->expectException(ExampleNotFound::class); + $this->expectExceptionMessage('Example "topic_1/example_1" does not exist.'); $service->code('topic_1', 'example_1'); } @@ -123,10 +126,8 @@ public function test_throw_exception_when_topic_directory_does_not_exists(): voi $path = __DIR__ . '/../Fixtures/InvalidExample'; $service = new Examples($path); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessageMatches( - '/Topic "non_existing_topic" doesn\'t exists, it should be located in path: ".*"./', - ); + $this->expectException(ExampleNotFound::class); + $this->expectExceptionMessage('Topic "non_existing_topic" does not exist.'); $service->examples('non_existing_topic'); } @@ -144,6 +145,123 @@ public function test_throw_exception_when_topic_directory_is_empty(): void $service->examples('topic_1'); } + public function test_a_card_of_an_example_with_options_lists_its_variants(): void + { + $service = new Examples(__DIR__ . '/../Fixtures/WithDataFiles'); + + static::assertSame( + [ + 'topic' => 'data_topic', + 'example' => 'option_example', + 'route' => [ + 'name' => 'example_option', + 'arguments' => ['topic' => 'data_topic', 'example' => 'option_example', 'option' => 'option_1'], + ], + 'title' => 'Fixture example with options', + 'summary' => 'A fixture example with one option, used to test the variants of a card on the examples hub.', + 'actions' => ['Read'], + 'tags' => ['CSV'], + 'variants' => [ + [ + 'option' => 'option_1', + 'label' => null, + 'route' => [ + 'name' => 'example_option', + 'arguments' => [ + 'topic' => 'data_topic', + 'example' => 'option_example', + 'option' => 'option_1', + ], + ], + ], + ], + ], + $service->cards()[1], + ); + } + + public function test_cards_are_ordered_by_topic_then_example_priority(): void + { + $service = new Examples(__DIR__ . '/../Fixtures/Valid'); + + static::assertSame( + [ + ['topic_1', 'example_1', 'Read', 'Fixture topic 1 example 1'], + ['topic_1', 'example_2', 'Read', 'Fixture topic 1 example 2'], + ['topic_2', 'example_1', 'Write', 'Fixture topic 2 example 1'], + ['topic_2', 'example_2', 'Write', 'Fixture topic 2 example 2'], + ['topic_3', 'example_1', 'Join', 'Fixture topic 3 example 1'], + ], + array_map(static fn(array $card): array => [ + $card['topic'], + $card['example'], + $card['actions'][0], + $card['title'], + ], $service->cards()), + ); + static::assertSame( + ['name' => 'example', 'arguments' => ['topic' => 'topic_1', 'example' => 'example_1']], + $service->cards()[0]['route'], + ); + static::assertSame(['CSV'], $service->cards()[0]['tags']); + static::assertSame([], $service->cards()[0]['variants']); + } + + public function test_examples_navigation_carries_the_tags(): void + { + static::assertSame( + ['CSV'], + (new Examples(__DIR__ . '/../Fixtures/Valid'))->examplesNavigation('topic_1')['example_1']['tags'], + ); + } + + public function test_topics_navigation_carries_the_action_as_label_and_the_count_of_examples(): void + { + $topic = (new Examples(__DIR__ . '/../Fixtures/Valid'))->topicsNavigation()['topic_1']; + + static::assertSame('Read', $topic['label']); + static::assertSame(2, $topic['count']); + } + + public function test_navigation_and_card_variants_carry_the_label(): void + { + $service = new Examples(__DIR__ . '/../Fixtures/WithDataFiles'); + + static::assertSame('With options', $service->examplesNavigation('data_topic')['option_example']['label']); + static::assertNull($service->examplesNavigation('data_topic')['plain_example']['label']); + static::assertNull($service->optionsNavigation('data_topic', 'option_example')['option_1']['label']); + static::assertNull($service->cards()[1]['variants'][0]['label']); + } + + public function test_meta_of_an_unknown_example_throws(): void + { + $service = new Examples(__DIR__ . '/../Fixtures/Valid'); + + $this->expectException(ExampleNotFound::class); + $this->expectExceptionMessage('Example "topic_1/example_9" does not exist.'); + + $service->meta('topic_1', 'example_9'); + } + + public function test_meta_of_an_unknown_option_throws(): void + { + $service = new Examples(__DIR__ . '/../Fixtures/WithDataFiles'); + + $this->expectException(ExampleNotFound::class); + $this->expectExceptionMessage('Option "data_topic/option_example/missing" does not exist.'); + + $service->meta('data_topic', 'option_example', 'missing'); + } + + public function test_meta_reads_the_three_levels(): void + { + $service = new Examples(__DIR__ . '/../Fixtures/WithDataFiles'); + + static::assertSame('Read', $service->meta('data_topic')->action); + static::assertSame('Fixture example with options', $service->meta('data_topic', 'option_example')->title); + static::assertSame('Fixture option 1', $service->meta('data_topic', 'option_example', 'option_1')->title); + } + public function test_throw_exception_when_topics_directory_is_empty(): void { $path = __DIR__ . '/../Fixtures/InvalidTopic'; diff --git a/web/landing/tests/Flow/Website/Tests/Integration/GuideExamplesTest.php b/web/landing/tests/Flow/Website/Tests/Integration/GuideExamplesTest.php new file mode 100644 index 0000000000..6d35da629f --- /dev/null +++ b/web/landing/tests/Flow/Website/Tests/Integration/GuideExamplesTest.php @@ -0,0 +1,29 @@ +all() as $guide) { + foreach ($guide->examples() as $example) { + static::assertFileExists($root . '/examples/topics/' . $example . '/code.php', sprintf( + 'Guide "%s" lists the example "%s", which has no code.php.', + $guide->path, + $example, + )); + } + } + } +} diff --git a/web/landing/tests/Flow/Website/Tests/Integration/TagIconsTest.php b/web/landing/tests/Flow/Website/Tests/Integration/TagIconsTest.php new file mode 100644 index 0000000000..2871b5c17a --- /dev/null +++ b/web/landing/tests/Flow/Website/Tests/Integration/TagIconsTest.php @@ -0,0 +1,51 @@ +cards() as $card) { + foreach ($card['tags'] as $tag) { + $icon = str_replace(' ', '-', mb_strtolower($tag)) . '.svg'; + + if (!file_exists(dirname(__DIR__, 5) . '/templates/tag_icons/' . $icon)) { + $missing[$tag] = $icon; + } + } + } + + static::assertSame([], $missing); + } + + public function test_every_tag_used_by_guides_has_an_icon(): void + { + $missing = []; + + foreach ((new Pages(dirname(__DIR__, 5) . '/content/guides'))->all() as $guide) { + foreach ($guide->card()['tags'] as $tag) { + $icon = str_replace(' ', '-', mb_strtolower($tag)) . '.svg'; + + if (!file_exists(dirname(__DIR__, 5) . '/templates/tag_icons/' . $icon)) { + $missing[$tag] = $icon; + } + } + } + + static::assertSame([], $missing); + } +} diff --git a/web/landing/tests/Flow/Website/Tests/Unit/Model/Documentation/PageTest.php b/web/landing/tests/Flow/Website/Tests/Unit/Model/Documentation/PageTest.php index e051bb23ca..e299d2e9f4 100644 --- a/web/landing/tests/Flow/Website/Tests/Unit/Model/Documentation/PageTest.php +++ b/web/landing/tests/Flow/Website/Tests/Unit/Model/Documentation/PageTest.php @@ -26,7 +26,7 @@ public function test_guide_card_front_matter(): void { $guide = new Page( 'x', - "---\nproblem: One INSERT per row takes minutes\nproof_label: 100,000 rows\nproof_before: 264s\nproof_after: 2.3s\nfeatured: true\n---\n# T\n", + "---\nproblem: One INSERT per row takes minutes\nproof_label: 100,000 rows\nproof_before: 264s\nproof_after: 2.3s\nfeatured: true\ntags: [CSV, PostgreSQL]\nactions: [Import]\n---\n# T\n", ); static::assertSame( @@ -36,6 +36,8 @@ public function test_guide_card_front_matter(): void 'proof_before' => '264s', 'proof_after' => '2.3s', 'featured' => true, + 'tags' => ['CSV', 'PostgreSQL'], + 'actions' => ['Import'], ], $guide->card(), ); @@ -50,11 +52,26 @@ public function test_guide_card_front_matter_is_optional(): void 'proof_before' => null, 'proof_after' => null, 'featured' => false, + 'tags' => [], + 'actions' => [], ], (new Page('x', "---\nseo_title: T\n---\n# T\n"))->card(), ); } + public function test_guide_examples_front_matter(): void + { + static::assertSame( + ['reading/csv', 'reading/dbal/key_set'], + (new Page('x', "---\nexamples: [reading/csv, reading/dbal/key_set]\n---\n# T\n"))->examples(), + ); + } + + public function test_guide_examples_front_matter_is_optional(): void + { + static::assertSame([], (new Page('x', "---\nseo_title: T\n---\n# T\n"))->examples()); + } + public function test_missing_guide_front_matter_fails(): void { $this->expectException(InvalidTypeException::class); diff --git a/web/landing/tests/Flow/Website/Tests/Unit/Model/TagCountsTest.php b/web/landing/tests/Flow/Website/Tests/Unit/Model/TagCountsTest.php new file mode 100644 index 0000000000..38f8618345 --- /dev/null +++ b/web/landing/tests/Flow/Website/Tests/Unit/Model/TagCountsTest.php @@ -0,0 +1,41 @@ + ['Read'], 'tags' => []], + ['actions' => ['Write'], 'tags' => []], + ['actions' => ['Read'], 'tags' => []], + ['actions' => ['Join'], 'tags' => []], + ]); + + static::assertSame(['Read' => 2, 'Join' => 1, 'Write' => 1], $counts->actions()); + } + + public function test_no_cards_give_no_counts(): void + { + $counts = TagCounts::fromCards([]); + + static::assertSame([], $counts->actions()); + static::assertSame([], $counts->tags()); + } + + public function test_tags_are_counted_and_sorted_by_name(): void + { + $counts = TagCounts::fromCards([ + ['actions' => [], 'tags' => ['CSV', 'JSON']], + ['actions' => [], 'tags' => ['CSV']], + ]); + + static::assertSame(['CSV' => 2, 'JSON' => 1], $counts->tags()); + } +} diff --git a/web/landing/tests/Flow/Website/Tests/Unit/Service/Examples/ExampleMetaTest.php b/web/landing/tests/Flow/Website/Tests/Unit/Service/Examples/ExampleMetaTest.php index c0db640430..05406799b9 100644 --- a/web/landing/tests/Flow/Website/Tests/Unit/Service/Examples/ExampleMetaTest.php +++ b/web/landing/tests/Flow/Website/Tests/Unit/Service/Examples/ExampleMetaTest.php @@ -7,8 +7,11 @@ use Flow\Website\Service\Examples\ExampleMeta; use Flow\Website\Service\Examples\InvalidExampleMetaException; use Flow\Website\Tests\Context\ExampleMetaContext; +use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\TestCase; +use function str_repeat; + final class ExampleMetaTest extends TestCase { private ExampleMetaContext $meta; @@ -116,4 +119,122 @@ public function test_the_root_must_be_a_map(): void $this->meta->parse("just a string\n"); } + + public function test_action_title_summary_and_tags_are_read(): void + { + $summary = str_repeat('s', 70); + + $meta = $this->meta->parse( + "priority: 3\naction: Read\ntitle: Read a CSV file\nsummary: {$summary}\ntags: [CSV, Local]\n", + ); + + static::assertSame('Read', $meta->action); + static::assertSame('Read a CSV file', $meta->title); + static::assertSame($summary, $meta->summary); + static::assertSame(['CSV', 'Local'], $meta->tags); + } + + public function test_meta_without_the_new_keys_has_null_texts_and_no_tags(): void + { + $meta = $this->meta->parse("priority: 3\n"); + + static::assertNull($meta->action); + static::assertNull($meta->title); + static::assertNull($meta->summary); + static::assertSame([], $meta->tags); + } + + public function test_a_title_longer_than_60_characters_is_a_hard_failure(): void + { + $title = str_repeat("\u{0105}", 60); + + static::assertSame($title, $this->meta->parse("priority: 3\ntitle: {$title}\n")->title); + + $this->expectException(InvalidExampleMetaException::class); + $this->expectExceptionMessageMatches('/"title" must be a non-empty string of at most 60 characters/'); + + $this->meta->parse("priority: 3\ntitle: " . str_repeat('a', 61) . "\n"); + } + + public function test_an_empty_title_is_a_hard_failure(): void + { + $this->expectException(InvalidExampleMetaException::class); + $this->expectExceptionMessageMatches('/"title" must be a non-empty string of at most 60 characters/'); + + $this->meta->parse("priority: 3\ntitle: \"\"\n"); + } + + public function test_a_summary_shorter_than_70_characters_is_a_hard_failure(): void + { + $this->expectException(InvalidExampleMetaException::class); + $this->expectExceptionMessageMatches('/"summary" must be a string of 70 to 155 characters/'); + + $this->meta->parse("priority: 3\nsummary: " . str_repeat('s', 69) . "\n"); + } + + public function test_a_summary_longer_than_155_characters_is_a_hard_failure(): void + { + static::assertSame( + str_repeat('s', 155), + $this->meta->parse("priority: 3\nsummary: " . str_repeat('s', 155) . "\n")->summary, + ); + + $this->expectException(InvalidExampleMetaException::class); + $this->expectExceptionMessageMatches('/"summary" must be a string of 70 to 155 characters/'); + + $this->meta->parse("priority: 3\nsummary: " . str_repeat('s', 156) . "\n"); + } + + public function test_an_action_longer_than_20_characters_is_a_hard_failure(): void + { + $this->expectException(InvalidExampleMetaException::class); + $this->expectExceptionMessageMatches('/"action" must be a non-empty string of at most 20 characters/'); + + $this->meta->parse("priority: 3\naction: " . str_repeat('a', 21) . "\n"); + } + + public function test_label_is_read(): void + { + static::assertSame('DBAL', $this->meta->parse("priority: 3\nlabel: DBAL\n")->label); + static::assertNull($this->meta->parse("priority: 3\n")->label); + } + + public function test_a_label_longer_than_30_characters_is_a_hard_failure(): void + { + static::assertSame( + str_repeat('l', 30), + $this->meta->parse("priority: 3\nlabel: " . str_repeat('l', 30) . "\n")->label, + ); + + $this->expectException(InvalidExampleMetaException::class); + $this->expectExceptionMessageMatches('/"label" must be a non-empty string of at most 30 characters/'); + + $this->meta->parse("priority: 3\nlabel: " . str_repeat('l', 31) . "\n"); + } + + public function test_an_empty_label_is_a_hard_failure(): void + { + $this->expectException(InvalidExampleMetaException::class); + $this->expectExceptionMessageMatches('/"label" must be a non-empty string of at most 30 characters/'); + + $this->meta->parse("priority: 3\nlabel: ' '\n"); + } + + #[TestWith(["priority: 3\ntags: CSV\n"])] + #[TestWith(["priority: 3\ntags: [1]\n"])] + public function test_tags_must_be_a_list_of_strings(string $yaml): void + { + $this->expectException(InvalidExampleMetaException::class); + $this->expectExceptionMessageMatches('/"tags" must be a list of distinct non-empty strings/'); + + $this->meta->parse($yaml); + } + + public function test_duplicate_tags_are_a_hard_failure(): void + { + $this->expectException(InvalidExampleMetaException::class); + $this->expectExceptionMessageMatches('/"tags" must be a list of distinct non-empty strings/'); + + $this->meta->parse("priority: 3\ntags: [CSV, CSV]\n"); + } }