Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[TASK] Introduce ImageGalleryRepository (#36) #37

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
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
68 changes: 49 additions & 19 deletions Classes/Controller/GalleryController.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

namespace Fab\NaturalGallery\Controller;

/**
Expand All @@ -14,24 +15,44 @@
* The TYPO3 project - inspiring people to share!
*/

use Fab\NaturalGallery\Domain\Repository\CategoryRepository;
use Fab\NaturalGallery\Persistence\MatcherFactory;
use Fab\NaturalGallery\Domain\Repository\ImageGalleryRepository;
use Fab\NaturalGallery\Persistence\DemandFactory;
use Fab\NaturalGallery\Persistence\OrderFactory;
use Fab\Vidi\Domain\Repository\ContentRepositoryFactory;
use Fab\NaturalGallery\Utility\ConfigurationUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Extbase\Persistence\QueryInterface;
use TYPO3\CMS\Extbase\Utility\DebuggerUtility;

/**
* Controller
*/
class GalleryController extends ActionController
{
protected CategoryRepository $categoryRepository;
protected ImageGalleryRepository $galleryRepository;

protected DemandFactory $demandFactory;

protected OrderFactory $orderFactory;

protected array $configuration = array();

protected $settings = array();

protected array $allowedColumns = [
'crdate',
'tstamp',
'title',
'uid',
];

public function initializeAction(): void
{
$this->galleryRepository = GeneralUtility::makeInstance(ImageGalleryRepository::class);
$this->orderFactory = GeneralUtility::makeInstance(OrderFactory::class);
$this->demandFactory = GeneralUtility::makeInstance(DemandFactory::class);
}

/**
* @return void|string
*/
Expand All @@ -41,31 +62,40 @@ public function listAction()
return '<strong style="color: red">Please save your plugin settings in the BE beforehand.</strong>';
}

// Initialize some objects related to the query.
$matcher = MatcherFactory::getInstance()->getMatcher($this->settings);
$order = OrderFactory::getInstance()->getOrder($this->settings);

// Fetch the adequate repository for a known data type.
$contentRepository = ContentRepositoryFactory::getInstance('sys_file');

// Fetch and count files
$images = $contentRepository->findBy($matcher, $order);
$images = $this->galleryRepository->findByDemand($this->getDemand(), $this->getOrderings());

// Assign template variables
$this->view->assign('settings', $this->settings);
$this->view->assign('data', $this->configurationManager->getcontentObject()->data);
$this->view->assign('images', $images);

$identifiers = GeneralUtility::trimExplode(',', $this->settings['categories'], TRUE);
$this->view->assign('categories', $this->categoryRepository->findByIdentifiers($identifiers));
$this->view->assign('categories', $this->galleryRepository->findByCategories($identifiers));
}

/**
* @param CategoryRepository $categoryRepository
*/
public function injectCategoryRepository(CategoryRepository $categoryRepository): void
protected function getOrderings(): array
{
$this->categoryRepository = $categoryRepository;
$sortBy = $this->settings['sorting'] ?? 'sys_file.tstamp';
if (!in_array($sortBy, $this->allowedColumns)) {
$sortBy = 'sys_file.tstamp';
}
$defaultDirection = QueryInterface::ORDER_DESCENDING;
$direction = $this->settings['direction'] ?? $defaultDirection;
if ($this->settings['direction'] && strtoupper($direction) === 'DESC') {
$defaultDirection = QueryInterface::ORDER_ASCENDING;
}
return [
$sortBy => $defaultDirection,
];
}

protected function getDemand(): array
{
return [
'likes' => $this->demandFactory->get($this->settings),
'identifiers' => GeneralUtility::trimExplode(',', $this->settings['categories'], TRUE)
];
}


}
182 changes: 182 additions & 0 deletions Classes/Domain/Repository/ImageGalleryRepository.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
<?php
namespace Fab\NaturalGallery\Domain\Repository;


