Filtrage d'une collection Doctrine

Publié le 19/03/2022 • Actualisé le 19/03/2022


English language detected! 🇬🇧

  We noticed that your browser is using English. Do you want to read this post in this language?

Read the english version 🇬🇧 Close

Dans ce bout de code, nous voyons comment filtrer une collection Doctrine. On dispose donc de cette fonction filter() qu'on peut apeller avec une fonction anonyme. Ici, j'utilise une fonction fléchée afin de garder le code concis et visible, juste en dessous on obtient le même résulat en utilisant la fonction array_fitler().


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use App\Data\ArticleData;
use App\Entity\Tag;

/**
 * J'utilise un trait PHP afin d'isoler chaque snippet dans un fichier.
 * Ce code doit être apellé d'un contrôleur Symfony étendant AbstractController (depuis Symfony 4.2)
 * ou Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Les services sont injectés dans le constructeur du contrôleur principal.
 *
 * @property ArticleData $articleData
 */
trait Snippet194Trait
{
    public function snippet194(): void
    {
        $snippet = $this->articleData->getSnippetById(194); // this snippet
        $tags = $snippet->getTags();

        echo sprintf('There is %d tags associated to the snippet.', $tags->count()).PHP_EOL;

        // now filter tags starting by "array"
        $filtered = $tags->filter(static fn (Tag $tag) => str_starts_with((string) $tag->getName(), 'array'));
        echo sprintf('There is %d tag(s) starting with "array".', $filtered->count()).PHP_EOL;

        // with array_filter()
        $filtered2 = array_filter($tags->toArray(), static fn (Tag $tag) => str_starts_with((string) $tag->getName(), 'array'));
        echo sprintf('There is %d tag(s) starting with "array".', \count($filtered2));

        // That's it! 😁
    }
}

 Exécuter le snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  Plus sur Stackoverflow   Lire la doc  Snippet aléatoire

  Travaillez avec moi !

<?php

declare(strict_types=1);

namespace App\Tests\Integration\Controller\Snippets;

use App\Data\ArticleData;
use App\Entity\Tag;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @see Snippet194Trait
 */
final class Snippet194Test extends KernelTestCase
{
    private ArticleData $articleData;

    protected function setUp(): void
    {
        $this->articleData = self::getContainer()->get(ArticleData::class);
    }

    /**
     * @see Snippet194Trait::snippet194
     */
    public function testSnippet194(): void
    {
        $snippet = $this->articleData->getSnippetById(194);
        $tags = $snippet->getTags();
        self::assertCount(6, $tags);
        $filtered = $tags->filter(static fn (Tag $tag) => str_starts_with((string) $tag->getName(), 'array'));
        self::assertCount(2, $filtered);
        $filtered2 = array_filter($tags->toArray(), static fn (Tag $tag) => str_starts_with((string) $tag->getName(), 'array'));
        self::assertCount(2, $filtered2);
        /** @var Tag $tag */
        $tag = $filtered->first();
        self::assertTrue(str_starts_with((string) $tag->getName(), 'array'));
    }
}