Adapter.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\ImportExport\Model\Import;
  7. use Magento\Framework\Filesystem\Directory\Write;
  8. /**
  9. * Import adapter model
  10. *
  11. * @author Magento Core Team <core@magentocommerce.com>
  12. */
  13. class Adapter
  14. {
  15. /**
  16. * Adapter factory. Checks for availability, loads and create instance of import adapter object.
  17. *
  18. * @param string $type Adapter type ('csv', 'xml' etc.)
  19. * @param Write $directory
  20. * @param string $source
  21. * @param mixed $options OPTIONAL Adapter constructor options
  22. *
  23. * @return AbstractSource
  24. *
  25. * @throws \Magento\Framework\Exception\LocalizedException
  26. */
  27. public static function factory($type, $directory, $source, $options = null)
  28. {
  29. if (!is_string($type) || !$type) {
  30. throw new \Magento\Framework\Exception\LocalizedException(
  31. __('The adapter type must be a non-empty string.')
  32. );
  33. }
  34. $adapterClass = 'Magento\ImportExport\Model\Import\Source\\' . ucfirst(strtolower($type));
  35. if (!class_exists($adapterClass)) {
  36. throw new \Magento\Framework\Exception\LocalizedException(
  37. __('\'%1\' file extension is not supported', $type)
  38. );
  39. }
  40. $adapter = new $adapterClass($source, $directory, $options);
  41. if (!$adapter instanceof AbstractSource) {
  42. throw new \Magento\Framework\Exception\LocalizedException(
  43. __('Adapter must be an instance of \Magento\ImportExport\Model\Import\AbstractSource')
  44. );
  45. }
  46. return $adapter;
  47. }
  48. /**
  49. * Create adapter instance for specified source file.
  50. *
  51. * @param string $source Source file path.
  52. * @param Write $directory
  53. * @param mixed $options OPTIONAL Adapter constructor options
  54. *
  55. * @return AbstractSource
  56. */
  57. public static function findAdapterFor($source, $directory, $options = null)
  58. {
  59. return self::factory(pathinfo($source, PATHINFO_EXTENSION), $directory, $source, $options);
  60. }
  61. }