Vinoteca: модуль, шаблон и компоненты интернет-магазина вина на 1С-Битрикс

This commit is contained in:
jimagie committed 2026-10-22 19:28:52 +05:00
commit bb7d8af290
469 files changed
+26426

No files matched your search

@@ -0,0 +1,320 @@
<?php
declare(strict_types=1);
namespace Jinove\Vinoteca;
use Bitrix\Main\Context;
use Bitrix\Main\Loader;
use Bitrix\Main\Localization\Loc;
use Jinove\Vinoteca\Catalog\EnumNames;
use Jinove\Vinoteca\Catalog\LocalizedText;
use Jinove\Vinoteca\Catalog\Prices;
use Jinove\Vinoteca\Catalog\Related;
use Jinove\Vinoteca\Catalog\SearchMeta;
use Jinove\Vinoteca\Catalog\Sections;
Loc::loadMessages(__FILE__);
class Search
{
public const INPUT_ID = "vino-search-input";
private const LANGUAGES = ["en", "pl"];
private const ENUMS = ["COUNTRY", "REGION", "GRAPE", "WINE_COLOR", "SUGAR"];
private const TITLE_ENUMS = ["COUNTRY", "REGION", "GRAPE"];
private const SNIPPET_LENGTH = 200;
private const THUMB_WIDTH = 144;
private const THUMB_HEIGHT = 180;
private const CACHE_DIR = "/jinove/vinoteca/search";
public static function beforeIndex(array $fields): array
{
if (($fields["MODULE_ID"] ?? "") !== "iblock" || !ctype_digit((string)($fields["ITEM_ID"] ?? "")) || !Loader::includeModule("iblock")) {
return $fields;
}
$iblockId = (int)($fields["PARAM2"] ?? 0);
if (!in_array($iblockId, array_values(self::kinds()), true)) {
return $fields;
}
$words = [];
$titles = [];
$rows = \CIBlockElement::GetProperty($iblockId, (int)$fields["ITEM_ID"], "sort", "asc", []);
while ($property = $rows->Fetch()) {
$code = (string)$property["CODE"];
if (preg_match('/_(EN|PL)$/', $code)) {
$value = is_array($property["VALUE"]) ? (string)($property["VALUE"]["TEXT"] ?? "") : (string)$property["VALUE"];
$words[] = strip_tags($value);
if (str_starts_with($code, "NAME_")) {
$titles[] = $value;
}
} elseif (in_array($code, self::ENUMS, true) && (string)$property["VALUE_XML_ID"] !== "") {
$names = [];
foreach (self::LANGUAGES as $language) {
$names[] = EnumNames::name($code, (string)$property["VALUE_XML_ID"], "", $language);
}
$words = array_merge($words, $names);
if (in_array($code, self::TITLE_ENUMS, true)) {
$titles = array_merge($titles, $names, [(string)$property["VALUE_ENUM"]]);
}
}
}
$words = array_filter(array_map("trim", $words));
if ($words) {
$fields["BODY"] = trim((string)($fields["BODY"] ?? "") . " " . implode(" ", array_unique($words)));
}
$titles = array_diff(array_unique(array_filter(array_map("trim", $titles))), [trim((string)($fields["TITLE"] ?? ""))]);
if ($titles) {
$fields["TITLE"] = trim((string)($fields["TITLE"] ?? "") . " " . implode(" ", $titles));
}
return $fields;
}
public static function folder(): string
{
return SITE_DIR . "search/";
}
public static function preparePage(): void
{
global $APPLICATION;
$query = trim((string)Context::getCurrent()->getRequest()->getQuery("q"));
$APPLICATION->SetTitle((string)Loc::getMessage("VINO_SEARCH_PAGE_H1"));
$APPLICATION->SetPageProperty("title", $query !== "" ? (string)Loc::getMessage("VINO_SEARCH_PAGE_TITLE_QUERY", ["#QUERY#" => htmlspecialcharsbx(mb_substr($query, 0, 60))]) : (string)Loc::getMessage("VINO_SEARCH_PAGE_H1"));
$APPLICATION->SetPageProperty("robots", "noindex, follow");
$APPLICATION->SetPageProperty("vino_alternates", "N");
}
public static function titleParams(): array
{
$kinds = self::kinds();
$params = [
"NUM_CATEGORIES" => "3",
"TOP_COUNT" => "6",
"ORDER" => "rank",
"USE_LANGUAGE_GUESS" => "N",
"CHECK_DATES" => "Y",
"SHOW_OTHERS" => "N",
"SHOW_INPUT" => "Y",
"PAGE" => "#SITE_DIR#search/",
"INPUT_ID" => self::INPUT_ID,
"CONTAINER_ID" => "vino-search-field",
];
$groups = [["wine"], ["brand"], ["article", "offer"]];
foreach ($groups as $index => $group) {
$types = [];
foreach ($group as $kind) {
$types[self::iblockType($kind)][] = (string)$kinds[$kind];
}
$params["CATEGORY_" . $index] = array_map(static fn(string $type): string => "iblock_" . $type, array_keys($types));
foreach ($types as $type => $ids) {
$params["CATEGORY_" . $index . "_iblock_" . $type] = $ids;
}
}
return $params;
}
public static function pageParams(): array
{
$params = [
"RESTART" => "Y",
"NO_WORD_LOGIC" => "N",
"CHECK_DATES" => "Y",
"USE_TITLE_RANK" => "Y",
"DEFAULT_SORT" => "rank",
"FILTER_NAME" => "",
"SHOW_WHERE" => "N",
"SHOW_WHEN" => "N",
"PAGE_RESULT_COUNT" => "12",
"AJAX_MODE" => "N",
"CACHE_TYPE" => "A",
"CACHE_TIME" => "3600",
"DISPLAY_TOP_PAGER" => "N",
"DISPLAY_BOTTOM_PAGER" => "Y",
"PAGER_TITLE" => (string)Loc::getMessage("VINO_SEARCH_PAGER_TITLE"),
"PAGER_SHOW_ALWAYS" => "N",
"PAGER_TEMPLATE" => "vinoteca",
"USE_LANGUAGE_GUESS" => "N",
"USE_SUGGEST" => "N",
"arrFILTER" => ["main"],
"arrFILTER_main" => [SITE_DIR . "about/", SITE_DIR . "privacy/", SITE_DIR . "consent/"],
];
foreach (self::kinds() as $kind => $iblockId) {
$type = self::iblockType($kind);
if (!in_array("iblock_" . $type, $params["arrFILTER"], true)) {
$params["arrFILTER"][] = "iblock_" . $type;
}
$params["arrFILTER_iblock_" . $type][] = (string)$iblockId;
}
return $params;
}
public static function suggest(array $categories): array
{
$hits = [];
foreach ($categories as $code => $category) {
if ($code === "all") {
continue;
}
foreach ((array)($category["ITEMS"] ?? []) as $item) {
if (($item["MODULE_ID"] ?? "") !== "") {
$hits[] = $item;
}
}
}
return self::describe($hits);
}
public static function describe(array $hits): array
{
$keys = [];
foreach ($hits as $index => $hit) {
$hits[$index]["URL"] = rtrim((string)preg_replace('/([?&])sphrase_id=[^&]*&?/', '$1', (string)($hit["URL"] ?? "")), "?&");
$keys[] = [$hit["MODULE_ID"] ?? "", $hit["PARAM2"] ?? "", $hit["ITEM_ID"] ?? "", $hits[$index]["URL"], $hit["TITLE"] ?? "", $hit["BODY"] ?? ""];
}
return (array)Cached::remember(self::CACHE_DIR, "describe_" . SITE_ID . "_" . md5(serialize($keys)), 3600, array_merge(array_map(static fn(int $iblockId): string => "iblock_id_" . $iblockId, self::kinds()), [Offers::CACHE_TAG]), static fn(): array => self::build($hits));
}
private static function build(array $hits): array
{
$kindsById = array_flip(self::kinds());
$elementIds = [];
$sectionIds = [];
foreach ($hits as $hit) {
if (($hit["MODULE_ID"] ?? "") !== "iblock") {
continue;
}
$itemId = (string)($hit["ITEM_ID"] ?? "");
if (ctype_digit($itemId) && isset($kindsById[(int)($hit["PARAM2"] ?? 0)])) {
$elementIds[] = (int)$itemId;
} elseif (preg_match('/^S(\d+)$/', $itemId, $match)) {
$sectionIds[] = (int)$match[1];
}
}
$elements = self::elements($elementIds);
$wineIds = array_keys(array_filter($elements, static fn(array $element): bool => $element["kind"] === "wine"));
$wines = Related::summariesById($wineIds);
$meta = SearchMeta::get($wineIds);
$prices = Prices::optimal($wineIds);
$sections = [];
if ($sectionIds) {
foreach (Sections::all() as $code => $section) {
if (in_array($section["ID"], $sectionIds, true)) {
$sections[$section["ID"]] = ["name" => (string)$section["NAME"], "url" => SITE_DIR . "catalog/" . $code . "/", "text" => (string)$section["DESCRIPTION"]];
}
}
}
$items = [];
foreach ($hits as $hit) {
$itemId = (string)($hit["ITEM_ID"] ?? "");
if (($hit["MODULE_ID"] ?? "") === "main") {
$items[] = self::item("page", (string)$hit["TITLE"], (string)$hit["URL"], self::snippet((string)($hit["BODY"] ?? "")));
continue;
}
if (preg_match('/^S(\d+)$/', $itemId, $match)) {
$section = $sections[(int)$match[1]] ?? null;
if ($section) {
$items[] = self::item("section", $section["name"], $section["url"], self::snippet($section["text"]));
}
continue;
}
$element = $elements[(int)$itemId] ?? null;
if ($element === null) {
continue;
}
if ($element["kind"] === "wine") {
$wine = $wines[(int)$itemId] ?? null;
if ($wine === null) {
continue;
}
$item = self::item("wine", (string)$wine["name"], (string)$wine["url"], (string)($meta[(int)$itemId]["META"] ?? ""));
$price = $prices[(int)$itemId] ?? null;
$item["price"] = $price ? Money::format((float)$price["price"], (string)$price["currency"]) : "";
} else {
$item = self::item($element["kind"], $element["name"], (string)$hit["URL"], self::snippet($element["text"]));
}
$item["image"] = $element["image"];
$items[] = $item;
}
return $items;
}
private static function item(string $kind, string $name, string $url, string $text): array
{
return [
"kind" => $kind,
"label" => (string)Loc::getMessage("VINO_SEARCH_KIND_" . strtoupper($kind)),
"name" => $name,
"url" => $url,
"meta" => $text,
"image" => "",
"price" => "",
];
}
private static function elements(array $ids): array
{
if (!$ids || !Loader::includeModule("iblock")) {
return [];
}
$kindsById = array_flip(self::kinds());
$found = [];
$rows = \CIBlockElement::GetList([], ["ID" => array_values(array_unique($ids))], false, false, ["ID", "IBLOCK_ID", "NAME", "PREVIEW_TEXT", "PREVIEW_PICTURE", "DETAIL_PICTURE"]);
while ($row = $rows->GetNextElement()) {
$element = $row->GetFields();
$element["PROPERTIES"] = $row->GetProperties();
$kind = $kindsById[(int)$element["IBLOCK_ID"]] ?? "";
$found[(int)$element["ID"]] = [
"kind" => $kind,
"name" => LocalizedText::field($element, "NAME"),
"text" => LocalizedText::field($element, "PREVIEW_TEXT"),
"image" => self::thumb((int)($element["PREVIEW_PICTURE"] ?: $element["DETAIL_PICTURE"])),
];
}
return $found;
}
private static function thumb(int $fileId): string
{
if ($fileId <= 0) {
return "";
}
$file = \CFile::ResizeImageGet($fileId, ["width" => self::THUMB_WIDTH, "height" => self::THUMB_HEIGHT], BX_RESIZE_IMAGE_EXACT, false);
return (string)($file["src"] ?? "");
}
private static function snippet(string $text): string
{
$text = trim((string)preg_replace('/\s+/u', " ", strip_tags(str_replace(["</p>", "<br>", "<br />"], " ", $text))));
if (mb_strlen($text) <= self::SNIPPET_LENGTH) {
return $text;
}
$cut = mb_substr($text, 0, self::SNIPPET_LENGTH);
$space = mb_strrpos($cut, " ");
return rtrim(mb_substr($cut, 0, $space ?: self::SNIPPET_LENGTH), " ,.;:") . "…";
}
private static function kinds(): array
{
return [
"wine" => Config::iblockId("catalog"),
"brand" => Config::iblockId("brands"),
"article" => Config::iblockId("news"),
"offer" => Config::iblockId("offers"),
];
}
private static function iblockType(string $kind): string
{
$iblock = Loader::includeModule("iblock") ? \CIBlock::GetArrayByID(self::kinds()[$kind]) : false;
return is_array($iblock) ? (string)$iblock["IBLOCK_TYPE_ID"] : "";
}
}