Image.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Eav\Model\Attribute\Data;
  7. /**
  8. * EAV Entity Attribute Image File Data Model
  9. *
  10. * @author Magento Core Team <core@magentocommerce.com>
  11. */
  12. class Image extends \Magento\Eav\Model\Attribute\Data\File
  13. {
  14. /**
  15. * Validate file by attribute validate rules
  16. *
  17. * Return array of errors
  18. *
  19. * @param array $value
  20. * @return array
  21. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  22. * @SuppressWarnings(PHPMD.NPathComplexity)
  23. */
  24. protected function _validateByRules($value)
  25. {
  26. $label = __($this->getAttribute()->getStoreLabel());
  27. $rules = $this->getAttribute()->getValidateRules();
  28. $imageProp = @getimagesize($value['tmp_name']);
  29. $allowImageTypes = [1 => 'gif', 2 => 'jpg', 3 => 'png'];
  30. if (!isset($allowImageTypes[$imageProp[2]])) {
  31. return [__('"%1" is not a valid image format', $label)];
  32. }
  33. // modify image name
  34. $extension = pathinfo($value['name'], PATHINFO_EXTENSION);
  35. if ($extension != $allowImageTypes[$imageProp[2]]) {
  36. $value['name'] = pathinfo($value['name'], PATHINFO_FILENAME) . '.' . $allowImageTypes[$imageProp[2]];
  37. }
  38. $errors = [];
  39. if (!empty($rules['max_file_size'])) {
  40. $size = $value['size'];
  41. if ($rules['max_file_size'] < $size) {
  42. $errors[] = __('"%1" exceeds the allowed file size.', $label);
  43. }
  44. }
  45. if (!empty($rules['max_image_width'])) {
  46. if ($rules['max_image_width'] < $imageProp[0]) {
  47. $r = $rules['max_image_width'];
  48. $errors[] = __('"%1" width exceeds allowed value of %2 px.', $label, $r);
  49. }
  50. }
  51. if (!empty($rules['max_image_height'])) {
  52. if ($rules['max_image_height'] < $imageProp[1]) {
  53. $r = $rules['max_image_height'];
  54. $errors[] = __('"%1" height exceeds allowed value of %2 px.', $label, $r);
  55. }
  56. }
  57. return $errors;
  58. }
  59. }