Oihana PHP Arango

Documents implements DocumentsModel uses AQLQueryTrait, BindsTrait, ConfigTrait, ContainerTrait, DoctorTrait, DocumentsArrayTrait, DocumentsMethodsTrait, FieldsTrait, QueryIDTrait, SchemaTrait, ToStringTrait

Represents a high-level ArangoDB Documents Model.

This class provides a unified abstraction layer to interact with an ArangoDB document collection. It manages schema definitions, query bindings, filters, joins, facets, sorting, and transformation rules.

It also integrates with a dependency injection container to dynamically resolve and initialize model components such as the database connection, logger, configuration, and mock/debug options.

Typical usage involves defining a set of model options describing how the collection should be initialized and how the documents should be retrieved, transformed, or persisted.

Example:

$database = new ArangoDB
([
     ArangoConfig::DATABASE   => "xyz" ,
     ArangoConfig::ENDPOINT   => "tcp://127.0.0.1:8529" ,
     ArangoConfig::USER       => "root" ,
     ArangoConfig::PASSWORD   => "your-secure-password" ,
     ArangoConfig::BATCH_SIZE => 50000 ,
     ArangoConfig::CONNECTION => "Keep-Alive" ,
     ArangoConfig::TIMEOUT    => 25 ,
     ArangoConfig::TYPE       => "Basic"
]);

$documents = new Documents( $container,
[
    'database'   => $database , // the
    'collection' => 'places',
    'lazy'       => true , // By default, creates the collection if not exist.
    'indexes'    => // auto-generate the collection's indexes when the collection is created.
    [
        new PersistentIndexOptions
        ([
            IndexOptions::NAME   => 'id' ,
            IndexOptions::FIELDS => [ Prop::ID ] ,
            IndexOptions::UNIQUE => true ,
        ])
    ],
    'alters' =>
    [
        Prop::URL => [ Alter::URL , Paths::PLACES , Prop::_KEY ]
    ],
    'filters' =>
    [
        Prop::CREATED  => FilterType::DATE ,
        Prop::MODIFIED => FilterType::DATE ,
        Prop::NAME     => FilterType::STRING ,
    ],
]);
Tags
see
DocumentsModel

Table of Contents

Interfaces

DocumentsModel

Constants

EDGE_SUFFIX  : string = '_e'
The suffix used for edge fields in queries.
FIELDS  : string = 'fields'
The 'fields' key for initialization arrays.
JOIN_SUFFIX  : string = '_j'
The suffix used for join fields in queries.
UNIQUE_SUFFIX  : string = '_u'
The suffix used for unique fields in queries.

Properties

$arrays  : array<string|int, mixed>
The per-field embedded-array configuration, normalised to `[ field => [ Arango::MODE => ArrayMode::*, Arango::COUNTER => ?string ] ]`.
$fields  : array<string, mixed>
The fields definitions to return in get/list methods.

Methods

