first commit

This commit is contained in:
Roman Pyrih
2023-07-24 08:30:51 +02:00
commit c2e100a763
7128 changed files with 1622619 additions and 0 deletions

View File

@@ -0,0 +1,325 @@
<?php
namespace BrizyMerge;
use BrizyMerge\Assets\Asset;
use BrizyMerge\Assets\AssetFont;
use BrizyMerge\Assets\AssetGroup;
use BrizyMerge\Assets\AssetLib;
class AssetAggregator
{
const FONT_TYPE_GOOGLE = 'google-font';
const FONT_TYPE_UPLOADED = 'uploaded-font';
/**
* @var AssetGroup[] $groups ;
*/
private $groups;
/**
* AssetAggregator constructor.
*
* @param $assets
*/
public function __construct($assets = [])
{
$this->groups = $assets;
}
/**
* @param $group
*/
public function addAssetGroup(AssetGroup $group)
{
$this->groups[] = $group;
}
/**
* @param AssetGroup[] $groups
*/
public function setAssetGroups($groups)
{
$this->groups[] = $groups;
}
/**
* This will return a list of assets ready to be included in page
*
* @return Asset[]
*/
public function getAssetList()
{
$assets = $this->getAggregatedAssets($this->groups);
list($freeLibMap, $proLibMap) = $this->getLibMaps($this->groups);
$assets = $this->normalizeAssets($assets, $freeLibMap, $proLibMap);
return $this->sortAssets($assets);
}
private function getLibMaps($groups)
{
$pro = null;
$free = null;
foreach ($groups as $group) {
/**
* @var AssetGroup $group ;
*/
if ($group->getMain() && $group->getMain()->isPro()) {
$pro = $group->getLibsMap();
} else {
$free = $group->getLibsMap();
}
if ($pro && $free) {
return [$free, $pro];
}
}
return [$free, $pro];
}
private function getAggregatedAssets($groups)
{
$assets = [];
$mainAsset = null;
foreach ($groups as $group) {
/**
* @var AssetGroup $group ;
*/
// set main asset and override if there are pro main assets
if ( ! $mainAsset || $group->getMain()->isPro()) {
$mainAsset = $group->getMain();
}
foreach ($group->getGeneric() as $asset) {
$assets[] = $asset;
}
foreach ($group->getPageFonts() as $font) {
$assets[] = $font;
}
foreach ($group->getPageStyles() as $style) {
$assets[] = $style;
}
$selectors = $group->getLibsSelectors();
$selectorsCount = count($selectors);
if ($selectorsCount != 0) {
$selectedLib = array_reduce(
$group->getLibsMap(),
function ($lib, $alib) use ($selectors, $selectorsCount) {
if ($lib) {
return $lib;
}
return count(
array_intersect($alib->getSelectors(), $selectors)
) == $selectorsCount ? $alib : null;
}
);
if ($selectedLib) {
$assets[] = $selectedLib;
}
}
$assets = array_filter(
$assets,
function ($a) {
return ! is_null($a);
}
);
}
// include main asset
if ($mainAsset) {
$assets[] = $mainAsset;
}
return $assets;
}
private function normalizeAssets($assets, $freeLibMap, $proLibMap)
{
// remove duplicates
$duplicateKeys = [];
$tmp = [];
foreach ($assets as $key => $val) {
if ( ! in_array($val, $tmp)) {
$tmp[] = $val;
} else {
$duplicateKeys[] = $key;
}
}
foreach ($duplicateKeys as $key) {
unset($assets[$key]);
}
// find libs and check if cannot be replace with a bigger lib to save requests
$freeLibsFoundKeys = [];
$freeLibsSelectorsFound = [];
$proLibsFoundKeys = [];
$proLibsSelectorsFound = [];
foreach ($assets as $key => $lib) {
if ($lib instanceof AssetLib && ! $lib->isPro()) {
$freeLibsFoundKeys[] = $key;
$freeLibsSelectorsFound = array_merge($freeLibsSelectorsFound, $lib->getSelectors());
}
if ($lib instanceof AssetLib && $lib->isPro()) {
$proLibsFoundKeys[] = $key;
$proLibsSelectorsFound = array_merge($proLibsSelectorsFound, $lib->getSelectors());
}
}
$assets = $this->groupLibs($assets, $freeLibMap, $freeLibsSelectorsFound, $freeLibsFoundKeys);
$assets = $this->groupLibs($assets, $proLibMap, $proLibsSelectorsFound, $proLibsFoundKeys);
$assets = $this->groupGoogleFonts($assets);
$assets = $this->groupUploadedFonts($assets);
return array_values($assets);
}
private function groupLibs($assets, $libMap, $selectorsFound, $foundLibPositions)
{
if (count($foundLibPositions) != 0) {
// try to find a lib containing all found selectors
$libsSelectorsFound = array_unique($selectorsFound);
$libsSelectorsFoundCount = count($libsSelectorsFound);
foreach ($libMap as $alib) {
if (count(array_intersect($alib->getSelectors(), $libsSelectorsFound)) == $libsSelectorsFoundCount) {
foreach ($foundLibPositions as $key) {
unset($assets[$key]);
}
$assets[] = $alib;
break;
}
}
}
return $assets;
}
private function groupGoogleFonts($assets)
{
return $this->groupFonts(
$assets,
self::FONT_TYPE_GOOGLE,
"/\?family=(.*?)(&|\")/",
function ($value,$matchTermination) {
return "?family={$value}{$matchTermination}";
}
);
}
private function groupUploadedFonts($assets)
{
return $this->groupFonts(
$assets,
self::FONT_TYPE_UPLOADED,
"/-font=(.*?)(&|\"|$)/",
function ($value,$matchTermination) {
return "-font={$value}{$matchTermination}";
}
);
}
private function groupFonts($assets, $fontType, $extractRegex, $replaceRegex)
{
// extract google fonts
$fonts = [];
$sampleFont = null;
$matchTermination = "";
foreach ($assets as $i => $asset) {
/**
* @var AssetFont $asset ;
*/
if ($asset instanceof AssetFont && $asset->getFontType() === $fontType) {
// obtain a font copy
if ( ! $sampleFont) {
$sampleFont = $asset;
}
$matches = [];
preg_match($extractRegex, $asset->getContentByType(), $matches);
if (isset($matches[1]) ) {
$fontString = urldecode($matches[1]);
$fontSets = explode('|', $fontString);
foreach ($fontSets as $set) {
list($family, $weights) = explode(':', $set);
$weights = explode(',', $weights);
if ( ! isset($fonts[$family])) {
$fonts[$family] = [];
}
$fonts[$family] = array_merge($fonts[$family], $weights);
}
}
unset($assets[$i]);
if(isset($matches[2]))
{
$matchTermination = $matches[2];
}
}
}
// generate font query value
if ( ! $sampleFont) {
return $assets;
}
$f = [];
foreach ($fonts as $family => $weight) {
$weight = array_unique($weight);
$f[] = $family.':'.implode(',', $weight);
}
$fontQueryValue = implode('|', $f);
$replaceValue = $replaceRegex($fontQueryValue, $matchTermination);
$sampleFont->setUrl(
preg_replace($extractRegex, $replaceValue, $sampleFont->getUrl())
);
$assets[] = $sampleFont;
return array_values($assets);
}
private function sortAssets($assets)
{
// sort asset list by score
usort(
$assets,
function ($as1, $as2) {
if ($as1->getScore() === $as2->getScore()) {
return 0;
}
return ($as1->getScore() < $as2->getScore()) ? -1 : 1;
}
);
return $assets;
}
}

