Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
SampleFileProvider.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
13 
19 {
24  private $samples;
25 
29  private $componentRegistrar;
30 
34  private $readFactory;
35 
41  public function __construct(
42  \Magento\Framework\Filesystem\Directory\ReadFactory $readFactory,
43  \Magento\Framework\Component\ComponentRegistrar $componentRegistrar,
44  array $samples = []
45  ) {
46  $this->readFactory = $readFactory;
47  $this->componentRegistrar = $componentRegistrar;
48  $this->samples = $samples;
49  }
50 
58  public function getSize(string $entityName)
59  {
60  $directoryRead = $this->getDirectoryRead($entityName);
61  $filePath = $this->getPath($entityName);
62  $fileSize = isset($directoryRead->stat($filePath)['size'])
63  ? $directoryRead->stat($filePath)['size'] : null;
64 
65  return $fileSize;
66  }
67 
75  public function getFileContents(string $entityName): string
76  {
77  $directoryRead = $this->getDirectoryRead($entityName);
78  $filePath = $this->getPath($entityName);
79 
80  return $directoryRead->readFile($filePath);
81  }
82 
87  private function getPath(string $entityName): string
88  {
89  $moduleName = $this->getModuleName($entityName);
90  $directoryRead = $this->getDirectoryRead($entityName);
91  $moduleDir = $this->componentRegistrar->getPath(ComponentRegistrar::MODULE, $moduleName);
92  $fileAbsolutePath = $moduleDir . '/Files/Sample/' . $entityName . '.csv';
93 
94  $filePath = $directoryRead->getRelativePath($fileAbsolutePath);
95 
96  if (!$directoryRead->isFile($filePath)) {
97  throw new NoSuchEntityException(__("There is no file: %file", ['file' => $filePath]));
98  }
99 
100  return $filePath;
101  }
102 
107  private function getDirectoryRead(string $entityName): ReadInterface
108  {
109  $moduleName = $this->getModuleName($entityName);
110  $moduleDir = $this->componentRegistrar->getPath(ComponentRegistrar::MODULE, $moduleName);
111  $directoryRead = $this->readFactory->create($moduleDir);
112 
113  return $directoryRead;
114  }
115 
121  private function getModuleName(string $entityName): string
122  {
123  if (!isset($this->samples[$entityName])) {
124  throw new NoSuchEntityException();
125  }
126 
127  return $this->samples[$entityName];
128  }
129 }
$componentRegistrar
Definition: bootstrap.php:23
__()
Definition: __.php:13
__construct(\Magento\Framework\Filesystem\Directory\ReadFactory $readFactory, \Magento\Framework\Component\ComponentRegistrar $componentRegistrar, array $samples=[])