Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

[!!!][FEATURE] Add support for different languages #2

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions Classes/Command/ImportCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ protected function configure(): void
InputArgument::REQUIRED,
'Storage pid of imported jobs',
);
$this->addOption(
'language',
'l',
InputOption::VALUE_REQUIRED,
'Job language, should be the two-letter ISO 639-1 code of a configured site language',
);
$this->addOption(
'force',
'f',
Expand Down Expand Up @@ -96,8 +102,10 @@ protected function initialize(InputInterface $input, OutputInterface $output): v

protected function execute(InputInterface $input, OutputInterface $output): int
{
/* @phpstan-ignore-next-line cast.int */
/* @phpstan-ignore cast.int */
$storagePid = max(0, (int)$input->getArgument('storage-pid'));
/** @var string|null $language */
$language = $input->getOption('language');
$force = (bool)$input->getOption('force');
$noDelete = (bool)$input->getOption('no-delete');
$noUpdate = (bool)$input->getOption('no-update');
Expand All @@ -111,7 +119,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}

// Fetch and import jobs from Personio API
$result = $this->personioImportService->import($storagePid, !$noUpdate, !$noDelete, $force, $dryRun);
$result = $this->personioImportService->import($storagePid, $language, !$noUpdate, !$noDelete, $force, $dryRun);

// Show result
$this->printResult($result);
Expand Down
2 changes: 1 addition & 1 deletion Classes/Domain/Factory/SchemaFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ private function decorateDescription(Job $job): string
// https://docs.typo3.org/c/typo3/cms-core/main/en-us/Changelog/12.0/Breaking-96520-EnforceNon-emptyConfigurationInCObjparseFunc.html
$parsedDescription = $this->contentObjectRenderer->parseFunc($description, null, '< lib.parseFunc_RTE');
} else {
/* @phpstan-ignore-next-line argument.type (Only relevant for legacy TYPO3 versions) */
/* @phpstan-ignore argument.type (Only relevant for legacy TYPO3 versions) */
$parsedDescription = $this->contentObjectRenderer->parseFunc($description, [], '< lib.parseFunc_RTE');
}

Expand Down
10 changes: 10 additions & 0 deletions Classes/Domain/Model/Job.php
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,16 @@ public function recalculateContentHash(): self
return $this;
}

/**
* @param int<-1, max> $languageId
*/
public function setLanguageId(int $languageId): self
{
$this->_languageUid = $languageId;

return $this;
}

/**
* @return array<string, mixed>
*/
Expand Down
37 changes: 35 additions & 2 deletions Classes/Domain/Repository/JobRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@

use CPSIT\Typo3PersonioJobs\Domain\Model\Dto\Demand;
use CPSIT\Typo3PersonioJobs\Domain\Model\Job;
use TYPO3\CMS\Core\Context\LanguageAspect;
use TYPO3\CMS\Core\Information\Typo3Version;
use TYPO3\CMS\Extbase\Persistence\QueryInterface;
use TYPO3\CMS\Extbase\Persistence\QueryResultInterface;
use TYPO3\CMS\Extbase\Persistence\Repository;

Expand All @@ -49,7 +52,10 @@ public function findByDemand(Demand $demand): QueryResultInterface
return $query->execute();
}

public function findOneByPersonioId(int $personioId, int $storagePid = null): ?Job
/**
* @param int<-1, max>|null $languageId
*/
public function findOneByPersonioId(int $personioId, int $storagePid = null, int $languageId = null): ?Job
{
$query = $this->createQuery();

Expand All @@ -60,6 +66,10 @@ public function findOneByPersonioId(int $personioId, int $storagePid = null): ?J
$query->matching($query->equals('personioId', $personioId));
$query->setLimit(1);

if ($languageId !== null) {
$this->setLanguageForQuery($query, $languageId);
}

return $query->execute()->getFirst();
}

Expand All @@ -74,16 +84,21 @@ public function findOneByJobDescription(int $jobDescription): ?Job

