Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CakePHP ListExpression
<?php
declare(strict_types=1);
namespace App\Database\Expression;
use Cake\Database\ExpressionInterface;
use Cake\Database\ValueBinder;
use Closure;
class ListExpression implements ExpressionInterface
{
/**
* Holds the identifier string
*
* @var array
*/
protected $_items;
/**
* Constructor
*
* @param array $items list items
*/
public function __construct(array $items)
{
$this->setItems($items);
}
/**
* Sets the items this expression represents
*
* @param array $items The items.
* @return void
*/
public function setItems(array $items): void
{
$this->_items = $items;
}
/**
* Returns the items this expression represents
*
* @return array
*/
public function getItems(): array
{
return $this->_items;
}
/**
* Converts the expression to its string representation
*
* @param \Cake\Database\ValueBinder $generator Placeholder generator object
* @return string
*/
public function sql(ValueBinder $generator): string
{
$result = '';
foreach ($this->_items as $item) {
if ($result !== '') {
$result .= ' ';
}
if (is_string($item)) {
$result .= $item;
} elseif ($item instanceof ExpressionInterface) {
$result .= $item->sql($generator);
}
}
return $result;
}
/**
* This method is a no-op, this is a leaf type of expression,
* hence there is nothing to traverse
*
* @param \Closure $visitor The callable to traverse with.
* @return $this
*/
public function traverse(Closure $visitor)
{
foreach ($this->_items as $v) {
if ($v instanceof ExpressionInterface) {
$visitor($v);
$v->traverse($visitor);
}
if (!is_array($v)) {
continue;
}
foreach ($v as $field) {
if ($field instanceof ExpressionInterface) {
$visitor($field);
$field->traverse($visitor);
}
}
}
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.