How can a PHP developer ensure proper validation of array elements when using the Command-Pattern or Fluent-Interface approach?

When using the Command-Pattern or Fluent-Interface approach in PHP, a developer can ensure proper validation of array elements by implementing validation checks within the methods that manipulate the array. This can include checking the data type, range, length, or any other specific validation criteria before performing any operations on the array elements.

class ArrayValidator
{
    private $array;

    public function __construct(array $array)
    {
        $this->array = $array;
    }

    public function addElement($element)
    {
        // Perform validation checks on $element before adding it to the array
        if (is_numeric($element) && $element > 0) {
            $this->array[] = $element;
        }
        
        return $this;
    }

    public function getArray()
    {
        return $this->array;
    }
}

// Example usage
$array = [1, 2, 3];
$validator = new ArrayValidator($array);
$validator->addElement(4)
          ->addElement("invalid")
          ->addElement(5);

$result = $validator->getArray();
print_r($result);