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

[ThemeBundle] introduce theme inheritance #1353

Merged
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,51 @@ public function getConfigTreeBuilder()
->booleanNode('pimcore_site')->defaultFalse()->end()
->booleanNode('pimcore_document_property')->defaultFalse()->end()
->end()
->end()
->arrayNode('inheritance')
->normalizeKeys(false)
->useAttributeAsKey('theme_name')
->beforeNormalization()
->always()
->then(function ($config) {
if (!\is_array($config)) {
return [];
}
// If XML config with only one routing attribute
if (2 === \count($config) && isset($config['theme_name']) && isset($config['parent_themes'])) {
$config = [0 => $config];
}

$newConfig = [];
foreach ($config as $k => $v) {
if (!\is_int($k)) {
$newConfig[$k] = [
'parent_themes' => $v['parent_themes'] ?? (\is_array($v) ? array_values($v) : [$v]),
];
} else {
$newConfig[$v['theme_name']]['parent_themes'] = array_map(
function ($a) {
return \is_string($a) ? $a : $a['service'];
},
array_values($v['parent_themes'])
);
}
}

return $newConfig;
})
->end()
->prototype('array')
->performNoDeepMerging()
->children()
->arrayNode('parent_themes')
->requiresAtLeastOneElement()
->prototype('scalar')->end()
->end()
->end()
->end()
->end()
->end()
->end();

return $treeBuilder;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@
namespace CoreShop\Bundle\ThemeBundle\DependencyInjection;

use CoreShop\Bundle\ThemeBundle\DependencyInjection\Compiler\CompositeThemeResolverPass;
use CoreShop\Bundle\ThemeBundle\Service\InheritanceLocator;
use CoreShop\Bundle\ThemeBundle\Service\PimcoreDocumentPropertyResolver;
use CoreShop\Bundle\ThemeBundle\Service\PimcoreSiteThemeResolver;
use CoreShop\Bundle\ThemeBundle\Service\ThemeResolverInterface;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class CoreShopThemeExtension extends Extension
Expand All @@ -41,6 +44,23 @@ public function load(array $configs, ContainerBuilder $container)
$container->removeDefinition(PimcoreDocumentPropertyResolver::class);
}

if (isset($config['inheritance']) && count($config['inheritance']) > 0) {
$container->setParameter('coreshop.theme_bundle.inheritance', $config['inheritance']);

$inheritanceLocator = new Definition(InheritanceLocator::class);
$inheritanceLocator->setArguments([
new Reference('kernel'),
new Reference('liip_theme.active_theme'),
'%kernel.root_dir%/Resources',
[],
'%liip_theme.path_patterns%',
'%coreshop.theme_bundle.inheritance%'
]);
$inheritanceLocator->setDecoratedService('liip_theme.file_locator');

$container->setDefinition(InheritanceLocator::class, $inheritanceLocator);
}

$container
->registerForAutoconfiguration(ThemeResolverInterface::class)
->addTag(CompositeThemeResolverPass::THEME_RESOLVER_TAG);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php
/**
* CoreShop.
*
* This source file is subject to the GNU General Public License version 3 (GPLv3)
* For the full copyright and license information, please view the LICENSE.md and gpl-3.0.txt
* files that are distributed with this source code.
*
* @copyright Copyright (c) 2015-2020 Dominik Pfaffenbauer (https://www.pfaffenbauer.at)
* @license https://www.coreshop.org/license GNU General Public License version 3 (GPLv3)
*/

namespace CoreShop\Bundle\ThemeBundle\Exception;

