Skip to content

Instantly share code, notes, and snippets.

@pixelbrackets
Created September 3, 2024 10:17
Show Gist options
  • Save pixelbrackets/4172d8c4a5be60bcca570f449f3e8e03 to your computer and use it in GitHub Desktop.
Save pixelbrackets/4172d8c4a5be60bcca570f449f3e8e03 to your computer and use it in GitHub Desktop.
TYPO3 FAL - Store given metadata in original file instead of reference if it is empty yet
<?php
// Located in sitepackage/Classes/Hook/DataHandlerHook.php
declare(strict_types=1);
namespace Acme\AcmeSitepackage\Hook;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\DataHandling\DataHandler;
use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException;
use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
use TYPO3\CMS\Core\Resource\ResourceFactory;
use TYPO3\CMS\Core\SingletonInterface;
class DataHandlerHook implements SingletonInterface
{
public function __construct(
protected ConnectionPool $connectionPool,
private readonly ResourceFactory $resourceFactory,
) {
}
/**
* @param string $status
* @param string $table
* @param string|int $id
* @param array<string, mixed> $fieldArray
* @param DataHandler $dataHandler
* @throws FileDoesNotExistException|ResourceDoesNotExistException
*/
public function processDatamap_postProcessFieldArray(
string $status,
string $table,
string|int $id,
array &$fieldArray,
DataHandler $dataHandler
): void {
// Store given metadata in original file instead if it is empty yet
if ($table === 'sys_file_reference') {
if ($status === 'new') {
$file = $this->resourceFactory->getFileObject($fieldArray['uid_local']);
} elseif (is_int($id)) {
$file = $this->resourceFactory->getFileReferenceObject($id)->getOriginalFile();
} else {
return;
}
$metaDataAspect = $file->getMetaData();
foreach (['title', 'description', 'alternative', 'copyright'] as $field) {
if (!empty($fieldArray[$field]) && empty($metaDataAspect->offsetGet($field))) {
$metaDataAspect->offsetSet($field, $fieldArray[$field]);
$fieldArray[$field] = null;
}
}
$metaDataAspect->save();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment