Completed
Push — master ( 349ff5...40080a )
by Jean-Christophe
03:11
created

InstanceViewer::getValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
namespace Ajax\semantic\widgets;
3
use Ajax\service\JString;
4
5
class InstanceViewer {
6
	private $instance;
7
	private $reflect;
8
	private $properties;
9
	private $captions;
10
	private $visibleProperties;
11
	private $values;
12
13
	public function __construct($instance=NULL,$captions=NULL){
14
		$this->values=[];
15
		if(isset($instance))
16
			$this->setInstance($instance);
17
		$this->setCaptions($captions);
18
	}
19
20
	public function getCaption($index){
21
		return $this->properties[$index]->getName();
22
	}
23
24
	public function getCaptions(){
25
		if(isset($this->captions)){
26
			return $this->captions;
27
		}
28
		$captions=[];
29
		$index=0;
30
		$count=$this->count();
31
		while($index<$count){
32
			$captions[]=$this->getCaption($index++);
33
		}
34
		return $captions;
35
	}
36
37
	public function getValues(){
38
		$values=[];
39
		$index=0;
40
		$count=$this->count();
41
		while($index<$count){
42
			$values[]=$this->getValue($index++);
43
		}
44
		return $values;
45
	}
46
47
	public function getValue($index){
48
		$this->properties[$index]->setAccessible(true);
49
		$value=$this->properties[$index]->getValue($this->instance);
50
		if(isset($this->values[$index])){
51
			$value= $this->values[$index]($value);
52
		}
53
		return $value;
54
	}
55
56
	public function count(){
57
		return \sizeof($this->properties);
58
	}
59
60
	public function showableProperty(\ReflectionProperty $rProperty){
61
		if(\is_array($this->visibleProperties)){
62
			return \array_search($rProperty->getName(), $this->visibleProperties);
63
		}
64
		return JString::startswith($rProperty->getName(),"_")===false;
65
	}
66
67
	public function setInstance($instance) {
68
		if(\is_string($instance)){
69
			$instance=new $instance();
70
		}
71
		$this->instance=$instance;
72
		$this->properties=[];
73
		$this->reflect=new \ReflectionClass($instance);
74
		$properties=$this->reflect->getProperties();
75
		foreach ($properties as $property){
76
			$showable=$this->showableProperty($property);
77
			if($showable!==false){
78
				if(\is_int($showable))
79
					$this->properties[$showable]=$property;
80
				else
81
					$this->properties[]=$property;
82
			}
83
		}
84
		return $this;
85
	}
86
87
	public function setCaptions($captions) {
88
		$this->captions=$captions;
89
		return $this;
90
	}
91
92
	public function setVisibleProperties($visibleProperties) {
93
		$this->visibleProperties=$visibleProperties;
94
		return $this;
95
	}
96
97
	public function setValueFunction($index,$callback){
98
		$this->values[$index]=$callback;
99
	}
100
101
102
}