FlexIndex.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. <?php
  2. /**
  3. * @package Grav\Framework\Flex
  4. *
  5. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Framework\Flex;
  9. use Grav\Common\Debugger;
  10. use Grav\Common\File\CompiledYamlFile;
  11. use Grav\Common\Grav;
  12. use Grav\Common\Session;
  13. use Grav\Framework\Cache\CacheInterface;
  14. use Grav\Framework\Collection\CollectionInterface;
  15. use Grav\Framework\Flex\Interfaces\FlexCollectionInterface;
  16. use Grav\Framework\Flex\Interfaces\FlexIndexInterface;
  17. use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
  18. use Grav\Framework\Flex\Interfaces\FlexStorageInterface;
  19. use Grav\Framework\Object\Interfaces\ObjectCollectionInterface;
  20. use Grav\Framework\Object\Interfaces\ObjectInterface;
  21. use Grav\Framework\Object\ObjectIndex;
  22. use Monolog\Logger;
  23. use Psr\SimpleCache\InvalidArgumentException;
  24. class FlexIndex extends ObjectIndex implements FlexCollectionInterface, FlexIndexInterface
  25. {
  26. /** @var FlexDirectory */
  27. private $_flexDirectory;
  28. /** @var string */
  29. private $_keyField;
  30. /** @var array */
  31. private $_indexKeys;
  32. /**
  33. * @param FlexDirectory $directory
  34. * @return static
  35. */
  36. public static function createFromStorage(FlexDirectory $directory)
  37. {
  38. return static::createFromArray(static::loadEntriesFromStorage($directory->getStorage()), $directory);
  39. }
  40. /**
  41. * {@inheritdoc}
  42. * @see FlexCollectionInterface::createFromArray()
  43. */
  44. public static function createFromArray(array $entries, FlexDirectory $directory, string $keyField = null)
  45. {
  46. $instance = new static($entries, $directory);
  47. $instance->setKeyField($keyField);
  48. return $instance;
  49. }
  50. /**
  51. * @param FlexStorageInterface $storage
  52. * @return array
  53. */
  54. public static function loadEntriesFromStorage(FlexStorageInterface $storage): array
  55. {
  56. return $storage->getExistingKeys();
  57. }
  58. /**
  59. * Initializes a new FlexIndex.
  60. *
  61. * @param array $entries
  62. * @param FlexDirectory|null $directory
  63. */
  64. public function __construct(array $entries = [], FlexDirectory $directory = null)
  65. {
  66. parent::__construct($entries);
  67. $this->_flexDirectory = $directory;
  68. $this->setKeyField(null);
  69. }
  70. /**
  71. * {@inheritdoc}
  72. * @see FlexCollectionInterface::search()
  73. */
  74. public function search(string $search, $properties = null, array $options = null)
  75. {
  76. return $this->__call('search', [$search, $properties, $options]);
  77. }
  78. /**
  79. * {@inheritdoc}
  80. * @see FlexCollectionInterface::sort()
  81. */
  82. public function sort(array $orderings)
  83. {
  84. return $this->orderBy($orderings);
  85. }
  86. /**
  87. * {@inheritdoc}
  88. * @see FlexCollectionInterface::filterBy()
  89. */
  90. public function filterBy(array $filters)
  91. {
  92. return $this->__call('filterBy', [$filters]);
  93. }
  94. /**
  95. * {@inheritdoc}
  96. * @see FlexCollectionInterface::getFlexType()
  97. */
  98. public function getFlexType(): string
  99. {
  100. return $this->_flexDirectory->getFlexType();
  101. }
  102. /**
  103. * {@inheritdoc}
  104. * @see FlexCollectionInterface::getFlexDirectory()
  105. */
  106. public function getFlexDirectory(): FlexDirectory
  107. {
  108. return $this->_flexDirectory;
  109. }
  110. /**
  111. * {@inheritdoc}
  112. * @see FlexCollectionInterface::getTimestamp()
  113. */
  114. public function getTimestamp(): int
  115. {
  116. $timestamps = $this->getTimestamps();
  117. return $timestamps ? max($timestamps) : time();
  118. }
  119. /**
  120. * {@inheritdoc}
  121. * @see FlexCollectionInterface::getCacheKey()
  122. */
  123. public function getCacheKey(): string
  124. {
  125. return $this->getTypePrefix() . $this->getFlexType() . '.' . sha1(json_encode($this->getKeys()) . $this->_keyField);
  126. }
  127. /**
  128. * {@inheritdoc}
  129. * @see FlexCollectionInterface::getCacheChecksum()
  130. */
  131. public function getCacheChecksum(): string
  132. {
  133. return sha1($this->getCacheKey() . json_encode($this->getTimestamps()));
  134. }
  135. /**
  136. * {@inheritdoc}
  137. * @see FlexCollectionInterface::getTimestamps()
  138. */
  139. public function getTimestamps(): array
  140. {
  141. return $this->getIndexMap('storage_timestamp');
  142. }
  143. /**
  144. * {@inheritdoc}
  145. * @see FlexCollectionInterface::getStorageKeys()
  146. */
  147. public function getStorageKeys(): array
  148. {
  149. return $this->getIndexMap('storage_key');
  150. }
  151. /**
  152. * {@inheritdoc}
  153. * @see FlexCollectionInterface::getFlexKeys()
  154. */
  155. public function getFlexKeys(): array
  156. {
  157. // Get storage keys for the objects.
  158. $keys = [];
  159. $type = $this->_flexDirectory->getFlexType() . '.obj:';
  160. foreach ($this->getEntries() as $key => $value) {
  161. $keys[$key] = $value['flex_key'] ?? $type . $value['storage_key'];
  162. }
  163. return $keys;
  164. }
  165. /**
  166. * {@inheritdoc}
  167. * @see FlexIndexInterface::withKeyField()
  168. */
  169. public function withKeyField(string $keyField = null)
  170. {
  171. $keyField = $keyField ?: 'key';
  172. if ($keyField === $this->getKeyField()) {
  173. return $this;
  174. }
  175. $type = $keyField === 'flex_key' ? $this->_flexDirectory->getFlexType() . '.obj:' : '';
  176. $entries = [];
  177. foreach ($this->getEntries() as $key => $value) {
  178. if (!isset($value['key'])) {
  179. $value['key'] = $key;
  180. }
  181. if (isset($value[$keyField])) {
  182. $entries[$value[$keyField]] = $value;
  183. } elseif ($keyField === 'flex_key') {
  184. $entries[$type . $value['storage_key']] = $value;
  185. }
  186. }
  187. return $this->createFrom($entries, $keyField);
  188. }
  189. /**
  190. * {@inheritdoc}
  191. * @see FlexCollectionInterface::getIndex()
  192. */
  193. public function getIndex()
  194. {
  195. return $this;
  196. }
  197. /**
  198. * {@inheritdoc}
  199. * @see FlexCollectionInterface::render()
  200. */
  201. public function render(string $layout = null, array $context = [])
  202. {
  203. return $this->__call('render', [$layout, $context]);
  204. }
  205. /**
  206. * @param bool $prefix
  207. * @return string
  208. * @deprecated 1.6 Use `->getFlexType()` instead.
  209. */
  210. public function getType($prefix = false)
  211. {
  212. user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getFlexType() method instead', E_USER_DEPRECATED);
  213. $type = $prefix ? $this->getTypePrefix() : '';
  214. return $type . $this->getFlexType();
  215. }
  216. /**
  217. * {@inheritdoc}
  218. * @see FlexIndexInterface::getFlexKeys()
  219. */
  220. public function getIndexMap(string $indexKey = null)
  221. {
  222. if (null === $indexKey) {
  223. return $this->getEntries();
  224. }
  225. // Get storage keys for the objects.
  226. $index = [];
  227. foreach ($this->getEntries() as $key => $value) {
  228. $index[$key] = $value[$indexKey] ?? null;
  229. }
  230. return $index;
  231. }
  232. /**
  233. * @return array
  234. */
  235. public function getMetaData(string $key): array
  236. {
  237. return $this->getEntries()[$key] ?? [];
  238. }
  239. /**
  240. * @return string
  241. */
  242. public function getKeyField() : string
  243. {
  244. return $this->_keyField ?? 'storage_key';
  245. }
  246. /**
  247. * @param string|null $namespace
  248. * @return CacheInterface
  249. */
  250. public function getCache(string $namespace = null)
  251. {
  252. return $this->_flexDirectory->getCache($namespace);
  253. }
  254. /**
  255. * @param array $orderings
  256. * @return FlexIndex|FlexCollection
  257. */
  258. public function orderBy(array $orderings)
  259. {
  260. if (!$orderings || !$this->count()) {
  261. return $this;
  262. }
  263. // Check if ordering needs to load the objects.
  264. if (array_diff_key($orderings, $this->getIndexKeys())) {
  265. return $this->__call('orderBy', [$orderings]);
  266. }
  267. // Ordering can be done by using index only.
  268. $previous = null;
  269. foreach (array_reverse($orderings) as $field => $ordering) {
  270. $field = (string)$field;
  271. if ($this->getKeyField() === $field) {
  272. $keys = $this->getKeys();
  273. $search = array_combine($keys, $keys) ?: [];
  274. } elseif ($field === 'flex_key') {
  275. $search = $this->getFlexKeys();
  276. } else {
  277. $search = $this->getIndexMap($field);
  278. }
  279. // Update current search to match the previous ordering.
  280. if (null !== $previous) {
  281. $search = array_replace($previous, $search);
  282. }
  283. // Order by current field.
  284. if ($ordering === 'DESC') {
  285. arsort($search, SORT_NATURAL);
  286. } else {
  287. asort($search, SORT_NATURAL);
  288. }
  289. $previous = $search;
  290. }
  291. return $this->createFrom(array_replace($previous, $this->getEntries()));
  292. }
  293. /**
  294. * {@inheritDoc}
  295. */
  296. public function call($method, array $arguments = [])
  297. {
  298. return $this->__call('call', [$method, $arguments]);
  299. }
  300. public function __call($name, $arguments)
  301. {
  302. /** @var Debugger $debugger */
  303. $debugger = Grav::instance()['debugger'];
  304. /** @var FlexCollection $className */
  305. $className = $this->_flexDirectory->getCollectionClass();
  306. $cachedMethods = $className::getCachedMethods();
  307. $flexType = $this->getFlexType();
  308. if (!empty($cachedMethods[$name])) {
  309. $type = $cachedMethods[$name];
  310. if ($type === 'session') {
  311. /** @var Session $session */
  312. $session = Grav::instance()['session'];
  313. $cacheKey = $session->getId() . $session->user->username;
  314. } else {
  315. $cacheKey = '';
  316. }
  317. $key = "{$flexType}.idx." . sha1($name . '.' . $cacheKey . json_encode($arguments) . $this->getCacheKey());
  318. $cache = $this->getCache('object');
  319. try {
  320. $result = $cache->get($key);
  321. // Make sure the keys aren't changed if the returned type is the same index type.
  322. if ($result instanceof self && $flexType === $result->getFlexType()) {
  323. $result = $result->withKeyField($this->getKeyField());
  324. }
  325. } catch (InvalidArgumentException $e) {
  326. /** @var Debugger $debugger */
  327. $debugger = Grav::instance()['debugger'];
  328. $debugger->addException($e);
  329. }
  330. if (!isset($result)) {
  331. $collection = $this->loadCollection();
  332. $result = $collection->{$name}(...$arguments);
  333. try {
  334. // If flex collection is returned, convert it back to flex index.
  335. if ($result instanceof FlexCollection) {
  336. $cached = $result->getFlexDirectory()->getIndex($result->getKeys(), $this->getKeyField());
  337. } else {
  338. $cached = $result;
  339. }
  340. $cache->set($key, $cached);
  341. } catch (InvalidArgumentException $e) {
  342. $debugger->addException($e);
  343. // TODO: log error.
  344. }
  345. }
  346. } else {
  347. $collection = $this->loadCollection();
  348. $result = $collection->{$name}(...$arguments);
  349. if (!isset($cachedMethods[$name])) {
  350. $class = \get_class($collection);
  351. $debugger->addMessage("Call '{$class}:{$name}()' isn't cached", 'debug');
  352. }
  353. }
  354. return $result;
  355. }
  356. /**
  357. * @return string
  358. */
  359. public function serialize()
  360. {
  361. return serialize(['type' => $this->getFlexType(), 'entries' => $this->getEntries()]);
  362. }
  363. /**
  364. * @param string $serialized
  365. */
  366. public function unserialize($serialized)
  367. {
  368. $data = unserialize($serialized, ['allowed_classes' => false]);
  369. $this->_flexDirectory = Grav::instance()['flex_objects']->getDirectory($data['type']);
  370. $this->setEntries($data['entries']);
  371. }
  372. /**
  373. * @param array $entries
  374. * @param string $keyField
  375. * @return static
  376. */
  377. protected function createFrom(array $entries, string $keyField = null)
  378. {
  379. $index = new static($entries, $this->_flexDirectory);
  380. $index->setKeyField($keyField ?? $this->_keyField);
  381. return $index;
  382. }
  383. /**
  384. * @param string|null $keyField
  385. */
  386. protected function setKeyField(string $keyField = null)
  387. {
  388. $this->_keyField = $keyField ?? 'storage_key';
  389. }
  390. protected function getIndexKeys()
  391. {
  392. if (null === $this->_indexKeys) {
  393. $entries = $this->getEntries();
  394. $first = reset($entries);
  395. if ($first) {
  396. $keys = array_keys($first);
  397. $keys = array_combine($keys, $keys) ?: [];
  398. } else {
  399. $keys = [];
  400. }
  401. $this->setIndexKeys($keys);
  402. }
  403. return $this->_indexKeys;
  404. }
  405. /**
  406. * @param array $indexKeys
  407. */
  408. protected function setIndexKeys(array $indexKeys)
  409. {
  410. // Add defaults.
  411. $indexKeys += [
  412. 'key' => 'key',
  413. 'storage_key' => 'storage_key',
  414. 'storage_timestamp' => 'storage_timestamp',
  415. 'flex_key' => 'flex_key'
  416. ];
  417. $this->_indexKeys = $indexKeys;
  418. }
  419. /**
  420. * @return string
  421. */
  422. protected function getTypePrefix()
  423. {
  424. return 'i.';
  425. }
  426. /**
  427. * @param string $key
  428. * @param mixed $value
  429. * @return ObjectInterface|null
  430. */
  431. protected function loadElement($key, $value): ?ObjectInterface
  432. {
  433. $objects = $this->_flexDirectory->loadObjects([$key => $value]);
  434. return $objects ? reset($objects): null;
  435. }
  436. /**
  437. * @param array|null $entries
  438. * @return ObjectInterface[]
  439. */
  440. protected function loadElements(array $entries = null): array
  441. {
  442. return $this->_flexDirectory->loadObjects($entries ?? $this->getEntries());
  443. }
  444. /**
  445. * @param array|null $entries
  446. * @return ObjectCollectionInterface
  447. */
  448. protected function loadCollection(array $entries = null): CollectionInterface
  449. {
  450. return $this->_flexDirectory->loadCollection($entries ?? $this->getEntries(), $this->_keyField);
  451. }
  452. /**
  453. * @param mixed $value
  454. * @return bool
  455. */
  456. protected function isAllowedElement($value): bool
  457. {
  458. return $value instanceof FlexObject;
  459. }
  460. /**
  461. * @param FlexObjectInterface $object
  462. * @return mixed
  463. */
  464. protected function getElementMeta($object)
  465. {
  466. return $object->getTimestamp();
  467. }
  468. /**
  469. * @param FlexStorageInterface $storage
  470. * @param array $index Saved index
  471. * @param array $entries Updated index
  472. * @return array Compiled list of entries
  473. */
  474. protected static function updateIndexFile(FlexStorageInterface $storage, array $index, array $entries): array
  475. {
  476. // Calculate removed objects.
  477. $removed = array_diff_key($index, $entries);
  478. // First get rid of all removed objects.
  479. if ($removed) {
  480. $index = array_diff_key($index, $removed);
  481. }
  482. if ($entries) {
  483. // Calculate difference between saved index and current data.
  484. foreach ($index as $key => $entry) {
  485. $storage_key = $entry['storage_key'] ?? null;
  486. if (isset($entries[$storage_key]) && $entries[$storage_key]['storage_timestamp'] === $entry['storage_timestamp']) {
  487. // Entry is up to date, no update needed.
  488. unset($entries[$storage_key]);
  489. }
  490. }
  491. if (empty($entries) && empty($removed)) {
  492. // No objects were added, updated or removed.
  493. return $index;
  494. }
  495. } elseif (!$removed) {
  496. // There are no objects and nothing was removed.
  497. return [];
  498. }
  499. // Index should be updated, lock the index file for saving.
  500. $indexFile = static::getIndexFile($storage);
  501. $indexFile->lock();
  502. // Read all the data rows into an array.
  503. $keys = array_fill_keys(array_keys($entries), null);
  504. $rows = $storage->readRows($keys);
  505. $keyField = $storage->getKeyField();
  506. // Go through all the updated objects and refresh their index data.
  507. $updated = $added = [];
  508. foreach ($rows as $key => $row) {
  509. if (null !== $row) {
  510. $entry = ['key' => $key] + $entries[$key];
  511. if ($keyField !== 'storage_key' && isset($row[$keyField])) {
  512. $entry['key'] = $row[$keyField];
  513. }
  514. static::updateIndexData($entry, $row);
  515. if (isset($row['__error'])) {
  516. $entry['__error'] = true;
  517. static::onException(new \RuntimeException(sprintf('Object failed to load: %s (%s)', $key, $row['__error'])));
  518. }
  519. if (isset($index[$key])) {
  520. // Update object in the index.
  521. $updated[$key] = $entry;
  522. } else {
  523. // Add object into the index.
  524. $added[$key] = $entry;
  525. }
  526. // Either way, update the entry.
  527. $index[$key] = $entry;
  528. } elseif (isset($index[$key])) {
  529. // Remove object from the index.
  530. $removed[$key] = $index[$key];
  531. unset($index[$key]);
  532. }
  533. }
  534. // Sort the index before saving it.
  535. ksort($index, SORT_NATURAL);
  536. static::onChanges($index, $added, $updated, $removed);
  537. $indexFile->save(['count' => \count($index), 'index' => $index]);
  538. $indexFile->unlock();
  539. return $index;
  540. }
  541. protected static function updateIndexData(array &$entry, array $data)
  542. {
  543. }
  544. protected static function loadEntriesFromIndex(FlexStorageInterface $storage)
  545. {
  546. $indexFile = static::getIndexFile($storage);
  547. $data = [];
  548. try {
  549. $data = (array)$indexFile->content();
  550. } catch (\Exception $e) {
  551. $e = new \RuntimeException(sprintf('Index failed to load: %s', $e->getMessage()), $e->getCode(), $e);
  552. static::onException($e);
  553. }
  554. return $data['index'] ?? [];
  555. }
  556. protected static function getIndexFile(FlexStorageInterface $storage)
  557. {
  558. // Load saved index file.
  559. $grav = Grav::instance();
  560. $locator = $grav['locator'];
  561. $filename = $locator->findResource($storage->getStoragePath() . '/index.yaml', true, true);
  562. return CompiledYamlFile::instance($filename);
  563. }
  564. protected static function onException(\Exception $e)
  565. {
  566. $grav = Grav::instance();
  567. /** @var Logger $logger */
  568. $logger = $grav['log'];
  569. $logger->addAlert($e->getMessage());
  570. /** @var Debugger $debugger */
  571. $debugger = $grav['debugger'];
  572. $debugger->addException($e);
  573. $debugger->addMessage($e, 'error');
  574. }
  575. protected static function onChanges(array $entries, array $added, array $updated, array $removed)
  576. {
  577. $message = sprintf('Index updated, %d objects (%d added, %d updated, %d removed).', \count($entries), \count($added), \count($updated), \count($removed));
  578. $grav = Grav::instance();
  579. /** @var Logger $logger */
  580. $logger = $grav['log'];
  581. $logger->addDebug($message);
  582. /** @var Debugger $debugger */
  583. $debugger = $grav['debugger'];
  584. $debugger->addMessage($message, 'debug');
  585. }
  586. public function __debugInfo()
  587. {
  588. return [
  589. 'type:private' => $this->getFlexType(),
  590. 'key:private' => $this->getKey(),
  591. 'entries_key:private' => $this->getKeyField(),
  592. 'entries:private' => $this->getEntries()
  593. ];
  594. }
  595. }