Class luya\cms\menu\Query

Inheritanceluya\cms\menu\Query » yii\base\BaseObject
Implementsluya\cms\menu\QueryOperatorFieldInterface, yii\base\Configurable
Available since version1.0.0
Source Code https://github.com/luyadev/luya-module-cms/blob/master/src/menu/Query.php

Menu Query Builder.

Ability to create menu query condition similar behavior, changing the language container and define with specification to fit your needs.

Basic example of making a menu selection:

$items = (new \luya\cms\menu\Query())->where([self::FIELD_PARENTNAVID => 0])->all();

By default the Menu Query will get the default language, or the current active language. To force a specific language use the lang() method in your query chain:

$items = (new \luya\cms\menu\Query())->where([self::FIELD_PARENTNAVID => 0])->lang('en')->all();

You can also find one element instead of all

$item = (new \luya\cms\menu\Query())->where([self::ID => 1])->one();

To include hidden pages to your selection use with:

$items = (new \luya\cms\menu\Query())->where([self::FIELD_PARENTNAVID => 0])->with(['hidden'])->all();

Attention: When you append the with['hidden'] state, the visibility of the item will be overriden, even when you change them with event inject. So take care of using with hidden when protecting items for beeing seen by guest users (in example of protected several items for not logged in users).

Public Properties

Hide inherited properties

Property Type Description Defined By
$lang string luya\cms\menu\Query
$menu luya\cms\Menu Application menu component object. luya\cms\menu\Query

Protected Properties

Hide inherited properties

Property Type Description Defined By
$whereOperators array An array with all available where operators. luya\cms\menu\Query

Public Methods

Hide inherited methods

Method Description Defined By
__call() Calls the named method which is not a class method. yii\base\BaseObject
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of an object property. yii\base\BaseObject
__isset() Checks if a property is set, i.e. defined and not null. yii\base\BaseObject
__set() Sets value of an object property. yii\base\BaseObject
__unset() Sets an object property to null. yii\base\BaseObject
all() Retrieve all found rows based on the filtering options and returns the the QueryIterator object which is represents an array. luya\cms\menu\Query
andWhere() Add another where statement to the existing, this is the case when using compare operators, as then only one where definition can bet set. luya\cms\menu\Query
canGetProperty() Returns a value indicating whether a property can be read. yii\base\BaseObject
canSetProperty() Returns a value indicating whether a property can be set. yii\base\BaseObject
className() Returns the fully qualified name of this class. yii\base\BaseObject
container() Helper method to define the container to retrieve all elements from. luya\cms\menu\Query
count() Returns the count for the provided filter options. luya\cms\menu\Query
createArrayIterator() Static method to create an iterator object based on the provided array data with optional language context. luya\cms\menu\Query
createItemObject() Static method to create the item object itself, is used for the one() method and in the current() method of the QueryIterator class. luya\cms\menu\Query
getLang() Return the current language from composition if not set via lang(). luya\cms\menu\Query
getMenu() Getter method to return menu component luya\cms\menu\Query
hasMethod() Returns a value indicating whether a method is defined. yii\base\BaseObject
hasProperty() Returns a value indicating whether a property is defined. yii\base\BaseObject
init() Initializes the object. yii\base\BaseObject
lang() Changeing the container in where the data should be collection, by default the composition langShortCode is the default language code. This represents the current active language, or the default language if no information is presented. luya\cms\menu\Query
limit() Set a limition for the amount of results. luya\cms\menu\Query
offset() Define offset start for the rows, if you defined offset to be 5 and you have 11 rows, the first 5 rows will be skiped. This is commonly used to make pagination function in combination with the limit() function. luya\cms\menu\Query
one() Retrieve only one result for your query, even if there are more rows then one, it will just pick the first row from the filtered result and return the item object. If the filtering based on the query settings does not return any result, the return will be false. luya\cms\menu\Query
orderBy() Order the query by one or multiple fields asc or desc. luya\cms\menu\Query
preloadModels() Preload models for the given Menu Query. luya\cms\menu\Query
root() Helper method to retrieve only the root elements for a given query. luya\cms\menu\Query
setMenu() Setter method for menu Container. luya\cms\menu\Query
tags() Filter by Tag IDs. luya\cms\menu\Query
where() Query where similar behavior of filtering items. luya\cms\menu\Query
with() With/Without expression to hidde or display data from the Menu Query. luya\cms\menu\Query

Property Details

Hide inherited properties

$lang public read-only property
public string getLang ( )
$menu public property

Application menu component object.

public luya\cms\Menu $menu null
$whereOperators protected property

An array with all available where operators.

protected array $whereOperators = [
    
'<',
    
'<=',
    
'>',
    
'>=',
    
'=',
    
'!=',
    
'==',
    
'in',
]