View File

@@ -0,0 +1,227 @@
<?php
namespace BrizyMerge\Assets;
class Asset
{
const TYPE_INLINE = 'inline';
const TYPE_CODE = 'code';
const TYPE_FILE = 'file';
/**
* @var string
*/
protected $name;
/**
* @var int
*/
protected $score;
/**
* @var string
*/
protected $type;
/**
* @var string
*/
protected $content;
/**
* @var string
*/
protected $url;
/**
* @var string[]
*/
protected $attrs;
/**
* @var bool
*/
protected $pro;
/**
* @param $data
*/
static function instanceFromJsonData($data)
{
$assetKeys = array_keys($data);
$allowedKeys = ['name', 'score', 'content', 'pro'];
if (count($keyDiff = array_diff($assetKeys, $allowedKeys)) !== 0) {
throw new \Exception('Invalid Asset fields provided: ' . json_encode($keyDiff));
}
if (count($keyDiff = array_diff($allowedKeys, $assetKeys)) !== 0) {
throw new \Exception('Missing Asset field: ' . json_encode($keyDiff));
}
return new self(
$data['name'],
$data['score'],
isset($data['content']['content']) ? $data['content']['content'] : null,
isset($data['content']['url']) ? $data['content']['url'] : null,
isset($data['content']['type']) ? $data['content']['type'] : null,
isset($data['content']['attr']) ? $data['content']['attr'] : [],
$data['pro']
);
}
/**
* Asset constructor.
*
* @param string $name
* @param int $score
* @param string $content
* @param false $pro
*/
public function __construct($name = '', $score = 0, $content = null, $url = '', $type = '', $attrs = [], $pro = false)
{
$this->name = $name;
$this->score = (int)$score;
$this->type = $type;
$this->content = $content;
$this->url = $url;
$this->attrs = $attrs;
$this->pro = $pro;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
*
* @return Asset
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @return int
*/
public function getScore()
{
return (int)$this->score;
}
/**
* @param int $score
*
* @return Asset
*/
public function setScore($score)
{
$this->score = (int)$score;
return $this;
}
/**
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* @param string $content
*
* @return Asset
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* @return bool
*/
public function isPro()
{
return $this->pro;
}
/**
* @param bool $pro
*
* @return Asset
*/
public function setPro($pro)
{
$this->pro = $pro;
return $this;
}
/**
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* @param string $type
* @return Asset
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* @return string
*/
public function getUrl()
{
return $this->url;
}
/**
* @param string $url
* @return Asset
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* @return string[]
*/
public function getAttrs()
{
return $this->attrs;
}
/**
* @param string[] $attrs
* @return Asset
*/
public function setAttrs($attrs)
{
$this->attrs = $attrs;
return $this;
}
}

View File

@@ -0,0 +1,89 @@
<?php
namespace BrizyMerge\Assets;
class AssetFont extends Asset
{
/**
* @var string
*/
protected $fontType;
/**
* @param $data
*/
static function instanceFromJsonData($data)
{
$assetKeys = array_keys($data);
$allowedKeys = ['name', 'score', 'content', 'pro', 'type'];
if (count($keyDiff = array_diff($assetKeys, $allowedKeys)) !== 0) {
throw new \Exception('Invalid AssetFont fields provided: ' . json_encode($keyDiff));
}
if (count($keyDiff = array_diff($allowedKeys, $assetKeys)) !== 0) {
throw new \Exception('Missing AssetFont field: ' . json_encode($keyDiff));
}
return new self($data['name'],
$data['score'],
isset($data['content']['content']) ? $data['content']['content'] : '',
isset($data['content']['url']) ? $data['content']['url'] : '',
isset($data['content']['type']) ? $data['content']['type'] : '',
isset($data['content']['attr']) ? $data['content']['attr'] : [],
$data['pro'],
$data['type']);
}
/**
* AssetLib constructor.
*
* @param string $name
* @param int $score
* @param string $content
* @param false $pro
* @param array $selectors
*/
public function __construct($name = '', $score = 0, $content = '', $url = '', $assetType = '', $attrs = [], $pro = false, $fontType = [])
{
parent::__construct($name, $score, $content, $url, $assetType, $attrs, $pro);
$this->fontType = $fontType;
}
/**
* @return string
*/
public function getFontType()
{
return $this->fontType;
}
/**
* @param string $type
*
* @return AssetFont
*/
public function setFontType($type)
{
$this->fontType = $type;
return $this;
}
/**
* @return string
*/
public function getContentByType()
{
switch ($this->getType()) {
case self::TYPE_INLINE:
case self::TYPE_CODE:
return $this->getContent();
case self::TYPE_FILE:
return $this->getUrl();
}
}
}

View File

@@ -0,0 +1,242 @@
<?php
namespace BrizyMerge\Assets;
class AssetGroup
{
/**
* @var Asset
*/
private $main;
/**
* @var Asset[]
*/
private $generic;
/**
* @var AssetLib[]
*/
private $libsMap;
/**
* @var string[]
*/
private $libsSelectors;
/**
* @var AssetFont[]
*/
private $pageFonts;
/**
* @var Asset
*/
private $pageStyles;
/**
* @param $data
*/
static function instanceFromJsonData($data)
{
$assetKeys = array_keys($data);
$allowedKeys = ['main', 'generic', 'libsMap', 'libsSelectors'];
if ($keyDiff = array_diff($assetKeys, $allowedKeys)) {
if ($keyDiff2 = array_diff(['pageFonts', 'pageStyles'], $keyDiff)) {
if (count($keyDiff2) != 0) {
throw new \Exception('Invalid AssetGroup fields provided: '.json_encode($keyDiff2));
}
}
}
// create main assets
$main = Asset::instanceFromJsonData($data['main']);
// create generic assets
$generic = [];
foreach ($data['generic'] as $entry) {
$generic[] = Asset::instanceFromJsonData($entry);
}
// create libsMap assets
$libsMap = [];
foreach ($data['libsMap'] as $entry) {
$libsMap[] = AssetLib::instanceFromJsonData($entry);
}
// create libsSelectors assets
$libsSelectors = [];
foreach ($data['libsSelectors'] as $entry) {
$libsSelectors[] = (string)$entry;
}
// create pageFonts assets
$pageFonts = [];
if (isset($data['pageFonts'])) {
foreach ($data['pageFonts'] as $entry) {
$pageFonts[] = AssetFont::instanceFromJsonData($entry);
}
}
// create pageStyles assets
$pageStyles = [];
if (isset($data['pageStyles'])) {
foreach ($data['pageStyles'] as $entry) {
$pageStyles[] = Asset::instanceFromJsonData($entry);
}
}
return new self($main, $generic, $libsMap, $libsSelectors, $pageFonts, $pageStyles);
}
/**
* AssetGroup constructor.
*
* @param array $main
* @param array $generic
* @param array $libsMap
* @param array $libsSelectors
* @param array $pageFonts
* @param array $pageStyles
*/
public function __construct(
$main = null,
$generic = [],
$libsMap = [],
$libsSelectors = [],
$pageFonts = [],
$pageStyles = []
) {
$this->main = $main;
$this->generic = $generic;
$this->libsMap = $libsMap;
$this->libsSelectors = $libsSelectors;
$this->pageFonts = $pageFonts;
$this->pageStyles = $pageStyles;
}
/**
* @return Asset[]
*/
public function getMain()
{
return $this->main;
}
/**
* @param Asset[] $main
*
* @return AssetGroup
*/
public function setMain($main)
{
$this->main = $main;
return $this;
}
/**
* @return Asset[]
*/
public function getGeneric()
{
return $this->generic;
}
/**
* @param Asset[] $generic
*
* @return AssetGroup
*/
public function setGeneric($generic)
{
$this->generic = $generic;
return $this;
}
/**
* @return AssetLib[]
*/
public function getLibsMap()
{
return $this->libsMap;
}
/**
* @param AssetLib[] $libsMap
*
* @return AssetGroup
*/
public function setLibsMap($libsMap)
{
$this->libsMap = $libsMap;
return $this;
}
/**
* @return string[]
*/
public function getLibsSelectors()
{
return $this->libsSelectors;
}
/**
* @param string[] $libsSelectors
*
* @return AssetGroup
*/
public function setLibsSelectors($libsSelectors)
{
$this->libsSelectors = $libsSelectors;
return $this;
}
/**
* @return AssetFont[]
*/
public function getPageFonts()
{
return $this->pageFonts;
}
/**
* @param AssetFont[] $pageFonts
*
* @return AssetGroup
*/
public function setPageFonts($pageFonts)
{
$this->pageFonts = $pageFonts;
return $this;
}
/**
* @return Asset
*/
public function getPageStyles()
{
return $this->pageStyles;
}
/**
* @param Asset $pageStyles
*
* @return AssetGroup
*/
public function setPageStyles($pageStyles)
{
$this->pageStyles = $pageStyles;
return $this;
}
}

View File

@@ -0,0 +1,78 @@
<?php
namespace BrizyMerge\Assets;
class AssetLib extends Asset
{
/**
* @var string[]
*/
protected $selectors;
/**
* @param $data
*/
static function instanceFromJsonData($data)
{
$assetKeys = array_keys($data);
$allowedKeys = ['name', 'score', 'content', 'pro', 'selectors'];
if (count($keyDiff = array_diff($assetKeys, $allowedKeys)) !== 0) {
throw new \Exception('Invalid AssetLib fields provided: ' . json_encode($keyDiff));
}
if (count($keyDiff = array_diff($allowedKeys, $assetKeys)) !== 0) {
throw new \Exception('Missing AssetLib field: ' . json_encode($keyDiff));
}
return new self(
$data['name'],
$data['score'],
isset($data['content']['content'])?$data['content']['content']:'',
isset($data['content']['url'])?$data['content']['url']:'',
isset($data['content']['type'])?$data['content']['type']:'',
isset($data['content']['attr'])?$data['content']['attr']:[],
$data['pro'],
$data['selectors']);
}
/**
* AssetLib constructor.
*
* @param string $name
* @param int $score
* @param string $content
* @param false $pro
* @param array $selectors
*/
public function __construct($name = '', $score = 0, $content = null, $url = '', $type = '', $attrs = [], $pro = false, $selectors = [])
{
parent::__construct($name, $score, $content, $url, $type, $attrs, $pro);
$this->selectors = $selectors;
}
/**
* @return string[]
*/
public function getSelectors()
{
return $this->selectors;
}
/**
* @param string[] $selectors
*
* @return AssetLib
*/
public function setSelectors($selectors)
{
$this->selectors = $selectors;
return $this;
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace BrizyMerge;
interface CompiledPageAssetsInterface
{
public function getHeadAssetList();
public function getBodyAssetList();
public function getHeadAssetAsHtml();
public function getBodyAssetAsHtml();
}

View File

@@ -0,0 +1,47 @@
<?php
namespace Brizy;
class BlockScreenshotContext extends Context {
/**
* @var object
*/
private $meta;
/**
* BlockScreenshotContext constructor.
*
* @param $data
*/
public function __construct( $data ) {
if(!is_object($data))
throw new \Exception('Invalid argument type. Object expected.');
parent::__construct( $data );
}
/**
* @return object
*/
public function getMeta() {
return $this->meta;
}
/**
* @param object $meta
*
* @return BlockScreenshotContext
*/
public function setMeta( $meta ) {
if(!is_object($meta))
throw new \Exception('Invalid argument type. Object expected.');
$this->meta = $meta;
return $this;
}
}

View File

@@ -0,0 +1,75 @@
<?php
namespace Brizy;
/**
* Class DataToProjectTransformer
* @package Brizy
*/
class BlockScreenshotTransformer implements DataTransformerInterface {
/**
* @param ContextInterface $context
*
* @return mixed
* @throws \Exception
*/
public function execute( ContextInterface $context ) {
/**
* @var BlockScreenshotContext $context ;
*/
$data = $context->getData();
$context->setMeta( $this->generateMeta( $data ) );
}
/**
* @param $block
*
* @return object
* @throws \Exception
*/
private function makeScreenshotAndType( $block ) {
return (object) [
"type" => $this->makeBlockType( $block ),
"_thumbnailSrc" => isset( $block->value->_thumbnailSrc ) ? $block->value->_thumbnailSrc : null,
"_thumbnailWidth" => isset( $block->value->_thumbnailWidth ) ? $block->value->_thumbnailWidth : null,
"_thumbnailHeight" => isset( $block->value->_thumbnailHeight ) ? $block->value->_thumbnailHeight : null,
"_thumbnailTime" => isset( $block->value->_thumbnailTime ) ? $block->value->_thumbnailTime : null
];
}
/**
* @param $blockData
*
* @return string
* @throws \Exception
*/
private function makeBlockType( $blockData ) {
if ( ! isset( $blockData->type ) ) {
throw new \Exception();
}
$type = $blockData->type;
if ( $type === "SectionPopup" || $type === "SectionPopup2" ) {
return "popup";
}
return "normal";
}
private function generateMeta( $data ) {
if ( ! is_object( $data ) || ! isset( $data->value ) ) {
throw new \Exception();
}
try {
return $this->makeScreenshotAndType( $data );
} catch ( \Exception $e ) {
throw new \Exception( $e );
}
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Brizy;
class ConditionsContext extends Context {
/**
* @var array
*/
private $globalBlocks;
/**
* @var array
*/
private $config;
/**
* @return array
*/
public function getGlobalBlocks() {
return $this->globalBlocks;
}
/**
* @param array $globalBlocks
*
* @return ConditionsContext
*/
public function setGlobalBlocks( $globalBlocks ) {
$this->globalBlocks = $globalBlocks;
return $this;
}
/**
* @return array
*/
public function getConfig() {
return $this->config;
}
/**
* @param array $config
*
* @return ConditionsContext
*/
public function setConfig( $config ) {
$this->config = $config;
return $this;
}
}

View File

@@ -0,0 +1,248 @@
<?php
namespace Brizy;
use stdClass;
/**
* Class ConditionsTransformer
* @package Brizy
*/
class ConditionsTransformer implements DataTransformerInterface {
/**
* @param ConditionsContext $context
*
* @return TransformerContext|mixed
*/
public function execute( ContextInterface $context ) {
//$this->page = json_decode($context->getData());
//$this->globalBlocks = json_decode($context->getGlobalBlocks());
//$this->options = json_decode($context->getConfig());
$this->transformPageData( $context );
$this->getGlobalBlocks( $context );
return $context;
}
// public function getMigratedData()
// {
// $newPage = $this->getPage();
// $newGlobalBlocks = $this->getGlobalBlocks();
// }
/**
* @param ConditionsContext $context
*
* @return mixed
*/
private function transformPageData( ConditionsContext $context ) {
$blocks = $context->getData()->items;
$surroundedBlocks = $this->getSurroundedIds( $blocks );
$newBlocks = array_reduce(
$blocks,
function ( $acc, $block ) use ( $surroundedBlocks ) {
$isTopCondition =
$this->isConditionBlock( $block ) &&
isset( $surroundedBlocks['top'] ) && in_array( $block->value->globalBlockId, $surroundedBlocks['top'] );
$isBottomCondition =
$this->isConditionBlock( $block ) &&
isset( $surroundedBlocks['bottom'] ) && in_array( $block->value->globalBlockId, $surroundedBlocks['bottom'] );
if ( ! $isTopCondition && ! $isBottomCondition ) {
array_push( $acc, $block );
}
return $acc;
},
[]
);
$context->getData()->items = $newBlocks;
return $context;
}
/**
* @param ConditionsContext $context
*
* @return ConditionsContext
*/
private function getGlobalBlocks( ConditionsContext $context ) {
$sortedGlobalBlocks = $context->getGlobalBlocks();
uasort( $sortedGlobalBlocks, function ( $a, $b ) {
if ( ! isset( $a->position ) && ! isset( $b->position ) ) {
return 0;
} elseif (
isset( $b->position ) &&
( ! isset( $a->position ) || $b->position->index < $a->position->index )
) {
return 1;
} else {
return - 1;
}
} );
$context->setGlobalBlocks( $sortedGlobalBlocks );
$this->insertSurroundedGlobalBlocks( $context, "bottom" );
$this->insertSurroundedGlobalBlocks( $context, "top" );
return $context;
}
/**
* @param ConditionsContext $context
* @param $type
*
* @return ConditionsContext
*/
private function insertSurroundedGlobalBlocks( ConditionsContext $context, $type ) {
$globalBlocks = $context->getGlobalBlocks();
//$globalBlocksAsObject = Conditions::turnIntoObject( $this->globalBlocks );
$blocks = $context->getData()->items;
$surroundedBlocks = $this->getSurroundedIds( $blocks );
$prevGlobalBlock = null;
$surroundedBlocks = $surroundedBlocks[ $type ];
if ( $surroundedBlocks[0] ) {
$globalBlock = $globalBlocks[ $surroundedBlocks[0] ];
if ( isset( $globalBlock->position ) && $globalBlock->position->index > 0 ) {
$prevGlobalBlock = $globalBlocks[ $globalBlock->position->index ];
}
}
$newSortedBlocks = array_values(
array_filter( $globalBlocks, function ( $item ) use (
$surroundedBlocks
) {
return ! in_array( $item->uid, $surroundedBlocks );
} )
);
$topLength = $this->array_count( $globalBlocks, function ( $value ) {
return isset( $value->position ) && $value->position->align === "top";
} );
$insertIndex = $prevGlobalBlock
? array_search( $prevGlobalBlock, $newSortedBlocks )
: $topLength;
$surroundedGlobalBlocks = array();
$currentRule = $this->getCurrentRule( $context->getConfig() );
foreach ( $surroundedBlocks as $uid ) {
$newGlobalBlock = json_decode( json_encode( $globalBlocks[ $uid ] ) );
$newGlobalBlock->position = new stdClass();
$newGlobalBlock->position->align = $type;
if ( ! isset( $newGlobalBlock->rules ) ) {
$newGlobalBlock->rules = new stdClass();
$newGlobalBlock->rules = $currentRule;
}
$surroundedGlobalBlocks[ $uid ] = $newGlobalBlock;
//array_push( $surroundedGlobalBlocks, $newGlobalBlock );
}
array_splice( $newSortedBlocks, $insertIndex, 0, $surroundedGlobalBlocks );
$newGlobalBlocks = array();
$i = 0;
foreach ( $newSortedBlocks as $value ) {
if ( isset( $value->position ) ) {
$value->position->index = $i;
$i ++;
}
array_push( $newGlobalBlocks, $value );
}
$context->setGlobalBlocks( $newGlobalBlocks );
return $context;
}
/**
* @param $config
*
* @return stdClass
*/
private function getCurrentRule( $config ) {
$PAGES_GROUP_ID = 1;
$POST_GROUP_ID = 1;
// $CATEGORIES_GROUP_ID = 2;
$TEMPLATES_GROUP_ID = 16;
$PAGE_TYPE = "page";
$POST_TYPE = "post";
$TEMPLATE_TYPE = "brizy_template";
$page = $config->page;
$isTemplate = $config->isTemplate;
$ruleMatches = $config->ruleMatches;
$result = new stdClass();
$result->id = $page;
if ( $isTemplate ) {
$result->group = $TEMPLATES_GROUP_ID;
$result->type = $TEMPLATE_TYPE;
} elseif ( $ruleMatches[0]->entityType === $POST_TYPE ) {
$result->group = $POST_GROUP_ID;
$result->type = $POST_TYPE;
} else {
$result->group = $PAGES_GROUP_ID;
$result->type = $PAGE_TYPE;
}
return $result;
}
private function getSurroundedIds( $blocks ) {
$top = array();
$bottom = array();
if ( count( $blocks ) > 0 ) {
$i = 0;
while ( $i <= count( $blocks ) - 1 ) {
$currentBlock = $blocks[ $i ];
if ( $currentBlock->type === "GlobalBlock" ) {
array_push( $top, $currentBlock->value->globalBlockId );
} else {
break;
}
$i ++;
}
$i = 0;
while ( $i <= count( $blocks ) - 1 ) {
$currentBlock = $blocks[ count( $blocks ) - 1 - $i ];
if ( $currentBlock->type === "GlobalBlock" ) {
array_push( $bottom, $currentBlock->value->globalBlockId );
} else {
break;
}
$i ++;
}
}
return array( $top, $bottom );
}
private function isConditionBlock( $block ) {
return $block->type === "GlobalBlock";
}
private function array_count( $arr, $callback ) {
$i = 0;
foreach ( $arr as $value ) {
if ( $callback( $value ) ) {
$i ++;
}
}
return $i;
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace Brizy;
abstract class Context implements ContextInterface {
/**
* @var mixed
*/
protected $data;
/**
* Context constructor.
*
* @param mixed $data
*/
public function __construct( $data ) {
$this->data = $data;
}
/**
* @return mixed
*/
public function getData() {
return $this->data;
}
/**
* @param mixed $data
*
* @return Context
*/
public function setData( $data ) {
$this->data = $data;
return $this;
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace Brizy;
interface ContextInterface {
/**
* @return mixed
*/
public function getData();
/**
* @param mixed $data
*
* @return Context
*/
public function setData( $data );
}

View File

@@ -0,0 +1,45 @@
<?php
namespace Brizy;
class DataToProjectContext extends Context {
/**
* @var string
*/
private $buildPath;
/**
* DataToProjectContext constructor.
*
* @param $globals
* @param $buildPath
*/
public function __construct( $globals, $buildPath ) {
parent::__construct( $globals );
$this->buildPath = $buildPath;
}
/**
* @return string
*/
public function getBuildPath() {
return $this->buildPath;
}
/**
* @param string $buildPath
*
* @return DataToProjectContext
*/
public function setBuildPath( $buildPath ) {
$this->buildPath = $buildPath;
return $this;
}
}

View File

@@ -0,0 +1,269 @@
<?php
namespace Brizy;
use Brizy\Utils\UUId;
/**
* Class DataToProjectTransformer
* @package Brizy
*/
class DataToProjectTransformer implements DataTransformerInterface
{
/**
* @param DataToProjectContext $context
*
* @return mixed
*/
public function execute(ContextInterface $context)
{
$defaults = $this->getDefaults($context->getBuildPath());
$styles = $this->getStyles($context->getBuildPath());
$fonts = $this->getFonts($context->getBuildPath());
return $this->merge($context->getData(), $defaults, $styles, $fonts);
}
/**
* @param $buildPath
*
* @return array
*/
private function getStyles($buildPath)
{
$templates = json_decode(
file_get_contents(
$buildPath .
DIRECTORY_SEPARATOR . "templates" .
DIRECTORY_SEPARATOR . "meta.json"
)
);
$result = array();
foreach ($templates->templates as $template) {
foreach ($template->styles as $style) {
$result[] = $style;
}
}
return $result;
}
/**
* @param $buildPath
*
* @return array
*/
private function getFonts($buildPath)
{
$fonts = json_decode(
file_get_contents(
$buildPath .
DIRECTORY_SEPARATOR . "googleFonts.json"
)
);
$result = array();
foreach ($fonts->items as $font) {
$result[] = $font;
}
return $result;
}
private function getStyleId($id)
{
$keyValue = array(
"default" => "kldugntsakdckzxhreidncqvgunudghrcuzv",
"Advisors" => "hhvfadskiuddpumderkrpfierxemmnfkkbdb",
"AlpineLodge" => "gkvpzagrxxxncblrivcrklhuxqlxuocpvxoi",
"Architekt" => "rtaizkhcpyvnsklrpneezuxfjbhxcgapvwzq",
"BaseGround" => "cwqlmorbdzpfjgeijdsucmmynmnvjjnhizgf",
"BeachResort" => "ogxvoqhdgowojrgovjtvfmgbdmtkrvfhzvut",
"CarClinic" => "sfacrfbudlqbjsohlttpgfdlcmpupwatrsqj",
"College" => "rrjgcxrizanoftyyjtlkpvxgboxzarhkjfpb",
"Creed" => "icwfpvkhphypjweexsymjpmobcndrdzvhypd",
"Flavour" => "wsndowxcdsndojazydvziriiurijzxxupmud",
"Gourmet" => "djgycpkivxkotophosklpovakaeglaphgeso",
"Hitched" => "ijwyqvltsbwnwwdgvsqbgazaafovftffjkeb",
"Hope" => "stclcsngwfgigirslshihqvfoffcvnuwutdo",
"InShape" => "yvabgehbjleqzdcbssoauoyeipqnrcctgsgf",
"Keynote" => "lywkwvivqbnmvopnhknegxidxkdhuglechhj",
"KidQuest" => "chnsxxxqibdfampcesxktddfoaftzkllzrem",
"Lavish" => "ldvzefmtepfgwsfrturzebeffqgrjygmvbpa",
"Molino" => "gznajvmfejckfmmzuabtsggydvuwqzzabzig",
"Moves" => "kqvgvsnfwhkwjwguzvsizkzdnpstlketofio",
"Parlor" => "eciislkkeivlbyblfujrudusvhkihlqtdura",
"Philanthropy" => "lnvuquwgkncpurwstjtvnamvymqgncggdgxm",
"Quantum" => "hkauzpefyxheerdsojcrzoznghmxyqxnpcos",
"ReelStory" => "zbncnqgfqctenhdippnnagyiwqrkblqykqfw",
"Skypoint" => "yvkltrdrjkjbolyedrpsprhaffytnuntjboy",
"Startapp" => "gwjxyiigrnkerwoorkywtgsfnfetztugngxc",
"Swipe" => "adodkqfglmmsgiwlrikyelxfaprxuwoeoemg",
"Wellness" => "pbbrkumtobavljgjvoqybsljdwhturhulobp",
"Yoga" => "pkfsnabwzdaviiiitkjgxdfxlslqbcapagwd"
);
return $keyValue[$id];
}
/**
* @param $styles
* @param $id
*
* @return | null
*/
private function getStyle($styles, $id)
{
foreach ($styles as $style) {
if ($style && $style->id === $id) {
return $style;
}
}
return null;
}
/**
* @param $buildPath
*
* @return mixed
*/
private function getDefaults($buildPath)
{
return json_decode(
file_get_contents(
$buildPath .
DIRECTORY_SEPARATOR . "defaults.json"
)
);
}
/**
* @param $styles
* @return array
*/
private function addStyleFontType($styles)
{
$finalStyles = array();
foreach ($styles as $style) {
$style->fontFamilyType = "google";
$finalStyles[] = $style;
}
return $finalStyles;
}
/**
* @param $globals
* @param $default
* @param $styles
* @param $fonts
*
* @return mixed
*/
private function merge($globals, $default, $styles, $fonts)
{
$result = $default;
// Check if globals is object
if (!is_object($globals)) {
throw new \Exception();
}
// extraFont
if (isset($globals->extraFonts)) {
$extraFonts = $globals->extraFonts;
$finalFonts = array();
foreach ($extraFonts as $fontKey) {
foreach ($fonts as $font) {
$fontFamilyToKey = preg_replace('/\s+/', '_', strtolower($font->family));
if ($fontKey === $fontFamilyToKey) {
$font->brizyId = UUId::uuid();
$finalFonts[] = $font;
}
}
}
$result->fonts->google = (object)array('data' => $finalFonts);
unset($globals->extraFonts);
}
// selectedStyle
if (isset($globals->styles) && isset($globals->styles->_selected)) {
$result->selectedStyle = $this->getStyleId($globals->styles->_selected);
unset($globals->styles->_selected);
}
// copy defaultStyle
if (!isset($globals->styles)) {
$result->selectedStyle = $this->getStyleId("default");
}
// extraFontStyles
if (isset($globals->styles) && isset($globals->styles->_extraFontStyles)) {
$result->extraFontStyles = $this->addStyleFontType($globals->styles->_extraFontStyles);
unset($globals->styles->_extraFontStyles);
}
// styles
// styles -> copy default
if (isset($globals->styles) && isset($globals->styles->default)) {
foreach ($result->styles as $i => $style) {
// Copy in defaultStyle current styles
if ($style->id === $result->selectedStyle) {
$result->styles[$i]->colorPalette = $globals->styles->default->colorPalette;
$result->styles[$i]->fontStyles = $this->addStyleFontType($globals->styles->default->fontStyles);
}
}
unset($globals->styles->default);
}
// styles -> copy others
if (isset ($globals->styles)) {
foreach ($globals->styles as $id => $data) {
$styleId = $this->getStyleId($id);
$style = $this->getStyle($styles, $styleId);
if (!is_object($style)) {
continue;
}
$result->styles[] = (object)array(
"id" => $styleId,
"title" => $style->title,
"colorPalette" => $data->colorPalette,
"fontStyles" => $this->addStyleFontType($data->fontStyles),
);
}
}
// styles -> missing selected style data
$selected_style_data_present = false;
foreach ($result->styles as $style) {
if ($style->id === $result->selectedStyle) {
$selected_style_data_present = true;
}
}
if (!$selected_style_data_present) {
$selected_style = $this->getStyle($styles, $result->selectedStyle);
if (is_object($selected_style)) {
$result->styles[] = (object)array(
"id" => $selected_style->id,
"title" => $selected_style->title,
"colorPalette" => $selected_style->colorPalette,
"fontStyles" => $this->addStyleFontType($selected_style->fontStyles),
);
}
}
return $result;
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace Brizy;
/**
* Interface DataTransformerInterface
* @package Brizy
*/
interface DataTransformerInterface {
/**
* @param ContextInterface $context
*
* @return mixed
*/
public function execute( ContextInterface $context );
}

View File

@@ -0,0 +1,100 @@
<?php
namespace Brizy;
use Brizy\Utils\UUId;
/**
* Class DataToProjectTransformer
* @package Brizy
*/
class FixDataToProjectTransformer implements DataTransformerInterface
{
/**
* @param ContextInterface $context
*
* @return mixed
* @throws \Exception
*/
public function execute(ContextInterface $context)
{
$defaults = $this->getDefaults($context->getBuildPath());
return $this->merge($context->getData(), $defaults);
}
/**
* @param $buildPath
*
* @return mixed
*/
private function getDefaults($buildPath)
{
return json_decode(
file_get_contents(
$buildPath .
DIRECTORY_SEPARATOR . "defaults.json"
)
);
}
/**
* @param $globals
* @param $default
*
* @return mixed
* @throws \Exception
*/
private function merge($globals, $default)
{
// Check if globals is object
if (!is_object($globals)) {
throw new \Exception();
}
$project = clone $globals;
if (isset($project->styles) && isset($project->selectedStyle)) {
$styles = $project->styles;
$selectedStyle = $project->selectedStyle;
$existed = false;
foreach ($styles as $style) {
if ($style->id === $selectedStyle) {
$existed = true;
}
}
if (!$existed) {
$overpass = clone $styles[0];
$defaultStyle = $this->getStyle($default->styles, $selectedStyle);
if ($defaultStyle) {
// copy project colorPalette and fontStyles to defaultStyles
$defaultStyle->id = $selectedStyle;
$defaultStyle->colorPalette = $overpass->colorPalette;
$defaultStyle->fontStyles = $overpass->fontStyles;
$project->styles[0] = $defaultStyle;
$defaultOverpass = $this->getStyle($default->styles, $overpass->id);
array_splice($project->styles, 1, 0, array($defaultOverpass));
}
}
}
return $project;
}
private function getStyle($styles, $selectedStyle)
{
foreach ($styles as $style) {
if ($style->id === $selectedStyle) {
return $style;
}
}
return null;
}
}

View File

@@ -0,0 +1,10 @@
<?php
namespace Brizy;
class TransformerContext extends Context {
}

View File

@@ -0,0 +1,25 @@
<?php
namespace Brizy\Utils;
/**
* Trait UUIdAware
* @package Brizy
*/
class UUId {
/**
* @param int $n
*
* @return string
*/
static public function uuid( $n = 32 ) {
$randomString = '';
for ( $i = 0; $i < $n; $i ++ ) {
$randomString .= chr( rand( 97, 122 ) );
}
return $randomString;
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace BrizyPlaceholders;
abstract class AbstractPlaceholder implements PlaceholderInterface
{
/**
* It should return an unique identifier of the placeholder
*
* @return mixed
*/
public function getUid()
{
return md5(microtime() . mt_rand(0, 10000));
}
public function shouldFallbackValue($value, ContextInterface $context, ContentPlaceholder $placeholder)
{
return empty($value);
}
public function getFallbackValue(ContextInterface $context, ContentPlaceholder $placeholder)
{
$attributes = $placeholder->getAttributes();
return isset($attributes[PlaceholderInterface::FALLBACK_KEY]) ? $attributes[PlaceholderInterface::FALLBACK_KEY] : '';
}
}

View File

@@ -0,0 +1,178 @@
<?php
namespace BrizyPlaceholders;
/**
* @internal
*
* Class ContentPlaceholder
*/
final class ContentPlaceholder
{
/**
* @var string
*/
protected $uid;
/**
* @var string
*/
protected $placeholder;
/**
* @var string
*/
protected $name;
/**
* @var []
*/
protected $attributes;
/**
* @var string
*/
protected $content;
/**
* @param $name
* @param $placeholder
* @param null $attributes
* @param null $content
*/
public function __construct($name, $placeholder, $attributes = null, $content = null)
{
$this->setUid(md5(microtime() . mt_rand(0, PHP_INT_MAX) . $placeholder));
$this->setPlaceholder($placeholder);
$this->setName($name);
$this->setAttributes($attributes);
$this->setContent($content);
}
/**
* @return null
* @throws \Exception
*/
public function getId() {
return $this->getAttribute( 'id' );
}
/**
* @return string
*/
public function getUid()
{
return $this->uid;
}
/**
* @param $uid
*
* @return $this
*/
public function setUid($uid)
{
$this->uid = $uid;
return $this;
}
/**
* @return string
*/
public function getPlaceholder()
{
return $this->placeholder;
}
/**
* @param $placeholder
*
* @return $this
*/
public function setPlaceholder($placeholder)
{
$this->placeholder = $placeholder;
return $this;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param $name
*
* @return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @return mixed
*/
public function getAttributes()
{
return $this->attributes;
}
/**
* @param $attributes
*
* @return $this
*/
public function setAttributes($attributes)
{
$this->attributes = $attributes;
return $this;
}
/**
* @param $name
*
* @return null
*/
public function getAttribute($name, $thowIfNotFound = false)
{
if (isset($this->attributes[$name])) {
return $this->attributes[$name];
}
if ($thowIfNotFound) {
throw new \Exception("The is not attribute '{$name}' set.");
}
return null;
}
/**
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* @param $content
*
* @return $this
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace BrizyPlaceholders;
interface ContextInterface
{
/**
* This will be called right after all placeholder are extracted from content
* @param $contentPlaceholders
* @param $instancePlaceholders
* @param $contentAfterExtractor
* @return mixed
*/
public function afterExtract($contentPlaceholders, $instancePlaceholders, $contentAfterExtractor);
}

View File

@@ -0,0 +1,9 @@
<?php
namespace BrizyPlaceholders;
final class EmptyContext implements ContextInterface
{
public function afterExtract($contentPlaceholders, $instancePlaceholders, $contentAfterExtractor) {
}
}

View File

@@ -0,0 +1,121 @@
<?php
namespace BrizyPlaceholders;
/**
* Class Extractor
*/
final class Extractor
{
//const PLACEHOLDER_REQEX = "/(?<placeholder>{{\s*(?<placeholderName>.+?)(?<attributes>(?:\s+)((?:\w+\s*=\s*(?:'|\"|\&quot;|\&apos;)(?:.[^\"']*|)(?:'|\"|\&quot;|\&apos;)\s*)*))?}}(?:(?<content>.*?){{\s*end_(\g{placeholderName})\s*}})?)/ims";
const PLACEHOLDER_REQEX = "/(?<placeholder>{{\s*(?<placeholderName>.+?)\s*(?<attributes>\s+((?:\w+(?:\[(?:\w+)?\])?\s*=\s*(?:'|\"|\&quot;|\&apos;|\&#x27;)(?:.[^\"']*?|)(?:'|\"|\&quot;|\&apos;|\&#x27;)\s*)*))?}}(?:(?<content>.*?){{\s*end_(\g{placeholderName})\s*}})?)/ims";
const ATTRIBUTE_REGEX = "/((?<attr_name>\w+)(?<array>\[(?<array_key>\w+)?\])?)\s*=\s*(?<quote>'|\"|\&quot;|\&apos;|\&#x27;)(?<attr_value>.*?)(\g{quote})/mi";
//const ATTRIBUTE_REGEX = "/(\w+)\s*=\s*(?<quote>'|\"|\&quot;|\&apos;)(.*?)(\g{quote})/mi";
/**
* @var RegistryInterface
*/
private $registry;
/**
* Extractor constructor.
*
* @param RegistryInterface $registry
*/
public function __construct($registry)
{
$this->registry = $registry;
}
public function stripPlaceholders($content)
{
$expression = self::PLACEHOLDER_REQEX;
return preg_replace($expression, '', $content);
}
/**
* @param $content
*
* @return array
*/
public function extract($content)
{
$placeholderInstances = array();
$contentPlaceholders = array();
$matches = array();
$expression = self::PLACEHOLDER_REQEX;
preg_match_all($expression, $content, $matches);
if (count($matches['placeholder']) == 0) {
return array($contentPlaceholders, [], $content);
}
foreach ($matches['placeholder'] as $i => $name) {
$instance = $this->registry->getPlaceholderSupportingName($matches['placeholderName'][$i]);
// ignore unknown placeholders
if ( ! $instance) {
continue;
}
$placeholderInstances[$i] = $instance;
$contentPlaceholders[$i] = $placeholder = new ContentPlaceholder(
$matches['placeholderName'][$i],
$matches['placeholder'][$i],
$this->getPlaceholderAttributes($matches['attributes'][$i]),
$matches['content'][$i]
);
$pos = strpos($content, $placeholder->getPlaceholder());
$length = strlen($placeholder->getPlaceholder());
if ($pos !== false) {
$content = substr_replace($content, $placeholder->getUid(), $pos, $length);
}
}
return array($contentPlaceholders, $placeholderInstances, $content);
}
/**
* Split the attributs from attribute string
*
* @param $attributeString
*
* @return array
*/
private function getPlaceholderAttributes($attributeString)
{
$attrString = trim($attributeString);
$attrMatches = array();
$attributes = array();
preg_match_all(self::ATTRIBUTE_REGEX, $attrString, $attrMatches);
if (isset($attrMatches[0]) && is_array($attrMatches[0])) {
foreach ($attrMatches[0] as $i => $attStr) {
$attrName = $attrMatches['attr_name'][$i];
$attrValue = urldecode($attrMatches['attr_value'][$i]);
$isArray = $attrMatches['array'][$i]!='';
$arrayKey = $attrMatches['array_key'][$i];
// check if the attribute is an array
if($isArray)
{
if($arrayKey)
$attributes[$attrName][$arrayKey] = $attrValue;
else
$attributes[$attrName][] = $attrValue;
} else {
$attributes[$attrName] = $attrValue;
}
}
}
return $attributes;
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace BrizyPlaceholders;
interface PlaceholderInterface
{
const FALLBACK_KEY = '_fallback';
/**
* Returns true if the placeholder can return a value for the given placeholder name
*
* @param $placeholderName
*
* @return mixed
*/
public function support($placeholderName);
/**
* Return the string value that will replace the placeholder name in content
*
* @param ContextInterface $context
* @param ContentPlaceholder $placeholder
*
* @return mixed
*/
public function getValue(ContextInterface $context, ContentPlaceholder $placeholder);
public function shouldFallbackValue($value, ContextInterface $context, ContentPlaceholder $placeholder);
public function getFallbackValue(ContextInterface $context, ContentPlaceholder $placeholder);
/**
* It should return an unique identifier of the placeholder
*
* @return mixed
*/
public function getUid();
}

View File

@@ -0,0 +1,49 @@
<?php
namespace BrizyPlaceholders;
/**
* Class Registry
* @package BrizyPlaceholders
*/
class Registry implements RegistryInterface
{
/**
* @var PlaceholderInterface[]
*/
public $placeholders = [];
/**
* @param PlaceholderInterface $instance
* @param string $label
* @param string $placeholderName
* @param string $groupName
*
* @return mixed|void
*/
public function registerPlaceholder(PlaceholderInterface $instance)
{
$this->placeholders[] = $instance;
}
/**
* @inheritDoc
*/
public function getPlaceholders()
{
return $this->placeholders;
}
/**
* @inheritDoc
*/
public function getPlaceholderSupportingName($name)
{
foreach ($this->placeholders as $aplaceholder) {
if ($aplaceholder->support($name)) {
return $aplaceholder;
}
}
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace BrizyPlaceholders;
interface RegistryInterface
{
/**
* Register a placeholder class
*
* @param PlaceholderInterface $instance
* @param $label
* @param $placeholderName
* @param $groupName
*
* @return mixed
*/
public function registerPlaceholder(PlaceholderInterface $instance);
/**
* Return all placeholders
*
* @return PlaceholderInterface[]
*/
public function getPlaceholders();
/**
* It will return first placeholder that supports the $name;
*
* @param $name
*
* @return mixed
*/
public function getPlaceholderSupportingName($name);
}

View File

@@ -0,0 +1,88 @@
<?php
namespace BrizyPlaceholders;
/**
* Class Replacer
*/
final class Replacer
{
/**
* @var ContextInterface
*/
private $context;
/**
* @var RegistryInterface
*/
private $registry;
/**
* Brizy_Content_PlaceholderReplacer constructor.
*
* @param $registry
*/
public function __construct($registry)
{
$this->registry = $registry;
}
/**
* @param $content
* @param ContextInterface $context
*
*$subContext @return string|string[]
*/
public function replacePlaceholders($content, ContextInterface $context)
{
$extractor = new Extractor($this->registry);
list($contentPlaceholders, $instancePlaceholders, $contentAfterExtractor) = $extractor->extract($content);
$context->afterExtract($contentPlaceholders, $instancePlaceholders, $contentAfterExtractor);
if ($contentPlaceholders && $instancePlaceholders) {
$content = $this->replaceWithExtractedData($contentPlaceholders, $instancePlaceholders, $contentAfterExtractor, $context);
}
return $content;
}
/**
* @param ContentPlaceholder[] $contentPlaceholders
* @param PlaceholderInterface[] $instancePlaceholders
* @param string $contentAfterExtractor
*/
public function replaceWithExtractedData(array $contentPlaceholders, array $instancePlaceholders, $contentAfterExtractor, ContextInterface $context)
{
$toReplace = array();
$toReplaceWithValues = array();
foreach ($contentPlaceholders as $index => $contentPlaceholder) {
try {
$toReplace[] = $contentPlaceholder->getUid();
/**
* @var PlaceholderInterface $instancePlaceholder ;
*/
$instancePlaceholder = $instancePlaceholders[$index];
if ($instancePlaceholder) {
$value = $instancePlaceholder->getValue($context, $contentPlaceholder);
if ($instancePlaceholder->shouldFallbackValue($value, $context, $contentPlaceholder)) {
$toReplaceWithValues[] = $instancePlaceholder->getFallbackValue($context, $contentPlaceholder);
} else {
$toReplaceWithValues[] = $value;
}
} else {
$toReplaceWithValues[] = '';
}
} catch (\Exception $e) {
array_pop($toReplace);
continue;
}
}
$content = str_replace($toReplace, $toReplaceWithValues, $contentAfterExtractor);
return $content;
}
}