__construct()  : mixed
Creates a new Documents instance.
arrayContains()  : bool
Checks whether the array `field` of a single document (identified by `owner`) contains `value`.
arrayDefaults()  : array<string, array<string|int, mixed>|int>
Returns the default seed for the declared embedded array fields: each array field defaults to `[]`, and each declared counter to `0`.
arrayInsert()  : object|null
Adds one or several values to the array `field` of a single document.
arrayMove()  : object|null
Moves an existing `value` to the given zero-based `position` inside the array `field`.
arrayPurgeRef()  : array<string|int, object>|int
Removes a `value` from the array `field` of **every** document of the collection that contains it — typically to purge a now-deleted reference.
arrayRemove()  : object|null
Removes one or several values from the array `field` of a single document.
diagnose()  : array<string|int, DiffReport>
Compares everything this model declares with the server state, without touching anything — the read-only half of {@see repair()}.
initializeArrays()  : static
Initialize the per-field embedded-array configuration from the `arrays` option.
initializeDocumentsMethods()  : static
Initialize the Documents HTTP methods signals.
initializeFields()  : static
Initialize fields definitions from an associative array.
prepareQueryFields()  : array<string, array<string|int, mixed>>|null
Prepares query fields based on internal definitions and optional skin filter.
repair()  : array<string|int, DiffReport>
Reconciles the server with everything this model declares — the acting half of {@see diagnose()}:
returnFields()  : string
Generates an AQL document expression or LET statement with the selected fields.
arrayCounter()  : string|null
Returns the configured length-counter attribute of an array field, or null.
arrayMode()  : string
Resolves the {@see ArrayMode} of an array field, honouring an optional per-call `mode` override, then the declared configuration, then defaulting to LIST.
arrayWith()  : string
Builds the `WITH { ... }` object clause: the array field, its optional length counter, and the `modified` timestamp unless `touch` is disabled.
ensureArrayDefaults()  : Closure|null
Builds an `ensure` closure that seeds the declared array fields to `[]` (and their counters to `0`) for any missing key of a document being created, then applies the optional user-supplied `ensure`. Returns the user closure unchanged when no array field is declared (so models without `AQL::ARRAYS` are untouched).
filterFieldsBySkin()  : array<string, mixed>
Filters fields based on an optional skin.
generateUniqueKey()  : string|null
Generates a unique key for special filters like edges, joins, or unique names.
normalizeFieldDefinition()  : array<string, mixed>
Normalize a field definition into a structured array for queries.
runArrayUpdate()  : object|null
Compiles and executes a single-document array UPDATE (`FOR ... FILTER ... LET ... UPDATE ... RETURN NEW`), emitting the update signals around the write.

Constants

EDGE_SUFFIX

The suffix used for edge fields in queries.

public string EDGE_SUFFIX = '_e'

FIELDS

The 'fields' key for initialization arrays.

public string FIELDS = 'fields'

JOIN_SUFFIX

The suffix used for join fields in queries.

public string JOIN_SUFFIX = '_j'

UNIQUE_SUFFIX

The suffix used for unique fields in queries.

public string UNIQUE_SUFFIX = '_u'

Properties

$arrays

The per-field embedded-array configuration, normalised to `[ field => [ Arango::MODE => ArrayMode::*, Arango::COUNTER => ?string ] ]`.

public array<string|int, mixed> $arrays = []

$fields

The fields definitions to return in get/list methods.

public array<string, mixed> $fields = []

Keys are field names, values are either a Filter constant, a definition array, or null.

Tags
example
$model->fields =>
[
    Schema::ACTIVE                => Filter::BOOL ,
    Schema::WITH_STATUS           => Field::FILTER => Filter::DEFAULT ,
    Schema::ID                    => Filter::ID ,
    Schema::NAME                  => null , // Filter::DEFAULT ,
    Schema::URL                   => Filter::URL ,
    Schema::CREATED               => Filter::DATETIME ,
    Schema::MODIFIED              => [ Field::FILTER => Filter::DATETIME ] ,
    Schema::IMAGE                 => [ Field::FILTER => Filter::EDGE ] ,
    Schema::ALTERNATIVE_HEADLINE  => Filter::TRANSLATE ,
    Schema::ALTERNATE_NAME        => Filter::TRANSLATE ,
    Schema::DESCRIPTION           => Filter::TRANSLATE ,
    Schema::HEADLINE              => Filter::TRANSLATE ,
    Schema::SLOGAN                => Filter::TRANSLATE ,
    Schema::SCOPE_HAS_PERMISSION  => [ Field::FILTER => Filter::BOOL ] ,
    Schema::TOKEN_EXPIRATION      => [ Field::FILTER => Filter::INT  ] ,
    Schema::PERMISSIONS           => [ Field::FILTER => Filter::EDGES , Field::SKINS => [ Skin::FULL ] ]
    Schema::NUM_PERMISSIONS       => Field::FILTER => Filter::EDGES_COUNT
] ;