Method Details

Hide inherited methods

__call() public method

Defined in: yii\base\BaseObject::__call()

Calls the named method which is not a class method.

Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.

public mixed __call ( $name, $params )
$name string

The method name

$params array

Method parameters

return mixed

The method return value

throws yii\base\UnknownMethodException

when calling unknown method

                public function __call($name, $params)
{
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__construct() public method

Defined in: yii\base\BaseObject::__construct()

Constructor.

The default implementation does two things:

  • Initializes the object with the given configuration $config.
  • Call init().

If this method is overridden in a child class, it is recommended that

  • the last parameter of the constructor is a configuration array, like $config here.
  • call the parent implementation at the end of the constructor.
public void __construct ( $config = [] )
$config array

Name-value pairs that will be used to initialize the object properties

                public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    $this->init();
}

            
__get() public method

Defined in: yii\base\BaseObject::__get()

Returns the value of an object property.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $value = $object->property;.

See also __set().

public mixed __get ( $name )
$name string

The property name

return mixed

The property value

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is write-only

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter();
    } elseif (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() public method

Defined in: yii\base\BaseObject::__isset()

Checks if a property is set, i.e. defined and not null.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($object->property).

Note that if the property is not defined, false will be returned.

See also https://www.php.net/manual/en/function.isset.php.

public boolean __isset ( $name )
$name string

The property name or the event name

return boolean

Whether the named property is set (not null).

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    return false;
}

            
__set() public method

Defined in: yii\base\BaseObject::__set()

Sets value of an object property.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $object->property = $value;.

See also __get().

public void __set ( $name, $value )
$name string

The property name or the event name

$value mixed

The property value

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is read-only

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter($value);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    } else {
        throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
    }
}

            
__unset() public method

Defined in: yii\base\BaseObject::__unset()

Sets an object property to null.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing unset($object->property).

Note that if the property is not defined, this method will do nothing. If the property is read-only, it will throw an exception.

See also https://www.php.net/manual/en/function.unset.php.

public void __unset ( $name )
$name string

The property name

throws yii\base\InvalidCallException

if the property is read only.

                public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter(null);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
    }
}

            
all() public method

Retrieve all found rows based on the filtering options and returns the the QueryIterator object which is represents an array.

public luya\cms\menu\QueryIteratorFilter all ( )
return luya\cms\menu\QueryIteratorFilter

Returns the QueryIterator object.

                public function all()
{
    return static::createArrayIterator($this->filter($this->menu[$this->getLang()], $this->_where, $this->_with), $this->getLang(), $this->_with, $this->_preloadModels);
}

            
andWhere() public method

Add another where statement to the existing, this is the case when using compare operators, as then only one where definition can bet set.

public luya\cms\menu\Query andWhere ( array $args )
$args array

                public function andWhere(array $args)
{
    return $this->where($args);
}

            
canGetProperty() public method

Defined in: yii\base\BaseObject::canGetProperty()

Returns a value indicating whether a property can be read.

A property is readable if:

  • the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also canSetProperty().

public boolean canGetProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property can be read

                public function canGetProperty($name, $checkVars = true)
{
    return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}

            
canSetProperty() public method

Defined in: yii\base\BaseObject::canSetProperty()

Returns a value indicating whether a property can be set.

A property is writable if:

  • the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also canGetProperty().

public boolean canSetProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property can be written

                public function canSetProperty($name, $checkVars = true)
{
    return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}

            
className() public static method
Deprecated since 2.0.14. On PHP >=5.5, use ::class instead.

Defined in: yii\base\BaseObject::className()

Returns the fully qualified name of this class.

public static string className ( )
return string

The fully qualified name of this class.

                public static function className()
{
    return get_called_class();
}

            
container() public method

Helper method to define the container to retrieve all elements from.

public luya\cms\menu\Query container ( $alias )
$alias string

The alias name from a given container to retrieve items from.

                public function container($alias)
{
    return $this->where([self::FIELD_CONTAINER => $alias]);
}

            
count() public method

Returns the count for the provided filter options.

public integer count ( )
return integer

The number of rows for your filtering options.

                public function count()
{
    return count($this->filter($this->menu[$this->getLang()], $this->_where, $this->_with));
}

            
createArrayIterator() public static method

Static method to create an iterator object based on the provided array data with optional language context.

public static luya\cms\menu\QueryIterator createArrayIterator ( array $data, $langContext, array $with = [], $preloadModels false )
$data array

The filtere results where the iterator object should be created with

$langContext string

The language short code context, if any.

$with array

An array with keys to include or not, f.e. ['hidden' => true] means include hidden elements or ['hidden' => false] means to not include hidden elements which is default.

