From b8552cc6b7b270cb445054dc73a470e945d2a60e Mon Sep 17 00:00:00 2001 From: Len Lorijn Date: Wed, 4 Jan 2023 14:31:10 +0000 Subject: [PATCH] Categories API endpoint so prismic can retrieve them --- Controller/Integration/Categories.php | 133 ++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 Controller/Integration/Categories.php diff --git a/Controller/Integration/Categories.php b/Controller/Integration/Categories.php new file mode 100644 index 0000000..f6d340c --- /dev/null +++ b/Controller/Integration/Categories.php @@ -0,0 +1,133 @@ +categoryCollectionFactory = $categoryCollectionFactory; + $this->jsonFactory = $jsonFactory; + $this->request = $request; + $this->json = $json; + $this->config = $config; + $this->storeManager = $storeManager; + } + + /** + * Execute view action + * + * @return ResultInterface + */ + public function execute() + { + //Protects the route in a way prismic can deal with it. + $this->protectRoute(); + + $attributes = array_unique( + ['name', 'image', 'description', 'is_active', 'updated_at'] + ); + + $categoryCollection = $this->categoryCollectionFactory + ->create() + ->addAttributeToFilter('is_active', 1) + ->addAttributeToSelect($attributes) + ->addAttributeToSort('updated_at', 'DESC') + ->setPageSize(50) + ->setCurPage((int)$this->request->getParam('page', 1)); + + $mediaUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA); + $results = array_values(array_map(function ($category) use ($mediaUrl) { + + $imageUrl = $category->getImage() ? $mediaUrl . 'catalog/product/' . $category->getImage() : ''; + + return [ + 'id' => $category->getId(), + 'title' => $category->getName(), + 'description' => $category->getDescription() ?? '', + 'image_url' => $imageUrl, + 'last_update' => (int)date('U', strtotime($category->getUpdatedAt())), + 'blob' => $category->getData() + ]; + }, $categoryCollection->getItems())); + + $jsonResult = $this->jsonFactory->create(); + $jsonResult->setData([ + 'results_size' => $categoryCollection->getSize(), + 'results' => $results + ]); + + return $jsonResult; + } + + /** + * + */ + private function protectRoute() + { + $accessToken = $this->config->getIntegrationFieldsAccessToken($this->storeManager->getStore()); + + if (!$accessToken) { + return null; + } + + if (empty($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] !== $accessToken) { + header('WWW-Authenticate: Basic realm="Prismic Integration"'); + header('HTTP/1.0 401 Unauthorized'); + echo 'Authentication necessary - see Access Token in Prismic under Settings > Integration Fields > your custom integration'; + exit; + } + } +}