|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Skywire\WordpressApi\Model\Index; |
| 4 | + |
| 5 | +use Magento\Framework\Exception\NoSuchEntityException; |
| 6 | +use Skywire\WordpressApi\Api\Data\Index\PathInterface; |
| 7 | +use Skywire\WordpressApi\Api\Index\PathRepositoryInterface; |
| 8 | +use Skywire\WordpressApi\Model\ResourceModel\Index\Path as PathResource; |
| 9 | +use Skywire\WordpressApi\Model\ResourceModel\Index\Path\CollectionFactory; |
| 10 | + |
| 11 | +class PathRepository implements PathRepositoryInterface |
| 12 | +{ |
| 13 | + /** |
| 14 | + * @var PathResource |
| 15 | + */ |
| 16 | + private $resource; |
| 17 | + |
| 18 | + /** |
| 19 | + * @var PathFactory |
| 20 | + */ |
| 21 | + private $pathFactory; |
| 22 | + |
| 23 | + /** |
| 24 | + * @var CollectionFactory |
| 25 | + */ |
| 26 | + private $collectionFactory; |
| 27 | + |
| 28 | + public function __construct(PathResource $resource, CollectionFactory $collectionFactory, PathFactory $pathFactory) |
| 29 | + { |
| 30 | + $this->resource = $resource; |
| 31 | + $this->pathFactory = $pathFactory; |
| 32 | + $this->collectionFactory = $collectionFactory; |
| 33 | + } |
| 34 | + |
| 35 | + public function getByPath(string $path): PathInterface |
| 36 | + { |
| 37 | + $model = $this->pathFactory->create(); |
| 38 | + |
| 39 | + $this->resource->load($model, $path, 'path'); |
| 40 | + |
| 41 | + if ($model->getId()) { |
| 42 | + return $model; |
| 43 | + } |
| 44 | + |
| 45 | + throw new NoSuchEntityException(); |
| 46 | + } |
| 47 | + |
| 48 | + public function slugExists(string $slug, string $type = null): bool |
| 49 | + { |
| 50 | + $collection = $this->collectionFactory->create() |
| 51 | + ->addFieldToFilter('slug', $slug); |
| 52 | + |
| 53 | + |
| 54 | + if ($type) { |
| 55 | + $collection->addFieldToFilter('type', $type); |
| 56 | + } |
| 57 | + |
| 58 | + return $collection->count() >= 1; |
| 59 | + } |
| 60 | + |
| 61 | + public function pathExists(string $path): bool |
| 62 | + { |
| 63 | + try { |
| 64 | + $this->getByPath($path); |
| 65 | + } catch (NoSuchEntityException $e) { |
| 66 | + return false; |
| 67 | + } |
| 68 | + |
| 69 | + return true; |
| 70 | + } |
| 71 | + |
| 72 | + public function create(PathInterface $path): PathInterface |
| 73 | + { |
| 74 | + $collection = $this->collectionFactory->create(); |
| 75 | + |
| 76 | + if ($collection->getItemByColumnValue('path', $path->getPath())) { |
| 77 | + $model = $this->getByPath($path->getPath()); |
| 78 | + $path->setId($model->getId()); |
| 79 | + } |
| 80 | + |
| 81 | + $this->resource->save($path); |
| 82 | + |
| 83 | + return $path; |
| 84 | + } |
| 85 | + |
| 86 | + |
| 87 | + public function save(PathInterface $path): PathInterface |
| 88 | + { |
| 89 | + $this->resource->save($path); |
| 90 | + |
| 91 | + return $path; |
| 92 | + } |
| 93 | +} |
0 commit comments