BatchRepository.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * Refer to LICENSE.txt distributed with the Temando Shipping module for notice of license
  4. */
  5. namespace Temando\Shipping\Model\ResourceModel\Batch;
  6. use Magento\Framework\Exception\LocalizedException;
  7. use Magento\Framework\Exception\NoSuchEntityException;
  8. use Temando\Shipping\Model\BatchInterface;
  9. use Temando\Shipping\Model\ResourceModel\Repository\BatchRepositoryInterface;
  10. use Temando\Shipping\Rest\Adapter\BatchApiInterface;
  11. use Temando\Shipping\Rest\EntityMapper\BatchResponseMapper;
  12. use Temando\Shipping\Rest\Exception\AdapterException;
  13. use Temando\Shipping\Rest\Request\ItemRequestInterfaceFactory;
  14. /**
  15. * Temando Batch Repository
  16. *
  17. * @package Temando\Shipping\Model
  18. * @author Rhodri Davies <rhodri.davies@temando.com>
  19. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  20. * @link http://www.temando.com/
  21. */
  22. class BatchRepository implements BatchRepositoryInterface
  23. {
  24. /**
  25. * @var BatchApiInterface
  26. */
  27. private $apiAdapter;
  28. /**
  29. * @var ItemRequestInterfaceFactory
  30. */
  31. private $batchRequestFactory;
  32. /**
  33. * @var BatchResponseMapper
  34. */
  35. private $batchMapper;
  36. /**
  37. * BatchRepository constructor.
  38. * @param BatchApiInterface $apiAdapter
  39. * @param ItemRequestInterfaceFactory $batchRequestFactory
  40. * @param BatchResponseMapper $batchMapper
  41. */
  42. public function __construct(
  43. BatchApiInterface $apiAdapter,
  44. ItemRequestInterfaceFactory $batchRequestFactory,
  45. BatchResponseMapper $batchMapper
  46. ) {
  47. $this->apiAdapter = $apiAdapter;
  48. $this->batchRequestFactory = $batchRequestFactory;
  49. $this->batchMapper = $batchMapper;
  50. }
  51. /**
  52. * @param string $batchId
  53. * @return BatchInterface
  54. * @throws NoSuchEntityException
  55. * @throws LocalizedException
  56. */
  57. public function getById($batchId)
  58. {
  59. if (!$batchId) {
  60. throw new LocalizedException(__('An error occurred while loading data.'));
  61. }
  62. try {
  63. $request = $this->batchRequestFactory->create(['entityId' => $batchId]);
  64. $apiBatch = $this->apiAdapter->getBatch($request);
  65. $batch = $this->batchMapper->map($apiBatch);
  66. } catch (AdapterException $e) {
  67. if ($e->getCode() === 404) {
  68. throw NoSuchEntityException::singleField('batchId', $batchId);
  69. }
  70. throw new LocalizedException(__('An error occurred while loading data.'), $e);
  71. }
  72. return $batch;
  73. }
  74. }