Created
August 15, 2020 21:25
-
-
Save skie/f6e4f1a1b61e0f902a507f7907c3bbf2 to your computer and use it in GitHub Desktop.
CakePHP ListExpression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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