Skip to content

Conversation

@Button99
Copy link
Contributor

This PR adds parameter validations to Collection::sliding() and LazyCollection::sliding() methods.
The methods will throw an InvalidArgumentException when the $steps and $size parameters are <1.

With that way we have 2 issues fixed.

  1. Size of 0 produced empty chunks.
// Before fix:
Collection::times(5)->sliding(0, 1)->toArray();
// Result: [[], [], [], [], [], []]

// Mathematical calculation:
// $chunks = floor((count - size) / step) + 1
// $chunks = floor((5 - 0) / 1) + 1 // 6
// Each chunk has size 0, resulting in 6 empty arrays
  1. Step of 0 caused DivisionByZeroError
  // Before fix:
  Collection::times(5)->sliding(2, 0)->toArray();
  // Result: DivisionByZeroError

  // Mathematical calculation:
  // $chunks = floor((5 - 2) / 0) + 1 = DivisionByZeroError

Thank you.

Comment on lines 1285 to 1286
* @param int $size
* @param int $step
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can narrow this further down then:

Suggested change
* @param int $size
* @param int $step
* @param positive-int $size
* @param positive-int $step

*
* @param int $size
* @param int $step
* @return static<int, static>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You might even reflect that in the return type:

Suggested change
* @return static<int, static>
* @return $size is positive-int ? $step is positive-int ? static<int, static> : never : never

@taylorotwell taylorotwell merged commit 98be693 into laravel:12.x Nov 24, 2025
73 of 74 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants