random() public method

Get one or more items randomly from the collection.
public random ( integer $amount = 1 ) : mixed
$amount integer
return mixed
Example #1
0
 /**
  * Get either the predefined (subset of) collection/model, or.
  * @return Collection|mixed|BaseModel
  */
 private function getPredefinedOrMocks()
 {
     if ($this->entityCount > 1) {
         $collection = new Collection();
         if ($this->predefinedEntities) {
             if ($this->predefinedEntities instanceof Collection) {
                 $collection = $collection->merge($this->predefinedEntities->random($this->entityCount));
             } else {
                 $collection->push($this->predefinedEntities);
             }
         }
         if ($collection->count() < $this->entityCount) {
             /** @var Collection $collection */
             $collection = $collection->merge($this->getModelMock($this->entityCount - $collection->count()));
         }
         return $collection;
     } else {
         if ($this->predefinedEntities) {
             if ($this->predefinedEntities instanceof Collection) {
                 return $this->predefinedEntities->random();
             } else {
                 return $this->predefinedEntities;
             }
         }
         return $this->getModelMock();
     }
 }
Example #2
0
 /**
  * @expectedException InvalidArgumentException
  */
 public function testRandomThrowsAnExceptionUsingAmountBiggerThanCollectionSize()
 {
     $data = new Collection([1, 2, 3]);
     $data->random(4);
 }
Example #3
0
 public function selectBanner()
 {
     $banners = new IlluminateCollection(['banners/parlamentares/bg_fotos01.jpg', 'banners/parlamentares/bg_fotos02.jpg', 'banners/parlamentares/bg_fotos03.jpg', 'banners/parlamentares/bg_fotos04.jpg', 'banners/parlamentares/bg_fotos05.jpg', 'banners/parlamentares/bg_fotos06.jpg', 'banners/parlamentares/bg_fotos07.jpg', 'banners/parlamentares/bg_fotos08.jpg', 'banners/parlamentares/bg_fotos09.jpg', 'banners/parlamentares/bg_fotos10.jpg']);
     $usedBanners = Session::get('used_banners') ?: [];
     if (count($usedBanners) >= $banners->count()) {
         $usedBanners = [];
     }
     $usedBanners = new IlluminateCollection($usedBanners);
     while (true) {
         $banner = $banners->random();
         if (!$usedBanners->contains($banner)) {
             break;
         }
     }
     $usedBanners->put(null, $banner);
     Session::put('used_banners', $usedBanners->toArray());
     return $banner;
 }