AttributeDataFactory.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Eav\Model;
  7. /**
  8. * EAV Entity Attribute Data Factory
  9. *
  10. * @author Magento Core Team <core@magentocommerce.com>
  11. */
  12. class AttributeDataFactory
  13. {
  14. const OUTPUT_FORMAT_JSON = 'json';
  15. const OUTPUT_FORMAT_TEXT = 'text';
  16. const OUTPUT_FORMAT_HTML = 'html';
  17. const OUTPUT_FORMAT_PDF = 'pdf';
  18. const OUTPUT_FORMAT_ONELINE = 'oneline';
  19. const OUTPUT_FORMAT_ARRAY = 'array';
  20. // available only for multiply attributes
  21. // available only for multiply attributes
  22. protected $_dataModels = [];
  23. /**
  24. * @var \Magento\Framework\ObjectManagerInterface
  25. */
  26. protected $_objectManager;
  27. /**
  28. * @var \Magento\Framework\Stdlib\StringUtils
  29. */
  30. protected $string;
  31. /**
  32. * @param \Magento\Framework\ObjectManagerInterface $objectManager
  33. * @param \Magento\Framework\Stdlib\StringUtils $string
  34. * @codeCoverageIgnore
  35. */
  36. public function __construct(
  37. \Magento\Framework\ObjectManagerInterface $objectManager,
  38. \Magento\Framework\Stdlib\StringUtils $string
  39. ) {
  40. $this->_objectManager = $objectManager;
  41. $this->string = $string;
  42. }
  43. /**
  44. * Return attribute data model by attribute
  45. * Set entity to data model (need for work)
  46. *
  47. * @param \Magento\Eav\Model\Attribute $attribute
  48. * @param \Magento\Framework\Model\AbstractModel $entity
  49. * @return \Magento\Eav\Model\Attribute\Data\AbstractData
  50. */
  51. public function create(\Magento\Eav\Model\Attribute $attribute, \Magento\Framework\Model\AbstractModel $entity)
  52. {
  53. /* @var $dataModel \Magento\Eav\Model\Attribute\Data\AbstractData */
  54. $dataModelClass = $attribute->getDataModel();
  55. if (!empty($dataModelClass)) {
  56. if (empty($this->_dataModels[$dataModelClass])) {
  57. $dataModel = $this->_objectManager->create($dataModelClass);
  58. $this->_dataModels[$dataModelClass] = $dataModel;
  59. } else {
  60. $dataModel = $this->_dataModels[$dataModelClass];
  61. }
  62. } else {
  63. if (empty($this->_dataModels[$attribute->getFrontendInput()])) {
  64. $dataModelClass = sprintf(
  65. 'Magento\Eav\Model\Attribute\Data\%s',
  66. $this->string->upperCaseWords($attribute->getFrontendInput())
  67. );
  68. $dataModel = $this->_objectManager->create($dataModelClass);
  69. $this->_dataModels[$attribute->getFrontendInput()] = $dataModel;
  70. } else {
  71. $dataModel = $this->_dataModels[$attribute->getFrontendInput()];
  72. }
  73. }
  74. $dataModel->setAttribute($attribute);
  75. $dataModel->setEntity($entity);
  76. return $dataModel;
  77. }
  78. }