From 4237041eb997f0d0a9b23212526b93ba02e0fe24 Mon Sep 17 00:00:00 2001 From: Norbert Orzechowicz Date: Wed, 18 Nov 2026 12:24:54 -0600 Subject: [PATCH 1/7] feat(flow-php/web): guides section with the first guide - /guides hub and guide pages with article structured data - guide: read a large csv file in php without running out of memory - every php block of a guide runs in the playground in tests - header no longer overflows at 1024 and 1280 px --- web/landing/config/services.yaml | 5 + .../guides/read-large-csv-file-in-php.md | 285 ++++++++++++++++++ .../Website/Controller/GuidesController.php | 53 ++++ .../EventListener/SitemapSubscriber.php | 21 ++ .../Flow/Website/Model/Documentation/Page.php | 15 + .../StaticSourceProvider/GuidesProvider.php | 29 ++ web/landing/templates/guides/guide.html.twig | 65 ++++ web/landing/templates/guides/index.html.twig | 75 +++++ .../templates/partials/footer.html.twig | 1 + .../templates/partials/header.html.twig | 12 +- .../Tests/Functional/GuidesCodeTest.php | 68 +++++ .../Tests/Functional/GuidesControllerTest.php | 124 ++++++++ .../Tests/Functional/HomeControllerTest.php | 3 + .../Tests/Integration/GuidesProviderTest.php | 23 ++ .../Unit/Model/Documentation/PageTest.php | 31 ++ 15 files changed, 805 insertions(+), 5 deletions(-) create mode 100644 web/landing/content/guides/read-large-csv-file-in-php.md create mode 100644 web/landing/src/Flow/Website/Controller/GuidesController.php create mode 100644 web/landing/src/Flow/Website/StaticSourceProvider/GuidesProvider.php create mode 100644 web/landing/templates/guides/guide.html.twig create mode 100644 web/landing/templates/guides/index.html.twig create mode 100644 web/landing/tests/Flow/Website/Tests/Functional/GuidesCodeTest.php create mode 100644 web/landing/tests/Flow/Website/Tests/Functional/GuidesControllerTest.php create mode 100644 web/landing/tests/Flow/Website/Tests/Integration/GuidesProviderTest.php create mode 100644 web/landing/tests/Flow/Website/Tests/Unit/Model/Documentation/PageTest.php diff --git a/web/landing/config/services.yaml b/web/landing/config/services.yaml index 413f899b61..747d31f29e 100644 --- a/web/landing/config/services.yaml +++ b/web/landing/config/services.yaml @@ -78,6 +78,11 @@ services: arguments: $basePath: '%documentation_base_path%' + guides.pages: + class: Flow\Website\Service\Documentation\Pages + arguments: + $basePath: '%kernel.project_dir%/content/guides' + Flow\Website\Twig\: resource: '../src/Flow/Website/Twig/**/*Extension.php' tags: [twig.extension] 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 new file mode 100644 index 0000000000..37a6518c01 --- /dev/null +++ b/web/landing/content/guides/read-large-csv-file-in-php.md @@ -0,0 +1,285 @@ +--- +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.' +group: Reading files +published: '2026-11-18' +updated: '2026-11-18' +--- + +# Read a large CSV file in PHP without running out of memory + +Let's say we got an export of orders: one CSV file, a million rows, 62Mb. +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? + +## The file + +First we need a file to work with, so let's generate one. +Set `$rows` to `1_000_000` to get the 62Mb version. + +```php + $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 output +GB 10030.00 +FR 10010.00 +DE 9990.00 +US 9970.00 +PL 9950.00 +``` + +With a thousand rows it works. With a million rows it ends like this: + +```text +Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 16777224 bytes) +``` + +`file()` keeps every line in memory at the same time. For our file that is 172Mb, and we have 128Mb. +We could raise `memory_limit`, but that only moves the problem to the next, bigger file. + +## 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. + +## Now sort it + +OK, but the next request comes the same day: the same file, sorted by amount, the biggest orders first. + +We can't sort a file one row at a time. To sort the rows we need all of them, so we are back to keeping the whole file in memory. + +```php + (float) $right['amount'] <=> (float) $left['amount']); + +$sorted = fopen(__DIR__ . '/orders-sorted.csv', 'w'); +fputcsv($sorted, $header, escape: ''); + +foreach ($orders as $order) { + fputcsv($sorted, $order, escape: ''); +} + +fclose($sorted); + +foreach (array_slice($orders, 0, 3) as $order) { + printf("%s %s %s\n", $order['id'], $order['email'], $order['amount']); +} +``` + +```text output +999 customer999@example.com 99.90 +998 customer998@example.com 99.80 +997 customer997@example.com 99.70 +``` + +With a thousand rows it works. With a million rows we are back where we started: + +```text +Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32768 bytes) +``` + +This time `fgetcsv` doesn't help. The script needs 624Mb for a 62Mb file, ten times its size, and it grows with every row. +To do it right we would have to cut the file into sorted chunks on disk and merge them back. That's a lot of code for "sort a file". + +## The same thing with Flow + +Flow needs PHP 8.3 or newer. + +```bash +composer require flow-php/etl flow-php/etl-adapter-csv +``` + +```php +read(from_csv(__DIR__ . '/orders.csv')) + ->sortBy(ref('amount')->desc()) + ->write(to_csv(__DIR__ . '/orders-sorted.csv')->saveMode(overwrite())) + ->run(); + +data_frame() + ->read(from_csv(__DIR__ . '/orders-sorted.csv')) + ->select('id', 'email', 'amount') + ->limit(3) + ->write(to_output(truncate: false)) + ->run(); +``` + +```text output ++-----+-------------------------+-----------+ +| id | email | amount | ++-----+-------------------------+-----------+ +| 999 | customer999@example.com | 99.900000 | +| 998 | customer998@example.com | 99.800000 | +| 997 | customer997@example.com | 99.700000 | ++-----+-------------------------+-----------+ +3 rows +``` + +[`from_csv`](/documentation/dsl/csv/from-csv) reads the file row by row, detects the separator and the type of every column, so `amount` is already a float. +[`sortBy`](/documentation/components/core/sort) keeps as many rows in memory as the limit allows and moves the rest to disk, so the script never needs more than it has. +The second pipeline is there only to show us the first three rows of the result. + +The revenue report from the beginning is the same shape: + +```php +read(from_csv(__DIR__ . '/orders.csv')) + ->groupBy([ref('country')]) + ->aggregate(sum(ref('amount'))) + ->sortBy(ref('amount_sum')->desc()) + ->write(to_output(truncate: false)) + ->run(); +``` + +```text output ++---------+--------------+ +| country | amount_sum | ++---------+--------------+ +| GB | 10030.000000 | +| FR | 10010.000000 | +| DE | 9990.000000 | +| US | 9970.000000 | +| PL | 9950.000000 | ++---------+--------------+ +5 rows +``` + +## How much memory does a large CSV file take in PHP + +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 | - | +| Sort by amount | Flow | 98Mb | 7.4s | +| Sort by amount | Flow with the `flow_php` extension | 18Mb | 1.0s | + +The numbers that matter are the ones that don't change. With three million rows and a 189Mb file the plain sort needs 1942Mb, and Flow still takes 97Mb, or 20Mb with the extension. + +[flow_php](/documentation/components/extensions/flow-php-ext) is an optional PHP extension. The scripts stay the same, without a single change. + +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/src/Flow/Website/Controller/GuidesController.php b/web/landing/src/Flow/Website/Controller/GuidesController.php new file mode 100644 index 0000000000..8133b7f2cb --- /dev/null +++ b/web/landing/src/Flow/Website/Controller/GuidesController.php @@ -0,0 +1,53 @@ +guides->get($slug); + } catch (RuntimeException) { + throw $this->createNotFoundException(); + } + + return $this->render('guides/guide.html.twig', ['guide' => $guide, 'slug' => $slug]); + } + + #[Route('/guides', name: 'guides', options: ['sitemap' => true])] + public function index(): Response + { + $groups = []; + + foreach ($this->guides->all() as $guide) { + $groups[$guide->group()][$guide->path] = $guide; + } + + ksort($groups); + + foreach (array_keys($groups) as $group) { + ksort($groups[$group]); + } + + return $this->render('guides/index.html.twig', ['groups' => $groups]); + } +} diff --git a/web/landing/src/Flow/Website/EventListener/SitemapSubscriber.php b/web/landing/src/Flow/Website/EventListener/SitemapSubscriber.php index a8f4b627e1..b84516e994 100644 --- a/web/landing/src/Flow/Website/EventListener/SitemapSubscriber.php +++ b/web/landing/src/Flow/Website/EventListener/SitemapSubscriber.php @@ -10,6 +10,7 @@ use Flow\Website\Service\Examples; use Presta\SitemapBundle\Event\SitemapPopulateEvent; use Presta\SitemapBundle\Sitemap\Url\UrlConcrete; +use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; @@ -22,6 +23,8 @@ public function __construct( private Posts $posts, private DSLDefinitions $dslDefinitions, private Pages $pages, + #[Autowire(service: 'guides.pages')] + private Pages $guides, ) {} public static function getSubscribedEvents() @@ -36,6 +39,7 @@ public function populate(SitemapPopulateEvent $event): void $this->populateExamples($event); $this->populateBlogPosts($event); $this->populateDocumentation($event); + $this->populateGuides($event); } private function populateBlogPosts(SitemapPopulateEvent $event): void @@ -138,4 +142,21 @@ private function populateExamples(SitemapPopulateEvent $event): void } } } + + private function populateGuides(SitemapPopulateEvent $event): void + { + foreach ($this->guides->all() as $guide) { + $event->getUrlContainer()->addUrl( + new UrlConcrete( + $event->getUrlGenerator()->generate( + 'guides_guide', + ['slug' => $guide->path], + UrlGeneratorInterface::ABSOLUTE_URL, + ), + changefreq: 'weekly', + ), + 'guides', + ); + } + } } diff --git a/web/landing/src/Flow/Website/Model/Documentation/Page.php b/web/landing/src/Flow/Website/Model/Documentation/Page.php index 92f60edf2b..2259e9fd89 100644 --- a/web/landing/src/Flow/Website/Model/Documentation/Page.php +++ b/web/landing/src/Flow/Website/Model/Documentation/Page.php @@ -34,6 +34,11 @@ public function editOnGitHubUrl(): string return 'https://github.com/flow-php/flow/edit/1.x/documentation/' . ltrim($this->path, '/'); } + public function group(): string + { + return type_string()->assert($this->frontMatter()['group'] ?? null); + } + public function package(): ?string { $frontMatter = $this->frontMatter(); @@ -41,6 +46,11 @@ public function package(): ?string return type_union(type_string(), type_null())->assert($frontMatter['package'] ?? null); } + public function published(): string + { + return type_string()->assert($this->frontMatter()['published'] ?? null); + } + public function title(): ?string { $frontMatter = $this->frontMatter(); @@ -48,6 +58,11 @@ public function title(): ?string return type_union(type_string(), type_null())->assert($frontMatter['seo_title'] ?? null) ?? 'Documentation'; } + public function updated(): string + { + return type_string()->assert($this->frontMatter()['updated'] ?? null); + } + /** * @return array */ diff --git a/web/landing/src/Flow/Website/StaticSourceProvider/GuidesProvider.php b/web/landing/src/Flow/Website/StaticSourceProvider/GuidesProvider.php new file mode 100644 index 0000000000..2d41875f2a --- /dev/null +++ b/web/landing/src/Flow/Website/StaticSourceProvider/GuidesProvider.php @@ -0,0 +1,29 @@ +guides->all() as $guide) { + $sources[] = new Source('guides_guide', ['slug' => $guide->path]); + } + + return $sources; + } +} diff --git a/web/landing/templates/guides/guide.html.twig b/web/landing/templates/guides/guide.html.twig new file mode 100644 index 0000000000..1b55f05941 --- /dev/null +++ b/web/landing/templates/guides/guide.html.twig @@ -0,0 +1,65 @@ +{% extends 'base.html.twig' %} + +{%- block title -%} + {{ guide.title }} | Flow PHP +{%- endblock -%} + +{%- block description -%} + {{ guide.description }} +{%- endblock -%} + +{%- block og_type -%}article{%- endblock -%} + +{%- block hero -%}{%- endblock -%} + +{%- block contributors -%}{%- endblock -%} + +{% block main %} +
+ + +

