FlexIndex.php 26 KB

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