$preloadModels boolean

Whether the models should be preload or not.

                public static function createArrayIterator(array $data, $langContext, array $with = [], $preloadModels = false)
{
    return (new QueryIteratorFilter(new QueryIterator(['data' => $data, 'lang' => $langContext, 'with' => $with, 'preloadModels' => $preloadModels])));
}

            
createItemObject() public static method

Static method to create the item object itself, is used for the one() method and in the current() method of the QueryIterator class.

public static luya\cms\menu\Item createItemObject ( array $itemArray, $langContext, $model null )
$itemArray array

The item array data for the object

$langContext string

The language short code context, if any.

$model

                public static function createItemObject(array $itemArray, $langContext, $model = null)
{
    return new Item(['itemArray' => $itemArray, 'lang' => $langContext, 'model' => $model]);
}

            
getLang() public method

Return the current language from composition if not set via lang().

public string getLang ( )

                public function getLang()
{
    if ($this->_lang === null) {
        $this->_lang = $this->menu->composition['langShortCode'];
    }
    return $this->_lang;
}

            
getMenu() public method

Getter method to return menu component

public luya\cms\Menu getMenu ( )
return luya\cms\Menu

Menu Container object

                public function getMenu()
{
    if ($this->_menu === null) {
        $this->_menu = Yii::$app->get('menu');
    }
    return $this->_menu;
}

            
hasMethod() public method

Defined in: yii\base\BaseObject::hasMethod()

Returns a value indicating whether a method is defined.

The default implementation is a call to php function method_exists(). You may override this method when you implemented the php magic method __call().

public boolean hasMethod ( $name )
$name string

The method name

return boolean

Whether the method is defined

                public function hasMethod($name)
{
    return method_exists($this, $name);
}

            
hasProperty() public method

Defined in: yii\base\BaseObject::hasProperty()

Returns a value indicating whether a property is defined.

A property is defined if:

  • the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also:

public boolean hasProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property is defined

                public function hasProperty($name, $checkVars = true)
{
    return $this->canGetProperty($name, $checkVars) || $this->canSetProperty($name, false);
}

            
init() public method

Defined in: yii\base\BaseObject::init()

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

public void init ( )

                public function init()
{
}

            
lang() public method

Changeing the container in where the data should be collection, by default the composition langShortCode is the default language code. This represents the current active language, or the default language if no information is presented.

public luya\cms\menu\Query lang ( $langShortCode )
$langShortCode string

Language Short Code e.g. de or en

                public function lang($langShortCode)
{
    $this->_lang = $langShortCode;
    return $this;
}

            
limit() public method

Set a limition for the amount of results.

public luya\cms\menu\Query limit ( $count )
$count integer

The number of rows to return

                public function limit($count)
{
    if (is_numeric($count)) {
        $this->_limit = $count;
    }
    return $this;
}

            
offset() public method

Define offset start for the rows, if you defined offset to be 5 and you have 11 rows, the first 5 rows will be skiped. This is commonly used to make pagination function in combination with the limit() function.

public luya\cms\menu\Query offset ( $offset )
$offset integer

Defines the amount of offset start position.

                public function offset($offset)
{
    if (is_numeric($offset)) {
        $this->_offset = $offset;
    }
    return $this;
}

            
one() public method

Retrieve only one result for your query, even if there are more rows then one, it will just pick the first row from the filtered result and return the item object. If the filtering based on the query settings does not return any result, the return will be false.

public luya\cms\menu\Item|boolean one ( )
return luya\cms\menu\Item|boolean

Returns the Item object or false if nothing found.

                public function one()
{
    $data = $this->filter($this->menu[$this->getLang()], $this->_where, $this->_with);
    if (count($data) == 0) {
        return false;
    }
    return static::createItemObject(array_values($data)[0], $this->getLang());
}

            
orderBy() public method (available since version 1.0.2)

Order the query by one or multiple fields asc or desc.

Use following PHP constants for directions:

  • SORT_ASC: 1..10, A..Z
  • SORT_DESC: 10..1, Z..A

Example using orderBy:

