PageRenderTime 43ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/magento/module-customer/Model/Metadata/Form/File.php

https://gitlab.com/yousafsyed/easternglamor
PHP | 312 lines | 194 code | 37 blank | 81 comment | 39 complexity | 026ed5f9a2e04142acacc0eda1b7e3cb MD5 | raw file
  1. <?php
  2. /**
  3. * Form Element File Data Model
  4. *
  5. * Copyright © 2016 Magento. All rights reserved.
  6. * See COPYING.txt for license details.
  7. */
  8. namespace Magento\Customer\Model\Metadata\Form;
  9. use Magento\Framework\File\UploaderFactory;
  10. use Magento\Framework\Filesystem;
  11. use Magento\Framework\App\Filesystem\DirectoryList;
  12. use Magento\Framework\Api\ArrayObjectSearch;
  13. /**
  14. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  15. */
  16. class File extends AbstractData
  17. {
  18. /**
  19. * Validator for check not protected extensions
  20. *
  21. * @var \Magento\MediaStorage\Model\File\Validator\NotProtectedExtension
  22. */
  23. protected $_validatorNotProtectedExtensions;
  24. /**
  25. * Core data
  26. *
  27. * @var \Magento\Framework\Url\EncoderInterface
  28. */
  29. protected $urlEncoder;
  30. /**
  31. * @var \Magento\MediaStorage\Model\File\Validator\NotProtectedExtension
  32. */
  33. protected $_fileValidator;
  34. /**
  35. * @var Filesystem
  36. */
  37. protected $_fileSystem;
  38. /**
  39. * @var UploaderFactory
  40. */
  41. private $uploaderFactory;
  42. /**
  43. * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
  44. * @param \Psr\Log\LoggerInterface $logger
  45. * @param \Magento\Customer\Api\Data\AttributeMetadataInterface $attribute
  46. * @param \Magento\Framework\Locale\ResolverInterface $localeResolver
  47. * @param null $value
  48. * @param string $entityTypeCode
  49. * @param bool $isAjax
  50. * @param \Magento\Framework\Url\EncoderInterface $urlEncoder
  51. * @param \Magento\MediaStorage\Model\File\Validator\NotProtectedExtension $fileValidator
  52. * @param Filesystem $fileSystem
  53. * @param UploaderFactory $uploaderFactory
  54. * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  55. */
  56. public function __construct(
  57. \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
  58. \Psr\Log\LoggerInterface $logger,
  59. \Magento\Customer\Api\Data\AttributeMetadataInterface $attribute,
  60. \Magento\Framework\Locale\ResolverInterface $localeResolver,
  61. $value,
  62. $entityTypeCode,
  63. $isAjax,
  64. \Magento\Framework\Url\EncoderInterface $urlEncoder,
  65. \Magento\MediaStorage\Model\File\Validator\NotProtectedExtension $fileValidator,
  66. Filesystem $fileSystem,
  67. UploaderFactory $uploaderFactory
  68. ) {
  69. parent::__construct($localeDate, $logger, $attribute, $localeResolver, $value, $entityTypeCode, $isAjax);
  70. $this->urlEncoder = $urlEncoder;
  71. $this->_fileValidator = $fileValidator;
  72. $this->_fileSystem = $fileSystem;
  73. $this->uploaderFactory = $uploaderFactory;
  74. }
  75. /**
  76. * {@inheritdoc}
  77. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  78. */
  79. public function extractValue(\Magento\Framework\App\RequestInterface $request)
  80. {
  81. if ($this->getIsAjaxRequest()) {
  82. return false;
  83. }
  84. $extend = $this->_getRequestValue($request);
  85. $attrCode = $this->getAttribute()->getAttributeCode();
  86. if ($this->_requestScope) {
  87. $value = [];
  88. if (strpos($this->_requestScope, '/') !== false) {
  89. $scopes = explode('/', $this->_requestScope);
  90. $mainScope = array_shift($scopes);
  91. } else {
  92. $mainScope = $this->_requestScope;
  93. $scopes = [];
  94. }
  95. if (!empty($_FILES[$mainScope])) {
  96. foreach ($_FILES[$mainScope] as $fileKey => $scopeData) {
  97. foreach ($scopes as $scopeName) {
  98. if (isset($scopeData[$scopeName])) {
  99. $scopeData = $scopeData[$scopeName];
  100. } else {
  101. $scopeData[$scopeName] = [];
  102. }
  103. }
  104. if (isset($scopeData[$attrCode])) {
  105. $value[$fileKey] = $scopeData[$attrCode];
  106. }
  107. }
  108. } else {
  109. $value = [];
  110. }
  111. } else {
  112. if (isset($_FILES[$attrCode])) {
  113. $value = $_FILES[$attrCode];
  114. } else {
  115. $value = [];
  116. }
  117. }
  118. if (!empty($extend['delete'])) {
  119. $value['delete'] = true;
  120. }
  121. return $value;
  122. }
  123. /**
  124. * Validate file by attribute validate rules
  125. * Return array of errors
  126. *
  127. * @param array $value
  128. * @return string[]
  129. */
  130. protected function _validateByRules($value)
  131. {
  132. $label = $value['name'];
  133. $rules = $this->getAttribute()->getValidationRules();
  134. $extension = pathinfo($value['name'], PATHINFO_EXTENSION);
  135. $fileExtensions = ArrayObjectSearch::getArrayElementByName(
  136. $rules,
  137. 'file_extensions'
  138. );
  139. if ($fileExtensions !== null) {
  140. $extensions = explode(',', $fileExtensions);
  141. $extensions = array_map('trim', $extensions);
  142. if (!in_array($extension, $extensions)) {
  143. return [__('"%1" is not a valid file extension.', $extension)];
  144. }
  145. }
  146. /**
  147. * Check protected file extension
  148. */
  149. if (!$this->_fileValidator->isValid($extension)) {
  150. return $this->_fileValidator->getMessages();
  151. }
  152. if (!$this->_isUploadedFile($value['tmp_name'])) {
  153. return [__('"%1" is not a valid file.', $label)];
  154. }
  155. $maxFileSize = ArrayObjectSearch::getArrayElementByName(
  156. $rules,
  157. 'max_file_size'
  158. );
  159. if ($maxFileSize !== null) {
  160. $size = $value['size'];
  161. if ($maxFileSize < $size) {
  162. return [__('"%1" exceeds the allowed file size.', $label)];
  163. }
  164. }
  165. return [];
  166. }
  167. /**
  168. * Helper function that checks if the file was uploaded.
  169. *
  170. * This helper function is needed for testing.
  171. *
  172. * @param string $filename
  173. * @return bool
  174. */
  175. protected function _isUploadedFile($filename)
  176. {
  177. return is_uploaded_file($filename);
  178. }
  179. /**
  180. * {@inheritdoc}
  181. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  182. * @SuppressWarnings(PHPMD.NPathComplexity)
  183. */
  184. public function validateValue($value)
  185. {
  186. if ($this->getIsAjaxRequest()) {
  187. return true;
  188. }
  189. $errors = [];
  190. $attribute = $this->getAttribute();
  191. $label = $attribute->getStoreLabel();
  192. $toDelete = !empty($value['delete']) ? true : false;
  193. $toUpload = !empty($value['tmp_name']) ? true : false;
  194. if (!$toUpload && !$toDelete && $this->_value) {
  195. return true;
  196. }
  197. if (!$attribute->isRequired() && !$toUpload) {
  198. return true;
  199. }
  200. if ($attribute->isRequired() && !$toUpload) {
  201. $errors[] = __('"%1" is a required value.', $label);
  202. }
  203. if ($toUpload) {
  204. $errors = array_merge($errors, $this->_validateByRules($value));
  205. }
  206. if (count($errors) == 0) {
  207. return true;
  208. }
  209. return $errors;
  210. }
  211. /**
  212. * {@inheritdoc}
  213. *
  214. * @return $this|string
  215. */
  216. public function compactValue($value)
  217. {
  218. if ($this->getIsAjaxRequest()) {
  219. return $this;
  220. }
  221. $attribute = $this->getAttribute();
  222. $original = $this->_value;
  223. $toDelete = false;
  224. if ($original) {
  225. if (!$attribute->isRequired() && !empty($value['delete'])) {
  226. $toDelete = true;
  227. }
  228. if (!empty($value['tmp_name'])) {
  229. $toDelete = true;
  230. }
  231. }
  232. $mediaDir = $this->_fileSystem->getDirectoryWrite(DirectoryList::MEDIA);
  233. $result = $original;
  234. // unlink entity file
  235. if ($toDelete) {
  236. $result = '';
  237. $mediaDir->delete($this->_entityTypeCode . $original);
  238. }
  239. if (!empty($value['tmp_name'])) {
  240. try {
  241. $uploader = $this->uploaderFactory->create(['fileId' => $value]);
  242. $uploader->setFilesDispersion(true);
  243. $uploader->setFilenamesCaseSensitivity(false);
  244. $uploader->setAllowRenameFiles(true);
  245. $uploader->save($mediaDir->getAbsolutePath($this->_entityTypeCode), $value['name']);
  246. $result = $uploader->getUploadedFileName();
  247. } catch (\Exception $e) {
  248. $this->_logger->critical($e);
  249. }
  250. }
  251. return $result;
  252. }
  253. /**
  254. * {@inheritdoc}
  255. */
  256. public function restoreValue($value)
  257. {
  258. return $this->_value;
  259. }
  260. /**
  261. * {@inheritdoc}
  262. */
  263. public function outputValue($format = \Magento\Customer\Model\Metadata\ElementFactory::OUTPUT_FORMAT_TEXT)
  264. {
  265. $output = '';
  266. if ($this->_value) {
  267. switch ($format) {
  268. case \Magento\Customer\Model\Metadata\ElementFactory::OUTPUT_FORMAT_JSON:
  269. $output = ['value' => $this->_value, 'url_key' => $this->urlEncoder->encode($this->_value)];
  270. break;
  271. }
  272. }
  273. return $output;
  274. }
  275. }