<?php
/**
* Elements DeMI
*
* This source file is available under the elements DeMI license version 1
*
* @copyright Copyright (c) elements.at New Media Solutions GmbH (https://www.elements.at/)
* @license elements DeMI Lizenz Version 1 (https://www.elements.at/de/demi-lizenz)
*/
namespace Elements\Bundle\DemiFrontendBundle\Service;
use App\Twig\LayoutExtension;
use Carbon\Carbon;
use Elements\Bundle\CmsToolsBundle\Tool\Helper\ElementsCustomDateFormat;
use Elements\Demi\AbstractObject;
use Elements\Demi\Accommodation\Search\Parameter\RoomRow;
use Elements\Demi\Accommodation\Search\ResultSet;
use Elements\Demi\Deskline\Booking\StandardInformation;
use Elements\Demi\Deskline\Constant\AddressInterface;
use Elements\Demi\Deskline\Constant\DescriptionInterface;
use Elements\Demi\Deskline\Constant\DocumentInterface;
use Elements\Demi\EcommerceFramework\Checkout\SessionCartItem;
use Elements\Demi\Frontend\Service\Configuration;
use Elements\Demi\Model\AccommodationProduct;
use Elements\Demi\Model\AccommodationService;
use Elements\Demi\Model\AccommodationServiceProvider;
use Elements\Demi\Model\DocumentImage;
use Elements\Demi\Model\Event;
use Elements\Demi\Model\HousePackageContainer;
use Elements\Demi\Model\HousePackageMaster;
use Elements\Demi\Model\Infrastructure;
use Elements\Demi\Model\Package;
use Elements\Demi\Model\Stars;
use Exception;
use JetBrains\PhpStorm\ArrayShape;
use Pimcore\Config;
use Pimcore\Db;
use Pimcore\Model\Asset;
use Pimcore\Model\Asset\Image;
use Pimcore\Model\DataObject\DemiAccommodationProduct;
use Pimcore\Model\DataObject\DemiAccommodationServiceProvider;
use Pimcore\Model\DataObject\DemiAdditionalProduct;
use Pimcore\Model\DataObject\DemiAdditionalServiceProvider;
use Pimcore\Model\DataObject\DemiEvent;
use Pimcore\Model\DataObject\DemiInfrastructure;
use Pimcore\Model\DataObject\Fieldcollection\Data\DemiAddress;
use Pimcore\Model\Document;
use Pimcore\Translation\Translator;
class DemiFrontendHelper
{
public function __construct(protected Translator $translator, protected Configuration $configurationService, protected ElementsCustomDateFormat $elementsCustomDateFormat, protected DemiUrl $demiUrl, protected \Elements\Bundle\DemiFrontendBundle\Service\Stars $accoStarsService, protected LayoutExtension $layoutExtension)
{
}
public function getStars(AccommodationServiceProvider $serviceProvider, bool $forceChars = false): string
{
$stars = $serviceProvider->getStars();
$starArray = [];
if ($stars instanceof Stars) {
$starNumbers = $stars->getStarsNumbers();
if (!$forceChars) {
$starArray[] = '<span class="star-holder" title="' . $starNumbers . ' ' . ' Stars' . '" aria-label="' . $starNumbers . ' ' . ' Stars' . '">';
}
for ($i = 0; $i < $starNumbers; $i++) {
if (!$forceChars) {
$starArray[] = '<span class="star demi-icon demi-icon-star"></span>';
} else {
$starArray[] = '*';
}
}
if ($stars->getIsSuperior()) {
if (!$forceChars) {
$starArray[] = '<span class="superior">S</span>';
} else {
$starArray[] = 'S';
}
}
if (!$forceChars) {
$starArray[] = '</span>';
}
}
return implode('', $starArray);
}
public function fillTranslation(array $arguments, string $translationKey, string $lang = ''): array|string
{
$translation = $this->translator->trans($translationKey, [], null, $lang);
foreach ($arguments as $key => $value) {
$translation = str_replace($key, $value, $translation);
}
return $translation;
}
/**
* @param $link
*
* @return string
*/
public function findNiceUrl($link): string
{
$pos = strpos($link, 'http://');
$pos1 = strpos($link, 'https://');
if ($pos !== false || $pos1 !== false) {
$newlink = $link;
} else {
$newlink = 'http://' . $link;
}
if ($newlink === 'http://' || $newlink === 'https://') {
$newlink = '';
}
return $newlink;
}
public function findFirstRegionforLanguage(string $language): string
{
try {
$languageRegionMapping = include PIMCORE_PATH . '/bundles/CoreBundle/Resources/misc/cldr-language-territory-mapping.php';
if (!$languageRegionMapping) {
$languageRegionMapping = include PIMCORE_PATH . '/lib/Pimcore/Bundle/CoreBundle/Resources/misc/cldr-language-territory-mapping.php';
}
} catch (\Throwable $e) {
//TODO: is this still necessary?
}
return $languageRegionMapping[$language][0];
}
public function getAllDemiTranslationKeys(): array
{
return array_filter($this->translator->getCatalogue()->all('messages'), static function ($v, $k) {
return str_starts_with($k, 'demi.');
}, ARRAY_FILTER_USE_BOTH);
}
public function getStaticMapUrl(float $lat, float $lon, string $size = '450x300', Bool $marker = false, string $markerColor = 'red', int $zoom = 15, array $customParams = []): string
{
$params = [];
if ($size != '') {
$params['size'] = $size;
}
if ($marker) {
$params['markers'] = 'color:' . $markerColor ?? 'red';
}
if ($zoom != '') {
$params['zoom'] = $zoom;
}
$params['center'] = $lat . ',' . $lon;
if (count($customParams) > 0) {
$params = array_merge($params, $customParams);
}
$queryString = http_build_query($params);
$browserApiKey = Config::getSystemConfiguration()['services']['google']['browserapikey'] ?? Config::getSystemConfiguration()['services']['google']['simpleapikey'];
$queryString .= (($queryString && $browserApiKey ? '&' : '') . ($browserApiKey ? ('key=' . $browserApiKey) : ''));
return '//maps.googleapis.com/maps/api/staticmap?' . $queryString;
}
public function getGoogleMapsUrl(string $accommodationName, DemiAddress $address, string $language = 'de', float $lat = 0.0, float $lon = 0.0, $googlePlaceId = null, int $zoom = 17): string
{
$addressArray = [];
if ($address->getAddressLine1() != '') {
$addressArray[] = $address->getAddressLine1();
}
if ($address->getAddressLine2() != '') {
$addressArray[] = $address->getAddressLine2();
}
if ($address->getZipcode() != '') {
$addressArray['zip'] = $address->getZipcode() . ' ';
}
if ($address->getTown() != '') {
$addressArray['zip'] .= $address->getTown() . ' ';
}
if ($address->getCity() != '') {
$addressArray['zip'] .= $address->getCity();
}
if ($address->getCountry() != '') {
$addressArray[] = $address->getCountry();
}
$accommodationName = str_replace(['/', ','], ' ', $accommodationName);
if ($googlePlaceId) {
return 'https://www.google.com/maps/search/?api=1&query=' . urlencode($accommodationName) . '&query_place_id=' . $googlePlaceId . '&hl=' . $language;
}
return 'https://www.google.at/maps/dir//' . $accommodationName . ', ' . implode(', ', $addressArray) . '/@' . $lat . ',' . $lon . ',' . $zoom . 'z?hl=' . $language;
}
public function getKeyFromString($string): string|array|null
{
$key = strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', $string));
return preg_replace_callback('#([\-.~_/]+)#', static function ($matches) {
return substr($matches[1], 0, 1);
}, $key);
}
public function getOccupancyString(RoomRow $roomRow): string
{
$adultStr = $this->translator->trans('demi.detail.enquiry.mail.adult', [], 'messages');
if ($roomRow->getAdults() > 1) {
$adultStr = $this->translator->trans('demi.detail.enquiry.mail.adults');
}
$occupancyStr = $roomRow->getUnits() . ' x ' . $roomRow->getAdults() . ' ' . $adultStr;
if (count($roomRow->getChildAges()) > 0) {
$kidStr = $this->translator->trans('demi.detail.enquiry.mail.child');
if (count($roomRow->getChildAges()) > 1) {
$kidStr = $this->translator->trans('demi.detail.enquiry.mail.children');
}
$occupancyStr .= ' ' . $this->translator->trans('demi.detail.enquiry.mail.and') . ' ' . count($roomRow->getChildAges()) . ' ' . $kidStr;
$occupancyStr .= ' (' . implode(', ', $roomRow->getChildAges()) . ')';
}
return $occupancyStr;
}
public function getFirstImageForHousePackageMaster(HousePackageMaster $housePackageMaster, AccommodationServiceProvider $accommodation, $fromDate): Image
{
$types = $this->getAccoImagesTypesAsArray($housePackageMaster);
if ($housePackageMaster->getFirstImage($types, $fromDate) instanceof Asset) {
return $housePackageMaster->getFirstImage($types, $fromDate);
}
$serviceImg = null;
foreach ($housePackageMaster->getProducts() as $accommodationProduct) {
if ($accommodationProduct->getService()->getFirstImage($types, $fromDate) instanceof Asset) {
$serviceImg = $accommodationProduct->getService()->getFirstImage($types, $fromDate);
break;
}
}
$imgSrc = null;
if ($serviceImg !== null) {
$imgSrc = $serviceImg;
} elseif ($accommodation->getFirstImage(null, $fromDate) instanceof Asset) {
$imgSrc = $accommodation->getFirstImage(null, $fromDate);
}
return $imgSrc;
}
public function hasRoomDetails(AccommodationProduct $accommodationProduct, Carbon $dateFrom, string $locale, bool $tableOnSide): bool
{
if (!$tableOnSide) {
return true;
}
$service = $accommodationProduct->getService();
$productText = $accommodationProduct->getDescription(null, $locale, $dateFrom);
if (empty($productText) && $this->configurationService->getFallbackLanguage()) {
$productText = $accommodationProduct->getDescription(null, $this->configurationService->getFallbackLanguage(), $dateFrom);
}
$serviceText = $service->getDescription(null, $locale, $dateFrom);
if (empty($serviceText) && $this->configurationService->getFallbackLanguage()) {
$serviceText = $service->getDescription(null, $this->configurationService->getFallbackLanguage(), $dateFrom);
}
$facilities = $service->getFacilities();
return $productText || $serviceText || ($facilities && count($facilities->getItems()) > 0);
}
#[ArrayShape(['hostImages' => "array", 'hostDescriptions' => "array"])]
public function getHostInformation(AccommodationServiceProvider $accommodation): array
{
$hostImages = [];
$hostDescriptions = [];
if ($accommodation->getAddresses()) {
foreach ($accommodation->getAddresses() as $address) {
//16.7.2019 info von christoph ebner - für die Anzeige nur die vom Adresstyp LandLord verwenden!
if ($address->getAddressType() === AddressInterface::ADDRESS_LANDLORD) {
if (!empty($address->getDocuments())) {
foreach ($address->getDocuments() as $item) {
if($item instanceof DocumentImage){
if (($item->getDocumentType() === DocumentInterface::DOCUMENT_TYPE_HOST_INFORMATION) && !in_array($item->getId(), array_keys($hostImages))) {
$hostImages[$item->getId()] = $item->getDocument();
}
}
}
}
if (!empty($address->getDescriptions())) {
foreach ($address->getDescriptions() as $item) {
if ($item->getDescriptionType() === DescriptionInterface::DESCRIPTION_SERVICE_PROVIDER_HOST_INFORMATION && $item->getDescriptionLanguage() == $this->translator->getLocale() && !in_array($item->getId(), $hostDescriptions, true)) {
$hostDescriptions[$item->getId()] = $item->getText();
}
}
}
}
}
}
return ['hostImages' => $hostImages, 'hostDescriptions' => $hostDescriptions];
}
public function getRoomPictures(AccommodationProduct $accommodationProduct, ?Carbon $dateFrom): array
{
$serviceImages = [];
if ($accommodationProduct->getService()) {
$serviceImages = $accommodationProduct->getService()->getImages(null, $dateFrom, false);
}
$productImages = $accommodationProduct->getImages(null, $dateFrom);
return array_merge($productImages, $serviceImages);
}
public function getCheapestProducts(array $packageProducts) : int
{
$myMinPrice = 0;
$productKey = 0;
$count = 0;
foreach ($packageProducts as $product) {
if (($myMinPrice === 0 || $myMinPrice > $product->getBasePrice()) && $product->getBasePrice() != null) {
$myMinPrice = $product->getBasePrice();
$product->getPriceInfo();
$productKey = $count;
}
$count++;
}
return $productKey;
}
#[ArrayShape(['price' => "int|mixed", 'priceInfo' => "mixed", 'cP' => "mixed"])]
public function getMinPriceOfHousePackageMasterResultSet(mixed $resultSet): array
{
if (!is_array($resultSet) && $resultSet instanceof ResultSet\HousePackageMaster) {
$productKeys = array_keys($resultSet->getProducts());
$firstProductId = $productKeys[0];
$cheapestProducts = [$resultSet->getProduct($firstProductId)];
} else {
$cheapestProducts = $resultSet;
}
$price = 0;
if ($cheapestProducts) {
foreach ($cheapestProducts as $cP) {
$price += $cP->getBasePrice();
//this is not entirely correct ... price info could vary from room row to roomrow
$priceInfo = $cP->getPriceInfo();
$cheapestProduct = $cP;
}
}
return ['price' => $price, 'priceInfo' => $priceInfo ?? [], 'cP' => $cheapestProduct ?? ''];
}
public function getAccoImagesTypesAsArray(AbstractObject $object): ?array
{
$types = null;
if ($object instanceof AccommodationServiceProvider || $object instanceof HousePackageMaster) {
$types = $this->configurationService->getImageTypesForAccos();
}
if ($types !== null) {
$typesToUse = [];
if ($object instanceof HousePackageMaster) {
$typesToUse[] = constant(get_class($object->getAdapter()) . '::' . 'DOCUMENT_TYPE_PACKAGE');
}
foreach ($types as $type) {
$typesToUse[] = constant(get_class($object->getAdapter()) . '::' . $type);
}
return $typesToUse;
}
return null;
}
public function sortCartItems(array $sessionCartItems): array
{
usort($sessionCartItems, static function (SessionCartItem $a, SessionCartItem $b) {
$productA = $a->getProduct();
$parentA = $productA->getParent()?->getParent();
$productB = $b->getProduct();
$parentB = $productB->getParent()?->getParent();
if ($a->getCartItemInfo()->getIsShipping()) {
return 1;
}
if ($b->getCartItemInfo()->getIsShipping()) {
return -1;
}
if ($productA instanceof DemiAccommodationProduct && $productB instanceof DemiAccommodationProduct &&
$parentA instanceof DemiAccommodationServiceProvider && $parentB instanceof DemiAccommodationServiceProvider) {
return -1;
}
if ($productA instanceof DemiAccommodationProduct && $productB instanceof DemiAccommodationProduct &&
$parentA instanceof DemiAccommodationServiceProvider && $parentB instanceof DemiAdditionalServiceProvider) {
return -1;
}
if ($productA instanceof DemiAccommodationProduct && $productB instanceof DemiAccommodationProduct &&
$parentA instanceof DemiAdditionalServiceProvider && $parentB instanceof DemiAccommodationServiceProvider) {
return 1;
}
if ($productA instanceof DemiAccommodationProduct && $productB instanceof DemiAccommodationProduct &&
$parentA instanceof DemiAdditionalServiceProvider && $parentB instanceof DemiAdditionalServiceProvider) {
return -1;
}
if ($productA instanceof DemiAccommodationProduct && $productB instanceof DemiAdditionalProduct &&
$parentA instanceof DemiAccommodationServiceProvider && $parentB instanceof DemiAccommodationServiceProvider) {
return -1;
}
if ($productA instanceof DemiAccommodationProduct && $productB instanceof DemiAdditionalProduct &&
$parentA instanceof DemiAccommodationServiceProvider && $parentB instanceof DemiAdditionalServiceProvider) {
return -1;
}
if ($productA instanceof DemiAccommodationProduct && $productB instanceof DemiAdditionalProduct &&
$parentA instanceof DemiAdditionalServiceProvider && $parentB instanceof DemiAccommodationServiceProvider) {
return -1;
}
if ($productA instanceof DemiAccommodationProduct && $productB instanceof DemiAdditionalProduct &&
$parentA instanceof DemiAdditionalServiceProvider && $parentB instanceof DemiAdditionalServiceProvider) {
return -1;
}
if ($productA instanceof DemiAdditionalProduct && $productB instanceof DemiAccommodationProduct &&
$parentA instanceof DemiAccommodationServiceProvider && $parentB instanceof DemiAccommodationServiceProvider) {
return 1;
}
if ($productA instanceof DemiAdditionalProduct && $productB instanceof DemiAccommodationProduct &&
$parentA instanceof DemiAccommodationServiceProvider && $parentB instanceof DemiAdditionalServiceProvider) {
return -1;
}
if ($productA instanceof DemiAdditionalProduct && $productB instanceof DemiAccommodationProduct &&
$parentA instanceof DemiAdditionalServiceProvider && $parentB instanceof DemiAccommodationServiceProvider) {
return 1;
}
if ($productA instanceof DemiAdditionalProduct && $productB instanceof DemiAccommodationProduct &&
$parentA instanceof DemiAdditionalServiceProvider && $parentB instanceof DemiAdditionalServiceProvider) {
return 1;
}
if ($productA instanceof DemiAdditionalProduct && $productB instanceof DemiAdditionalProduct &&
$parentA instanceof DemiAccommodationServiceProvider && $parentB instanceof DemiAccommodationServiceProvider) {
return -1;
}
if ($productA instanceof DemiAdditionalProduct && $productB instanceof DemiAdditionalProduct &&
$parentA instanceof DemiAccommodationServiceProvider && $parentB instanceof DemiAdditionalServiceProvider) {
return -1;
}
if ($productA instanceof DemiAdditionalProduct && $productB instanceof DemiAdditionalProduct &&
$parentA instanceof DemiAdditionalServiceProvider && $parentB instanceof DemiAccommodationServiceProvider) {
return 1;
}
return -1;
});
return $sessionCartItems;
}
public function getJsonTelephone(DemiAddress $addr): string
{
if (method_exists($addr, 'getPhone') && !empty($addr->getPhone())) {
return $addr->getPhone();
}
if (method_exists($addr, 'getMobile') && !empty($addr->getMobile())) {
return $addr->getMobile();
}
return '';
}
#[ArrayShape(['from' => "string", 'tio' => "string"])]
public function getDestinationPackageRangesAsTimestring(HousePackageContainer|Package $package): array
{
$ranges = [];
if ($package->getValidDates() && $package->getValidDates()->getItems()) {
foreach ($package->getValidDates()->getItems() as $item) {
$from = $this->elementsCustomDateFormat->dateToString($item->getDateFrom()->startOfDay());
$to = $this->elementsCustomDateFormat->dateToString($item->getDateTo()->endOfDay());
$ranges[] = ['from' => $from, 'to' => $to];
}
}
return $ranges;
}
public function getDestinationPackageWeekdayDurations(HousePackageContainer|Package $package): array
{
$weekdayDurationDaysArray = [];
foreach ($package->getPackageDuration() as $entry) {
$getters = [0 => 'getSun', 1 => 'getMon', 2 => 'getTue', 3 => 'getWed', 4 => 'getThu', 5 => 'getFri', 6 => 'getSat'];
foreach ($getters as $weekday => $getter) {
if ($entry->$getter()) {
if ($weekdayDurationDaysArray[$weekday]) {
$weekdayDurationDaysArray[$weekday][] = $entry->getDurationDays() - 1;
} else {
$weekdayDurationDaysArray[$weekday] = [$entry->getDurationDays() - 1];
}
}
}
}
return $weekdayDurationDaysArray;
}
public function getNextPossibleArrivalDay(HousePackageContainer|Package $package): ?Carbon
{
$currentTime = time();
$todayDefinition = new Carbon('now');
$bookingStopOffset = 0;
if ($package instanceof Package) {
$bookingStopOffset = $package->getBookingstop();
}
$todayDefinition->addDays($bookingStopOffset);
$possibleWeekDays = array_keys($this->getDestinationPackageWeekdayDurations($package));
foreach ($package->getValidDates() as $item) {
if ($item->getDateFrom()->copy()->subDays($bookingStopOffset)->getTimestamp() >= $currentTime) {
//next possible
return $item->getDateFrom();
}
if (($item->getDateFrom()->getTimestamp() < $currentTime && $item->getDateTo()->getTimestamp() >= $currentTime)
|| ($item->getDateFrom()->getTimestamp() > $currentTime && $item->getDateFrom()->copy()->subDays($bookingStopOffset)->getTimestamp() < $currentTime)) {
//current possible
$today = $todayDefinition->clone();
for ($i = 0; $i < 7; $i++) {
if (in_array($today->dayOfWeek, $possibleWeekDays)) {
if ($today->getTimestamp() < $item->getDateTo()->getTimestamp()) {
return $today->setTime('0', '0', '0');
}
} else {
$today->addDay();
}
}
}
}
return null;
}
public function findHousePackageMasterSelfAssignList(Document $doc, HousePackageMaster $destinationPackage) : ?Document
{
$documentListing = new Document\Listing();
$documentListing->setCondition("path like '" . $doc->getRealFullPath() . "%'");
foreach ($documentListing->load() as $document) {
if ($document instanceof Document\Page) {
$docPackage = $document->getProperty('demi_housePackageMasterSelfAssign');
if ($docPackage instanceof HousePackageMaster && $docPackage->getId() == $destinationPackage->getId()) {
return $document;
}
}
}
return null;
}
public function findHousePackageContainerList(Document $doc, HousePackageContainer $destinationPackage): Document\Page|Document|null
{
$documentListing = new Document\Listing();
$documentListing->setCondition("path like '" . $doc->getRealFullPath() . "%'");
foreach ($documentListing->load() as $document) {
if ($document instanceof Document\Page) {
$docPackage = $document->getProperty('demi_housePackageContainer');
if ($docPackage instanceof HousePackageContainer && $docPackage->getId() == $destinationPackage->getId()) {
return $document;
}
}
}
return null;
}
public function findDestinationPackageAccoList(Document $doc, Package $destinationPackage): Document\Page|Document|null
{
$documentListing = new Document\Listing();
$documentListing->setCondition("path like '" . $doc->getRealFullPath() . "%'");
foreach ($documentListing->load() as $document) {
if ($document instanceof Document\Page && $document->getEditable('package')) {
$docPackage = $document->getEditable('package')->getElement();
if ($docPackage instanceof Package && $docPackage->getId() == $destinationPackage->getId()) {
return $document;
}
}
}
return null;
}
public function getFromFilterElement(Document\Editable\Relation $filterSnippet, string $filterName): array
{
$elementArray = [];
if ($parentElement = $filterSnippet->getElement()) {
$elements = $parentElement->getElements();
foreach ($elements as $key => $element) {
if (str_contains($key, $filterName)) {
$elementArray = [...$elementArray, ...$element->getElements()];
}
}
}
return $elementArray;
}
public function getDestinationPackageHolidayThemeFilter(Document $document, bool $predefined = false): bool|array
{
$holidayThemes = [];
$showOnSiteHolidayThemes = $holidayThemesList = $holidayThemesObjectList = null;
foreach ($document->getEditables() as $element) {
if (str_contains($element->getName(), 'showOnSiteDestinationPackagesHolidayThemes')) {
$showOnSiteHolidayThemes = $element;
} elseif (str_contains($element->getName(), 'destinationPackagesHolidayThemesList')) {
$holidayThemesList = $element;
} elseif (str_contains($element->getName(), 'destinationPackagesHolidayThemesObjectList')) {
$holidayThemesObjectList = $element;
}
}
if ($holidayThemesObjectList !== null && $holidayThemesList !== null && (($showOnSiteHolidayThemes !== null && $showOnSiteHolidayThemes->isChecked()) || $predefined)) {
$holidayThemesIds = $holidayThemesList->getData() ?: [];
if (count($holidayThemesIds) == 0) {
$holidayThemesIds = $holidayThemesObjectList->getData() ?: [];
}
foreach ($holidayThemesIds as $id) {
$holidayThemes[] = (is_string($id) || is_int($id)) ? \Pimcore\Model\DataObject\AbstractObject::getById($id) : $id;
}
return $holidayThemes;
}
// predefined filter
return false;
}
public function getDestinationPackageRegionFilter(Document $document): bool|array
{
$showOnSiteOwners = null;
foreach ($document->getEditables() as $element) {
if (str_contains($element->getName(), 'showOnSiteOwners')) {
$showOnSiteOwners = $element;
}
}
if ($showOnSiteOwners !== null && $showOnSiteOwners->isChecked()) {
$allOwners = [];
$dummyPackage = new Package();
$query = 'SELECT DISTINCT owner from object_' . $dummyPackage->getClassId();
$db = Db::get();
$result = $db->fetchAll($query);
foreach ($result as $r) {
if ($r['owner'] !== null) {
$allOwners[] = $r['owner'];
}
}
return $allOwners;
}
return false;
}
public function getStandardInformation(StandardInformation $standardInformation, string $payment, bool $linked = false): string|array
{
if (stripos($payment, 'nopayment') !== false) {
$payment = 'NoPayment';
} else {
$payment = 'Payment';
}
$standardInformationType = $standardInformation->getType() . $payment;
$info = match ($standardInformationType) {
'PackagePayment' => $linked ? $standardInformation->getPackageLinkedPayment() : $standardInformation->getPackagePayment(),
'PackageNoPayment' => $linked ? $standardInformation->getPackageLinkedNoPayment() : $standardInformation->getPackageNoPayment(),
'CombinedArrangementPayment' => $linked ? $standardInformation->getCombinedArrangementLinkedPayment() : $standardInformation->getCombinedArrangementPayment(),
'CombinedArrangementNoPayment' => $linked ? $standardInformation->getCombinedArrangementLinkedNoPayment() : $standardInformation->getCombinedArrangementNoPayment(),
default => '',
};
return str_replace(['[OPERATORNAME]', '[ORGANISATIONNAME]', '[INSURANCENAME]', '[INSURANCEADDRESS]', '<a '],
[$standardInformation->getOperator(), $standardInformation->getOrganisation(), $standardInformation->getInsuranceName(),
$standardInformation->getInsuranceAddress(), '<a target="_blank"'], $info);
}
public function getNameAndCopyrightForImage(Image $assetImage, bool $noHtml = false): string
{
$parts = [];
$imageTexts = $this->layoutExtension->getImageTexts($assetImage);
$parsedCopyright = $this->parseImageTexts($imageTexts, false);
if ($title = $assetImage->getMetadata('title')) {
$part = trim(htmlentities($title));
if (!$noHtml) {
$part = str_replace("'", '', $part);
$part = '<span class=\'demi-image-name\'>' . $part . '</span>';
}
$parts[] = $part;
}
if ($parsedCopyright) {
$part = trim(htmlentities($parsedCopyright));
if (!$noHtml) {
$part = str_replace("'", '', $part);
$part = '<span class=\'demi-image-copyright\'>' . $part . '</span>';
}
$parts[] = $part;
}
return implode(' | ', $parts);
}
public function getStaticImageMap(AccommodationServiceProvider $acco): ?Image
{
$town = $acco->getTown();
$district = $acco->getDistrict();
$region = $acco->getRegion();
if ($town && method_exists($town, 'getImageMap') && $town->getImageMap() instanceof Image) {
return $town->getImageMap();
}
if ($district && method_exists($district, 'getImageMap') && $district->getImageMap() instanceof Image) {
return $district->getImageMap();
}
if ($region && method_exists($region, 'getImageMap') && $region->getImageMap() instanceof Image) {
return $region->getImageMap();
}
if ($this->configurationService->getFallbackImageMap() instanceof Image) {
return $this->configurationService->getFallbackImageMap();
}
return null;
}
public function getMinBedroomsForFilter()
{
$dummy = new AccommodationService();
$classId = $dummy->getClassId();
$query = 'select MIN(bedrooms) as min from object_' . $classId;
$db = Db::get();
$result = $db->fetchRow($query);
return $result['min'] ?: 0;
}
public function getMaxBedroomsForFilter()
{
$dummy = new AccommodationService();
$classId = $dummy->getClassId();
$query = 'select MAX(bedrooms) as max from object_' . $classId;
$db = Db::get();
$result = $db->fetchRow($query);
return $result['max'] ?: 0;
}
public function getDestinationPackageDurationInfo(Package|HousePackageContainer $destinationPackage): string
{
$info = '';
if ($destinationPackage->getPackageDuration()) {
$possibleNights = [];
foreach ($destinationPackage->getPackageDuration() as $item) {
$possibleNights[] = (int)$item->getDurationDays() - 1;
}
$singleNight = true;
if (count($possibleNights) > 1|| $possibleNights[0] > 1) {
$singleNight = false;
}
sort($possibleNights);
if (empty($possibleNights) || (count($possibleNights) == 1 && $possibleNights[0] == 0)) {
$info = $this->translator->trans('demi.destinationpackage.without-accommodation');
} else {
$info = implode(' ' . $this->translator->trans('demi.or-short') . ' ', $possibleNights) . ' ' . $this->translator->trans($singleNight ? 'demi.night' : 'demi.nights');
}
}
return $info;
}
public function getLinktypeIconArray(): array
{
return [
0 => 'link',
1 => 'link',
2 => 'map',
3 => 'play-circle',
4 => 'image',
5 => 'live-cam',
6 => 'facebook',
7 => 'link',
8 => 'share',
9 => 'image',
10 => 'play-circle',
11 => 'twitter',
12 => 'instagram',
13 => 'foursquare',
14 => 'tumbler',
15 => 'youtube',
16 => 'vimeo',
17 => 'pinterest',
18 => 'flickr',
];
}
public function parseAddressData(AbstractObject $object, array $availableBlocks = []): array
{
if (!method_exists($object, 'getAddresses')) {
return [];
}
if (!empty($object->getAddresses())) {
foreach ($object->getAddresses() as $address) {
//Address Block
if (array_key_exists($address->getAddressType(), $availableBlocks)) {
$addressBlock = [];
if ($address->getCompany() !== '') {
$addressBlock[] = $address->getCompany();
}
if ($address->getFirstname() !== '') {
$addressBlock[] = $address->getFirstname() . ' ' . $address->getLastname();
}
if ($address->getAddressLine1() !== '') {
$addressBlock[] = $address->getAddressLine1();
}
if ($address->getAddressLine2() !== '') {
$addressBlock[] = $address->getAddressLine2();
}
if ($address->getZipcode() !== '' || $address->getTown()) {
$addressBlock[] = $address->getZipcode() . ' ' . $address->getTown();
}
$availableBlocks[$address->getAddressType()]['inhalt']['address'] = implode('<br>', $addressBlock);
$availableBlocks[$address->getAddressType()]['inhalt']['phone'] = $address->getPhone();
$availableBlocks[$address->getAddressType()]['inhalt']['mobile'] = $address->getMobile();
$availableBlocks[$address->getAddressType()]['inhalt']['mail'] = $address->getEmail();
$availableBlocks[$address->getAddressType()]['inhalt']['url'] = $address->getUrl();
}
}
}
return $availableBlocks;
}
public function parseImageTexts(array|bool $imageTexts, bool $withTitle = false) : string
{
if(!is_array($imageTexts)) {
return '';
}
$text = '';
if ($withTitle && isset($imageTexts['title']) && $imageTexts['title'] !== '') {
$text = $imageTexts['title'];
}
if ((isset($imageTexts['copyright']) || isset($imageTexts['author'])) && $withTitle) {
$text .= ' | ';
}
if (isset($imageTexts['copyright'])) {
$text .= $imageTexts['copyright'];
}
if (isset($imageTexts['copyright'], $imageTexts['author'])) {
$text .= ' | ';
}
if (isset($imageTexts['author'])) {
$text .= $imageTexts['author'];
}
return $text;
}
public function getBookingLink(DemiEvent|DemiInfrastructure $object, string $language): string
{
$detailPath = $this->configurationService->getAdditionalServiceDetailPath($language);
if (!empty($detailPath)) {
foreach ($object->getConnectedEntries() as $connectedEntry) {
if ($connectedEntry instanceof \Elements\Demi\Model\AdditionalService) {
return $this->demiUrl->__invoke([
'name' => $connectedEntry->getName(),
'id' => $connectedEntry->getId(),
'path' => $detailPath->getFullPath()
], 'demi_additionalservice_detail', true);
}
}
}
return "";
}
#[ArrayShape(['id' => "int", 'image' => "object", "link" => "string"])]
public function getConnectedEntries(DemiEvent|DemiInfrastructure|DemiAccommodationServiceProvider $object, string $language, array $types = ['Event', 'Infrastructure', 'AdditionalService', 'AccommodationServiceProvider']): array
{
$entries = [];
foreach ($object->getConnectedEntries() as $connectedEntry) {
if ($connectedEntry instanceof \Elements\Demi\Model\AdditionalService && in_array('AdditionalService', $types)) {
$detailPath = $this->configurationService->getAdditionalServiceDetailPath($language);
if (!empty($detailPath)) {
$path = $this->demiUrl->__invoke([
'name' => $connectedEntry->getName(),
'id' => $connectedEntry->getId(),
'path' => $detailPath->getFullPath()
], 'demi_additionalservice_detail', true);
$entries[] = [
'id' => $connectedEntry->getId(),
'image' => $connectedEntry->getFirstImage(),
'link' => $path,
'title' => $connectedEntry->getName(),
'type' => "additionalService"
];
}
} else if ($connectedEntry instanceof Infrastructure && in_array('Infrastructure', $types)){
$detailPath = $this->configurationService->getInfrastructureDetailPath($language);
if (!empty($detailPath)) {
$path = $this->demiUrl->__invoke([
'name' => $connectedEntry->getName(),
'id' => $connectedEntry->getId(),
'path' => $detailPath->getFullPath()
], 'demi_infrastructure_detail', true);
$entries[] = [
'id' => $connectedEntry->getId(),
'image' => $connectedEntry->getFirstImage(),
'link' => $path,
'title' => $connectedEntry->getName(),
'type' => "infrastructure"
];
}
} else if ($connectedEntry instanceof Event && in_array('Event', $types)){
$detailPath = $this->configurationService->getEventDetailPath($language);
if (!empty($detailPath)) {
$path = $this->demiUrl->__invoke([
'name' => $connectedEntry->getName(),
'id' => $connectedEntry->getId(),
'path' => $detailPath->getFullPath()
], 'demi_event_detail', true);
$entries[] = [
'id' => $connectedEntry->getId(),
'image' => $connectedEntry->getFirstImage(),
'link' => $path,
'title' => $connectedEntry->getName(),
'type' => "event"
];
}
} else if ($connectedEntry instanceof AccommodationServiceProvider && in_array('AccommodationServiceProvider', $types)){
$path = $this->demiUrl->__invoke([
'accommodation' => $connectedEntry
], 'demi_acco_detail_page', true);
$entries[] = [
'id' => $connectedEntry->getId(),
'image' => $connectedEntry->getFirstImage(),
'link' => $path,
'title' => $this->accoStarsService->getAccoNameWithStars($connectedEntry),
'type' => 'accommodation'
];
}
}
return $entries;
}
}