Methods

__construct()

Creates a new Documents instance.

public __construct(Container $container[, array<string|int, mixed> $init = [] ][, string $type = CollectionType::DOCUMENT ]) : mixed
Parameters
$container : Container

The DI Container reference.

$init : array<string|int, mixed> = []

The options of the Documents model :

  • 'alters' - An associative array of transformation rules used to alter or enrich the document properties returned by the model.
  • 'collection' - The name of the ArangoDB Document collection to manage
  • 'database' - The ArangoDB database reference or its definition in the DI Container.
  • 'edges' - All the edges definitions of the collection
  • 'facets' - The facet definitions to register
  • 'fields' - The optional fields definitions to returns in the get/list methods.
  • 'fillable' - The fillable definitions to register
  • 'filters' - The filter definitions to register
  • 'groupable' - The optional whitelist/mapping (`urlKey => fieldPath`) of groupable dimensions for `?groupBy=` / `?group=`.
  • 'indexes' - The definition of the indexes to auto-register when the collection is created (if not exist)
  • 'joins' - The joins definitions to register
  • 'lazy' - Indicates if the model create the collection if not exit.
  • 'mock' - Indicates if the methods return a mock value (debug mode only)
  • 'options' - Indicates the ArangoDB collection options to initialize the lazy new collection
  • 'searchable' - Indicates the search definitions.
  • 'sortable' - Defines the sortable strategies for a map of specific properties.
  • 'type' - Indicates the type of the collection - document (default) or edge.
$type : string = CollectionType::DOCUMENT

The default type of the collection (Default -> 'document' [2] )T

Tags
throws
ContainerExceptionInterface
NotFoundExceptionInterface
DependencyException
NotFoundException
ReflectionException

arrayContains()

Checks whether the array `field` of a single document (identified by `owner`) contains `value`.

public arrayContains([array{owner?: mixed, field?: string, value?: mixed, key?: string, prefix?: string, debug?: bool} $init = [] ]) : bool

Generated AQL: RETURN LENGTH( FOR doc IN @@collection FILTER doc._key == @key && POSITION(doc.field, @value) RETURN 1 ) > 0

Parameters
$init : array{owner?: mixed, field?: string, value?: mixed, key?: string, prefix?: string, debug?: bool} = []
Tags
throws
ArangoException
BindException
ContainerExceptionInterface
DependencyException
NotFoundException
NotFoundExceptionInterface
ReflectionException
Return values
bool

True if the value is present.

arrayDefaults()

Returns the default seed for the declared embedded array fields: each array field defaults to `[]`, and each declared counter to `0`.

public arrayDefaults() : array<string, array<string|int, mixed>|int>

Used to initialize a freshly created document so that every declared array field is always a real (possibly empty) array — see ensureArrayDefaults().

Return values
array<string, array<string|int, mixed>|int>

e.g. [ 'tracks' => [], 'numberOfTracks' => 0, 'tags' => [] ].

arrayInsert()

Adds one or several values to the array `field` of a single document.

public arrayInsert([array{owner?: mixed, field?: string, value?: mixed, side?: string, mode?: string, key?: string, prefix?: string, touch?: bool, options?: array|object|string|null, debug?: bool} $init = [] ]) : object|null

The uniqueness and sorting are driven by the field's ArrayMode; value may be a scalar or an array (its elements are appended, never nested).

Generated AQL (LIST/SET, side RIGHT): ... UPDATE doc WITH { field: APPEND(doc.field, @value [, true]) [, counter: LENGTH(...)] [, modified: ...] } ...

Parameters
$init : array{owner?: mixed, field?: string, value?: mixed, side?: string, mode?: string, key?: string, prefix?: string, touch?: bool, options?: array|object|string|null, debug?: bool} = []
Tags
throws
ArangoException
BindException
ContainerExceptionInterface
DependencyException
NotFoundException
NotFoundExceptionInterface
ReflectionException
Throwable
Return values
object|null

