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

[FEATURE] Add categories DataProcessor #653

Open
wants to merge 18 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
136 changes: 136 additions & 0 deletions Classes/DataProcessing/CategoriesProcessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
<?php

/*
* This file is part of the "headless" Extension for TYPO3 CMS.
*
* For the full copyright and license information, please read the
* LICENSE.md file that was distributed with this source code.
*/

declare(strict_types=1);

namespace FriendsOfTYPO3\Headless\DataProcessing;

use TYPO3\CMS\Core\Utility\ArrayUtility;
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
use TYPO3\CMS\Frontend\ContentObject\DataProcessorInterface;

/**
* Example usage (get categories by relation field):
* categories = JSON
* categories {
* dataProcessing {
* 10 = headless-categories
* 10 {
* relation.fieldName = categories
* as = categories
* }
* }
* }
* Example usage (get categories by comma-separated-list of category ids):
*
* categories = JSON
* categories {
* dataProcessing {
* 10 = headless-categories
* 10 {
* uidInList = 1,3,5
*
* as = categories
* }
* }
* }
* Example usage (get categories by comma-separated-list of category ids from custom pid):
*
* categories = JSON
* categories {
* dataProcessing {
* 10 = headless-categories
* 10 {
* uidInList = 1,3,5
* pidInList = leveluid:0
* recursive = 250
*
* as = categories
* }
* }
* }
*
* @codeCoverageIgnore
**/
class CategoriesProcessor implements DataProcessorInterface
{
/**
* Fetches categories from the database
*
* @param ContentObjectRenderer $cObj The data of the content element or page
* @param array $contentObjectConfiguration The configuration of Content Object
* @param array $processorConfiguration The configuration of this processor
* @param array $processedData Key/value store of processed data (e.g. to be passed to a Fluid View)
*
* @return array the processed data as key/value store
*/
public function process(
ContentObjectRenderer $cObj,
array $contentObjectConfiguration,
array $processorConfiguration,
array $processedData
): array {
if (isset($processorConfiguration['if.']) && !$cObj->checkIf($processorConfiguration['if.'])) {
return $processedData;
}

$defaultQueryConfig = [
'pidInList' => (string)$cObj->stdWrapValue('pidInList', $processorConfiguration, 'root'),
'recursive' => (string)$cObj->stdWrapValue('recursive', $processorConfiguration, '0'),
'selectFields' => '{#sys_category}.{#uid} AS id, {#sys_category}.{#title}',
];
$queryConfig = [];

$uidInList = (string)$cObj->stdWrapValue('uidInList', $processorConfiguration, '');
if (!empty($uidInList)) {
$queryConfig = [
'uidInList' => $uidInList,
'languageField' => 0,
];
}

if (!empty($processorConfiguration['relation.'])) {
$referenceConfiguration = $processorConfiguration['relation.'];
$relationField = $cObj->stdWrapValue('fieldName', $referenceConfiguration ?? []);
if (!empty($relationField)) {
$relationTable = $cObj->stdWrapValue('table', $referenceConfiguration, $cObj->getCurrentTable());

if (!empty($relationTable)) {
$queryConfig = [
'join' => '{#sys_category_record_mm} on {#sys_category_record_mm}.{#uid_local} = {#sys_category}.{#uid}',
'where' => '({#sys_category_record_mm}.{#tablenames} = \'' . $relationTable . '\' AND {#sys_category_record_mm}.{#fieldname} = \'' . $relationField . '\' AND {#sys_category_record_mm}.{#uid_foreign}=' . $cObj->data['uid'] . ')',
];
}
}
}

if (empty($queryConfig) === true) {
return $processedData;
}

ArrayUtility::mergeRecursiveWithOverrule(
$queryConfig,
$defaultQueryConfig
);

$targetVariableName = $cObj->stdWrapValue('as', $processorConfiguration, 'categories');
$categories = $cObj->getRecords('sys_category', $queryConfig);

$processedRecordVariables = [];
foreach ($categories as $key => $category) {
$processedRecordVariables[$key] = ArrayUtility::filterRecursive($category, function ($key) {
return $key === 'id' || $key === 'title';
}, ARRAY_FILTER_USE_KEY);
}

$processedData[$targetVariableName] = $processedRecordVariables;

return $processedData;
}
}
2 changes: 2 additions & 0 deletions Configuration/Services.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use FriendsOfTYPO3\Headless\ContentObject\IntegerContentObject;
use FriendsOfTYPO3\Headless\ContentObject\JsonContentContentObject;
use FriendsOfTYPO3\Headless\ContentObject\JsonContentObject;
use FriendsOfTYPO3\Headless\DataProcessing\CategoriesProcessor;
use FriendsOfTYPO3\Headless\DataProcessing\DatabaseQueryProcessor;
use FriendsOfTYPO3\Headless\DataProcessing\FilesProcessor;
use FriendsOfTYPO3\Headless\DataProcessing\FlexFormProcessor;
Expand Down Expand Up @@ -120,6 +121,7 @@
GalleryProcessor::class => ['identifier' => 'headless-gallery', 'share' => false, 'public' => false],
DatabaseQueryProcessor::class => ['identifier' => 'headless-database-query', 'share' => false, 'public' => true],
FlexFormProcessor::class => ['identifier' => 'headless-flex-form', 'share' => false, 'public' => false],
CategoriesProcessor::class => ['identifier' => 'headless-categories', 'share' => false, 'public' => false],
] as $class => $processorConfig
) {
$service = $services->set($class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,16 @@ page {
}
}
meta =< lib.meta
categories =< lib.categories
categories = JSON
categories {
dataProcessing {
10 = headless-categories
10 {
relation.fieldName = categories
as = categories
}
}
}
breadcrumbs =< lib.breadcrumbs
appearance =< lib.pageAppearance
content =< lib.content
Expand Down
40 changes: 7 additions & 33 deletions Configuration/TypoScript/ContentElement/ContentElement.typoscript
Original file line number Diff line number Diff line change
Expand Up @@ -14,40 +14,14 @@ lib.contentElement {
colPos {
field = colPos
}
categories = COA
categories = JSON
categories {
10 = CONTENT
10 {
table = sys_category
select {
pidInList = root
selectFields = sys_category.title
join = sys_category_record_mm on sys_category_record_mm.uid_local = sys_category.uid
where {
field = uid
wrap = AND sys_category_record_mm.tablenames = 'tt_content' AND sys_category_record_mm.uid_foreign=|
}
}
renderObj = TEXT
renderObj {
field = title
wrap = |###BREAK###
}
}
stdWrap.split {
token = ###BREAK###
cObjNum = 1 |*|2|*| 3
1 {
current = 1
stdWrap.wrap = |
}
2 {
current = 1
stdWrap.wrap = ,|
}
3 {
current = 1
stdWrap.wrap = |
dataProcessing {
10 = headless-categories
10 {
relation.fieldName = categories

as = categories
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,9 @@ Used for processing flexforms.

### RootSitesProcessor
Render your all headless sites configuration for your frontend application.
### CategoriesProcessor
This processor returns an array of categories (`id` and `title`) by either a
relation record or a comma separated list of category uids

## Contributing
![Alt](https://repobeats.axiom.co/api/embed/197db91cad9195bb15a06c91fda5a215bff26cba.svg)
Expand Down
2 changes: 1 addition & 1 deletion Tests/Functional/ContentTypes/BaseContentTypeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public function setUp(): void
$this->importDataSet(__DIR__ . '/../Fixtures/content.xml');
}

protected function checkDefaultContentFields($contentElement, $id, $pid, $type, $colPos = 0, $categories = '')
protected function checkDefaultContentFields($contentElement, $id, $pid, $type, $colPos = 0, $categories = [])
{
self::assertEquals($id, $contentElement['id'], 'id mismatch');
self::assertEquals($type, $contentElement['type'], 'type mismatch');
Expand Down
7 changes: 6 additions & 1 deletion Tests/Functional/ContentTypes/ShortcutElementTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,12 @@ public function testShortcutContentElement()
self::assertFalse(isset($contentElement['content']['shortcut'][0]['bodytext']));

// element at pos 1 is our TextElement
$this->checkDefaultContentFields($contentElement['content']['shortcut'][1], 1, 1, 'text', 0, 'SysCategory1Title,SysCategory2Title');
$categories = [
['id' => 1, 'title' => 'SysCategory1Title'],
['id' => 2, 'title' => 'SysCategory2Title'],
];

$this->checkDefaultContentFields($contentElement['content']['shortcut'][1], 1, 1, 'text', 0, $categories);
$this->checkAppearanceFields($contentElement['content']['shortcut'][1], 'layout-1', 'Frame', 'SpaceBefore', 'SpaceAfter');
$this->checkHeaderFields($contentElement['content']['shortcut'][1], 'Header', 'SubHeader', 1, 2);
$this->checkHeaderFieldsLink($contentElement['content']['shortcut'][1], 'Page 1', '/page1?parameter=999&cHash=', '_blank');
Expand Down
6 changes: 5 additions & 1 deletion Tests/Functional/ContentTypes/TextElementTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,12 @@ public function testTextContentElement()
$fullTree = json_decode((string)$response->getBody(), true);

$contentElement = $fullTree['content']['colPos0'][0];
$categories = [
['id' => 1, 'title' => 'SysCategory1Title'],
['id' => 2, 'title' => 'SysCategory2Title'],
];

$this->checkDefaultContentFields($contentElement, 1, 1, 'text', 0, 'SysCategory1Title,SysCategory2Title');
$this->checkDefaultContentFields($contentElement, 1, 1, 'text', 0, $categories);
$this->checkAppearanceFields($contentElement, 'layout-1', 'Frame', 'SpaceBefore', 'SpaceAfter');
$this->checkHeaderFields($contentElement, 'Header', 'SubHeader', 1, 2);
$this->checkHeaderFieldsLink($contentElement, 'Page 1', '/page1?parameter=999&cHash=', '_blank');
Expand Down
Loading