+ Last updated +

+ +
+ + + {{ guide.content|markdown_to_html }} +
+ +

+ Found a typo or an outdated section? + + Edit this guide on GitHub + +

+
+ + +{% endblock %} diff --git a/web/landing/templates/guides/index.html.twig b/web/landing/templates/guides/index.html.twig new file mode 100644 index 0000000000..b1de1f63de --- /dev/null +++ b/web/landing/templates/guides/index.html.twig @@ -0,0 +1,75 @@ +{% extends 'base.html.twig' %} + +{%- block title -%} + Guides | Flow PHP +{%- endblock -%} + +{%- block description -%} + Real data problems in PHP, one per page, with code that runs: large CSV files, imports, exports and memory errors. +{%- endblock -%} + +{%- block hero -%}{%- endblock -%} + +{% block main %} +
+
+
+ + + Guides + +

Data processing in PHP

+

+ One problem per page, with code that runs. + Each guide shows the plain PHP way first, then the same thing with Flow. +

+
+ +
    +
  • + + Every script runs in the playground +
  • +
  • + + Plain PHP first, then Flow +
  • +
  • + + Memory and time, measured +
  • +
+
+ + {% for group, guides in groups %} +
+

{{ group }}

+ + {{ guides|length }} +
+ +
+ {% for slug, guide in guides %} + {% set guideUrl = path('guides_guide', {slug: slug}) %} + + {% endfor %} +
+ {% endfor %} +
+{% endblock %} diff --git a/web/landing/templates/partials/footer.html.twig b/web/landing/templates/partials/footer.html.twig index 11c331aed7..9ba41db159 100644 --- a/web/landing/templates/partials/footer.html.twig +++ b/web/landing/templates/partials/footer.html.twig @@ -15,6 +15,7 @@

Product