FlexIndex.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. <?php
  2. /**
  3. * @package Grav\Framework\Flex
  4. *
  5. * @copyright Copyright (c) 2015 - 2021 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Framework\Flex;
  9. use Exception;
  10. use Grav\Common\Debugger;
  11. use Grav\Common\File\CompiledYamlFile;
  12. use Grav\Common\Grav;
  13. use Grav\Common\Inflector;
  14. use Grav\Common\Session;
  15. use Grav\Framework\Cache\CacheInterface;
  16. use Grav\Framework\Collection\CollectionInterface;
  17. use Grav\Framework\Flex\Interfaces\FlexCollectionInterface;
  18. use Grav\Framework\Flex\Interfaces\FlexIndexInterface;
  19. use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
  20. use Grav\Framework\Flex\Interfaces\FlexStorageInterface;
  21. use Grav\Framework\Object\Interfaces\ObjectInterface;
  22. use Grav\Framework\Object\ObjectIndex;
  23. use Monolog\Logger;
  24. use Psr\SimpleCache\InvalidArgumentException;
  25. use RuntimeException;
  26. use function count;
  27. use function get_class;
  28. use function in_array;
  29. /**
  30. * Class FlexIndex
  31. * @package Grav\Framework\Flex
  32. * @template TKey
  33. * @template T of FlexObjectInterface
  34. * @template C of FlexCollectionInterface
  35. * @extends ObjectIndex<TKey,T>
  36. * @implements FlexIndexInterface<TKey,T>
  37. * @mixin C
  38. */
  39. class FlexIndex extends ObjectIndex implements FlexCollectionInterface, FlexIndexInterface
  40. {
  41. const VERSION = 1;
  42. /** @var FlexDirectory|null */
  43. private $_flexDirectory;
  44. /** @var string */
  45. private $_keyField;
  46. /** @var array */
  47. private $_indexKeys;
  48. /**
  49. * @param FlexDirectory $directory
  50. * @return static
  51. * @phpstan-return static<TKey,T,C>
  52. */
  53. public static function createFromStorage(FlexDirectory $directory)
  54. {
  55. return static::createFromArray(static::loadEntriesFromStorage($directory->getStorage()), $directory);
  56. }
  57. /**
  58. * {@inheritdoc}
  59. * @see FlexCollectionInterface::createFromArray()
  60. */
  61. public static function createFromArray(array $entries, FlexDirectory $directory, string $keyField = null)
  62. {
  63. $instance = new static($entries, $directory);
  64. $instance->setKeyField($keyField);
  65. return $instance;
  66. }
  67. /**
  68. * @param FlexStorageInterface $storage
  69. * @return array
  70. */
  71. public static function loadEntriesFromStorage(FlexStorageInterface $storage): array
  72. {
  73. return $storage->getExistingKeys();
  74. }
  75. /**
  76. * You can define indexes for fast lookup.
  77. *
  78. * Primary key: $meta['key']
  79. * Secondary keys: $meta['my_field']
  80. *
  81. * @param array $meta
  82. * @param array $data
  83. * @param FlexStorageInterface $storage
  84. * @return void
  85. */
  86. public static function updateObjectMeta(array &$meta, array $data, FlexStorageInterface $storage)
  87. {
  88. // For backwards compatibility, no need to call this method when you override this method.
  89. static::updateIndexData($meta, $data);
  90. }
  91. /**
  92. * Initializes a new FlexIndex.
  93. *
  94. * @param array $entries
  95. * @param FlexDirectory|null $directory
  96. */
  97. public function __construct(array $entries = [], FlexDirectory $directory = null)
  98. {
  99. // @phpstan-ignore-next-line
  100. if (get_class($this) === __CLASS__) {
  101. user_error('Using ' . __CLASS__ . ' directly is deprecated since Grav 1.7, use \Grav\Common\Flex\Types\Generic\GenericIndex or your own class instead', E_USER_DEPRECATED);
  102. }
  103. parent::__construct($entries);
  104. $this->_flexDirectory = $directory;
  105. $this->setKeyField(null);
  106. }
  107. /**
  108. * {@inheritdoc}
  109. * @see FlexCommonInterface::hasFlexFeature()
  110. */
  111. public function hasFlexFeature(string $name): bool
  112. {
  113. return in_array($name, $this->getFlexFeatures(), true);
  114. }
  115. /**
  116. * {@inheritdoc}
  117. * @see FlexCommonInterface::hasFlexFeature()
  118. */
  119. public function getFlexFeatures(): array
  120. {
  121. $implements = class_implements($this->getFlexDirectory()->getCollectionClass());
  122. $list = [];
  123. foreach ($implements as $interface) {
  124. if ($pos = strrpos($interface, '\\')) {
  125. $interface = substr($interface, $pos+1);
  126. }
  127. $list[] = Inflector::hyphenize(str_replace('Interface', '', $interface));
  128. }
  129. return $list;
  130. }
  131. /**
  132. * {@inheritdoc}
  133. * @see FlexCollectionInterface::search()
  134. */
  135. public function search(string $search, $properties = null, array $options = null)
  136. {
  137. return $this->__call('search', [$search, $properties, $options]);
  138. }
  139. /**
  140. * {@inheritdoc}
  141. * @see FlexCollectionInterface::sort()
  142. */
  143. public function sort(array $orderings)
  144. {
  145. return $this->orderBy($orderings);
  146. }
  147. /**
  148. * {@inheritdoc}
  149. * @see FlexCollectionInterface::filterBy()
  150. */
  151. public function filterBy(array $filters)
  152. {
  153. return $this->__call('filterBy', [$filters]);
  154. }
  155. /**
  156. * {@inheritdoc}
  157. * @see FlexCollectionInterface::getFlexType()
  158. */
  159. public function getFlexType(): string
  160. {
  161. return $this->getFlexDirectory()->getFlexType();
  162. }
  163. /**
  164. * {@inheritdoc}
  165. * @see FlexCollectionInterface::getFlexDirectory()
  166. */
  167. public function getFlexDirectory(): FlexDirectory
  168. {
  169. if (null === $this->_flexDirectory) {
  170. throw new RuntimeException('Flex Directory not defined, object is not fully defined');
  171. }
  172. return $this->_flexDirectory;
  173. }
  174. /**
  175. * {@inheritdoc}
  176. * @see FlexCollectionInterface::getTimestamp()
  177. */
  178. public function getTimestamp(): int
  179. {
  180. $timestamps = $this->getTimestamps();
  181. return $timestamps ? max($timestamps) : time();
  182. }
  183. /**
  184. * {@inheritdoc}
  185. * @see FlexCollectionInterface::getCacheKey()
  186. */
  187. public function getCacheKey(): string
  188. {
  189. return $this->getTypePrefix() . $this->getFlexType() . '.' . sha1(json_encode($this->getKeys()) . $this->_keyField);
  190. }
  191. /**
  192. * {@inheritdoc}
  193. * @see FlexCollectionInterface::getCacheChecksum()
  194. */
  195. public function getCacheChecksum(): string
  196. {
  197. $list = [];
  198. foreach ($this->getEntries() as $key => $value) {
  199. $list[$key] = $value['checksum'] ?? $value['storage_timestamp'];
  200. }
  201. return sha1((string)json_encode($list));
  202. }
  203. /**
  204. * {@inheritdoc}
  205. * @see FlexCollectionInterface::getTimestamps()
  206. */
  207. public function getTimestamps(): array
  208. {
  209. return $this->getIndexMap('storage_timestamp');
  210. }
  211. /**
  212. * {@inheritdoc}
  213. * @see FlexCollectionInterface::getStorageKeys()
  214. */
  215. public function getStorageKeys(): array
  216. {
  217. return $this->getIndexMap('storage_key');
  218. }
  219. /**
  220. * {@inheritdoc}
  221. * @see FlexCollectionInterface::getFlexKeys()
  222. */
  223. public function getFlexKeys(): array
  224. {
  225. // Get storage keys for the objects.
  226. $keys = [];
  227. $type = $this->getFlexDirectory()->getFlexType() . '.obj:';
  228. foreach ($this->getEntries() as $key => $value) {
  229. $keys[$key] = $value['flex_key'] ?? $type . $value['storage_key'];
  230. }
  231. return $keys;
  232. }
  233. /**
  234. * {@inheritdoc}
  235. * @see FlexIndexInterface::withKeyField()
  236. */
  237. public function withKeyField(string $keyField = null)
  238. {
  239. $keyField = $keyField ?: 'key';
  240. if ($keyField === $this->getKeyField()) {
  241. return $this;
  242. }
  243. $type = $keyField === 'flex_key' ? $this->getFlexDirectory()->getFlexType() . '.obj:' : '';
  244. $entries = [];
  245. foreach ($this->getEntries() as $key => $value) {
  246. if (!isset($value['key'])) {
  247. $value['key'] = $key;
  248. }
  249. if (isset($value[$keyField])) {
  250. $entries[$value[$keyField]] = $value;
  251. } elseif ($keyField === 'flex_key') {
  252. $entries[$type . $value['storage_key']] = $value;
  253. }
  254. }
  255. return $this->createFrom($entries, $keyField);
  256. }
  257. /**
  258. * {@inheritdoc}
  259. * @see FlexCollectionInterface::getIndex()
  260. */
  261. public function getIndex()
  262. {
  263. return $this;
  264. }
  265. /**
  266. * @return FlexCollectionInterface
  267. * @phpstan-return C
  268. */
  269. public function getCollection()
  270. {
  271. return $this->loadCollection();
  272. }
  273. /**
  274. * {@inheritdoc}
  275. * @see FlexCollectionInterface::render()
  276. */
  277. public function render(string $layout = null, array $context = [])
  278. {
  279. return $this->__call('render', [$layout, $context]);
  280. }
  281. /**
  282. * {@inheritdoc}
  283. * @see FlexIndexInterface::getFlexKeys()
  284. */
  285. public function getIndexMap(string $indexKey = null)
  286. {
  287. if (null === $indexKey) {
  288. return $this->getEntries();
  289. }
  290. // Get storage keys for the objects.
  291. $index = [];
  292. foreach ($this->getEntries() as $key => $value) {
  293. $index[$key] = $value[$indexKey] ?? null;
  294. }
  295. return $index;
  296. }
  297. /**
  298. * @param string $key
  299. * @return array
  300. * @phpstan-param TKey $key
  301. */
  302. public function getMetaData($key): array
  303. {
  304. return $this->getEntries()[$key] ?? [];
  305. }
  306. /**
  307. * @return string
  308. */
  309. public function getKeyField(): string
  310. {
  311. return $this->_keyField ?? 'storage_key';
  312. }
  313. /**
  314. * @param string|null $namespace
  315. * @return CacheInterface
  316. */
  317. public function getCache(string $namespace = null)
  318. {
  319. return $this->getFlexDirectory()->getCache($namespace);
  320. }
  321. /**
  322. * @param array $orderings
  323. * @return static
  324. * @phpstan-return static<TKey,T,C>
  325. */
  326. public function orderBy(array $orderings)
  327. {
  328. if (!$orderings || !$this->count()) {
  329. return $this;
  330. }
  331. // Handle primary key alias.
  332. $keyField = $this->getFlexDirectory()->getStorage()->getKeyField();
  333. if ($keyField !== 'key' && $keyField !== 'storage_key' && isset($orderings[$keyField])) {
  334. $orderings['key'] = $orderings[$keyField];
  335. unset($orderings[$keyField]);
  336. }
  337. // Check if ordering needs to load the objects.
  338. if (array_diff_key($orderings, $this->getIndexKeys())) {
  339. return $this->__call('orderBy', [$orderings]);
  340. }
  341. // Ordering can be done by using index only.
  342. $previous = null;
  343. foreach (array_reverse($orderings) as $field => $ordering) {
  344. $field = (string)$field;
  345. if ($this->getKeyField() === $field) {
  346. $keys = $this->getKeys();
  347. $search = array_combine($keys, $keys) ?: [];
  348. } elseif ($field === 'flex_key') {
  349. $search = $this->getFlexKeys();
  350. } else {
  351. $search = $this->getIndexMap($field);
  352. }
  353. // Update current search to match the previous ordering.
  354. if (null !== $previous) {
  355. $search = array_replace($previous, $search);
  356. }
  357. // Order by current field.
  358. if (strtoupper($ordering) === 'DESC') {
  359. arsort($search, SORT_NATURAL | SORT_FLAG_CASE);
  360. } else {
  361. asort($search, SORT_NATURAL | SORT_FLAG_CASE);
  362. }
  363. $previous = $search;
  364. }
  365. return $this->createFrom(array_replace($previous ?? [], $this->getEntries()) ?? []);
  366. }
  367. /**
  368. * {@inheritDoc}
  369. */
  370. public function call($method, array $arguments = [])
  371. {
  372. return $this->__call('call', [$method, $arguments]);
  373. }
  374. /**
  375. * @param string $name
  376. * @param array $arguments
  377. * @return mixed
  378. */
  379. public function __call($name, $arguments)
  380. {
  381. /** @var Debugger $debugger */
  382. $debugger = Grav::instance()['debugger'];
  383. /** @var FlexCollection $className */
  384. $className = $this->getFlexDirectory()->getCollectionClass();
  385. $cachedMethods = $className::getCachedMethods();
  386. $flexType = $this->getFlexType();
  387. if (!empty($cachedMethods[$name])) {
  388. $type = $cachedMethods[$name];
  389. if ($type === 'session') {
  390. /** @var Session $session */
  391. $session = Grav::instance()['session'];
  392. $cacheKey = $session->getId() . ($session->user->username ?? '');
  393. } else {
  394. $cacheKey = '';
  395. }
  396. $key = "{$flexType}.idx." . sha1($name . '.' . $cacheKey . json_encode($arguments) . $this->getCacheKey());
  397. $checksum = $this->getCacheChecksum();
  398. $cache = $this->getCache('object');
  399. try {
  400. $cached = $cache->get($key);
  401. $test = $cached[0] ?? null;
  402. $result = $test === $checksum ? ($cached[1] ?? null) : null;
  403. // Make sure the keys aren't changed if the returned type is the same index type.
  404. if ($result instanceof self && $flexType === $result->getFlexType()) {
  405. $result = $result->withKeyField($this->getKeyField());
  406. }
  407. } catch (InvalidArgumentException $e) {
  408. $debugger->addException($e);
  409. }
  410. if (!isset($result)) {
  411. $collection = $this->loadCollection();
  412. $result = $collection->{$name}(...$arguments);
  413. $debugger->addMessage("Cache miss: '{$flexType}::{$name}()'", 'debug');
  414. try {
  415. // If flex collection is returned, convert it back to flex index.
  416. if ($result instanceof FlexCollection) {
  417. $cached = $result->getFlexDirectory()->getIndex($result->getKeys(), $this->getKeyField());
  418. } else {
  419. $cached = $result;
  420. }
  421. $cache->set($key, [$checksum, $cached]);
  422. } catch (InvalidArgumentException $e) {
  423. $debugger->addException($e);
  424. // TODO: log error.
  425. }
  426. }
  427. } else {
  428. $collection = $this->loadCollection();
  429. $result = $collection->{$name}(...$arguments);
  430. if (!isset($cachedMethods[$name])) {
  431. $debugger->addMessage("Call '{$flexType}:{$name}()' isn't cached", 'debug');
  432. }
  433. }
  434. return $result;
  435. }
  436. /**
  437. * @return array
  438. */
  439. public function __serialize(): array
  440. {
  441. return ['type' => $this->getFlexType(), 'entries' => $this->getEntries()];
  442. }
  443. /**
  444. * @param array $data
  445. * @return void
  446. */
  447. public function __unserialize(array $data): void
  448. {
  449. $this->_flexDirectory = Grav::instance()['flex']->getDirectory($data['type']);
  450. $this->setEntries($data['entries']);
  451. }
  452. /**
  453. * @return array
  454. */
  455. public function __debugInfo()
  456. {
  457. return [
  458. 'type:private' => $this->getFlexType(),
  459. 'key:private' => $this->getKey(),
  460. 'entries_key:private' => $this->getKeyField(),
  461. 'entries:private' => $this->getEntries()
  462. ];
  463. }
  464. /**
  465. * @param array $entries
  466. * @param string|null $keyField
  467. * @return static
  468. * @phpstan-return static<TKey,T,C>
  469. */
  470. protected function createFrom(array $entries, string $keyField = null)
  471. {
  472. $index = new static($entries, $this->getFlexDirectory());
  473. $index->setKeyField($keyField ?? $this->_keyField);
  474. return $index;
  475. }
  476. /**
  477. * @param string|null $keyField
  478. * @return void
  479. */
  480. protected function setKeyField(string $keyField = null)
  481. {
  482. $this->_keyField = $keyField ?? 'storage_key';
  483. }
  484. /**
  485. * @return array
  486. */
  487. protected function getIndexKeys()
  488. {
  489. if (null === $this->_indexKeys) {
  490. $entries = $this->getEntries();
  491. $first = reset($entries);
  492. if ($first) {
  493. $keys = array_keys($first);
  494. $keys = array_combine($keys, $keys) ?: [];
  495. } else {
  496. $keys = [];
  497. }
  498. $this->setIndexKeys($keys);
  499. }
  500. return $this->_indexKeys;
  501. }
  502. /**
  503. * @param array $indexKeys
  504. * @return void
  505. */
  506. protected function setIndexKeys(array $indexKeys)
  507. {
  508. // Add defaults.
  509. $indexKeys += [
  510. 'key' => 'key',
  511. 'storage_key' => 'storage_key',
  512. 'storage_timestamp' => 'storage_timestamp',
  513. 'flex_key' => 'flex_key'
  514. ];
  515. $this->_indexKeys = $indexKeys;
  516. }
  517. /**
  518. * @return string
  519. */
  520. protected function getTypePrefix()
  521. {
  522. return 'i.';
  523. }
  524. /**
  525. * @param string $key
  526. * @param mixed $value
  527. * @return ObjectInterface|null
  528. */
  529. protected function loadElement($key, $value): ?ObjectInterface
  530. {
  531. $objects = $this->getFlexDirectory()->loadObjects([$key => $value]);
  532. return $objects ? reset($objects): null;
  533. }
  534. /**
  535. * @param array|null $entries
  536. * @return ObjectInterface[]
  537. */
  538. protected function loadElements(array $entries = null): array
  539. {
  540. return $this->getFlexDirectory()->loadObjects($entries ?? $this->getEntries());
  541. }
  542. /**
  543. * @param array|null $entries
  544. * @return CollectionInterface
  545. * @phpstan-return C
  546. */
  547. protected function loadCollection(array $entries = null): CollectionInterface
  548. {
  549. return $this->getFlexDirectory()->loadCollection($entries ?? $this->getEntries(), $this->_keyField);
  550. }
  551. /**
  552. * @param mixed $value
  553. * @return bool
  554. */
  555. protected function isAllowedElement($value): bool
  556. {
  557. return $value instanceof FlexObject;
  558. }
  559. /**
  560. * @param FlexObjectInterface $object
  561. * @return mixed
  562. */
  563. protected function getElementMeta($object)
  564. {
  565. return $object->getMetaData();
  566. }
  567. /**
  568. * @param FlexObjectInterface $element
  569. * @return string
  570. */
  571. protected function getCurrentKey($element)
  572. {
  573. $keyField = $this->getKeyField();
  574. if ($keyField === 'storage_key') {
  575. return $element->getStorageKey();
  576. }
  577. if ($keyField === 'flex_key') {
  578. return $element->getFlexKey();
  579. }
  580. if ($keyField === 'key') {
  581. return $element->getKey();
  582. }
  583. return $element->getKey();
  584. }
  585. /**
  586. * @param FlexStorageInterface $storage
  587. * @param array $index Saved index
  588. * @param array $entries Updated index
  589. * @param array $options
  590. * @return array Compiled list of entries
  591. */
  592. protected static function updateIndexFile(FlexStorageInterface $storage, array $index, array $entries, array $options = []): array
  593. {
  594. $indexFile = static::getIndexFile($storage);
  595. if (null === $indexFile) {
  596. return $entries;
  597. }
  598. // Calculate removed objects.
  599. $removed = array_diff_key($index, $entries);
  600. // First get rid of all removed objects.
  601. if ($removed) {
  602. $index = array_diff_key($index, $removed);
  603. }
  604. if ($entries && empty($options['force_update'])) {
  605. // Calculate difference between saved index and current data.
  606. foreach ($index as $key => $entry) {
  607. $storage_key = $entry['storage_key'] ?? null;
  608. if (isset($entries[$storage_key]) && $entries[$storage_key]['storage_timestamp'] === $entry['storage_timestamp']) {
  609. // Entry is up to date, no update needed.
  610. unset($entries[$storage_key]);
  611. }
  612. }
  613. if (empty($entries) && empty($removed)) {
  614. // No objects were added, updated or removed.
  615. return $index;
  616. }
  617. } elseif (!$removed) {
  618. // There are no objects and nothing was removed.
  619. return [];
  620. }
  621. // Index should be updated, lock the index file for saving.
  622. $indexFile->lock();
  623. // Read all the data rows into an array using chunks of 100.
  624. $keys = array_fill_keys(array_keys($entries), null);
  625. $chunks = array_chunk($keys, 100, true);
  626. $updated = $added = [];
  627. foreach ($chunks as $keys) {
  628. $rows = $storage->readRows($keys);
  629. $keyField = $storage->getKeyField();
  630. // Go through all the updated objects and refresh their index data.
  631. foreach ($rows as $key => $row) {
  632. if (null !== $row || !empty($options['include_missing'])) {
  633. $entry = $entries[$key] + ['key' => $key];
  634. if ($keyField !== 'storage_key' && isset($row[$keyField])) {
  635. $entry['key'] = $row[$keyField];
  636. }
  637. static::updateObjectMeta($entry, $row ?? [], $storage);
  638. if (isset($row['__ERROR'])) {
  639. $entry['__ERROR'] = true;
  640. static::onException(new RuntimeException(sprintf('Object failed to load: %s (%s)', $key,
  641. $row['__ERROR'])));
  642. }
  643. if (isset($index[$key])) {
  644. // Update object in the index.
  645. $updated[$key] = $entry;
  646. } else {
  647. // Add object into the index.
  648. $added[$key] = $entry;
  649. }
  650. // Either way, update the entry.
  651. $index[$key] = $entry;
  652. } elseif (isset($index[$key])) {
  653. // Remove object from the index.
  654. $removed[$key] = $index[$key];
  655. unset($index[$key]);
  656. }
  657. }
  658. unset($rows);
  659. }
  660. // Sort the index before saving it.
  661. ksort($index, SORT_NATURAL | SORT_FLAG_CASE);
  662. static::onChanges($index, $added, $updated, $removed);
  663. $indexFile->save(['version' => static::VERSION, 'timestamp' => time(), 'count' => count($index), 'index' => $index]);
  664. $indexFile->unlock();
  665. return $index;
  666. }
  667. /**
  668. * @param array $entry
  669. * @param array $data
  670. * @return void
  671. * @deprecated 1.7 Use static ::updateObjectMeta() method instead.
  672. */
  673. protected static function updateIndexData(array &$entry, array $data)
  674. {
  675. }
  676. /**
  677. * @param FlexStorageInterface $storage
  678. * @return array
  679. */
  680. protected static function loadIndex(FlexStorageInterface $storage)
  681. {
  682. $indexFile = static::getIndexFile($storage);
  683. if ($indexFile) {
  684. $data = [];
  685. try {
  686. $data = (array)$indexFile->content();
  687. $version = $data['version'] ?? null;
  688. if ($version !== static::VERSION) {
  689. $data = [];
  690. }
  691. } catch (Exception $e) {
  692. $e = new RuntimeException(sprintf('Index failed to load: %s', $e->getMessage()), $e->getCode(), $e);
  693. static::onException($e);
  694. }
  695. if ($data) {
  696. return $data;
  697. }
  698. }
  699. return ['version' => static::VERSION, 'timestamp' => 0, 'count' => 0, 'index' => []];
  700. }
  701. /**
  702. * @param FlexStorageInterface $storage
  703. * @return array
  704. */
  705. protected static function loadEntriesFromIndex(FlexStorageInterface $storage)
  706. {
  707. $data = static::loadIndex($storage);
  708. return $data['index'] ?? [];
  709. }
  710. /**
  711. * @param FlexStorageInterface $storage
  712. * @return CompiledYamlFile|null
  713. */
  714. protected static function getIndexFile(FlexStorageInterface $storage)
  715. {
  716. if (!method_exists($storage, 'isIndexed') || !$storage->isIndexed()) {
  717. return null;
  718. }
  719. $path = $storage->getStoragePath();
  720. if (!$path) {
  721. return null;
  722. }
  723. // Load saved index file.
  724. $grav = Grav::instance();
  725. $locator = $grav['locator'];
  726. $filename = $locator->findResource("{$path}/index.yaml", true, true);
  727. return CompiledYamlFile::instance($filename);
  728. }
  729. /**
  730. * @param Exception $e
  731. * @return void
  732. */
  733. protected static function onException(Exception $e)
  734. {
  735. $grav = Grav::instance();
  736. /** @var Logger $logger */
  737. $logger = $grav['log'];
  738. $logger->addAlert($e->getMessage());
  739. /** @var Debugger $debugger */
  740. $debugger = $grav['debugger'];
  741. $debugger->addException($e);
  742. $debugger->addMessage($e, 'error');
  743. }
  744. /**
  745. * @param array $entries
  746. * @param array $added
  747. * @param array $updated
  748. * @param array $removed
  749. * @return void
  750. */
  751. protected static function onChanges(array $entries, array $added, array $updated, array $removed)
  752. {
  753. $addedCount = count($added);
  754. $updatedCount = count($updated);
  755. $removedCount = count($removed);
  756. if ($addedCount + $updatedCount + $removedCount) {
  757. $message = sprintf('Index updated, %d objects (%d added, %d updated, %d removed).', count($entries), $addedCount, $updatedCount, $removedCount);
  758. $grav = Grav::instance();
  759. /** @var Debugger $debugger */
  760. $debugger = $grav['debugger'];
  761. $debugger->addMessage($message, 'debug');
  762. }
  763. }
  764. // DEPRECATED METHODS
  765. /**
  766. * @param bool $prefix
  767. * @return string
  768. * @deprecated 1.6 Use `->getFlexType()` instead.
  769. */
  770. public function getType($prefix = false)
  771. {
  772. user_error(__CLASS__ . '::' . __FUNCTION__ . '() is deprecated since Grav 1.6, use ->getFlexType() method instead', E_USER_DEPRECATED);
  773. $type = $prefix ? $this->getTypePrefix() : '';
  774. return $type . $this->getFlexType();
  775. }
  776. }