89 lines
3.0 KiB
PHP
89 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace KupShop\FeedGeneratorBundle\Utils;
|
|
|
|
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
|
|
|
|
class Map
|
|
{
|
|
use \DatabaseCommunication;
|
|
|
|
/** @var array */
|
|
protected $maps;
|
|
|
|
protected function getMap(string $mapName, bool $forceReload = false, bool $readOnly = false): array
|
|
{
|
|
if (empty($mapName)) {
|
|
return [];
|
|
}
|
|
if (!isset($this->maps[$mapName]) || $forceReload) {
|
|
$map = $this->selectSQL('feed_maps', ['name' => $mapName])->fetch();
|
|
if (!$map) {
|
|
if ($readOnly) {
|
|
return [];
|
|
}
|
|
$this->insertSQL('feed_maps', ['name' => $mapName]);
|
|
$mapID = sqlInsertId();
|
|
} else {
|
|
$mapID = $map['id'];
|
|
}
|
|
$this->maps[$mapName] = ['id' => $mapID, 'name' => $mapName, 'phrases' => []];
|
|
$phrases = $this->selectSQL('feed_map_phrases', ['id_feed_map' => $mapID]);
|
|
foreach ($phrases as $phrase) {
|
|
$this->maps[$mapName]['phrases'][$phrase['original']] = $phrase['mapped'];
|
|
}
|
|
}
|
|
|
|
return $this->maps[$mapName];
|
|
}
|
|
|
|
// TODO: make $key required (?string $key) when on PHP 7.1
|
|
public function map(string $mapName, ?string $key = null, ?string $description = null, ?string $fallback = null)
|
|
{
|
|
$map = $this->getMap($mapName);
|
|
if (!empty($map) && isset($map['phrases'][$key])) {
|
|
$result = $map['phrases'][$key];
|
|
|
|
return $result === '' ? ($fallback ?? '') : $result;
|
|
} elseif (!empty($map) && !empty($key) && !array_key_exists($key, $map['phrases'])) {
|
|
try {
|
|
$this->insertSQL('feed_map_phrases', [
|
|
'id_feed_map' => $map['id'],
|
|
'original' => $key,
|
|
'description' => $description ?? '',
|
|
]);
|
|
$this->maps[$mapName]['phrases'][$key] = '';
|
|
} catch (UniqueConstraintViolationException $e) {
|
|
$map = $this->getMap($mapName, true);
|
|
if (!empty($map) && isset($map['phrases'][$key])) {
|
|
$result = $map['phrases'][$key];
|
|
|
|
return $result === '' ? ($fallback ?? '') : $result;
|
|
}
|
|
} catch (\Exception $e) {
|
|
}
|
|
}
|
|
|
|
return $fallback ?? '';
|
|
}
|
|
|
|
// TODO: make $key required (?string $key) when on PHP 7.1
|
|
public function mapContains(string $mapName, ?string $key = null): bool
|
|
{
|
|
$map = $this->getMap($mapName, false, true);
|
|
|
|
return !empty($map) && array_key_exists($key, $map['phrases']);
|
|
}
|
|
|
|
// TODO: make $key required (?string $key) when on PHP 7.1
|
|
public function findInMap(string $mapName, ?string $key = null): string
|
|
{
|
|
$map = $this->getMap($mapName, false, true);
|
|
if (!empty($map) && isset($map['phrases'][$key])) {
|
|
return $map['phrases'][$key];
|
|
}
|
|
|
|
return '';
|
|
}
|
|
}
|