Skip to content

Commit

Permalink
change EnumTrait
Browse files Browse the repository at this point in the history
  • Loading branch information
mdmunir committed Feb 4, 2016
1 parent 92ada64 commit c2f674c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 32 deletions.
39 changes: 11 additions & 28 deletions EnumTrait.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

namespace mdm\converter;

use ReflectionClass;

/**
Expand All @@ -15,7 +16,7 @@ trait EnumTrait
* @var array
*/
private static $_constants = [];

/**
* Get all constant name
* @param string $prefix
Expand Down Expand Up @@ -48,37 +49,19 @@ public static function constants($prefix = '')
return self::$_constants[$className][$prefix];
}

/**
*
* @param string $name
* @return type
*/
public function __get($name)
protected function getLogical($attribute, $prefix)
{
if (isset($this->enumAttributes, $this->enumAttributes[$name])) {
list($attr, $prefix) = $this->enumAttributes[$name];
$enums = static::enums($prefix);
return isset($enums[$this->$attr]) ? $enums[$this->$attr] : null;
} else {
return parent::__get($name);
}
$enums = static::enums($prefix);
return isset($enums[$this->$attribute]) ? $enums[$this->$attribute] : null;
}

/**
*
* @param string $name
* @param mixed $value
*/
public function __set($name, $value)
protected function setLogical($attribute, $prefix, $value)
{
if (isset($this->enumAttributes, $this->enumAttributes[$name])) {
list($attr, $prefix) = $this->enumAttributes[$name];
$constant = static::constants($prefix);
if (isset($constant[strtoupper($value)])) {
$this->$attr = $constant[strtoupper($value)];
}
} else {
parent::__set($name, $value);
$constant = static::constants($prefix);
if (isset($constant[strtoupper($value)])) {
$this->$attribute = $constant[strtoupper($value)];
} elseif ($value === null) {
$this->$attribute = null;
}
}
}
15 changes: 11 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,20 @@ Use to get list of constant
class Post extends ActiveRecord
{
use \mdm\converter\EnumTrait;

protected $enumAttributes = [
'nmStatus' => ['status', 'STATUS_'],
];

const STATUS_DRAFT = 1;
const STATUS_PUBLISHED = 2;
const STATUS_DELETED = 3;

public function getNmStatus()
{
return $this->getLogical('status', 'STATUS_');
}

public function setNmStatus($value)
{
return $this->setLogical('status', 'STATUS_', $value);
}

}

Expand Down

0 comments on commit c2f674c

Please sign in to comment.