Code.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. /**
  3. * Google Optimizer Scripts Helper
  4. *
  5. * Copyright © Magento, Inc. All rights reserved.
  6. * See COPYING.txt for license details.
  7. */
  8. namespace Magento\GoogleOptimizer\Helper;
  9. /**
  10. * @api
  11. * @since 100.0.2
  12. */
  13. class Code
  14. {
  15. /**
  16. * @var \Magento\GoogleOptimizer\Model\Code
  17. */
  18. protected $_codeModel;
  19. /**
  20. * @var \Magento\Framework\Model\AbstractModel
  21. */
  22. protected $_entity;
  23. /**
  24. * @param \Magento\GoogleOptimizer\Model\Code $code
  25. */
  26. public function __construct(\Magento\GoogleOptimizer\Model\Code $code)
  27. {
  28. $this->_codeModel = $code;
  29. }
  30. /**
  31. * Get loaded Code object by Entity
  32. *
  33. * @param \Magento\Framework\Model\AbstractModel $entity
  34. * @return \Magento\GoogleOptimizer\Model\Code
  35. */
  36. public function getCodeObjectByEntity(\Magento\Framework\Model\AbstractModel $entity)
  37. {
  38. $this->_entity = $entity;
  39. $this->_checkEntityIsEmpty();
  40. if ($entity instanceof \Magento\Cms\Model\Page) {
  41. $this->_codeModel->loadByEntityIdAndType($entity->getId(), $this->_getEntityType());
  42. } else {
  43. $this->_codeModel->loadByEntityIdAndType($entity->getId(), $this->_getEntityType(), $entity->getStoreId());
  44. }
  45. return $this->_codeModel;
  46. }
  47. /**
  48. * Get Entity Type by Entity object
  49. *
  50. * @return string
  51. * @throws \InvalidArgumentException
  52. */
  53. protected function _getEntityType()
  54. {
  55. $type = $this->_getTypeString();
  56. if (empty($type)) {
  57. throw new \InvalidArgumentException('The model class is not valid');
  58. }
  59. return $type;
  60. }
  61. /**
  62. * Get Entity Type string
  63. *
  64. * @return string
  65. */
  66. protected function _getTypeString()
  67. {
  68. $type = '';
  69. if ($this->_entity instanceof \Magento\Catalog\Model\Category) {
  70. $type = \Magento\GoogleOptimizer\Model\Code::ENTITY_TYPE_CATEGORY;
  71. }
  72. if ($this->_entity instanceof \Magento\Catalog\Model\Product) {
  73. $type = \Magento\GoogleOptimizer\Model\Code::ENTITY_TYPE_PRODUCT;
  74. }
  75. if ($this->_entity instanceof \Magento\Cms\Model\Page) {
  76. $type = \Magento\GoogleOptimizer\Model\Code::ENTITY_TYPE_PAGE;
  77. }
  78. return $type;
  79. }
  80. /**
  81. * Check if Entity is Empty
  82. *
  83. * @return $this
  84. * @throws \InvalidArgumentException
  85. */
  86. protected function _checkEntityIsEmpty()
  87. {
  88. if (!$this->_entity->getId()) {
  89. throw new \InvalidArgumentException('The model is empty');
  90. }
  91. return $this;
  92. }
  93. }