The updated document, or null if no document matched.

arrayMove()

Moves an existing `value` to the given zero-based `position` inside the array `field`.

public arrayMove([array{owner?: mixed, field?: string, value?: mixed, position?: int, key?: string, prefix?: string, touch?: bool, options?: array|object|string|null, debug?: bool} $init = [] ]) : object|null

Unsupported on a ArrayMode::SORTED_SET field (the sort order overrides any manual position): an UnsupportedOperationException is thrown.

Generated AQL:

LET __rm  = REMOVE_VALUE(doc.field, @value)
LET __arr = APPEND( PUSH( SLICE(__rm, 0, <pos>), @value, true ), SLICE(__rm, <pos>) )
UPDATE doc WITH { field: __arr [, counter: LENGTH(__arr)] [, modified: ...] } ...
Parameters
$init : array{owner?: mixed, field?: string, value?: mixed, position?: int, key?: string, prefix?: string, touch?: bool, options?: array|object|string|null, debug?: bool} = []
Tags
throws
ArangoException
BindException
ContainerExceptionInterface
DependencyException
NotFoundException
NotFoundExceptionInterface
ReflectionException
Throwable
UnsupportedOperationException
Return values
object|null

The updated document, or null if no document matched.

arrayPurgeRef()

Removes a `value` from the array `field` of **every** document of the collection that contains it — typically to purge a now-deleted reference.

public arrayPurgeRef([array{field?: string, value?: mixed, prefix?: string, touch?: bool, count?: bool, options?: array|object|string|null, debug?: bool} $init = [] ]) : array<string|int, object>|int

Generated AQL: FOR doc IN @@collection FILTER POSITION(doc.field, @value) LET __arr = REMOVE_VALUE(doc.field, @value) UPDATE doc WITH { ... } ... RETURN NEW

Parameters
$init : array{field?: string, value?: mixed, prefix?: string, touch?: bool, count?: bool, options?: array|object|string|null, debug?: bool} = []
Tags
throws
ArangoException
BindException
ContainerExceptionInterface
DependencyException
NotFoundException
NotFoundExceptionInterface
ReflectionException
Throwable
Return values
array<string|int, object>|int

The list of modified documents, or their count when count is true.

arrayRemove()

Removes one or several values from the array `field` of a single document.

public arrayRemove([array{owner?: mixed, field?: string, value?: mixed, key?: string, prefix?: string, touch?: bool, options?: array|object|string|null, debug?: bool} $init = [] ]) : object|null

Generated AQL (scalar value): ... UPDATE doc WITH { field: REMOVE_VALUE(doc.field, @value) [, counter: LENGTH(...)] [, modified: ...] } ... (an array value uses REMOVE_VALUES instead).

Parameters
$init : array{owner?: mixed, field?: string, value?: mixed, key?: string, prefix?: string, touch?: bool, options?: array|object|string|null, debug?: bool} = []
Tags
throws
ArangoException
BindException
ContainerExceptionInterface
DependencyException
NotFoundException
NotFoundExceptionInterface
ReflectionException
Throwable
Return values
object|null

The updated document, or null if no document matched.

diagnose()

Compares everything this model declares with the server state, without touching anything — the read-only half of {@see repair()}.

public diagnose() : array<string|int, DiffReport>

The returned list carries one DiffReport per declared structure object, in dependency order:

  1. the collection (DiffKind::COLLECTION) — existence and type (2 document / 3 edge);
  2. the declared indexes (DiffKind::INDEXES, only when the model declares AQL::INDEXES) — one aggregated report: missing indexes, definition drifts (immutable → drop + recreate required), server indexes that are no longer declared;
  3. the View (DiffKind::VIEW, only when the model declares an AQL::VIEW block) — the SearchTrait::viewDiff() report with its declaration-coherence checks.

A model without a collection resolves to a single DiffStatus::INVALID report; without a database to a single DiffStatus::UNREACHABLE report.

