<?php
namespace App\Helpers;
use App\Model\ProductCategory;
use App\Model\Project;
use Pimcore\Db;
use Pimcore\Model\DataObject\Product;
use Pimcore\Model\DataObject\Sector;
use Pimcore\Model\Document;
class PageObjectRelationHelper
{
protected $locale;
/**
* @param Product $object
* @return false|Document|Document\Page
*
* Gets the related product page that has a relation to this Object for a specific language.
*/
function getProductPageFromProductObject(Product $object)
{
return $this->getPageFromObject($object->getId(), "product", "App\\\Controller\\\ProductController::singleAction");
}
/**
* @param ProductCategory $object
* @return false|Document|Document\Page
*
* Gets the related product page that has a relation to this Object for a specific language.
*/
function getProductCategoryPageFromProductCategoryObject(ProductCategory $object)
{
return $this->getPageFromObject($object->getId(), "productCategory", "App\\\Controller\\\ProductCategoryController::singleAction");
}
/**
* @param ProductCategory $object
* @return false|Document|Document\Page
*
* Gets the related product page that has a relation to this Object for a specific language.
*/
function getSectorPageFromSectorObject(Sector $object)
{
return $this->getPageFromObject($object->getId(), "sector", "App\\\Controller\\\SectorController::singleAction");
}
/**
* @param ProductCategory $object
* @return false|Document|Document\Page
*
* Gets the related project page that has a relation to this Object for a specific language.
*/
function getProjectPageFromSectorObject(Project $object)
{
return $this->getPageFromObject($object->getId(), "project", "App\\\Controller\\\ProjectController::singleAction");
}
private function getPageFromObject(int $objectId, string $relationName, string $controller)
{
// Get All pages(table documents)
// that have a relation named $relationName(from table documents_editables) and where in that relation the id of the $objectId is present
// and where the controller == $controller (from table documents_page)
//TODO use binding to prevent SQL injection:
$sql = <<< SQL
SELECT * FROM `documents_editables`
INNER JOIN `documents` ON `documents_editables`.`documentId` = `documents`.`id`
INNER JOIN `documents_page` ON `documents_editables`.`documentId` = `documents_page`.`id`
where `documents_editables`.`name` = '$relationName'
AND `documents_page`.`controller` = '$controller'
AND `documents_editables`.`data` LIKE '%"id";i:$objectId;%'
AND `documents`.`published` = 1
SQL;
foreach (Db::get()->fetchAll($sql) as $pageData) {
$page = self::getPageObjectById($pageData);
if (!$page) {
continue;
}
/** @var Document\Editable\Relation $pageRelationEditable */
if ($page->getProperty('language') == LocaleHelper::getCurrentLocale()) {
return $page;
}
}
return null;
}
private static function getPageObjectById(array $pageArray)
{
if (isset($pageArray['id'])) {
return Document\Page::getById($pageArray['id']);
}
return null;
}
}