/**
* @param list<Job> $existingJobs
* @param int<-1, max>|null $languageId
* @return QueryResultInterface<Job>
*/
public function findOrphans(array $existingJobs, int $storagePid = null): QueryResultInterface
public function findOrphans(array $existingJobs, int $storagePid = null, int $languageId = null): QueryResultInterface
{
$query = $this->createQuery();

if ($storagePid !== null) {
$query->getQuerySettings()->setStoragePageIds([$storagePid]);
}

if ($languageId !== null) {
$this->setLanguageForQuery($query, $languageId);
}

if ($existingJobs !== []) {
$query->matching(
$query->logicalNot(
Expand All @@ -97,4 +112,22 @@ public function findOrphans(array $existingJobs, int $storagePid = null): QueryR

return $query->execute();
}

/**
* @param QueryInterface<Job> $query
* @param int<-1, max> $languageId
*/
protected function setLanguageForQuery(QueryInterface $query, int $languageId): void
{
$querySettings = $query->getQuerySettings();

// https://docs.typo3.org/c/typo3/cms-core/main/en-us/Changelog/12.0/Breaking-97926-ExtbaseQuerySettingsMethodsRemoved.html
if ((new Typo3Version())->getMajorVersion() >= 12) {
$languageAspect = new LanguageAspect($languageId, overlayType: LanguageAspect::OVERLAYS_MIXED);
$querySettings->setLanguageAspect($languageAspect);
} else {
/* @phpstan-ignore method.notFound */
$querySettings->setLanguageUid($languageId);
}
}
}
6 changes: 6 additions & 0 deletions Classes/Event/AfterJobsMappedEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ final class AfterJobsMappedEvent
public function __construct(
private readonly Uri $requestUri,
private readonly array $jobs,
private readonly ?string $language = null,
) {}

public function getRequestUri(): Uri
Expand All @@ -54,4 +55,9 @@ public function getJobs(): array
{
return $this->jobs;
}

public function getLanguage(): ?string
{
return $this->language;
}
}
41 changes: 41 additions & 0 deletions Classes/Exception/UnavailableLanguageException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

/*
* This file is part of the TYPO3 CMS extension "personio_jobs".
*
* Copyright (C) 2024 Elias Häußler <e.haeussler@familie-redlich.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

namespace CPSIT\Typo3PersonioJobs\Exception;

/**
* UnavailableLanguageException
*
* @author Elias Häußler <e.haeussler@familie-redlich.de>
* @license GPL-3.0-or-later
*/
final class UnavailableLanguageException extends \Exception
{
public static function create(string $language): self
{
return new self(
sprintf('The given language "%s" is not available on this site.', $language),
1704297254,
);
}
}
9 changes: 7 additions & 2 deletions Classes/Service/PersonioApiService.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,14 @@ public function __construct(
* @throws ArrayPathIsInvalid
* @throws XmlIsMalformed
*/
public function getJobs(): array
public function getJobs(string $language = null): array
{
$requestUri = $this->apiUrl->withPath('/xml');

if ($language !== null) {
$requestUri = $requestUri->withQuery('language=' . $language);
}

$response = $this->requestFactory->request((string)$requestUri);
$source = XmlSource::fromXmlString((string)$response->getBody())
->asCollection('position')
Expand All @@ -81,7 +86,7 @@ public function getJobs(): array
try {
$jobs = $this->mapper->map('list<' . Job::class . '>', $source['position']);

$this->eventDispatcher->dispatch(new AfterJobsMappedEvent($requestUri, $jobs));
$this->eventDispatcher->dispatch(new AfterJobsMappedEvent($requestUri, $jobs, $language));

return $jobs;
} catch (MappingError $error) {
Expand Down
58 changes: 52 additions & 6 deletions Classes/Service/PersonioImportService.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,15 @@
use CPSIT\Typo3PersonioJobs\Enums\ImportOperation;
use CPSIT\Typo3PersonioJobs\Event\AfterJobsImportedEvent;
use CPSIT\Typo3PersonioJobs\Exception\InvalidParametersException;
use CPSIT\Typo3PersonioJobs\Exception\UnavailableLanguageException;
use CPSIT\Typo3PersonioJobs\Helper\SlugHelper;
use EliasHaeussler\ValinorXml\Exception\ArrayPathHasUnexpectedType;
use EliasHaeussler\ValinorXml\Exception\ArrayPathIsInvalid;
use EliasHaeussler\ValinorXml\Exception\XmlIsMalformed;
use Psr\EventDispatcher\EventDispatcherInterface;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
use TYPO3\CMS\Core\Site\SiteFinder;
use TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface;

/**
Expand All @@ -55,6 +58,7 @@ public function __construct(
private readonly JobRepository $jobRepository,
private readonly PersistenceManagerInterface $persistenceManager,
private readonly PersonioApiService $personioApiService,
private readonly SiteFinder $siteFinder,
) {
$this->result = new ImportResult(false);
}
Expand All @@ -64,10 +68,12 @@ public function __construct(
* @throws ArrayPathHasUnexpectedType
* @throws ArrayPathIsInvalid
* @throws InvalidParametersException
* @throws UnavailableLanguageException
* @throws XmlIsMalformed
*/
public function import(
int $storagePid,
string $language = null,
bool $updateExistingJobs = true,
bool $deleteOrphans = true,
bool $forceImport = false,
Expand All @@ -80,9 +86,16 @@ public function import(
throw InvalidParametersException::create('$updateExistingJobs', '$forceImport');
}

// Resolve language id
if ($language !== null) {
$languageId = $this->resolveLanguageId($language, $storagePid) ?? throw UnavailableLanguageException::create($language);
} else {
$languageId = null;
}

// Fetch jobs from Personio API
$jobs = $this->personioApiService->getJobs();
$orphans = $deleteOrphans ? $this->jobRepository->findOrphans($jobs, $storagePid) : [];
$jobs = $this->personioApiService->getJobs($language);
$orphans = $deleteOrphans ? $this->jobRepository->findOrphans($jobs, $storagePid, $languageId) : [];

// Process imported jobs
foreach ($jobs as $job) {
Expand All @@ -92,7 +105,7 @@ public function import(
$jobDescription->setPid($storagePid);
}

$this->addOrUpdateJob($job, $storagePid, $forceImport, $updateExistingJobs);
$this->addOrUpdateJob($job, $storagePid, $languageId, $forceImport, $updateExistingJobs);
}

// Remove orphaned jobs
Expand All @@ -106,9 +119,19 @@ public function import(
return $this->result;
}

private function addOrUpdateJob(Job $job, int $storagePid, bool $force = false, bool $update = true): void
{
$existingJob = $this->jobRepository->findOneByPersonioId($job->getPersonioId(), $storagePid);
/**
* @param int<-1, max>|null $languageId
*/
private function addOrUpdateJob(
Job $job,
int $storagePid,
int $languageId = null,
bool $force = false,
bool $update = true,
): void {
$job->setLanguageId($languageId ?? -1);

$existingJob = $this->jobRepository->findOneByPersonioId($job->getPersonioId(), $storagePid, $languageId);

// Add non-existing job
if ($existingJob === null) {
Expand Down Expand Up @@ -241,4 +264,27 @@ private function getModifiedJobs(): \Generator
yield $newJob;
}
}

/**
* @phpstan-return non-negative-int
*/
private function resolveLanguageId(string $language, int $storagePid): ?int
{
try {
$site = $this->siteFinder->getSiteByPageId($storagePid);
} catch (SiteNotFoundException) {
return null;
}

foreach ($site->getLanguages() as $siteLanguage) {
if ($siteLanguage->getTwoLetterIsoCode() === $language) {
/** @var non-negative-int $languageId */
$languageId = $siteLanguage->getLanguageId();

return $languageId;
}
}

return null;
}
}
Loading