Skip to content

Commit

Permalink
Working at searchRequestLogs
Browse files Browse the repository at this point in the history
  • Loading branch information
Torsten Freyda committed Mar 5, 2024
1 parent 0e984b1 commit 096b456
Show file tree
Hide file tree
Showing 9 changed files with 497 additions and 30 deletions.
90 changes: 90 additions & 0 deletions src/Commands/SearchLogTransfer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php
/**
* MuckiSearchPlugin plugin
*
*
* @category Muckiware
* @package MuckiSearch
* @copyright Copyright (c) 2023 by Muckiware
*
* @author Muckiware
*
*/

namespace MuckiSearchPlugin\Commands;

use Symfony\Component\Console\Attribute\AsCommand;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Process\Process;
use Shopware\Core\Framework\Context;

use MuckiSearchPlugin\Services\Settings as PluginSettings;
use MuckiSearchPlugin\Services\SearchTermLog;


#[AsCommand('muckiware:search:log:transfer')]
class SearchLogTransfer extends Command
{
/**
* @var null
*/
protected $container = null;

public function __construct(
protected PluginSettings $settings,
protected LoggerInterface $logger,
protected SearchTermLog $searchTermLog
) {

parent::__construct(self::$defaultName);
}

public function setContainer(ContainerInterface $container): void
{
$this->container = $container;
}

/**
* @return ContainerInterface
*/
public function getContainer(): ContainerInterface
{
if (!$this->container) {
throw new \LogicException('Cannot retrieve the container from a non-booted kernel.');
}
return $this->container;
}

/**
* @internal
*/
public function configure(): void
{
$this->setDescription('Transfer search logs into database');
}

/**
* @param InputInterface $input
* @param OutputInterface $output
* @return int
* @throws \Exception
*/
public function execute(InputInterface $input, OutputInterface $output): int
{
$serverInfoAsString = $this->searchTermLog->saveSearchLogsIntoDb();
if($serverInfoAsString) {

$output->writeln($serverInfoAsString);
return self::SUCCESS;
}

return self::FAILURE;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
use Shopware\Core\Framework\DataAbstractionLayer\Field\TranslatedField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\TranslationsAssociationField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\UpdatedAtField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\VersionField;
use Shopware\Core\Framework\DataAbstractionLayer\FieldCollection;
use Shopware\Core\System\SalesChannel\SalesChannelDefinition;

Expand All @@ -54,6 +55,7 @@ public function getCollectionClass(): string {
protected function defineFields(): FieldCollection {
return new FieldCollection([
(new idField('id', 'id'))->addFlags(new Required(), new PrimaryKey()),
(new VersionField())->addFlags(new ApiAware()),
(new FkField('sales_channel_id', 'salesChannelId', SalesChannelDefinition::class))->addFlags(new Required()),
(new TranslatedField('searchTerm')),
(new TranslatedField('hits')),
Expand Down
3 changes: 3 additions & 0 deletions src/Core/Defaults.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ final class Defaults

public const DEFAULT_SERVER_PORT = 9200;

public const DEFAULT_SESSION_FIELD_LAST_SEARCH_REQUEST = 'muwa_last_search_request_timestamp';
public const DEFAULT_SESSION_FIELD_SEARCH_REQUESTS = 'muwa_last_search_requests';

public const DEFAULT_INDEX_NAME_PATTERN = '{{salesChannelId}}-{{entity}}-{{languageId}}';

public const DEFAULT_PRODUCT_MAPPINGS = 'id:keyword,productNumber:keyword,translations.DEFAULT.name:text,translations.DEFAULT.description:text,cover.media.url:text';
Expand Down
92 changes: 92 additions & 0 deletions src/Entities/SessionSearchRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php declare(strict_types=1);

namespace MuckiSearchPlugin\Entities;

class SessionSearchRequest
{
/**
* UUID for a search log
* @var string
*/
protected string $id;

protected string $searchTerm;

protected string $sessionId;

protected string $languageId;

protected string $salesChannelId;

protected int $hits;

public function getId(): string
{
return $this->id;
}

public function setId(string $id): void
{
$this->id = $id;
}

public function getSearchTerm(): string
{
return $this->searchTerm;
}

public function setSearchTerm(string $searchTerm): void
{
$this->searchTerm = $searchTerm;
}

public function getSessionId(): string
{
return $this->sessionId;
}

public function setSessionId(string $sessionId): void
{
$this->sessionId = $sessionId;
}

public function getLanguageId(): string
{
return $this->languageId;
}

public function setLanguageId(string $languageId): void
{
$this->languageId = $languageId;
}

public function getSalesChannelId(): string
{
return $this->salesChannelId;
}

public function setSalesChannelId(string $salesChannelId): void
{
$this->salesChannelId = $salesChannelId;
}

public function getHits(): int
{
return $this->hits;
}

public function setHits(int $hits): void
{
$this->hits = $hits;
}

public function toSerialize(): string
{
return serialize(get_object_vars($this));
}

public function toArray(): array
{
return get_object_vars($this);
}
}
8 changes: 5 additions & 3 deletions src/Migration/Migration1708858240.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,27 @@ public function update(Connection $connection): void
$connection->executeUpdate('
CREATE TABLE IF NOT EXISTS `muwa_search_request_logs` (
`id` binary(16) NOT NULL,
`version_id` binary(16) NOT NULL,
`sales_channel_id` binary(16) NOT NULL,
`created_at` datetime(3) NOT NULL,
`updated_at` datetime(3) DEFAULT NULL,
PRIMARY KEY (`id`),
PRIMARY KEY (`id`, `version_id`),
KEY `fk.muwa_search_request_logs.sales_channel_id` (`sales_channel_id`),
CONSTRAINT `fk.muwa_search_request_logs.sales_channel_id` FOREIGN KEY (`sales_channel_id`) REFERENCES `sales_channel` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `muwa_search_request_logs_translation` (
`muwa_search_request_logs_id` binary(16) NOT NULL,
`muwa_search_request_logs_version_id` binary(16) NOT NULL,
`language_id` binary(16) NOT NULL,
`search_term` varchar(255) NOT NULL,
`hits` int(7) NULL,
`created_at` datetime(3) NOT NULL,
`updated_at` datetime(3) DEFAULT NULL,
PRIMARY KEY (`muwa_search_request_logs_id`,`language_id`),
PRIMARY KEY (`muwa_search_request_logs_id`,`muwa_search_request_logs_version_id`,`language_id`),
KEY `fk.muwa_search_request_logs_translation.language_id` (`language_id`),
CONSTRAINT `fk.muwa_search_request_logs_translation.language_id` FOREIGN KEY (`language_id`) REFERENCES `language` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk.muwa_search_request_logs_translation.muwa_index_structure_id` FOREIGN KEY (`muwa_search_request_logs_id`) REFERENCES `muwa_search_request_logs` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
CONSTRAINT `fk.muwa_search_request_logs_translation.muwa_index_structure_id` FOREIGN KEY (`muwa_search_request_logs_id`, `muwa_search_request_logs_version_id`) REFERENCES `muwa_search_request_logs` (`id`, `version_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
');
}
Expand Down
24 changes: 23 additions & 1 deletion src/Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@
<argument type="service" id="service_container"/>
</call>
</service>
<service class="MuckiSearchPlugin\Commands\SearchLogTransfer" id="mucki.search.commands.searchLog.transfer" public="true">
<argument type="service" id="MuckiSearchPlugin\Services\Settings"/>
<argument type="service" id="Psr\Log\LoggerInterface"/>
<argument type="service" id="MuckiSearchPlugin\Services\SearchTermLog"/>
<tag name="console.command"/>
<call method="setContainer">
<argument type="service" id="service_container"/>
</call>
</service>

<service id="MuckiSearchPlugin\Controller\IndicesController" public="true">
<argument type="service" id="MuckiSearchPlugin\Services\Settings"/>
Expand Down Expand Up @@ -150,6 +159,13 @@
<argument type="service" id="searchclient.factory"/>
<argument type="service" id="MuckiSearchPlugin\Services\IndicesSettings"/>
</service>
<service id="MuckiSearchPlugin\Services\SearchTermLog" public="true">
<argument type="service" id="Psr\Log\LoggerInterface"/>
<argument type="service" id="mucki_search_plugin.filesystem.private"/>
</service>
<service id="MuckiSearchPlugin\Services\Session" public="true">
<argument type="service" id="session.factory"/>
</service>
<service id="MuckiSearchPlugin\Services\Settings" public="true">
<argument type="service" id="Shopware\Core\System\SystemConfig\SystemConfigService"/>
</service>
Expand All @@ -166,7 +182,13 @@
<argument type="service" id="Symfony\Component\HttpFoundation\RequestStack"/>
<tag name="kernel.event_subscriber" priority="1000"/>
</service>

<service id="MuckiSearchPlugin\Subscriber\SearchSubscriber">
<argument type="service" id="MuckiSearchPlugin\Services\Session"/>
<argument type="service" id="MuckiSearchPlugin\Services\Settings"/>
<argument type="service" id="MuckiSearchPlugin\Services\SearchTermLog"/>
<argument type="service" id="muwa_search_request_logs.repository"/>
<tag name="kernel.event_subscriber"/>
</service>
<service class="MuckiSearchPlugin\Subscriber\SearchSuggestSubscriber" id="muckiSearchPlugin.subscriber.searchSuggestSubscriber">
<argument type="service" id="MuckiSearchPlugin\Services\Settings"/>
<argument type="service" id="Symfony\Component\HttpFoundation\RequestStack"/>
Expand Down
82 changes: 82 additions & 0 deletions src/Services/SearchTermLog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php
/**
* MuckiSearchPlugin plugin
*
*
* @category Muckiware
* @package MuckiSearch
* @copyright Copyright (c) 2023 by Muckiware
*
* @author Muckiware
*
*/

namespace MuckiSearchPlugin\Services;

use League\Flysystem\FilesystemException;
use League\Flysystem\FilesystemOperator;
use League\Flysystem\FileAttributes;
use Psr\Log\LoggerInterface;

use MuckiSearchPlugin\Entities\SessionSearchRequest;

class SearchTermLog
{
public function __construct(
protected LoggerInterface $logger,
private readonly FilesystemOperator $fileSystemPrivate
){}

/**
* @throws FilesystemException
*/
public function saveSearchLogSessionToFile(string $sessionId, string $currentSearchRequests): void
{
try {

$this->fileSystemPrivate->delete($sessionId);
$this->fileSystemPrivate->write($sessionId, $currentSearchRequests);
} catch (FilesystemException $e) {

$this->logger->error('Not possible to write search log file', array('mucki','search'));
$this->logger->error($e->getMessage(), array('mucki','search'));
}
}

/**
* @throws FilesystemException
*/
public function saveSearchLogsIntoDb(): bool
{
$listContents = $this->fileSystemPrivate->listContents('', true)->toArray();
foreach ($listContents as $listContent) {

/** @var SessionSearchRequest $searchLogs */
$searchLogs = $this->getSearchLogsFromFiles($listContent->path());
$this->writeSearchLogs($searchLogs);
}
return true;
}

public function writeSearchLogs(SessionSearchRequest $searchLogs): void
{
$logData = array(
'id' => $searchLogs->getId(),
'salesChannelId' => $searchLogs->getSalesChannelId(),
'searchTerm' => $searchLogs->getSearchTerm(),
'hits' => $searchLogs->getHits()
);
// $this->searchRequestLogsRepository->create([$logData], $event->getContext());
//
// $versionLogId = $this->searchRequestLogsRepository->createVersion($logId, $event->getContext());
// $versionContext = $event->getContext()->createWithVersionId($versionLogId);
}

/**
* @throws FilesystemException
*/
public function getSearchLogsFromFiles(string $location): array
{
return unserialize($this->fileSystemPrivate->read($location));
}
}
Loading

0 comments on commit 096b456

Please sign in to comment.