mapper.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. <?php
  2. /*
  3. Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved.
  4. This file is part of the Fat-Free Framework (http://fatfreeframework.com).
  5. This is free software: you can redistribute it and/or modify it under the
  6. terms of the GNU General Public License as published by the Free Software
  7. Foundation, either version 3 of the License, or later.
  8. Fat-Free Framework is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License along
  13. with Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. namespace DB\Jig;
  16. //! Flat-file DB mapper
  17. class Mapper extends \DB\Cursor {
  18. protected
  19. //! Flat-file DB wrapper
  20. $db,
  21. //! Data file
  22. $file,
  23. //! Document identifier
  24. $id,
  25. //! Document contents
  26. $document=[],
  27. //! field map-reduce handlers
  28. $_reduce;
  29. /**
  30. * Return database type
  31. * @return string
  32. **/
  33. function dbtype() {
  34. return 'Jig';
  35. }
  36. /**
  37. * Return TRUE if field is defined
  38. * @return bool
  39. * @param $key string
  40. **/
  41. function exists($key) {
  42. return array_key_exists($key,$this->document);
  43. }
  44. /**
  45. * Assign value to field
  46. * @return scalar|FALSE
  47. * @param $key string
  48. * @param $val scalar
  49. **/
  50. function set($key,$val) {
  51. return ($key=='_id')?FALSE:($this->document[$key]=$val);
  52. }
  53. /**
  54. * Retrieve value of field
  55. * @return scalar|FALSE
  56. * @param $key string
  57. **/
  58. function &get($key) {
  59. if ($key=='_id')
  60. return $this->id;
  61. if (array_key_exists($key,$this->document))
  62. return $this->document[$key];
  63. user_error(sprintf(self::E_Field,$key),E_USER_ERROR);
  64. }
  65. /**
  66. * Delete field
  67. * @return NULL
  68. * @param $key string
  69. **/
  70. function clear($key) {
  71. if ($key!='_id')
  72. unset($this->document[$key]);
  73. }
  74. /**
  75. * Convert array to mapper object
  76. * @return object
  77. * @param $id string
  78. * @param $row array
  79. **/
  80. protected function factory($id,$row) {
  81. $mapper=clone($this);
  82. $mapper->reset();
  83. $mapper->id=$id;
  84. foreach ($row as $field=>$val)
  85. $mapper->document[$field]=$val;
  86. $mapper->query=[clone($mapper)];
  87. if (isset($mapper->trigger['load']))
  88. \Base::instance()->call($mapper->trigger['load'],$mapper);
  89. return $mapper;
  90. }
  91. /**
  92. * Return fields of mapper object as an associative array
  93. * @return array
  94. * @param $obj object
  95. **/
  96. function cast($obj=NULL) {
  97. if (!$obj)
  98. $obj=$this;
  99. return $obj->document+['_id'=>$this->id];
  100. }
  101. /**
  102. * Convert tokens in string expression to variable names
  103. * @return string
  104. * @param $str string
  105. **/
  106. function token($str) {
  107. $str=preg_replace_callback(
  108. '/(?<!\w)@(\w(?:[\w\.\[\]])*)/',
  109. function($token) {
  110. // Convert from JS dot notation to PHP array notation
  111. return '$'.preg_replace_callback(
  112. '/(\.\w+)|\[((?:[^\[\]]*|(?R))*)\]/',
  113. function($expr) {
  114. $fw=\Base::instance();
  115. return
  116. '['.
  117. ($expr[1]?
  118. $fw->stringify(substr($expr[1],1)):
  119. (preg_match('/^\w+/',
  120. $mix=$this->token($expr[2]))?
  121. $fw->stringify($mix):
  122. $mix)).
  123. ']';
  124. },
  125. $token[1]
  126. );
  127. },
  128. $str
  129. );
  130. return trim($str);
  131. }
  132. /**
  133. * Return records that match criteria
  134. * @return static[]|FALSE
  135. * @param $filter array
  136. * @param $options array
  137. * @param $ttl int
  138. * @param $log bool
  139. **/
  140. function find($filter=NULL,array $options=NULL,$ttl=0,$log=TRUE) {
  141. if (!$options)
  142. $options=[];
  143. $options+=[
  144. 'order'=>NULL,
  145. 'limit'=>0,
  146. 'offset'=>0,
  147. 'group'=>NULL,
  148. ];
  149. $fw=\Base::instance();
  150. $cache=\Cache::instance();
  151. $db=$this->db;
  152. $now=microtime(TRUE);
  153. $data=[];
  154. if (!$fw->CACHE || !$ttl || !($cached=$cache->exists(
  155. $hash=$fw->hash($this->db->dir().
  156. $fw->stringify([$filter,$options])).'.jig',$data)) ||
  157. $cached[0]+$ttl<microtime(TRUE)) {
  158. $data=$db->read($this->file);
  159. if (is_null($data))
  160. return FALSE;
  161. foreach ($data as $id=>&$doc) {
  162. $doc['_id']=$id;
  163. unset($doc);
  164. }
  165. if ($filter) {
  166. if (!is_array($filter))
  167. return FALSE;
  168. // Normalize equality operator
  169. $expr=preg_replace('/(?<=[^<>!=])=(?!=)/','==',$filter[0]);
  170. // Prepare query arguments
  171. $args=isset($filter[1]) && is_array($filter[1])?
  172. $filter[1]:
  173. array_slice($filter,1,NULL,TRUE);
  174. $args=is_array($args)?$args:[1=>$args];
  175. $keys=$vals=[];
  176. $tokens=array_slice(
  177. token_get_all('<?php '.$this->token($expr)),1);
  178. $data=array_filter($data,
  179. function($_row) use($fw,$args,$tokens) {
  180. $_expr='';
  181. $ctr=0;
  182. $named=FALSE;
  183. foreach ($tokens as $token) {
  184. if (is_string($token))
  185. if ($token=='?') {
  186. // Positional
  187. $ctr++;
  188. $key=$ctr;
  189. }
  190. else {
  191. if ($token==':')
  192. $named=TRUE;
  193. else
  194. $_expr.=$token;
  195. continue;
  196. }
  197. elseif ($named &&
  198. token_name($token[0])=='T_STRING') {
  199. $key=':'.$token[1];
  200. $named=FALSE;
  201. }
  202. else {
  203. $_expr.=$token[1];
  204. continue;
  205. }
  206. $_expr.=$fw->stringify(
  207. is_string($args[$key])?
  208. addcslashes($args[$key],'\''):
  209. $args[$key]);
  210. }
  211. // Avoid conflict with user code
  212. unset($fw,$tokens,$args,$ctr,$token,$key,$named);
  213. extract($_row);
  214. // Evaluate pseudo-SQL expression
  215. return eval('return '.$_expr.';');
  216. }
  217. );
  218. }
  219. if (isset($options['group'])) {
  220. $cols=array_reverse($fw->split($options['group']));
  221. // sort into groups
  222. $data=$this->sort($data,$options['group']);
  223. foreach($data as $i=>&$row) {
  224. if (!isset($prev)) {
  225. $prev=$row;
  226. $prev_i=$i;
  227. }
  228. $drop=false;
  229. foreach ($cols as $col)
  230. if ($prev_i!=$i && array_key_exists($col,$row) &&
  231. array_key_exists($col,$prev) && $row[$col]==$prev[$col])
  232. // reduce/modify
  233. $drop=!isset($this->_reduce[$col]) || call_user_func_array(
  234. $this->_reduce[$col][0],[&$prev,&$row])!==FALSE;
  235. elseif (isset($this->_reduce[$col])) {
  236. $null=null;
  237. // initial
  238. call_user_func_array($this->_reduce[$col][0],[&$row,&$null]);
  239. }
  240. if ($drop)
  241. unset($data[$i]);
  242. else {
  243. $prev=&$row;
  244. $prev_i=$i;
  245. }
  246. unset($row);
  247. }
  248. // finalize
  249. if ($this->_reduce[$col][1])
  250. foreach($data as $i=>&$row) {
  251. $row=call_user_func($this->_reduce[$col][1],$row);
  252. if (!$row)
  253. unset($data[$i]);
  254. unset($row);
  255. }
  256. }
  257. if (isset($options['order']))
  258. $data=$this->sort($data,$options['order']);
  259. $data=array_slice($data,
  260. $options['offset'],$options['limit']?:NULL,TRUE);
  261. if ($fw->CACHE && $ttl)
  262. // Save to cache backend
  263. $cache->set($hash,$data,$ttl);
  264. }
  265. $out=[];
  266. foreach ($data as $id=>&$doc) {
  267. unset($doc['_id']);
  268. $out[]=$this->factory($id,$doc);
  269. unset($doc);
  270. }
  271. if ($log && isset($args)) {
  272. if ($filter)
  273. foreach ($args as $key=>$val) {
  274. $vals[]=$fw->stringify(is_array($val)?$val[0]:$val);
  275. $keys[]='/'.(is_numeric($key)?'\?':preg_quote($key)).'/';
  276. }
  277. $db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
  278. $this->file.' [find] '.
  279. ($filter?preg_replace($keys,$vals,$filter[0],1):''));
  280. }
  281. return $out;
  282. }
  283. /**
  284. * Sort a collection
  285. * @param $data
  286. * @param $cond
  287. * @return mixed
  288. */
  289. protected function sort($data,$cond) {
  290. $cols=\Base::instance()->split($cond);
  291. uasort(
  292. $data,
  293. function($val1,$val2) use($cols) {
  294. foreach ($cols as $col) {
  295. $parts=explode(' ',$col,2);
  296. $order=empty($parts[1])?
  297. SORT_ASC:
  298. constant($parts[1]);
  299. $col=$parts[0];
  300. if (!array_key_exists($col,$val1))
  301. $val1[$col]=NULL;
  302. if (!array_key_exists($col,$val2))
  303. $val2[$col]=NULL;
  304. list($v1,$v2)=[$val1[$col],$val2[$col]];
  305. if ($out=strnatcmp($v1,$v2)*
  306. (($order==SORT_ASC)*2-1))
  307. return $out;
  308. }
  309. return 0;
  310. }
  311. );
  312. return $data;
  313. }
  314. /**
  315. * Add reduce handler for grouped fields
  316. * @param $key string
  317. * @param $handler callback
  318. * @param $finalize callback
  319. */
  320. function reduce($key,$handler,$finalize=null){
  321. $this->_reduce[$key]=[$handler,$finalize];
  322. }
  323. /**
  324. * Count records that match criteria
  325. * @return int
  326. * @param $filter array
  327. * @param $options array
  328. * @param $ttl int
  329. **/
  330. function count($filter=NULL,array $options=NULL,$ttl=0) {
  331. $now=microtime(TRUE);
  332. $out=count($this->find($filter,$options,$ttl,FALSE));
  333. $this->db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
  334. $this->file.' [count] '.($filter?json_encode($filter):''));
  335. return $out;
  336. }
  337. /**
  338. * Return record at specified offset using criteria of previous
  339. * load() call and make it active
  340. * @return array
  341. * @param $ofs int
  342. **/
  343. function skip($ofs=1) {
  344. $this->document=($out=parent::skip($ofs))?$out->document:[];
  345. $this->id=$out?$out->id:NULL;
  346. if ($this->document && isset($this->trigger['load']))
  347. \Base::instance()->call($this->trigger['load'],$this);
  348. return $out;
  349. }
  350. /**
  351. * Insert new record
  352. * @return array
  353. **/
  354. function insert() {
  355. if ($this->id)
  356. return $this->update();
  357. $db=$this->db;
  358. $now=microtime(TRUE);
  359. while (($id=uniqid(NULL,TRUE)) &&
  360. ($data=&$db->read($this->file)) && isset($data[$id]) &&
  361. !connection_aborted())
  362. usleep(mt_rand(0,100));
  363. $this->id=$id;
  364. $pkey=['_id'=>$this->id];
  365. if (isset($this->trigger['beforeinsert']) &&
  366. \Base::instance()->call($this->trigger['beforeinsert'],
  367. [$this,$pkey])===FALSE)
  368. return $this->document;
  369. $data[$id]=$this->document;
  370. $db->write($this->file,$data);
  371. $db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
  372. $this->file.' [insert] '.json_encode($this->document));
  373. if (isset($this->trigger['afterinsert']))
  374. \Base::instance()->call($this->trigger['afterinsert'],
  375. [$this,$pkey]);
  376. $this->load(['@_id=?',$this->id]);
  377. return $this->document;
  378. }
  379. /**
  380. * Update current record
  381. * @return array
  382. **/
  383. function update() {
  384. $db=$this->db;
  385. $now=microtime(TRUE);
  386. $data=&$db->read($this->file);
  387. if (isset($this->trigger['beforeupdate']) &&
  388. \Base::instance()->call($this->trigger['beforeupdate'],
  389. [$this,['_id'=>$this->id]])===FALSE)
  390. return $this->document;
  391. $data[$this->id]=$this->document;
  392. $db->write($this->file,$data);
  393. $db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
  394. $this->file.' [update] '.json_encode($this->document));
  395. if (isset($this->trigger['afterupdate']))
  396. \Base::instance()->call($this->trigger['afterupdate'],
  397. [$this,['_id'=>$this->id]]);
  398. return $this->document;
  399. }
  400. /**
  401. * Delete current record
  402. * @return bool
  403. * @param $filter array
  404. * @param $quick bool
  405. **/
  406. function erase($filter=NULL,$quick=FALSE) {
  407. $db=$this->db;
  408. $now=microtime(TRUE);
  409. $data=&$db->read($this->file);
  410. $pkey=['_id'=>$this->id];
  411. if ($filter) {
  412. foreach ($this->find($filter,NULL,FALSE) as $mapper)
  413. if (!$mapper->erase(null,$quick))
  414. return FALSE;
  415. return TRUE;
  416. }
  417. elseif (isset($this->id)) {
  418. unset($data[$this->id]);
  419. parent::erase();
  420. }
  421. else
  422. return FALSE;
  423. if (!$quick && isset($this->trigger['beforeerase']) &&
  424. \Base::instance()->call($this->trigger['beforeerase'],
  425. [$this,$pkey])===FALSE)
  426. return FALSE;
  427. $db->write($this->file,$data);
  428. if ($filter) {
  429. $args=isset($filter[1]) && is_array($filter[1])?
  430. $filter[1]:
  431. array_slice($filter,1,NULL,TRUE);
  432. $args=is_array($args)?$args:[1=>$args];
  433. foreach ($args as $key=>$val) {
  434. $vals[]=\Base::instance()->
  435. stringify(is_array($val)?$val[0]:$val);
  436. $keys[]='/'.(is_numeric($key)?'\?':preg_quote($key)).'/';
  437. }
  438. }
  439. $db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
  440. $this->file.' [erase] '.
  441. ($filter?preg_replace($keys,$vals,$filter[0],1):''));
  442. if (!$quick && isset($this->trigger['aftererase']))
  443. \Base::instance()->call($this->trigger['aftererase'],
  444. [$this,$pkey]);
  445. return TRUE;
  446. }
  447. /**
  448. * Reset cursor
  449. * @return NULL
  450. **/
  451. function reset() {
  452. $this->id=NULL;
  453. $this->document=[];
  454. parent::reset();
  455. }
  456. /**
  457. * Hydrate mapper object using hive array variable
  458. * @return NULL
  459. * @param $var array|string
  460. * @param $func callback
  461. **/
  462. function copyfrom($var,$func=NULL) {
  463. if (is_string($var))
  464. $var=\Base::instance()->$var;
  465. if ($func)
  466. $var=call_user_func($func,$var);
  467. foreach ($var as $key=>$val)
  468. $this->set($key,$val);
  469. }
  470. /**
  471. * Populate hive array variable with mapper fields
  472. * @return NULL
  473. * @param $key string
  474. **/
  475. function copyto($key) {
  476. $var=&\Base::instance()->ref($key);
  477. foreach ($this->document as $key=>$field)
  478. $var[$key]=$field;
  479. }
  480. /**
  481. * Return field names
  482. * @return array
  483. **/
  484. function fields() {
  485. return array_keys($this->document);
  486. }
  487. /**
  488. * Retrieve external iterator for fields
  489. * @return object
  490. **/
  491. function getiterator() {
  492. return new \ArrayIterator($this->cast());
  493. }
  494. /**
  495. * Instantiate class
  496. * @return void
  497. * @param $db object
  498. * @param $file string
  499. **/
  500. function __construct(\DB\Jig $db,$file) {
  501. $this->db=$db;
  502. $this->file=$file;
  503. $this->reset();
  504. }
  505. }