mapper.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. 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|array
  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. $tag='';
  155. if (is_array($ttl))
  156. list($ttl,$tag)=$ttl;
  157. if (!$fw->CACHE || !$ttl || !($cached=$cache->exists(
  158. $hash=$fw->hash($this->db->dir().
  159. $fw->stringify([$filter,$options])).($tag?'.'.$tag:'').'.jig',$data)) ||
  160. $cached[0]+$ttl<microtime(TRUE)) {
  161. $data=$db->read($this->file);
  162. if (is_null($data))
  163. return FALSE;
  164. foreach ($data as $id=>&$doc) {
  165. $doc['_id']=$id;
  166. unset($doc);
  167. }
  168. if ($filter) {
  169. if (!is_array($filter))
  170. return FALSE;
  171. // Normalize equality operator
  172. $expr=preg_replace('/(?<=[^<>!=])=(?!=)/','==',$filter[0]);
  173. // Prepare query arguments
  174. $args=isset($filter[1]) && is_array($filter[1])?
  175. $filter[1]:
  176. array_slice($filter,1,NULL,TRUE);
  177. $args=is_array($args)?$args:[1=>$args];
  178. $keys=$vals=[];
  179. $tokens=array_slice(
  180. token_get_all('<?php '.$this->token($expr)),1);
  181. $data=array_filter($data,
  182. function($_row) use($fw,$args,$tokens) {
  183. $_expr='';
  184. $ctr=0;
  185. $named=FALSE;
  186. foreach ($tokens as $token) {
  187. if (is_string($token))
  188. if ($token=='?') {
  189. // Positional
  190. $ctr++;
  191. $key=$ctr;
  192. }
  193. else {
  194. if ($token==':')
  195. $named=TRUE;
  196. else
  197. $_expr.=$token;
  198. continue;
  199. }
  200. elseif ($named &&
  201. token_name($token[0])=='T_STRING') {
  202. $key=':'.$token[1];
  203. $named=FALSE;
  204. }
  205. else {
  206. $_expr.=$token[1];
  207. continue;
  208. }
  209. $_expr.=$fw->stringify(
  210. is_string($args[$key])?
  211. addcslashes($args[$key],'\''):
  212. $args[$key]);
  213. }
  214. // Avoid conflict with user code
  215. unset($fw,$tokens,$args,$ctr,$token,$key,$named);
  216. extract($_row);
  217. // Evaluate pseudo-SQL expression
  218. return eval('return '.$_expr.';');
  219. }
  220. );
  221. }
  222. if (isset($options['group'])) {
  223. $cols=array_reverse($fw->split($options['group']));
  224. // sort into groups
  225. $data=$this->sort($data,$options['group']);
  226. foreach($data as $i=>&$row) {
  227. if (!isset($prev)) {
  228. $prev=$row;
  229. $prev_i=$i;
  230. }
  231. $drop=false;
  232. foreach ($cols as $col)
  233. if ($prev_i!=$i && array_key_exists($col,$row) &&
  234. array_key_exists($col,$prev) && $row[$col]==$prev[$col])
  235. // reduce/modify
  236. $drop=!isset($this->_reduce[$col]) || call_user_func_array(
  237. $this->_reduce[$col][0],[&$prev,&$row])!==FALSE;
  238. elseif (isset($this->_reduce[$col])) {
  239. $null=null;
  240. // initial
  241. call_user_func_array($this->_reduce[$col][0],[&$row,&$null]);
  242. }
  243. if ($drop)
  244. unset($data[$i]);
  245. else {
  246. $prev=&$row;
  247. $prev_i=$i;
  248. }
  249. unset($row);
  250. }
  251. // finalize
  252. if ($this->_reduce[$col][1])
  253. foreach($data as $i=>&$row) {
  254. $row=call_user_func($this->_reduce[$col][1],$row);
  255. if (!$row)
  256. unset($data[$i]);
  257. unset($row);
  258. }
  259. }
  260. if (isset($options['order']))
  261. $data=$this->sort($data,$options['order']);
  262. $data=array_slice($data,
  263. $options['offset'],$options['limit']?:NULL,TRUE);
  264. if ($fw->CACHE && $ttl)
  265. // Save to cache backend
  266. $cache->set($hash,$data,$ttl);
  267. }
  268. $out=[];
  269. foreach ($data as $id=>&$doc) {
  270. unset($doc['_id']);
  271. $out[]=$this->factory($id,$doc);
  272. unset($doc);
  273. }
  274. if ($log && isset($args)) {
  275. if ($filter)
  276. foreach ($args as $key=>$val) {
  277. $vals[]=$fw->stringify(is_array($val)?$val[0]:$val);
  278. $keys[]='/'.(is_numeric($key)?'\?':preg_quote($key)).'/';
  279. }
  280. $db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
  281. $this->file.' [find] '.
  282. ($filter?preg_replace($keys,$vals,$filter[0],1):''));
  283. }
  284. return $out;
  285. }
  286. /**
  287. * Sort a collection
  288. * @param $data
  289. * @param $cond
  290. * @return mixed
  291. */
  292. protected function sort($data,$cond) {
  293. $cols=\Base::instance()->split($cond);
  294. uasort(
  295. $data,
  296. function($val1,$val2) use($cols) {
  297. foreach ($cols as $col) {
  298. $parts=explode(' ',$col,2);
  299. $order=empty($parts[1])?
  300. SORT_ASC:
  301. constant($parts[1]);
  302. $col=$parts[0];
  303. if (!array_key_exists($col,$val1))
  304. $val1[$col]=NULL;
  305. if (!array_key_exists($col,$val2))
  306. $val2[$col]=NULL;
  307. list($v1,$v2)=[$val1[$col],$val2[$col]];
  308. if ($out=strnatcmp($v1,$v2)*
  309. (($order==SORT_ASC)*2-1))
  310. return $out;
  311. }
  312. return 0;
  313. }
  314. );
  315. return $data;
  316. }
  317. /**
  318. * Add reduce handler for grouped fields
  319. * @param $key string
  320. * @param $handler callback
  321. * @param $finalize callback
  322. */
  323. function reduce($key,$handler,$finalize=null){
  324. $this->_reduce[$key]=[$handler,$finalize];
  325. }
  326. /**
  327. * Count records that match criteria
  328. * @return int
  329. * @param $filter array
  330. * @param $options array
  331. * @param $ttl int|array
  332. **/
  333. function count($filter=NULL,array $options=NULL,$ttl=0) {
  334. $now=microtime(TRUE);
  335. $out=count($this->find($filter,$options,$ttl,FALSE));
  336. $this->db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
  337. $this->file.' [count] '.($filter?json_encode($filter):''));
  338. return $out;
  339. }
  340. /**
  341. * Return record at specified offset using criteria of previous
  342. * load() call and make it active
  343. * @return array
  344. * @param $ofs int
  345. **/
  346. function skip($ofs=1) {
  347. $this->document=($out=parent::skip($ofs))?$out->document:[];
  348. $this->id=$out?$out->id:NULL;
  349. if ($this->document && isset($this->trigger['load']))
  350. \Base::instance()->call($this->trigger['load'],$this);
  351. return $out;
  352. }
  353. /**
  354. * Insert new record
  355. * @return array
  356. **/
  357. function insert() {
  358. if ($this->id)
  359. return $this->update();
  360. $db=$this->db;
  361. $now=microtime(TRUE);
  362. while (($id=uniqid(NULL,TRUE)) &&
  363. ($data=&$db->read($this->file)) && isset($data[$id]) &&
  364. !connection_aborted())
  365. usleep(mt_rand(0,100));
  366. $this->id=$id;
  367. $pkey=['_id'=>$this->id];
  368. if (isset($this->trigger['beforeinsert']) &&
  369. \Base::instance()->call($this->trigger['beforeinsert'],
  370. [$this,$pkey])===FALSE)
  371. return $this->document;
  372. $data[$id]=$this->document;
  373. $db->write($this->file,$data);
  374. $db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
  375. $this->file.' [insert] '.json_encode($this->document));
  376. if (isset($this->trigger['afterinsert']))
  377. \Base::instance()->call($this->trigger['afterinsert'],
  378. [$this,$pkey]);
  379. $this->load(['@_id=?',$this->id]);
  380. return $this->document;
  381. }
  382. /**
  383. * Update current record
  384. * @return array
  385. **/
  386. function update() {
  387. $db=$this->db;
  388. $now=microtime(TRUE);
  389. $data=&$db->read($this->file);
  390. if (isset($this->trigger['beforeupdate']) &&
  391. \Base::instance()->call($this->trigger['beforeupdate'],
  392. [$this,['_id'=>$this->id]])===FALSE)
  393. return $this->document;
  394. $data[$this->id]=$this->document;
  395. $db->write($this->file,$data);
  396. $db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
  397. $this->file.' [update] '.json_encode($this->document));
  398. if (isset($this->trigger['afterupdate']))
  399. \Base::instance()->call($this->trigger['afterupdate'],
  400. [$this,['_id'=>$this->id]]);
  401. return $this->document;
  402. }
  403. /**
  404. * Delete current record
  405. * @return bool
  406. * @param $filter array
  407. * @param $quick bool
  408. **/
  409. function erase($filter=NULL,$quick=FALSE) {
  410. $db=$this->db;
  411. $now=microtime(TRUE);
  412. $data=&$db->read($this->file);
  413. $pkey=['_id'=>$this->id];
  414. if ($filter) {
  415. foreach ($this->find($filter,NULL,FALSE) as $mapper)
  416. if (!$mapper->erase(null,$quick))
  417. return FALSE;
  418. return TRUE;
  419. }
  420. elseif (isset($this->id)) {
  421. unset($data[$this->id]);
  422. parent::erase();
  423. }
  424. else
  425. return FALSE;
  426. if (!$quick && isset($this->trigger['beforeerase']) &&
  427. \Base::instance()->call($this->trigger['beforeerase'],
  428. [$this,$pkey])===FALSE)
  429. return FALSE;
  430. $db->write($this->file,$data);
  431. if ($filter) {
  432. $args=isset($filter[1]) && is_array($filter[1])?
  433. $filter[1]:
  434. array_slice($filter,1,NULL,TRUE);
  435. $args=is_array($args)?$args:[1=>$args];
  436. foreach ($args as $key=>$val) {
  437. $vals[]=\Base::instance()->
  438. stringify(is_array($val)?$val[0]:$val);
  439. $keys[]='/'.(is_numeric($key)?'\?':preg_quote($key)).'/';
  440. }
  441. }
  442. $db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
  443. $this->file.' [erase] '.
  444. ($filter?preg_replace($keys,$vals,$filter[0],1):''));
  445. if (!$quick && isset($this->trigger['aftererase']))
  446. \Base::instance()->call($this->trigger['aftererase'],
  447. [$this,$pkey]);
  448. return TRUE;
  449. }
  450. /**
  451. * Reset cursor
  452. * @return NULL
  453. **/
  454. function reset() {
  455. $this->id=NULL;
  456. $this->document=[];
  457. parent::reset();
  458. }
  459. /**
  460. * Hydrate mapper object using hive array variable
  461. * @return NULL
  462. * @param $var array|string
  463. * @param $func callback
  464. **/
  465. function copyfrom($var,$func=NULL) {
  466. if (is_string($var))
  467. $var=\Base::instance()->$var;
  468. if ($func)
  469. $var=call_user_func($func,$var);
  470. foreach ($var as $key=>$val)
  471. $this->set($key,$val);
  472. }
  473. /**
  474. * Populate hive array variable with mapper fields
  475. * @return NULL
  476. * @param $key string
  477. **/
  478. function copyto($key) {
  479. $var=&\Base::instance()->ref($key);
  480. foreach ($this->document as $key=>$field)
  481. $var[$key]=$field;
  482. }
  483. /**
  484. * Return field names
  485. * @return array
  486. **/
  487. function fields() {
  488. return array_keys($this->document);
  489. }
  490. /**
  491. * Retrieve external iterator for fields
  492. * @return object
  493. **/
  494. function getiterator() {
  495. return new \ArrayIterator($this->cast());
  496. }
  497. /**
  498. * Instantiate class
  499. * @return void
  500. * @param $db object
  501. * @param $file string
  502. **/
  503. function __construct(\DB\Jig $db,$file) {
  504. $this->db=$db;
  505. $this->file=$file;
  506. $this->reset();
  507. }
  508. }