Tags
throws
ReflectionException

When a declared IndexOptions cannot be serialised.

Return values
array<string|int, DiffReport>

One report per declared structure object.

initializeArrays()

Initialize the per-field embedded-array configuration from the `arrays` option.

public initializeArrays([array<string|int, mixed> $init = [] ]) : static

Each entry is either an ArrayMode shorthand ('tags' => ArrayMode::SET) or a richer definition ('tracks' => [ ArrayMode::LIST , Arango::COUNTER => 'numberOfTracks' ]).

Parameters
$init : array<string|int, mixed> = []
Return values
static

initializeDocumentsMethods()

Initialize the Documents HTTP methods signals.

public initializeDocumentsMethods() : static
Return values
static

initializeFields()

Initialize fields definitions from an associative array.

public initializeFields([array<string, mixed> $init = [] ]) : static
Parameters
$init : array<string, mixed> = []

Optional initialization array containing a 'fields' key.

Return values
static

prepareQueryFields()

Prepares query fields based on internal definitions and optional skin filter.

public prepareQueryFields([array<string|int, mixed>|null $fields = null ][, string|null $skin = null ][, string|null $parentKey = null ][, string|array<string|int, mixed>|null $in = null ]) : array<string, array<string|int, mixed>>|null

Converts string filters to array format, applies skins, and normalizes each field.

Parameters
$fields : array<string|int, mixed>|null = null

Optional custom fields to process (defaults to $this->fields).

$skin : string|null = null

Optional skin to filter applicable fields.

$parentKey : string|null = null

Optional parent key definition.

$in : string|array<string|int, mixed>|null = null

Optional field or list of fields to filter the final fields definitions.

Tags
example
$fields = $model->prepareQueryFields('full');
// Returns normalized array of fields including only those matching the 'full' skin
Return values
array<string, array<string|int, mixed>>|null

Normalized fields ready for query, or null if none.

repair()

Reconciles the server with everything this model declares — the acting half of {@see diagnose()}:

public repair([bool $force = false ]) : array<string|int, DiffReport>
  1. a missing collection is created with its declared type and its declared indexes (exactly what the lazy provisioning would do);
  2. missing indexes are created on an existing collection — the case the lazy provisioning never covers; a drifted index is only rebuilt (drop + recreate) when $force is true, because the rebuild opens a window where queries lose the index and a unique index may fail to recreate over duplicated data;
  3. the View is created or resynchronized through SearchTrait::viewSync() (updateProperties(), the View stays queryable while re-indexing).

DiffStatus::INVALID and DiffStatus::UNREACHABLE reports are never acted on; a drifted collection type is never repaired (recreating a collection means losing its documents — that is a migration, not a repair).

Parameters
$force : bool = false

Allow the drop + recreate of drifted indexes.

Tags
throws
ReflectionException

When a declared IndexOptions cannot be serialised.

Return values
array<string|int, DiffReport>

The diagnose() reports, with $applied set on every object actually created or updated.

returnFields()

Generates an AQL document expression or LET statement with the selected fields.

public returnFields([array<string, mixed> $init = [] ][, array<string|int, mixed> &$variables = [] ][, bool $isVariable = false ]) : string

Supports edges, joins, skins, and query fields.

Parameters
$init : array<string, mixed> = []

Options to customize the query:

  • string|array $fields: comma-separated list or array of field names
  • ?array $queryFields: prepared query fields (overrides internal $fields)
  • ?string $lang: optional language key
  • string $docRef: document reference name
  • bool $isResult: whether to assign to result variable
$variables : array<string|int, mixed> = []
$isVariable : bool = false

Whether to generate a LET statement instead of RETURN

Tags
throws
ContainerExceptionInterface
NotFoundExceptionInterface
Exception
example
$aql = $model->returnFields
([
    Arango::QUERY_FIELDS => $queryFields,
    Arango::DOC_REF      => 'doc',
    Arango::SKIN         => 'full'
]);
Return values
string

