| 
<?php
/*################################################################################*
 #
 #   (c)Copyright Till Wehowski, http://Webfan.de
 #    License: Do What The Fuck You Want To Public License
 */
 namespace webdof\Serialize\Bit;
 use webdof\Serialize;
 
 
 class FlagMask extends \webdof\Serialize\Bit\Bitmask
 {
 const OK = 0; //offset bit keys/num
 const OL = 1; //offset label text
 const OV = 2; //offset value
 const P2 = 3;
 protected $labels;
 
 
 public function clear()
 {
 parent::clear();
 $this->setLabels( array(  ) );
 }
 
 
 public function toInt()
 {
 $check = 0;
 foreach($this->labels as $bit => $label)
 {
 if($label[self::OV])$check += $label[self::P2];
 }
 $this->flags = $check;
 return $this->flags;
 }
 
 
 public function calc($r)
 {
 if(!is_array($this->labels))$this->labels = array();
 
 foreach($this->labels as $bit => $label)
 {
 $this->labels[$bit][self::OV] = 0;
 }
 
 $check = 0;
 foreach($r as $bit => $pow)
 {
 $this->labels[$bit][self::OV] = 1;
 $this->labels[$bit][self::P2] = $pow;
 $check += $pow;
 }
 
 if($check !== $this->flags)
 {
 echo "error invalid value: \n";
 var_dump($check, $this->flags);
 echo "\n";
 return trigger_error( 'Inconsistence ('.$check.' expected, '.$this->flags.' given) in '.get_class($this)
 .' '.__METHOD__.' '.basename(__FILE__).' line '.__LINE__ ,  E_USER_FATAL );
 }
 
 return $r;
 }
 
 
 public function load($flags)
 {
 $this->flags = (int)$flags;
 $r = parent::load($this->flags);
 return $this->calc($r);
 }
 
 public function max()
 {
 return pow(2,count($this->labels));
 }
 
 
 public function getLabels()
 {
 return $this->labels;
 }
 
 
 public function setLabels(Array $labels = array( array('read', 'lesen'), array('write', 'Schreiben erlaubt', FALSE) ) )
 {
 $this->load( 0 );
 $this->labels = $labels;
 foreach($this->labels as $bit => $label)
 {
 $this->labels[$bit] = $label;
 $this->set($label[self::OK], ((isset($label[self::OV]) && $label[self::OV] === TRUE )
 ? TRUE
 : FALSE)
 );
 }
 }
 
 
 public function is($flag)
 {
 if(is_string($flag))
 {
 foreach($this->labels as $bit => $label)
 {
 if($label[self::OK] !== $flag)
 {
 continue;
 }
 $flag = $bit;
 break;
 }
 }
 
 
 
 return parent::is($flag);
 }
 
 public function set($flag, $value)
 {
 if(is_string($flag))
 {
 foreach($this->labels as $bit => $label)
 {
 if($label[self::OK] !== $flag)
 {
 continue;
 }
 $flag = $bit;
 break;
 }
 }
 
 
 $this->labels[$flag][self::OV] = ($value==1) ? $value : FALSE;
 $this->labels[$flag][self::P2] = pow(2,$flag);
 parent::set($flag, $value);
 $this->toInt();
 }
 
 
 
 
 }
 |