Skip to content

Commit

Permalink
diff() and fix documented param types
Browse files Browse the repository at this point in the history
  • Loading branch information
valzargaming committed Jan 17, 2025
1 parent 9ea4a19 commit cb0a8f3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
1 change: 1 addition & 0 deletions src/Discord/Helpers/CollectionInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public function merge($collection): self;
public function toArray();
public function keys(): array;
public function values(): array;
public function diff(): array;
public function offsetExists($offset): bool;
#[\ReturnTypeWillChange]
public function offsetGet($offset);
Expand Down
34 changes: 30 additions & 4 deletions src/Discord/Helpers/CollectionTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ trait CollectionTrait
*
* @param array $items
* @param ?string $discrim
* @param string|null $class
* @param ?string $class
*/
public function __construct(array $items = [], ?string $discrim = 'id', ?string $class = null)
{
Expand All @@ -32,7 +32,7 @@ public function __construct(array $items = [], ?string $discrim = 'id', ?string
*
* @param array $items
* @param ?string $discrim
* @param string|null $class
* @param ?string $class
*
* @return static
*/
Expand Down Expand Up @@ -298,8 +298,8 @@ public function clear(): void
/**
* Slices the collection.
*
* @param int $offset
* @param null|int $length
* @param int $offset
* @param ?int $length
* @param bool $preserve_keys
*
* @return CollectionInterface
Expand Down Expand Up @@ -331,6 +331,32 @@ public function sort(callable|int|null $callback)
return new Collection($items, $this->discrim, $this->class);
}

/**
* Computes the difference between the current collection and the given array.
*
* If a callback is provided and is callable, it uses `array_udiff_assoc` to compute the difference.
* Otherwise, it uses `array_diff`.
*
* @param CollectionInterface|array $array
* @param ?callable $callback
*
* @return CollectionInterface
*/
public function diff($array, ?callable $callback)
{
$array = $array instanceof CollectionInterface
? $array->toArray()
: $array;

$items = $this->items;

$callback && is_callable($callback)
? array_udiff_assoc($items, $array, $callback)
: array_diff($items, $array);

return new Collection($items, $this->discrim, $this->class);
}

/**
* Applies the given callback function to each item in the collection.
*
Expand Down

0 comments on commit cb0a8f3

Please sign in to comment.