master

laravel/framework

Last updated at: 29/12/2023 09:22

Sequence.php

TLDR

This file contains the implementation of a Sequence class in the Illuminate\Database\Eloquent\Factories namespace.

Classes

Sequence

The Sequence class represents a sequence of return values. It implements the Countable interface and has the following properties:

  • $sequence: an array representing the sequence of return values.
  • $count: the count of the sequence items.
  • $index: the current index of the sequence iteration.

The class has the following methods:

  • __construct(...$sequence): A constructor method that accepts a variable number of arguments to initialize the sequence. It sets the $sequence property and calculates the $count property based on the number of arguments passed.
  • count(): int: A method that returns the current count of the sequence items.
  • __invoke(): A magic method that returns the next value in the sequence. It uses the $index property to retrieve the value from the sequence array and increments the $index by 1.
<?php

namespace Illuminate\Database\Eloquent\Factories;

use Countable;

class Sequence implements Countable
{
    /**
     * The sequence of return values.
     *
     * @var array
     */
    protected $sequence;

    /**
     * The count of the sequence items.
     *
     * @var int
     */
    public $count;

    /**
     * The current index of the sequence iteration.
     *
     * @var int
     */
    public $index = 0;

    /**
     * Create a new sequence instance.
     *
     * @param  mixed  ...$sequence
     * @return void
     */
    public function __construct(...$sequence)
    {
        $this->sequence = $sequence;
        $this->count = count($sequence);
    }

    /**
     * Get the current count of the sequence items.
     *
     * @return int
     */
    public function count(): int
    {
        return $this->count;
    }

    /**
     * Get the next value in the sequence.
     *
     * @return mixed
     */
    public function __invoke()
    {
        return tap(value($this->sequence[$this->index % $this->count], $this), function () {
            $this->index = $this->index + 1;
        });
    }
}