Media.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\MediaStorage\Helper\File;
  7. use Magento\Framework\App\Filesystem\DirectoryList;
  8. /**
  9. * Class Media
  10. */
  11. class Media extends \Magento\Framework\App\Helper\AbstractHelper
  12. {
  13. /**
  14. * @var \Magento\Framework\Stdlib\DateTime\DateTime
  15. */
  16. protected $_date;
  17. /**
  18. * @var \Magento\Framework\Filesystem
  19. */
  20. protected $filesystem;
  21. /**
  22. * Constructor
  23. *
  24. * @param \Magento\Framework\App\Helper\Context $context
  25. * @param \Magento\Framework\Stdlib\DateTime\DateTime $date
  26. * @param \Magento\Framework\Filesystem $filesystem
  27. */
  28. public function __construct(
  29. \Magento\Framework\App\Helper\Context $context,
  30. \Magento\Framework\Stdlib\DateTime\DateTime $date,
  31. \Magento\Framework\Filesystem $filesystem
  32. ) {
  33. parent::__construct($context);
  34. $this->_date = $date;
  35. $this->filesystem = $filesystem;
  36. }
  37. /**
  38. * Collect file info
  39. *
  40. * Return array(
  41. * filename => string
  42. * content => string|bool
  43. * update_time => string
  44. * directory => string
  45. *
  46. * @param string $mediaDirectory
  47. * @param string $path
  48. * @return array
  49. * @throws \Magento\Framework\Exception\LocalizedException
  50. */
  51. public function collectFileInfo($mediaDirectory, $path)
  52. {
  53. $path = ltrim($path, '\\/');
  54. $fullPath = $mediaDirectory . '/' . $path;
  55. $dir = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
  56. $relativePath = $dir->getRelativePath($fullPath);
  57. if (!$dir->isFile($relativePath)) {
  58. throw new \Magento\Framework\Exception\LocalizedException(
  59. __('The "%1" file doesn\'t exist. Verify the file and try again.', $fullPath)
  60. );
  61. }
  62. if (!$dir->isReadable($relativePath)) {
  63. throw new \Magento\Framework\Exception\LocalizedException(__('File %1 is not readable', $fullPath));
  64. }
  65. $path = str_replace(['/', '\\'], '/', $path);
  66. $directory = dirname($path);
  67. if ($directory == '.') {
  68. $directory = null;
  69. }
  70. return [
  71. 'filename' => basename($path),
  72. 'content' => $dir->readFile($relativePath),
  73. 'update_time' => $this->_date->date(),
  74. 'directory' => $directory
  75. ];
  76. }
  77. }