FlexIndex.php 26 KB

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