use Fab\NaturalGallery\Persistence\Matcher;
use Fab\NaturalGallery\Persistence\Order;
use Fab\NaturalGallery\Utility\ConfigurationUtility;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
use TYPO3\CMS\Core\Utility\GeneralUtility;


class ImageGalleryRepository
{

protected string $tableName = 'sys_file';

protected array $settings;

public function getDefaultData(string $field):string
{
return ConfigurationUtility::getInstance()->get($field);
}

public function findByUid(int $uid): array
{
$query = $this->getQueryBuilder();
$query
->select('*')
->from($this->tableName)
->where(
$this->getQueryBuilder()
->expr()
->eq('uid', $this->getQueryBuilder()->expr()->literal($uid)),
);

$messages = $query->execute()->fetchOne();

return is_array($messages) ? $messages : [];
}

// public function findByCategory(int $category): array
// {
// /** @var QueryBuilder $query */
// $queryBuilder = $this->getQueryBuilder();
// $queryBuilder->select('*')
// ->from($this->tableName)
// ->innerJoin(
// 'sys_file',
// 'sys_file_metadata',
// 'sys_file_metadata',
// 'sys_file.uid = sys_file_metadata.file'
// )
// ->innerJoin(
// 'sys_file_metadata',
// 'sys_category_record_mm',
// 'sys_category_record_mm',
// 'sys_category_record_mm.uid_foreign = sys_file_metadata.uid AND tablenames = "sys_file_metadata" AND fieldname = "categories"'
// )
// ->where(
// $queryBuilder->expr()->eq('sys_category_record_mm.uid_local', $category)
// )
// ->addOrderBy('sys_file_metadata.year', 'DESC')
// ->addOrderBy('sys_file_metadata.title', 'ASC');

// return $queryBuilder
// ->execute()
// ->fetchAllAssociative();
// }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Lebeau09 on peut enlever cette partie


public function findByCategories(array $categories): array
{
$queryBuilder = $this->getQueryBuilder();
$queryBuilder->select('*')
->from($this->tableName)
->innerJoin(
'sys_file',
'sys_file_metadata',
'sys_file_metadata',
'sys_file.uid = sys_file_metadata.file'
)
->innerJoin(
'sys_file_metadata',
'sys_category_record_mm',
'sys_category_record_mm',
'sys_category_record_mm.uid_foreign = sys_file_metadata.uid AND tablenames = "sys_file_metadata" AND fieldname = "categories"'
);

if (!empty($categories)) {
$queryBuilder->where(
$queryBuilder->expr()->in('sys_category_record_mm.uid_local', $categories)
);
}

$queryBuilder->addOrderBy('sys_file_metadata.year', 'DESC')
->addOrderBy('sys_file_metadata.title', 'ASC');

return $queryBuilder
->execute()
->fetchAllAssociative();

}

public function findByDemand(array|Matcher $demand = [], array $orderings = [], int $offset = 0, int $limit = 0): array
{
$queryBuilder = $this->getQueryBuilder();
$constraints = [];


if ($demand['likes']) {
foreach ($demand['likes'] as $field => $value) {
$constraints[] = $queryBuilder->select('*')->from($this->tableName)
->expr()
->like(
$field,
$queryBuilder->createNamedParameter('%' . $queryBuilder->escapeLikeWildcards($value) . '%'),
);
}

if ($constraints) {
$queryBuilder->where($queryBuilder->expr()->orX(...$constraints));
}

# We handle the sorting
$queryBuilder->addOrderBy(key($orderings), current($orderings));

}


if ($demand['identifiers']) {
$queryBuilder->select('*')
->from($this->tableName)
->innerJoin(
'sys_file',
'sys_file_metadata',
'sys_file_metadata',
'sys_file.uid = sys_file_metadata.file'
)
->innerJoin(
'sys_file_metadata',
'sys_category_record_mm',
'sys_category_record_mm',
'sys_category_record_mm.uid_foreign = sys_file_metadata.uid AND tablenames = "sys_file_metadata" AND fieldname = "categories"'
);

if (!empty($demand['identifiers'])) {
$queryBuilder->where(
$queryBuilder->expr()->in('sys_category_record_mm.uid_local', $demand['identifiers'])
);
}

$queryBuilder->addOrderBy('sys_file_metadata.year', 'DESC')
->addOrderBy('sys_file_metadata.title', 'ASC');
}

if ($limit > 0) {
$queryBuilder->setMaxResults($limit);
}

return $queryBuilder->execute()->fetchAllAssociative();
}


public function findByUids(array $uids): array
{
$query = $this->getQueryBuilder();
$query
->select('*')
->from($this->tableName)
->where($this->getQueryBuilder()->expr()->in('uid', $uids));

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

protected function getQueryBuilder(): QueryBuilder
{
/** @var ConnectionPool $connectionPool */
$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
return $connectionPool->getQueryBuilderForTable($this->tableName);
}

}
104 changes: 104 additions & 0 deletions Classes/Persistence/DemandFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
<?php
namespace Fab\NaturalGallery\Persistence;

/**
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/

use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
use TYPO3\CMS\Core\Resource\File;
use TYPO3\CMS\Core\Resource\ResourceFactory;
use TYPO3\CMS\Core\SingletonInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;


/**
* Factory class related to Matcher object.
*/
class DemandFactory implements SingletonInterface
{

protected array $settings = [];

protected string $tableName = 'sys_file';

protected function applyCriteriaFromFolders(\Fab\NaturalGallery\Persistence\Matcher $matcher): \Fab\NaturalGallery\Persistence\Matcher
{
$folders = '';
if (!empty($this->settings['folders'])) {

if (str_contains($this->settings['folders'], 't3://')) {
$decodedUrl = urldecode($this->settings['folders']);

// In case identifier=/ is missing.
if (!str_contains($decodedUrl, 'identifier=')) {
$decodedUrl .= '&identifier=/';
}
preg_match("/storage=([\d]+)&identifier=(.+)/", $decodedUrl, $matches);
if (count($matches) === 3) {
$folders = $matches[1] . ':' . ltrim($matches[2], '/');
}
} else {
$folders = $this->settings['folders'];
}
$folderIdentifiers = GeneralUtility::trimExplode(',', $folders, true);
$fileUids = [];
foreach ($folderIdentifiers as $folderIdentifier) {
$folderIdentifier = str_replace('file:', '', $folderIdentifier);
$folder = GeneralUtility::makeInstance(ResourceFactory::class)->getFolderObjectFromCombinedIdentifier($folderIdentifier);
$files = $folder->getFiles();
foreach ($files as $file) {
$fileUids[] = $file->getUid();
}
}

$matcher->in('uid', $fileUids);
}

return $matcher;
}
protected function applyCriteriaFromAdditionalConstraints(Matcher $matcher): Matcher
{

if (!empty($this->settings['additionalEquals'])) {
$constraints = GeneralUtility::trimExplode(',', $this->settings['additionalEquals'], TRUE);
foreach ($constraints as $constraint) {

if (preg_match('/.+=.+/isU', $constraint, $matches)) {
$constraintParts = GeneralUtility::trimExplode('=', $constraint, TRUE);
if (count($constraintParts) === 2) {
$matcher->equals(trim($constraintParts[0]), trim($constraintParts[1]));
}
} elseif (preg_match('/.+like.+/isU', $constraint, $matches)) {
$constraintParts = GeneralUtility::trimExplode('like', $constraint, TRUE);
if (count($constraintParts) === 2) {
$matcher->like(trim($constraintParts[0]), trim($constraintParts[1]));
}
}

}
}
return $matcher;
}

public function get(array $settings): Matcher
{
$this->settings = $settings;
$matcher = GeneralUtility::makeInstance(Matcher::class);
// We only want files of type images, consider it as a prerequisite.
$matcher->equals('type', File::FILETYPE_IMAGE);
$matcher = $this->applyCriteriaFromFolders($matcher);
return $this->applyCriteriaFromAdditionalConstraints($matcher);
}

}
Loading
Loading