Files
chill-bundles/src/Bundle/ChillPersonBundle/DataFixtures/Helper/PersonRandomHelper.php
2021-12-21 10:59:23 +01:00

52 lines
1.3 KiB
PHP

<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\PersonBundle\DataFixtures\Helper;
use Chill\PersonBundle\Entity\Person;
use Doctrine\ORM\EntityManagerInterface;
use function array_pop;
use function random_int;
trait PersonRandomHelper
{
private ?int $countPersons = null;
private array $randPersons = [];
protected function getRandomPerson(EntityManagerInterface $em): Person
{
$fetchBy = 5;
if (null === $this->countPersons) {
$qb = $em->createQueryBuilder();
$this->countPersons = $qb->select('count(p)')
->from(Person::class, 'p')
->getQuery()
->getSingleScalarResult();
}
if ([] === $this->randPersons) {
$qb = $em->createQueryBuilder();
$this->randPersons = $qb
->select('p')
->from(Person::class, 'p')
->getQuery()
->setFirstResult(random_int(0, $this->countPersons - $fetchBy))
->setMaxResults($fetchBy)
->getResult();
}
return array_pop($this->randPersons);
}
}