Model.php 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  1. <?php
  2. /*
  3. * This file is part of the Redisun package.
  4. *
  5. * (c) LI Mengxiang <limengxiang876@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Limen\Redisun;
  11. use Exception;
  12. use Limen\Redisun\Commands\Command;
  13. use Limen\Redisun\Commands\Factory;
  14. use Limen\Redisun\Commands\FactoryInterface;
  15. use Predis\Client as RedisClient;
  16. /**
  17. * CRUD model for redis
  18. * Class Model
  19. *
  20. * @package Limen\Redisun
  21. *
  22. * @author LI Mengxiang <limengxiang876@gmail.com>
  23. */
  24. abstract class Model
  25. {
  26. const TYPE_STRING = 'string';
  27. const TYPE_SET = 'set';
  28. const TYPE_SORTED_SET = 'zset';
  29. const TYPE_LIST = 'list';
  30. const TYPE_HASH = 'hash';
  31. // not expired ttl
  32. const TTL_PERSIST = '-1';
  33. /**
  34. * Redis data type
  35. * @var string
  36. * Could be string, list, set, zset, hash
  37. */
  38. protected $type;
  39. /**
  40. * Redis key representation.
  41. * users:{id}:phone e.g.
  42. * @var string
  43. */
  44. protected $key;
  45. /**
  46. * @var string
  47. */
  48. protected $delimiter = ':';
  49. /**
  50. * Primary key name like database
  51. * @var string
  52. */
  53. protected $primaryFieldName = 'id';
  54. /**
  55. * @var string
  56. */
  57. protected $fieldWrapper = '{}';
  58. /**
  59. * @var QueryBuilder
  60. */
  61. protected $queryBuilder;
  62. /**
  63. * @var FactoryInterface
  64. */
  65. protected $commandFactory;
  66. /**
  67. * @var array
  68. */
  69. protected $orderBys = [];
  70. /**
  71. * offset for pagination
  72. * @var int
  73. */
  74. protected $offset;
  75. /**
  76. * limit for pagination
  77. * @var int
  78. */
  79. protected $limit;
  80. /**
  81. * Push method for list type
  82. * @var string
  83. */
  84. protected $listPushMethod = 'rpush';
  85. /**
  86. * @var RedisClient
  87. */
  88. protected $redClient;
  89. /**
  90. * if set to true, the subclass must override method compare()
  91. * @var bool
  92. */
  93. protected $sortable = false;
  94. /**
  95. * @var array
  96. */
  97. private $orderByFieldIndices = [];
  98. public function __construct($parameters = null, $options = null)
  99. {
  100. $this->initRedisClient($parameters, $options);
  101. $this->newQuery();
  102. $this->setCommandFactory();
  103. }
  104. /**
  105. * Refresh query builder
  106. * @return $this
  107. */
  108. public function newQuery()
  109. {
  110. $this->orderBys = [];
  111. $this->limit = null;
  112. $this->offset = null;
  113. return $this->freshQueryBuilder();
  114. }
  115. /**
  116. * @param $factory FactoryInterface
  117. */
  118. public function setCommandFactory($factory = null)
  119. {
  120. $this->commandFactory = $factory ?: new Factory();
  121. }
  122. /**
  123. * @return FactoryInterface
  124. */
  125. public function getCommandFactory()
  126. {
  127. return $this->commandFactory;
  128. }
  129. /**
  130. * @return QueryBuilder
  131. */
  132. public function getQueryBuilder()
  133. {
  134. return $this->queryBuilder;
  135. }
  136. /**
  137. * @return string
  138. */
  139. public function getPrimaryFieldName()
  140. {
  141. return $this->primaryFieldName;
  142. }
  143. /**
  144. * Query like database
  145. * The {$bindingKey} part in the key representation would be replace by $value
  146. * @param $field string
  147. * @param $value string
  148. * @return $this
  149. */
  150. public function where($field, $value)
  151. {
  152. $this->queryBuilder->whereEqual($field, $value);
  153. return $this;
  154. }
  155. /**
  156. * @param $field
  157. * @param array $values
  158. * @return $this
  159. */
  160. public function whereIn($field, array $values)
  161. {
  162. $this->queryBuilder->whereIn($field, $values);
  163. return $this;
  164. }
  165. /**
  166. * @param $field
  167. * @param string $order
  168. * @return $this
  169. */
  170. public function orderBy($field, $order = 'asc')
  171. {
  172. $this->orderBys[$field] = $order;
  173. return $this;
  174. }
  175. /**
  176. * @param int $offset
  177. * @return $this
  178. */
  179. public function skip($offset)
  180. {
  181. $this->offset = $offset;
  182. return $this;
  183. }
  184. /**
  185. * @param int $limit
  186. * @return $this
  187. */
  188. public function take($limit)
  189. {
  190. $this->limit = $limit;
  191. return $this;
  192. }
  193. /**
  194. * Get all items
  195. * @return array
  196. */
  197. public function all()
  198. {
  199. $this->newQuery();
  200. return $this->get();
  201. }
  202. /**
  203. * Retrieve items
  204. * @return array
  205. */
  206. public function get()
  207. {
  208. $data = $this->getProxy();
  209. return $data;
  210. }
  211. /**
  212. * @return int
  213. */
  214. public function count()
  215. {
  216. return count($this->prepareKeys());
  217. }
  218. /**
  219. * @param string $order asc|desc
  220. * @return array
  221. * @throws Exception
  222. */
  223. public function sort($order = 'asc')
  224. {
  225. $this->checkSortable();
  226. $values = $this->get();
  227. if (!$values) {
  228. return [];
  229. }
  230. if ($order == 'asc') {
  231. usort($values, [$this, 'compare']);
  232. } else {
  233. usort($values, [$this, 'revcompare']);
  234. }
  235. return $values;
  236. }
  237. /**
  238. * @return mixed
  239. * @throws Exception
  240. */
  241. public function max()
  242. {
  243. $this->checkSortable();
  244. $values = $this->get();
  245. if (!$values) {
  246. return null;
  247. }
  248. $max = array_pop($values);
  249. foreach ($values as $v) {
  250. if ($this->compare($v, $max) === 1) {
  251. $max = $v;
  252. }
  253. }
  254. return $max;
  255. }
  256. /**
  257. * @return mixed
  258. * @throws Exception
  259. */
  260. public function min()
  261. {
  262. $this->checkSortable();
  263. $values = $this->get();
  264. if (!$values) {
  265. return null;
  266. }
  267. $min = array_pop($values);
  268. foreach ($values as $v) {
  269. if ($this->compare($v, $min) === -1) {
  270. $min = $v;
  271. }
  272. }
  273. return $min;
  274. }
  275. /**
  276. * @return array
  277. */
  278. public function getKeys()
  279. {
  280. return $this->prepareKeys();
  281. }
  282. /**
  283. * @return array
  284. */
  285. public function getCompleteKeys()
  286. {
  287. return $this->prepareCompleteKeys();
  288. }
  289. /**
  290. * @return number
  291. */
  292. public function sum()
  293. {
  294. $values = $this->get();
  295. return array_sum($values);
  296. }
  297. /**
  298. * Retrieve first item
  299. * @return mixed|null
  300. */
  301. public function first()
  302. {
  303. $items = $this->take(1)->get();
  304. return $items ? array_shift($items) : null;
  305. }
  306. /**
  307. * Create an item
  308. * @param $id int|string Primary key
  309. * @param $value mixed
  310. * @param int $ttl
  311. * @param bool|null check key exists or not before create, not check if null
  312. * @return bool
  313. */
  314. public function create($id, $value, $ttl = null, $exists = null)
  315. {
  316. $this->newQuery();
  317. $queryKey = $this->queryBuilder->whereEqual($this->primaryFieldName, $id)->firstQueryKey();
  318. if (!$this->isCompleteKey($queryKey)) {
  319. return false;
  320. }
  321. return $this->insertProxy($queryKey, $value, $ttl, $exists);
  322. }
  323. /**
  324. * Similar to setnx
  325. * @param $id
  326. * @param $value
  327. * @param null $ttl
  328. * @return bool
  329. */
  330. public function createNotExists($id, $value, $ttl = null)
  331. {
  332. return $this->create($id, $value, $ttl, false);
  333. }
  334. /**
  335. * Similar to setxx
  336. * @param $id
  337. * @param $value
  338. * @param null $ttl
  339. * @return bool
  340. */
  341. public function createExists($id, $value, $ttl = null)
  342. {
  343. return $this->create($id, $value, $ttl, true);
  344. }
  345. /**
  346. * @param array $bindings
  347. * @param $value
  348. * @param int $ttl
  349. * @param bool $exists
  350. * @return mixed
  351. */
  352. public function insert(array $bindings, $value, $ttl = null, $exists = null)
  353. {
  354. $this->newQuery();
  355. foreach ($bindings as $k => $v) {
  356. $this->queryBuilder->whereEqual($k, $v);
  357. }
  358. $queryKey = $this->queryBuilder->firstQueryKey();
  359. if (!$this->isCompleteKey($queryKey)) {
  360. return false;
  361. }
  362. return $this->insertProxy($queryKey, $value, $ttl, $exists);
  363. }
  364. /**
  365. * Insert when key exists
  366. *
  367. * @param array $bindings
  368. * @param $value
  369. * @param null $ttl
  370. * @return mixed
  371. */
  372. public function insertExists(array $bindings, $value, $ttl = null)
  373. {
  374. return $this->insert($bindings, $value, $ttl, true);
  375. }
  376. /**
  377. * Insert when key not exists
  378. *
  379. * @param array $bindings
  380. * @param $value
  381. * @param null $ttl
  382. * @return mixed
  383. */
  384. public function insertNotExists(array $bindings, $value, $ttl = null)
  385. {
  386. return $this->insert($bindings, $value, $ttl, false);
  387. }
  388. /**
  389. * find an item
  390. * @param $id int|string Primary key
  391. * @return mixed
  392. */
  393. public function find($id)
  394. {
  395. $this->newQuery();
  396. $this->queryBuilder->whereEqual($this->primaryFieldName, $id);
  397. $queryKey = $this->queryBuilder->firstQueryKey();
  398. if (!$this->isCompleteKey($queryKey)) {
  399. return null;
  400. }
  401. list($method, $parameters) = $this->getFindMethodAndParameters();
  402. array_unshift($parameters, $queryKey);
  403. $value = call_user_func_array([$this->redClient, $method], $parameters);
  404. return $value;
  405. }
  406. /**
  407. * Update items, need to use where() first
  408. * @param $value
  409. * @param int $ttl ttl in second
  410. * @return mixed
  411. */
  412. public function update($value, $ttl = null)
  413. {
  414. $queryKeys = $this->prepareKeys(false);
  415. if (count($queryKeys)) {
  416. return $this->updateBatchProxy($queryKeys, $value, $ttl);
  417. }
  418. return false;
  419. }
  420. /**
  421. * Delete items
  422. * @return bool|int
  423. */
  424. public function delete()
  425. {
  426. $queryKeys = $this->prepareKeys(false);
  427. if (count($queryKeys) > 0) {
  428. return $this->redClient->del($queryKeys);
  429. }
  430. return false;
  431. }
  432. /**
  433. * Destroy item
  434. * @param string $id primary key
  435. * @return bool
  436. * @throws Exception
  437. */
  438. public function destroy($id)
  439. {
  440. $this->newQuery();
  441. $queryKey = $this->queryBuilder->whereEqual($this->primaryFieldName, $id)->firstQueryKey();
  442. if (!$this->isCompleteKey($queryKey)) {
  443. return false;
  444. }
  445. return (bool)$this->redClient->del([$queryKey]);
  446. }
  447. /**
  448. * @param array $ids primary keys
  449. * @return array
  450. * @throws Exception
  451. */
  452. public function findBatch(array $ids)
  453. {
  454. $primaryKeys = [];
  455. foreach ($ids as $id) {
  456. $primaryKeys[$id] = $this->getPrimaryKey($id);
  457. }
  458. $this->newQuery()->whereIn($this->getPrimaryFieldName(), $ids);
  459. $queryKeys = $this->prepareCompleteKeys();
  460. if (!$queryKeys) {
  461. return [];
  462. }
  463. $data = $this->getProxy($queryKeys);
  464. $list = [];
  465. foreach ($data as $k => $v) {
  466. $id = array_search($k, $primaryKeys);
  467. if ($id) {
  468. $list[$id] = $v;
  469. }
  470. }
  471. return $list;
  472. }
  473. /**
  474. * @param array $ids primary keys
  475. * @return int
  476. */
  477. public function destroyBatch(array $ids)
  478. {
  479. $this->newQuery()->whereIn($this->getPrimaryFieldName(), $ids);
  480. $queryKeys = $this->prepareCompleteKeys();
  481. if (!$queryKeys) {
  482. return false;
  483. }
  484. return $this->redClient->del($queryKeys);
  485. }
  486. /**
  487. * @param array $ids primary keys
  488. * @param $value
  489. * @param int|null $ttl
  490. * @return mixed
  491. */
  492. public function updateBatch(array $ids, $value, $ttl = null)
  493. {
  494. $this->newQuery()->whereIn($this->getPrimaryFieldName(), $ids);
  495. $queryKeys = $this->prepareCompleteKeys();
  496. if (!$queryKeys) {
  497. return false;
  498. }
  499. return $this->updateBatchProxy($queryKeys, $value, $ttl);
  500. }
  501. /**
  502. * Get key and set new value
  503. *
  504. * @param string|array $value
  505. * @param null $ttl
  506. * @return mixed
  507. * @throws Exception
  508. */
  509. public function getAndSet($value, $ttl = null)
  510. {
  511. $keys = $this->queryBuilder->getQueryKeys();
  512. if (count($keys) > 1) {
  513. throw new Exception('GetAndSet doesnt support multiple keys');
  514. } elseif (count($keys) == 0) {
  515. throw new Exception('No query keys');
  516. }
  517. $key = $keys[0];
  518. if (!$this->isCompleteKey($key)) {
  519. throw new Exception('Not complete key');
  520. }
  521. $value = $this->castValueForUpdate($value);
  522. $commandName = 'getset' . ucfirst($this->type);
  523. $command = $this->commandFactory->getCommand($commandName, [$key], $value);
  524. if (!is_null($ttl)) {
  525. $command->setTtl($ttl);
  526. }
  527. $result = $this->executeCommand($command);
  528. $data = isset($result[$key]) ? $result[$key] : null;
  529. if ($data && $this->type == static::TYPE_HASH) {
  530. $data = $this->resolveHash($data);
  531. }
  532. return $data;
  533. }
  534. /**
  535. * Call Predis function
  536. * @param $method
  537. * @param array $parameters
  538. * @return mixed
  539. * @throws \Exception
  540. */
  541. public function __call($method, $parameters = [])
  542. {
  543. $keys = $this->queryBuilder->getQueryKeys();
  544. if (count($keys) > 1) {
  545. throw new Exception('More than one key had been built and redis built-in method "' . $method . '" dont support batch operation.');
  546. } elseif (count($keys) === 0) {
  547. throw new Exception('No query keys had been built, need to use where() first.');
  548. }
  549. array_unshift($parameters, $keys[0]);
  550. return call_user_func_array([$this->redClient, $method], $parameters);
  551. }
  552. /**
  553. * Compare items to sort
  554. * @param $a
  555. * @param $b
  556. * @return int 1.a>b 0.a=b -1.a<b
  557. */
  558. protected function compare($a, $b)
  559. {
  560. return $a > $b ? 1 : ($a == $b ? 0 : -1);
  561. }
  562. /**
  563. * @param $a
  564. * @param $b
  565. * @return int
  566. */
  567. protected function revcompare($a, $b)
  568. {
  569. return -$this->compare($a, $b);
  570. }
  571. /**
  572. * Initialize redis client
  573. *
  574. * @param $parameters
  575. * @param $options
  576. */
  577. protected function initRedisClient($parameters, $options)
  578. {
  579. $this->redClient = new RedisClient($parameters, $options);
  580. }
  581. /**
  582. * Prepare query keys
  583. * @param bool $forGet
  584. * @return array
  585. */
  586. protected function prepareKeys($forGet = true)
  587. {
  588. $queryKeys = $this->queryBuilder->getQueryKeys();
  589. // Caution! Would get all items.
  590. if (!$queryKeys) {
  591. $queryKeys = [$this->key];
  592. }
  593. $existKeys = $this->getExistKeys($queryKeys);
  594. if ($forGet) {
  595. $this->setOrderByFieldIndices();
  596. if ($this->orderByFieldIndices) {
  597. uasort($existKeys, [$this, 'sortByFields']);
  598. }
  599. if ($this->offset || $this->limit) {
  600. $existKeys = array_slice($existKeys, (int)$this->offset, $this->limit);
  601. }
  602. }
  603. return $existKeys;
  604. }
  605. /**
  606. * @return array
  607. */
  608. protected function prepareCompleteKeys()
  609. {
  610. $keys = $this->queryBuilder->getQueryKeys();
  611. if (!$keys) {
  612. return [];
  613. }
  614. return array_filter($keys, [$this, 'isCompleteKey']);
  615. }
  616. /**
  617. * @param $key
  618. * @return bool
  619. */
  620. protected function isCompleteKey($key)
  621. {
  622. return !$this->hasUnboundField($key);
  623. }
  624. /**
  625. * @param $key
  626. * @param $value
  627. * @param null $ttl
  628. * @param null|bool $exists
  629. * @return bool
  630. */
  631. protected function insertProxy($key, $value, $ttl = null, $exists = null)
  632. {
  633. $method = $this->getUpdateMethod();
  634. if (!$method) {
  635. return false;
  636. }
  637. $value = $this->castValueForUpdate($value);
  638. $command = $this->commandFactory->getCommand($method, [$key], $value);
  639. if ($ttl) {
  640. $command->setTtl($ttl);
  641. }
  642. if ($exists === false) {
  643. $command->pleaseNotExists();
  644. } elseif ($exists === true) {
  645. $command->pleaseExists();
  646. }
  647. $command->pleaseDeleteIfExists();
  648. $response = $this->executeCommand($command);
  649. return isset($response[$key]) && $response[$key];
  650. }
  651. /**
  652. * @param $keys
  653. * @param $value
  654. * @param int $ttl ttl in second
  655. * @return bool
  656. */
  657. protected function updateBatchProxy($keys, $value, $ttl = null)
  658. {
  659. $method = $this->getUpdateMethod();
  660. if (empty($method)) {
  661. return false;
  662. }
  663. $value = $this->castValueForUpdate($value);
  664. $command = $this->commandFactory->getCommand($method, $keys, $value);
  665. $command->pleaseDeleteIfExists();
  666. if ($ttl) {
  667. $command->setTtl($ttl);
  668. }
  669. return $this->executeCommand($command);
  670. }
  671. /**
  672. * @param $queryKeys
  673. * @return array
  674. */
  675. protected function getProxy($queryKeys = null)
  676. {
  677. if ($queryKeys === null) {
  678. $queryKeys = $this->prepareKeys();
  679. }
  680. $data = [];
  681. if ($queryKeys) {
  682. list($method, $params) = $this->getFindMethodAndParameters();
  683. $command = $this->commandFactory->getCommand($method, $queryKeys);
  684. $data = $this->executeCommand($command);
  685. }
  686. if ($data && $this->type == static::TYPE_HASH) {
  687. $data = $this->resolveHashes($data);
  688. }
  689. return $data;
  690. }
  691. /**
  692. * @return $this
  693. */
  694. protected function freshQueryBuilder()
  695. {
  696. $this->queryBuilder = new QueryBuilder($this->key);
  697. $keyParts = $this->explodeKey($this->key);
  698. foreach ($keyParts as $part) {
  699. if ($this->isUnboundField($part)) {
  700. $this->queryBuilder->setFieldNeedle($this->trimWrapper($part), $part);
  701. }
  702. }
  703. return $this;
  704. }
  705. /**
  706. * Get update method according to redis data type
  707. *
  708. * @return string
  709. */
  710. protected function getUpdateMethod()
  711. {
  712. $method = '';
  713. switch ($this->type) {
  714. case 'string':
  715. $method = 'set';
  716. break;
  717. case 'list':
  718. $method = $this->listPushMethod;
  719. break;
  720. case 'set':
  721. $method = 'sadd';
  722. break;
  723. case 'zset':
  724. $method = 'zadd';
  725. break;
  726. case 'hash':
  727. $method = 'hmset';
  728. break;
  729. default:
  730. break;
  731. }
  732. return $method;
  733. }
  734. /**
  735. * Cast value data type for update according to redis data type
  736. *
  737. * @param $value
  738. * @return array
  739. */
  740. protected function castValueForUpdate($value)
  741. {
  742. switch ($this->type) {
  743. case 'string':
  744. $value = [(string)$value];
  745. break;
  746. case 'list':
  747. case 'set':
  748. $value = (array)$value;
  749. break;
  750. case 'zset':
  751. $casted = [];
  752. foreach ($value as $k => $v) {
  753. $casted[] = $v;
  754. $casted[] = $k;
  755. }
  756. $value = $casted;
  757. break;
  758. case 'hash':
  759. $casted = [];
  760. foreach ($value as $k => $v) {
  761. $casted[] = $k;
  762. $casted[] = $v;
  763. }
  764. $value = $casted;
  765. break;
  766. default:
  767. break;
  768. }
  769. return $value;
  770. }
  771. /**
  772. * Get find method and default parameters according to redis data type.
  773. * @return array
  774. */
  775. protected function getFindMethodAndParameters()
  776. {
  777. $method = '';
  778. $parameters = [];
  779. switch ($this->type) {
  780. case 'string':
  781. $method = 'get';
  782. break;
  783. case 'list':
  784. $method = 'lrange';
  785. $parameters = [0, -1];
  786. break;
  787. case 'set':
  788. $method = 'smembers';
  789. break;
  790. case 'zset':
  791. $method = 'zrange';
  792. $parameters = [0, -1];
  793. break;
  794. case 'hash':
  795. $method = 'hgetall';
  796. break;
  797. default:
  798. break;
  799. }
  800. return [$method, $parameters];
  801. }
  802. /**
  803. * Get existed keys in redis database
  804. *
  805. * @param $queryKeys
  806. * @return array|mixed
  807. */
  808. protected function getExistKeys($queryKeys)
  809. {
  810. $keys = $this->markUnboundFields($queryKeys);
  811. $exist = [];
  812. if ($keys) {
  813. $command = $this->commandFactory->getCommand('keys', $keys);
  814. $exist = $this->executeCommand($command);
  815. $exist = array_unique($exist);
  816. }
  817. return $exist;
  818. }
  819. /**
  820. * @param Command $command
  821. * @return mixed
  822. */
  823. protected function executeCommand($command)
  824. {
  825. $evalArgs = $command->getArguments();
  826. array_unshift($evalArgs, $command->getKeysCount());
  827. try {
  828. array_unshift($evalArgs, sha1($command->getScript()));
  829. $data = call_user_func_array([$this->redClient, 'evalsha'], $evalArgs);
  830. } catch (\Exception $e) {
  831. if (strpos($e->getMessage(), 'NOSCRIPT') !== false) {
  832. $evalArgs[0] = $command->getScript();
  833. $data = call_user_func_array([$this->redClient, 'eval'], $evalArgs);
  834. } else {
  835. throw $e;
  836. }
  837. }
  838. $data = $command->parseResponse($data);
  839. return $data;
  840. }
  841. /**
  842. * Check a key whether has unbound field
  843. *
  844. * @param $key
  845. * @return bool
  846. */
  847. protected function hasUnboundField($key)
  848. {
  849. $parts = $this->explodeKey($key);
  850. foreach ($parts as $part) {
  851. if ($this->isUnboundField($part)) {
  852. return true;
  853. }
  854. }
  855. return false;
  856. }
  857. /**
  858. * @param string $part key particle
  859. * @return bool|string
  860. */
  861. protected function getFieldName($part)
  862. {
  863. if ($this->isUnboundField($part)) {
  864. return substr($part, 1, -1);
  865. }
  866. return false;
  867. }
  868. /**
  869. * Mark unbound field with *
  870. *
  871. * @param $keys
  872. * @return array
  873. */
  874. protected function markUnboundFields($keys)
  875. {
  876. $marked = [];
  877. foreach ($keys as $key) {
  878. $parts = $this->explodeKey($key);
  879. foreach ($parts as &$part) {
  880. if ($this->isUnboundField($part)) {
  881. $part = '*';
  882. }
  883. }
  884. $marked[] = $this->joinToKey($parts);
  885. }
  886. return $marked;
  887. }
  888. /**
  889. * Compare two keys by key field(s)
  890. *
  891. * @param $key1
  892. * @param $key2
  893. * @return int
  894. */
  895. protected function sortByFields($key1, $key2)
  896. {
  897. $key1Parts = $this->explodeKey($key1);
  898. $key2Parts = $this->explodeKey($key2);
  899. $flag = 0;
  900. foreach ($this->orderByFieldIndices as $index => $order) {
  901. if ($flag !== 0) {
  902. break;
  903. }
  904. if ($key1Parts[$index] > $key2Parts[$index]) {
  905. $flag = $order == 'asc' ? 1 : -1;
  906. } elseif ($key1Parts[$index] < $key2Parts[$index]) {
  907. $flag = $order == 'asc' ? -1 : 1;
  908. } else {
  909. $flag = 0;
  910. }
  911. }
  912. return $flag;
  913. }
  914. /**
  915. * @param string $field
  916. * @return string
  917. */
  918. protected function getFieldNeedle($field)
  919. {
  920. return $this->fieldWrapper[0] . $field . $this->fieldWrapper[1];
  921. }
  922. /**
  923. * @param $id
  924. * @return mixed
  925. */
  926. protected function getPrimaryKey($id)
  927. {
  928. return str_replace($this->getFieldNeedle($this->getPrimaryFieldName()), $id, $this->key);
  929. }
  930. /**
  931. * @throws Exception
  932. */
  933. private function checkSortable()
  934. {
  935. if (!$this->sortable) {
  936. throw new Exception(get_class($this) . ' is not sortable.');
  937. }
  938. }
  939. /**
  940. * Set order by field and order
  941. */
  942. private function setOrderByFieldIndices()
  943. {
  944. $keyParts = $this->explodeKey($this->key);
  945. foreach ($this->orderBys as $field => $order) {
  946. $needle = $this->fieldWrapper[0] . $field . $this->fieldWrapper[1];
  947. $this->orderByFieldIndices[array_search($needle, $keyParts)] = $order;
  948. }
  949. }
  950. /**
  951. * @param $key
  952. * @return array
  953. */
  954. private function explodeKey($key)
  955. {
  956. return explode($this->delimiter, $key);
  957. }
  958. /**
  959. * @param $parts
  960. * @return string
  961. */
  962. private function joinToKey($parts)
  963. {
  964. return join($this->delimiter, $parts);
  965. }
  966. /**
  967. * @param $part
  968. * @return bool
  969. */
  970. private function isUnboundField($part)
  971. {
  972. return $this->fieldWrapper[0] === $part[0]
  973. && $this->fieldWrapper[1] === $part[strlen($part) - 1];
  974. }
  975. /**
  976. * @param $part
  977. * @return bool|string
  978. */
  979. private function trimWrapper($part)
  980. {
  981. return substr($part, 1, -1);
  982. }
  983. /**
  984. * raw hash data to associate array
  985. * @param array $hashes
  986. * @return array
  987. */
  988. private function resolveHashes(array $hashes)
  989. {
  990. $assoc = [];
  991. foreach ($hashes as $k => $hash) {
  992. $item = $this->resolveHash($hash);
  993. if ($item) {
  994. $assoc[$k] = $item;
  995. }
  996. }
  997. return $assoc;
  998. }
  999. /**
  1000. * @param $hash
  1001. * @return array
  1002. */
  1003. private function resolveHash($hash)
  1004. {
  1005. $array = [];
  1006. for ($i = 0; $i < count($hash); $i = $i + 2) {
  1007. $array[$hash[$i]] = $hash[$i + 1];
  1008. }
  1009. return $array;
  1010. }
  1011. }