vendor/contao-bootstrap/grid/src/GridProvider.php line 73

Open in your IDE?
  1. <?php
  2. /**
  3.  * Contao Bootstrap grid.
  4.  *
  5.  * @filesource
  6.  */
  7. declare(strict_types=1);
  8. namespace ContaoBootstrap\Grid;
  9. use ContaoBootstrap\Grid\Definition\Grid;
  10. use InvalidArgumentException;
  11. use RuntimeException;
  12. /**
  13.  * GridProvider is the main entry point to get grids or grid iterators.
  14.  */
  15. final class GridProvider
  16. {
  17.     /**
  18.      * Grid builder.
  19.      */
  20.     private GridBuilder $builder;
  21.     /**
  22.      * Map of created grids.
  23.      *
  24.      * @var array<int,Grid>
  25.      */
  26.     private array $grids = [];
  27.     /**
  28.      * Map of grid iterators.
  29.      *
  30.      * @var array<string,GridIterator>
  31.      */
  32.     private array $iterators = [];
  33.     /**
  34.      * @param GridBuilder $builder The grid builder.
  35.      */
  36.     public function __construct(GridBuilder $builder)
  37.     {
  38.         $this->builder $builder;
  39.     }
  40.     /**
  41.      * Get a grid.
  42.      *
  43.      * @param int $gridId Grid id.
  44.      *
  45.      * @throws RuntimeException When grid could not be build.
  46.      */
  47.     public function getGrid(int $gridId): Grid
  48.     {
  49.         if (! isset($this->grids[$gridId])) {
  50.             $this->grids[$gridId] = $this->builder->build($gridId);
  51.         }
  52.         return $this->grids[$gridId];
  53.     }
  54.     /**
  55.      * Get the grid iterator.
  56.      *
  57.      * @param string   $uniqueId Unique id to reference a grid iterator.
  58.      * @param int|null $gridId   The grid id.
  59.      *
  60.      * @throws RuntimeException When grid could not be build.
  61.      */
  62.     public function getIterator(string $uniqueId, ?int $gridId null): GridIterator
  63.     {
  64.         if (! isset($this->iterators[$uniqueId])) {
  65.             if ($gridId === null) {
  66.                 throw new InvalidArgumentException('GridId required if iterator does not yet exist');
  67.             }
  68.             $grid     $this->getGrid($gridId);
  69.             $iterator = new GridIterator($grid);
  70.             $this->iterators[$uniqueId] = $iterator;
  71.         }
  72.         return $this->iterators[$uniqueId];
  73.     }
  74. }