Skip to content

Instantly share code, notes, and snippets.

@aotd1
Last active August 29, 2015 14:23
Show Gist options
  • Save aotd1/cdf743638df0e133659e to your computer and use it in GitHub Desktop.
Save aotd1/cdf743638df0e133659e to your computer and use it in GitHub Desktop.
Yii2 Postgresql array variables trait
<?php
namespace app\components;
use yii\base\InvalidValueException;
/**
* Class PgArrayTrait
* @property string[] $arrayFields
*/
trait PgArrayTrait
{
public function beforeSave($insert)
{
//@TODO: Check dirty attributes, don't touch unchanged
foreach ($this->arrayFields as $name) {
if (is_array($this->$name)) {
$this->$name = self::PhpToPgArray($this->$name);
}
}
return parent::beforeSave($insert);
}
public function afterSave($insert, $changedAttributes)
{
//@TODO: Check dirtynes of attributes, maybe need [[setOldAttribute]] like in [[afterFind]]
foreach ($this->arrayFields as $name) {
if (!is_array($this->$name)) {
$this->$name = self::PgToPhpArray($this->$name);
}
}
return parent::afterSave($insert, $changedAttributes);
}
public function afterFind()
{
foreach ($this->arrayFields as $name) {
$this->setOldAttribute($name, $this->$name = self::PgToPhpArray($this->$name));
}
parent::afterFind();
}
protected static function PhpToPgArray(array $values)
{
//@TODO: sanitize it!
return '{'.implode(',', $values).'}';
}
protected static function PgToPhpArray($value)
{
if (empty($value)) {
return [];
}
if ($value[0] !== '{' || mb_substr($value, -1) !== '}') {
throw new InvalidValueException();
}
return explode(',', mb_substr($value, 1, -1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment