Upgrade to 3.6.6

This commit is contained in:
Bastian Allgeier
2022-05-05 13:58:33 +02:00
parent 5c64df9e2b
commit d515908e2e
12 changed files with 190 additions and 24 deletions

View File

@@ -335,6 +335,29 @@ class A
return array_pop($array);
}
/**
* Returns a number of random elements from an array,
* either in original or shuffled order
*
* @param array $array
* @param int $count
* @param bool $shuffle
* @return array
*/
public static function random(array $array, int $count = 1, bool $shuffle = false): array
{
if ($shuffle) {
return array_slice(self::shuffle($array), 0, $count);
}
if ($count === 1) {
$key = array_rand($array);
return [$key => $array[$key]];
}
return self::get($array, array_rand($array, $count));
}
/**
* Fills an array up with additional elements to certain amount.
*

View File

@@ -870,6 +870,25 @@ class Collection extends Iterator implements Countable
return $result;
}
/**
* Returns a new collection consisting of random elements,
* from the original collection, shuffled or ordered
*
* @param int $count
* @param bool $shuffle
* @return static
*/
public function random(int $count = 1, bool $shuffle = false)
{
if ($shuffle) {
return $this->shuffle()->slice(0, $count);
}
$collection = clone $this;
$collection->data = A::random($collection->data, $count);
return $collection;
}
/**
* Removes an element from the array by key
*

View File

@@ -2,6 +2,7 @@
namespace Kirby\Toolkit;
use Kirby\Exception\InvalidArgumentException;
use stdClass;
/**
@@ -62,14 +63,31 @@ class Obj extends stdClass
}
/**
* Property Getter
* Gets one or multiple properties of the object
*
* @param string $property
* @param mixed $fallback
* @param string|array $property
* @param mixed $fallback If multiple properties are requested:
* Associative array of fallback values per key
* @return mixed
*/
public function get(string $property, $fallback = null)
public function get($property, $fallback = null)
{
if (is_array($property)) {
if ($fallback === null) {
$fallback = [];
}
if (!is_array($fallback)) {
throw new InvalidArgumentException('The fallback value must be an array when getting multiple properties');
}
$result = [];
foreach ($property as $key) {
$result[$key] = $this->$key ?? $fallback[$key] ?? null;
}
return $result;
}
return $this->$property ?? $fallback;
}