ContentValidator.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Downloadable\Model\Sample;
  7. use Magento\Downloadable\Api\Data\SampleInterface;
  8. use Magento\Downloadable\Model\File\ContentValidator as FileContentValidator;
  9. use Magento\Framework\Exception\InputException;
  10. use Magento\Framework\Url\Validator as UrlValidator;
  11. class ContentValidator
  12. {
  13. /**
  14. * @var UrlValidator
  15. */
  16. protected $urlValidator;
  17. /**
  18. * @var FileContentValidator
  19. */
  20. protected $fileContentValidator;
  21. /**
  22. * @param FileContentValidator $fileContentValidator
  23. * @param UrlValidator $urlValidator
  24. */
  25. public function __construct(
  26. FileContentValidator $fileContentValidator,
  27. UrlValidator $urlValidator
  28. ) {
  29. $this->fileContentValidator = $fileContentValidator;
  30. $this->urlValidator = $urlValidator;
  31. }
  32. /**
  33. * Check if sample content is valid
  34. *
  35. * @param SampleInterface $sample
  36. * @param bool $validateSampleContent
  37. * @return bool
  38. * @throws InputException
  39. */
  40. public function isValid(SampleInterface $sample, $validateSampleContent = true)
  41. {
  42. if (filter_var($sample->getSortOrder(), FILTER_VALIDATE_INT) === false || $sample->getSortOrder() < 0) {
  43. throw new InputException(__('Sort order must be a positive integer.'));
  44. }
  45. if ($validateSampleContent) {
  46. $this->validateSampleResource($sample);
  47. }
  48. return true;
  49. }
  50. /**
  51. * Validate sample resource (file or URL)
  52. *
  53. * @param SampleInterface $sample
  54. * @throws InputException
  55. * @return void
  56. */
  57. protected function validateSampleResource(SampleInterface $sample)
  58. {
  59. $sampleFile = $sample->getSampleFileContent();
  60. if ($sample->getSampleType() == 'file'
  61. && (!$sampleFile || !$this->fileContentValidator->isValid($sampleFile))
  62. ) {
  63. throw new InputException(__('Provided file content must be valid base64 encoded data.'));
  64. }
  65. if ($sample->getSampleType() == 'url'
  66. && !$this->urlValidator->isValid($sample->getSampleUrl())
  67. ) {
  68. throw new InputException(__('Sample URL must have valid format.'));
  69. }
  70. }
  71. }