FileStorage.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @package Grav\Framework\Flex
  5. *
  6. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  7. * @license MIT License; see LICENSE file for details.
  8. */
  9. namespace Grav\Framework\Flex\Storage;
  10. use Grav\Framework\Flex\Interfaces\FlexStorageInterface;
  11. /**
  12. * Class FileStorage
  13. * @package Grav\Framework\Flex\Storage
  14. */
  15. class FileStorage extends FolderStorage
  16. {
  17. /**
  18. * {@inheritdoc}
  19. * @see FlexStorageInterface::__construct()
  20. */
  21. public function __construct(array $options)
  22. {
  23. $this->dataPattern = '{FOLDER}/{KEY}';
  24. if (!isset($options['formatter']) && isset($options['pattern'])) {
  25. $options['formatter'] = $this->detectDataFormatter($options['pattern']);
  26. }
  27. parent::__construct($options);
  28. }
  29. /**
  30. * {@inheritdoc}
  31. * @see FlexStorageInterface::getMediaPath()
  32. */
  33. public function getMediaPath(string $key = null): string
  34. {
  35. return $key ? \dirname($this->getStoragePath($key)) . '/' . $key : $this->getStoragePath();
  36. }
  37. /**
  38. * {@inheritdoc}
  39. */
  40. protected function getKeyFromPath(string $path): string
  41. {
  42. return basename($path, $this->dataFormatter->getDefaultFileExtension());
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. protected function buildIndex(): array
  48. {
  49. if (!file_exists($this->getStoragePath())) {
  50. return [];
  51. }
  52. $flags = \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS;
  53. $iterator = new \FilesystemIterator($this->getStoragePath(), $flags);
  54. $list = [];
  55. /** @var \SplFileInfo $info */
  56. foreach ($iterator as $filename => $info) {
  57. if (!$info->isFile() || !($key = $this->getKeyFromPath($filename)) || strpos($info->getFilename(), '.') === 0) {
  58. continue;
  59. }
  60. $list[$key] = [
  61. 'storage_key' => $key,
  62. 'storage_timestamp' => $info->getMTime()
  63. ];
  64. }
  65. ksort($list, SORT_NATURAL);
  66. return $list;
  67. }
  68. }