class CircularDependencyFoundException extends \Exception
{
/**
* @param string[] $themes
* @param \Exception $previous
*/
public function __construct(array $themes, ?\Exception $previous = null)
{
$cycle = $this->getCycleFromArray($themes);

$message = sprintf(
'Circular dependency was found while resolving theme "%s", caused by cycle "%s".',
$this->getFirstTheme($themes),
$this->formatCycleToString($cycle)
);

parent::__construct($message, 0, $previous);
}

private function getCycleFromArray(array $themes)
{
while (reset($themes) !== end($themes) || 1 === count($themes)) {
array_shift($themes);
}

if (0 === count($themes)) {
throw new \InvalidArgumentException('There is no cycle within given themes.');
}

return $themes;
}

private function formatCycleToString(array $themes)
{
return implode(' -> ', $themes);
}

/**
* @param string[] $themes
*/
private function getFirstTheme(array $themes)
{
return reset($themes);
}
}
115 changes: 115 additions & 0 deletions src/CoreShop/Bundle/ThemeBundle/Service/InheritanceLocator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
<?php
/**
* CoreShop.
*
* This source file is subject to the GNU General Public License version 3 (GPLv3)
* For the full copyright and license information, please view the LICENSE.md and gpl-3.0.txt
* files that are distributed with this source code.
*
* @copyright Copyright (c) 2015-2020 Dominik Pfaffenbauer (https://www.pfaffenbauer.at)
* @license https://www.coreshop.org/license GNU General Public License version 3 (GPLv3)
*/

namespace CoreShop\Bundle\ThemeBundle\Service;

use Liip\ThemeBundle\ActiveTheme;
use Liip\ThemeBundle\Locator\FileLocator;
use Sylius\Bundle\ThemeBundle\Loader\CircularDependencyFoundException;
use Sylius\Bundle\ThemeBundle\Model\ThemeInterface;
use Symfony\Component\HttpKernel\KernelInterface;

class InheritanceLocator extends FileLocator
{
protected $kernel;
protected $path;
protected $basePaths = array();
protected $pathPatterns;
protected $activeTheme;
protected $lastTheme;
protected $inheritance;

public function __construct(
KernelInterface $kernel,
ActiveTheme $activeTheme,
$path = null,
array $paths = array(),
array $pathPatterns = array(),
array $inheritance = []
) {
parent::__construct($kernel, $activeTheme, $path, $paths, $pathPatterns);

$this->inheritance = $inheritance;
}

protected function getPathsForBundleResource($parameters)
{
$paths = array();
$hierarchy = $this->resolveHierarchy();

foreach ($hierarchy as $theme) {
$parameters['%current_theme%'] = $theme;

$paths[] = strtr('%bundle_path%/Resources/themes/%current_theme%/%template%', $parameters);

if (!empty($parameters['%dir%'])) {
$paths[] = strtr('%dir%/themes/%current_theme%/%bundle_name%/%template%', $parameters);
}
}

return array_merge($paths, parent::getPathsForBundleResource($parameters));
}

protected function getPathsForAppResource($parameters)
{
$paths = array();
$hierarchy = $this->resolveHierarchy();

foreach ($hierarchy as $theme) {
$parameters['%current_theme%'] = $theme;

$paths[] = strtr("%app_path%/themes/%current_theme%/%template%", $parameters);
}

return array_merge($paths, parent::getPathsForAppResource($parameters));
}

protected function resolveHierarchy()
{
$this->checkCircularDependency($this->lastTheme);

return $this->getThemeHierarchy($this->lastTheme);
}

protected function getThemeHierarchy(string $theme): array
{
$parents = [];
$inheritance = isset($this->inheritance[$theme]) ? $this->inheritance[$theme]['parent_themes'] : [];

foreach ($inheritance as $parent) {
$parents = array_merge(
$parents,
$this->getThemeHierarchy($parent)
);
}

return array_merge([$theme], $parents);
}

protected function checkCircularDependency(string $theme, array $previousThemes = []): void
{
$inheritance = isset($this->inheritance[$theme]) ? $this->inheritance[$theme]['parent_themes'] : [];

if (0 === count($inheritance)) {
return;
}

$previousThemes[] = $theme;
foreach ($inheritance as $parent) {
if (in_array($parent, $previousThemes, true)) {
throw new \CoreShop\Bundle\ThemeBundle\Exception\CircularDependencyFoundException(array_merge($previousThemes, [$parent]));
}

$this->checkCircularDependency($parent, $previousThemes);
}
}
}