Oihana PHP

assertDocumentKeyValid.php

Table of Contents

Functions

assertDocumentKeyValid()  : bool
Validates the key, separator, and type of the provided document before performing key-based operations.

Functions

assertDocumentKeyValid()

Validates the key, separator, and type of the provided document before performing key-based operations.

assertDocumentKeyValid(array<string|int, mixed>|object $document, string $key[, string $separator = '.' ][, bool|null &$isArray = null ]) : bool

This internal helper ensures that:

  • The key is not empty.
  • The separator is not empty.
  • The document matches the expected type (array or object), or infers the type if $isArray is null.

If a mismatch between the inferred or forced type and the actual document type occurs, an InvalidArgumentException is thrown.

Parameters
$document : array<string|int, mixed>|object

The input document (either an array or an object).

$key : string

The key or property name/path to validate.

$separator : string = '.'

The separator for nested paths (default is '.').

$isArray : bool|null = null

Optional reference: true for array, false for object, null to infer automatically.

Tags
throws
InvalidArgumentException

If the key or separator is empty, or the document type does not match $isArray.

example

Returns true:

$doc = ['foo' => 'bar'];
assertDocumentKeyValid( $doc , 'foo' ) ;

Returns false, sets $isArray = false

$doc = (object)['foo' => 'bar'];
assertDocumentKeyValid( $doc , 'foo' , '.' , $isArray ) ;

Returns true, sets $isArray = true

$doc = ['foo' => 'bar'];
assertDocumentKeyValid( $doc , 'foo' , '.' , $isArray ) ;

Throws InvalidArgumentException: "Key cannot be empty."

$doc = ['foo' => 'bar'];
assertDocumentKeyValid( $doc , '' , '.' ) ;

Throws InvalidArgumentException: "Separator cannot be empty."

$doc = (object)['foo' => 'bar'] ;
assertDocumentKeyValid( $doc , 'foo' , '' ) ;

Throws InvalidArgumentException: "Type mismatch: expected object, got array."

$doc = ['foo' => 'bar'];
assertDocumentKeyValid( $doc , 'foo' , '.' , false ) ;

Throws InvalidArgumentException: "Type mismatch: expected array, got stdClass."

$doc = new stdClass;
assertDocumentKeyValid( $doc , 'foo' , '.' , true ) ;
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
bool

Returns the resolved value of $isArray: true for array, false for object.


        
On this page

Search results