SampleRepository.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Downloadable\Model;
  7. use Magento\Catalog\Api\Data\ProductInterface;
  8. use Magento\Catalog\Api\ProductRepositoryInterface;
  9. use Magento\Downloadable\Api\Data\SampleInterfaceFactory;
  10. use Magento\Downloadable\Model\Product\Type;
  11. use Magento\Downloadable\Api\Data\File\ContentUploaderInterface;
  12. use Magento\Downloadable\Api\Data\SampleInterface;
  13. use Magento\Downloadable\Model\Product\TypeHandler\Sample as SampleHandler;
  14. use Magento\Downloadable\Model\Sample\ContentValidator;
  15. use Magento\Framework\EntityManager\MetadataPool;
  16. use Magento\Framework\Exception\InputException;
  17. use Magento\Framework\Exception\NoSuchEntityException;
  18. use Magento\Framework\Exception\StateException;
  19. use Magento\Framework\Json\EncoderInterface;
  20. use Magento\Framework\App\ObjectManager;
  21. /**
  22. * Class SampleRepository
  23. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  24. */
  25. class SampleRepository implements \Magento\Downloadable\Api\SampleRepositoryInterface
  26. {
  27. /**
  28. * @var \Magento\Catalog\Api\ProductRepositoryInterface
  29. */
  30. protected $productRepository;
  31. /**
  32. * @var ContentValidator
  33. */
  34. protected $contentValidator;
  35. /**
  36. * @var Type
  37. */
  38. protected $downloadableType;
  39. /**
  40. * @var SampleFactory
  41. */
  42. protected $sampleFactory;
  43. /**
  44. * @var SampleInterfaceFactory
  45. */
  46. protected $sampleDataObjectFactory;
  47. /**
  48. * @var ContentUploaderInterface
  49. */
  50. protected $fileContentUploader;
  51. /**
  52. * @var EncoderInterface
  53. */
  54. protected $jsonEncoder;
  55. /**
  56. * @var SampleHandler
  57. */
  58. private $sampleTypeHandler;
  59. /**
  60. * @var MetadataPool
  61. */
  62. private $metadataPool;
  63. /**
  64. * @param ProductRepositoryInterface $productRepository
  65. * @param Type $downloadableType
  66. * @param SampleInterfaceFactory $sampleDataObjectFactory
  67. * @param ContentValidator $contentValidator
  68. * @param ContentUploaderInterface $fileContentUploader
  69. * @param EncoderInterface $jsonEncoder
  70. * @param SampleFactory $sampleFactory
  71. */
  72. public function __construct(
  73. ProductRepositoryInterface $productRepository,
  74. Type $downloadableType,
  75. SampleInterfaceFactory $sampleDataObjectFactory,
  76. ContentValidator $contentValidator,
  77. ContentUploaderInterface $fileContentUploader,
  78. EncoderInterface $jsonEncoder,
  79. SampleFactory $sampleFactory
  80. ) {
  81. $this->productRepository = $productRepository;
  82. $this->downloadableType = $downloadableType;
  83. $this->contentValidator = $contentValidator;
  84. $this->fileContentUploader = $fileContentUploader;
  85. $this->jsonEncoder = $jsonEncoder;
  86. $this->sampleFactory = $sampleFactory;
  87. $this->sampleDataObjectFactory = $sampleDataObjectFactory;
  88. }
  89. /**
  90. * {@inheritdoc}
  91. */
  92. public function getList($sku)
  93. {
  94. /** @var \Magento\Catalog\Model\Product $product */
  95. $product = $this->productRepository->get($sku);
  96. return $this->getSamplesByProduct($product);
  97. }
  98. /**
  99. * Build a sample data object
  100. *
  101. * @param \Magento\Downloadable\Model\Sample $resourceData
  102. * @return \Magento\Downloadable\Model\Sample
  103. */
  104. protected function buildSample($resourceData)
  105. {
  106. $sample = $this->sampleDataObjectFactory->create();
  107. $this->setBasicFields($resourceData, $sample);
  108. return $sample;
  109. }
  110. /**
  111. * Subroutine for buildLink and buildSample
  112. *
  113. * @param \Magento\Downloadable\Model\Link|\Magento\Downloadable\Model\Sample $resourceData
  114. * @param \Magento\Downloadable\Api\Data\LinkInterface|\Magento\Downloadable\Api\Data\SampleInterface $dataObject
  115. * @return null
  116. */
  117. protected function setBasicFields($resourceData, $dataObject)
  118. {
  119. $dataObject->setId($resourceData->getId());
  120. $storeTitle = $resourceData->getStoreTitle();
  121. $title = $resourceData->getTitle();
  122. if (!empty($storeTitle)) {
  123. $dataObject->setTitle($storeTitle);
  124. } else {
  125. $dataObject->setTitle($title);
  126. }
  127. $dataObject->setSortOrder($resourceData->getSortOrder());
  128. $dataObject->setSampleType($resourceData->getSampleType());
  129. $dataObject->setSampleFile($resourceData->getSampleFile());
  130. $dataObject->setSampleUrl($resourceData->getSampleUrl());
  131. }
  132. /**
  133. * List of links with associated samples
  134. *
  135. * @param \Magento\Catalog\Api\Data\ProductInterface $product
  136. * @return \Magento\Downloadable\Api\Data\SampleInterface[]
  137. */
  138. public function getSamplesByProduct(\Magento\Catalog\Api\Data\ProductInterface $product)
  139. {
  140. $sampleList = [];
  141. $samples = $this->downloadableType->getSamples($product);
  142. /** @var \Magento\Downloadable\Model\Sample $sample */
  143. foreach ($samples as $sample) {
  144. $sampleList[] = $this->buildSample($sample);
  145. }
  146. return $sampleList;
  147. }
  148. /**
  149. * Update downloadable sample of the given product
  150. *
  151. * @param string $sku
  152. * @param \Magento\Downloadable\Api\Data\SampleInterface $sample
  153. * @param bool $isGlobalScopeContent
  154. * @return int
  155. * @throws InputException
  156. * @throws NoSuchEntityException
  157. */
  158. public function save(
  159. $sku,
  160. SampleInterface $sample,
  161. $isGlobalScopeContent = true
  162. ) {
  163. $product = $this->productRepository->get($sku, true);
  164. $sampleId = $sample->getId();
  165. if ($sampleId) {
  166. return $this->updateSample($product, $sample, $isGlobalScopeContent);
  167. } else {
  168. if ($product->getTypeId() !== Type::TYPE_DOWNLOADABLE) {
  169. throw new InputException(
  170. __('The product needs to be the downloadable type. Verify the product and try again.')
  171. );
  172. }
  173. $validateSampleContent = !($sample->getSampleType() === 'file' && $sample->getSampleFile());
  174. if (!$this->contentValidator->isValid($sample, $validateSampleContent)) {
  175. throw new InputException(
  176. __('The sample information is invalid. Verify the information and try again.')
  177. );
  178. }
  179. if (!in_array($sample->getSampleType(), ['url', 'file'], true)) {
  180. throw new InputException(__('The sample type is invalid. Verify the sample type and try again.'));
  181. }
  182. $title = $sample->getTitle();
  183. if (empty($title)) {
  184. throw new InputException(__('The sample title is empty. Enter the title and try again.'));
  185. }
  186. return $this->saveSample($product, $sample, $isGlobalScopeContent);
  187. }
  188. }
  189. /**
  190. * @param \Magento\Catalog\Api\Data\ProductInterface $product
  191. * @param SampleInterface $sample
  192. * @param bool $isGlobalScopeContent
  193. * @return int
  194. */
  195. protected function saveSample(
  196. \Magento\Catalog\Api\Data\ProductInterface $product,
  197. SampleInterface $sample,
  198. $isGlobalScopeContent
  199. ) {
  200. $sampleData = [
  201. 'sample_id' => (int)$sample->getId(),
  202. 'is_delete' => 0,
  203. 'type' => $sample->getSampleType(),
  204. 'sort_order' => $sample->getSortOrder(),
  205. 'title' => $sample->getTitle(),
  206. ];
  207. if ($sample->getSampleType() === 'file' && $sample->getSampleFile() === null) {
  208. $sampleData['file'] = $this->jsonEncoder->encode(
  209. [
  210. $this->fileContentUploader->upload($sample->getSampleFileContent(), 'sample'),
  211. ]
  212. );
  213. } elseif ($sample->getSampleType() === 'url') {
  214. $sampleData['sample_url'] = $sample->getSampleUrl();
  215. } else {
  216. //existing file
  217. $sampleData['file'] = $this->jsonEncoder->encode(
  218. [
  219. [
  220. 'file' => $sample->getSampleFile(),
  221. 'status' => 'old',
  222. ],
  223. ]
  224. );
  225. }
  226. $downloadableData = ['sample' => [$sampleData]];
  227. if ($isGlobalScopeContent) {
  228. $product->setStoreId(0);
  229. }
  230. $this->getSampleTypeHandler()->save($product, $downloadableData);
  231. return $product->getLastAddedSampleId();
  232. }
  233. /**
  234. * @param \Magento\Catalog\Api\Data\ProductInterface $product
  235. * @param SampleInterface $sample
  236. * @param bool $isGlobalScopeContent
  237. * @return int
  238. * @throws InputException
  239. * @throws NoSuchEntityException
  240. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  241. * @SuppressWarnings(PHPMD.NPathComplexity)
  242. */
  243. protected function updateSample(
  244. \Magento\Catalog\Api\Data\ProductInterface $product,
  245. SampleInterface $sample,
  246. $isGlobalScopeContent
  247. ) {
  248. $sampleId = $sample->getId();
  249. /** @var $existingSample \Magento\Downloadable\Model\Sample */
  250. $existingSample = $this->sampleFactory->create()->load($sampleId);
  251. if (!$existingSample->getId()) {
  252. throw new NoSuchEntityException(
  253. __('No downloadable sample with the provided ID was found. Verify the ID and try again.')
  254. );
  255. }
  256. $linkFieldValue = $product->getData(
  257. $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField()
  258. );
  259. if ($existingSample->getProductId() != $linkFieldValue) {
  260. throw new InputException(
  261. __("The downloadable sample isn't related to the product. Verify the link and try again.")
  262. );
  263. }
  264. $validateFileContent = $sample->getSampleFileContent() === null ? false : true;
  265. if (!$this->contentValidator->isValid($sample, $validateFileContent)) {
  266. throw new InputException(__('The sample information is invalid. Verify the information and try again.'));
  267. }
  268. if ($isGlobalScopeContent) {
  269. $product->setStoreId(0);
  270. }
  271. $title = $sample->getTitle();
  272. if (empty($title)) {
  273. if ($isGlobalScopeContent) {
  274. throw new InputException(__('The sample title is empty. Enter the title and try again.'));
  275. }
  276. // use title from GLOBAL scope
  277. $existingSample->setTitle(null);
  278. } else {
  279. $existingSample->setTitle($sample->getTitle());
  280. }
  281. if ($sample->getSampleType() === 'file' && $sample->getSampleFileContent() === null) {
  282. $sample->setSampleFile($existingSample->getSampleFile());
  283. }
  284. $this->saveSample($product, $sample, $isGlobalScopeContent);
  285. return $existingSample->getId();
  286. }
  287. /**
  288. * {@inheritdoc}
  289. */
  290. public function delete($id)
  291. {
  292. /** @var $sample \Magento\Downloadable\Model\Sample */
  293. $sample = $this->sampleFactory->create()->load($id);
  294. if (!$sample->getId()) {
  295. throw new NoSuchEntityException(
  296. __('No downloadable sample with the provided ID was found. Verify the ID and try again.')
  297. );
  298. }
  299. try {
  300. $sample->delete();
  301. } catch (\Exception $exception) {
  302. throw new StateException(__('The sample with "%1" ID can\'t be deleted.', $sample->getId()), $exception);
  303. }
  304. return true;
  305. }
  306. /**
  307. * Get MetadataPool instance
  308. *
  309. * @deprecated 100.1.0
  310. * @return MetadataPool
  311. */
  312. private function getMetadataPool()
  313. {
  314. if (!$this->metadataPool) {
  315. $this->metadataPool = ObjectManager::getInstance()->get(MetadataPool::class);
  316. }
  317. return $this->metadataPool;
  318. }
  319. /**
  320. * Get SampleTypeHandler Instance
  321. *
  322. * @deprecated 100.1.0
  323. * @return SampleHandler
  324. */
  325. private function getSampleTypeHandler()
  326. {
  327. if (!$this->sampleTypeHandler) {
  328. $this->sampleTypeHandler = ObjectManager::getInstance()->get(SampleHandler::class);
  329. }
  330. return $this->sampleTypeHandler;
  331. }
  332. }