$query = new Query()->orderBy([Query::FIELD_TIMESTAMPCREATE => SORT_ASC, Query::FIELD_ALIAS => SORT_DESC'])->all();
public luya\cms\menu\Query orderBy ( array $order )
$order array

An array with fields to sort where key is the field and value the direction.

                public function orderBy(array $order)
{
    $orderBy = ['keys' => [], 'directions' => []];
    foreach ($order as $key => $direction) {
        $orderBy['keys'][] = $key;
        $orderBy['directions'][] = $direction;
    }
    $this->_order = $orderBy;
    return $this;
}

            
preloadModels() public method

Preload models for the given Menu Query.

When menu item method {{luya\cms\menu\Item::getModel()}} is called, it will lazy load the given {{luya\cms\models\Nav}} model. This can be slow on large menus, therfore you can preload those models for the given Menu Query by enabling this method.

public luya\cms\menu\Query preloadModels ( $preloadModels true )
$preloadModels boolean

Whether to preload all {{luya\cms\menu\Item}} models for {{luya\cms\menu\Item::getModel()}} or not.

                public function preloadModels($preloadModels = true)
{
    $this->_preloadModels = $preloadModels;
    return $this;
}

            
root() public method

Helper method to retrieve only the root elements for a given query.

public luya\cms\menu\Query root ( )

                public function root()
{
    return $this->where([self::FIELD_PARENTNAVID => 0]);
}

            
setMenu() public method

Setter method for menu Container.

public void setMenu ( luya\cms\Menu $menu )
$menu luya\cms\Menu

                public function setMenu(Menu $menu)
{
    $this->_menu = $menu;
}

            
tags() public method (available since version 2.2.0)

Filter by Tag IDs.

An example of how to filter a menu based on tag ids:

foreach (Yii::$app->menu->find()->container('default')->tags([1,2])->limit(3)->al() as $item) {
    echo $item->title;
}

Returns all pages in the default container with tag ids 1 & 2 limited by 3 entries.

public luya\cms\menu\Query tags ( $tags )
$tags string|array

This can be either a string with a tag id or an array with tag ids.

                public function tags($tags)
{
    $ids = TagRelation::find()
        ->select(['pk_id'])
        ->where([
            'and',
            ['=', 'table_name', Nav::tableName()],
            ['in', 'tag_id', (array) $tags]
        ])
        ->column();
    return $this->where(['in', self::FIELD_NAVID, $ids]);
}

            
where() public method

Query where similar behavior of filtering items.

Key Value Filtering

When using key value where condition, the operator equal (=) will be used by default.

where(['field' => 'value'])

which is equals to in operator mode:

where(['=', 'field', 'value']);

Its also possible to have multiple AND where conditions with equal (=) operator:

`php where(['field' => 'value', 'anotherfield' => 'anothervalue']); ``

Operator Filtering

where(['operator', 'field', 'value']);

Available compare operators:

  • < expression where field is smaller then value.
  • > expression where field is bigger then value.
  • = expression where field is equal value.
  • <= expression where field is small or equal then value.
  • >= expression where field is bigger or equal then value.
  • == expression where field is equal to the value and even the type must be equal.
  • in expression where the second value is an array with values to look inside.

Only one operator speific argument can be provided, to chain another expression use the andWhere() method.

Multi Dimension Filtering

The most common case for filtering items is the equal expression combined with add statements.

For example the following expression

where(['=', 'parent_nav_id', 0])->andWhere(['=', 'container', 'footer']);

is equal to the short form multi deimnsion filtering expression

where(['parent_nav_id' => 0, 'container' => 'footer']);

Its not possibile to make where conditions on the same column name (id in this example).

where(['>', 'id', 1])->andWHere(['<', 'id', 3]);

This will only append the first condition where id is bigger then 1 and ignore the second one.

Example using in operator

where(['in', 'container', ['default', 'footer']); // querys all items from the containers `default` and `footer`.
public luya\cms\menu\Query where ( array $args )
$args array

The where defintion can be either an key-value pairing or a condition representen as array.

throws luya\cms\Exception

                public function where(array $args)
{
    if (ArrayHelper::isAssociative($args, false)) {
        // ensure: ['container' => 'default', 'parent_nav_id' => 0] is possible
        foreach ($args as $key => $value) {
            $this->_where[] = ['op' => '=', 'field' => $key, 'value' => $value];
        }
    } else {
        if (count($args) !== 3) {
            throw new Exception("Where operator format requires at least 3 elements. [operator, attribute, value]");
        }
        if (!in_array($args[0], $this->whereOperators, true)) {
            throw new Exception(sprintf("The given where operator '%s' does not exists. https://luya.io/api/luya-cms-menu-Query#where()-detail for all available conditions.", $args[0]));
        }
        $this->_where[] = ['op' => $args[0], 'field' => $args[1], 'value' => $args[2]];
    }
    return $this;
}

            
with() public method

With/Without expression to hidde or display data from the Menu Query.

public luya\cms\menu\Query with ( $types )
$types string|array

Can be a string containg "hidden" or an array with multiple with statements for example ['hidden'].

                public function with($types)
{
    $types = (array) $types;
    foreach ($types as $type) {
        if (isset($this->_with[$type])) {
            $this->_with[$type] = true;
        }
    }
    return $this;
}