Compiled AQL query fragment

arrayCounter()

Returns the configured length-counter attribute of an array field, or null.

protected arrayCounter(string|null $field) : string|null
Parameters
$field : string|null
Return values
string|null

arrayMode()

Resolves the {@see ArrayMode} of an array field, honouring an optional per-call `mode` override, then the declared configuration, then defaulting to LIST.

protected arrayMode(string|null $field[, array<string|int, mixed> $init = [] ]) : string
Parameters
$field : string|null
$init : array<string|int, mixed> = []
Return values
string

arrayWith()

Builds the `WITH { ... }` object clause: the array field, its optional length counter, and the `modified` timestamp unless `touch` is disabled.

protected arrayWith(string|null $field, string $arrayVar[, array<string|int, mixed> $init = [] ]) : string
Parameters
$field : string|null

The array attribute name.

$arrayVar : string

The AQL variable holding the new array (e.g. '__arr').

$init : array<string|int, mixed> = []
Return values
string

ensureArrayDefaults()

Builds an `ensure` closure that seeds the declared array fields to `[]` (and their counters to `0`) for any missing key of a document being created, then applies the optional user-supplied `ensure`. Returns the user closure unchanged when no array field is declared (so models without `AQL::ARRAYS` are untouched).

protected ensureArrayDefaults([Closure|null $ensure = null ]) : Closure|null
Parameters
$ensure : Closure|null = null

An optional user ensure closure to compose with.

Return values
Closure|null

filterFieldsBySkin()

Filters fields based on an optional skin.

private filterFieldsBySkin(array<string, mixed> $fields, string|null $skin) : array<string, mixed>
Parameters
$fields : array<string, mixed>

Fields to filter

$skin : string|null

Skin to match

Return values
array<string, mixed>

Filtered fields

generateUniqueKey()

Generates a unique key for special filters like edges, joins, or unique names.

private generateUniqueKey(string $key, string|null $filter[, string|null $parentKey = null ]) : string|null
Parameters
$key : string

Base field key

$filter : string|null

Filter type

$parentKey : string|null = null

Optional parent key.

Return values
string|null

Generated unique key or existing

normalizeFieldDefinition()

Normalize a field definition into a structured array for queries.

private normalizeFieldDefinition(string $key[, array<string|int, mixed> $options = [] ][, string|null $parentKey = null ]) : array<string, mixed>
  • Converts string filters to array
  • Handles subfields for DOCUMENT or MAP filters
  • Generates unique keys for special filters
Parameters
$key : string

Field name

$options : array<string|int, mixed> = []

Field options, may include:

  • Field::FILTER
  • Field::NAME
  • Field::QUOTED
  • Field::FIELDS (for DOCUMENT or MAP)
$parentKey : string|null = null

The Optional parent key

Tags
example
$normalized = $this->normalizeFieldDefinition( 'permissions',
[
    Field::FILTER => Filter::EDGES,
    Field::SKINS => [Skin::FULL]
]);
Return values
array<string, mixed>

Normalized field definition

runArrayUpdate()

Compiles and executes a single-document array UPDATE (`FOR ... FILTER ... LET ... UPDATE ... RETURN NEW`), emitting the update signals around the write.

private runArrayUpdate(string|null $field, array<string|int, mixed> $lets, string $filter, array<string|int, mixed> &$binds, array<string|int, mixed> $init) : object|null
Parameters
$field : string|null

The array attribute name.

$lets : array<string|int, mixed>

The ordered LET clauses producing the __arr variable.

$filter : string

The FILTER predicate locating the document.

$binds : array<string|int, mixed>

The bind variables (mutated by reference).

$init : array<string|int, mixed>
Tags
throws
ArangoException
BindException
ContainerExceptionInterface
DependencyException
NotFoundException
NotFoundExceptionInterface
ReflectionException
Throwable
Return values
object|null
On this page

Search results