1+ <?php
2+
3+ namespace PFinal \Database ;
4+
5+ use Leaf \Application ;
6+ use Leaf \Pagination ;
7+
8+ /**
9+ * 数据提供者
10+ */
11+ class DataProvider implements \JsonSerializable, \ArrayAccess, \Iterator
12+ {
13+ /** @var $page Pagination */
14+ protected $ page ;
15+ /** @var $query Builder */
16+ protected $ query ;
17+
18+ private $ data ;
19+
20+ /**
21+ * @param \PFinal\Database\Builder $query
22+ */
23+ public function __construct ($ query )
24+ {
25+ $ this ->query = $ query ;
26+ }
27+
28+ /**
29+ * @return array
30+ */
31+ public function getData ()
32+ {
33+ $ this ->fillData ();
34+ return $ this ->data ;
35+ }
36+
37+ /**
38+ * @return Pagination
39+ */
40+ public function getPage ()
41+ {
42+ if ($ this ->page === null ) {
43+
44+ $ this ->page = Application::$ app ->make ('Leaf \\Pagination ' );
45+
46+ $ countQuery = clone $ this ->query ;
47+ $ this ->page ->itemCount = $ countQuery ->count ();
48+ }
49+
50+ return $ this ->page ;
51+ }
52+
53+ /**
54+ * 分页按扭
55+ *
56+ * @param string $baseUrl
57+ * @param null $prefix
58+ * @param null $suffix
59+ * @return string
60+ */
61+ public function createLinks ($ baseUrl = '' , $ prefix = null , $ suffix = null )
62+ {
63+ return $ this ->getPage ()->createLinks ($ baseUrl , $ prefix , $ suffix );
64+ }
65+
66+ /**
67+ * @return array
68+ */
69+ public function jsonSerialize ()
70+ {
71+ return array (
72+ 'page ' => $ this ->getPage (),
73+ 'data ' => $ this ->getData (),
74+ );
75+ }
76+
77+ private function fillData ()
78+ {
79+ if ($ this ->data === null ) {
80+ $ this ->data = $ this ->query ->limit ($ this ->getPage ()->limit )->findAll ();
81+ }
82+ }
83+
84+ public function offsetExists ($ offset )
85+ {
86+ $ this ->fillData ();
87+ return isset ($ this ->data [$ offset ]);
88+ }
89+
90+ public function offsetGet ($ offset )
91+ {
92+ $ this ->fillData ();
93+ return $ this ->data [$ offset ];
94+ }
95+
96+ public function offsetSet ($ offset , $ value )
97+ {
98+ $ this ->fillData ();
99+ $ this ->data [$ offset ] = $ value ;
100+ }
101+
102+ public function offsetUnset ($ offset )
103+ {
104+ $ this ->fillData ();
105+ unset($ this ->data [$ offset ]);
106+ }
107+
108+ private $ position = 0 ;
109+
110+ public function current ()
111+ {
112+ $ this ->fillData ();
113+ return $ this ->data [$ this ->position ];
114+ }
115+
116+ public function next ()
117+ {
118+ ++$ this ->position ;
119+ }
120+
121+ public function key ()
122+ {
123+ return $ this ->position ;
124+ }
125+
126+ public function valid ()
127+ {
128+ $ this ->fillData ();
129+ return isset ($ this ->data [$ this ->position ]);
130+ }
131+
132+ public function rewind ()
133+ {
134+ $ this ->position = 0 ;
135+ }
136+ }
0 commit comments