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,7 @@
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit8f26576b30ceed4ca5a9626b6c5b70d5::getLoader();

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;
}
}

View File

@@ -0,0 +1,477 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see https://www.php-fig.org/psr/psr-0/
* @see https://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
private $vendorDir;
// PSR-4
private $prefixLengthsPsr4 = array();
private $prefixDirsPsr4 = array();
private $fallbackDirsPsr4 = array();
// PSR-0
private $prefixesPsr0 = array();
private $fallbackDirsPsr0 = array();
private $useIncludePath = false;
private $classMap = array();
private $classMapAuthoritative = false;
private $missingClasses = array();
private $apcuPrefix;
private static $registeredLoaders = array();
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
}
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array $classMap Class to filename map
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*/
public function add($prefix, $paths, $prepend = false)
{
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
(array) $paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
(array) $paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
(array) $paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 base directories
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
if (null === $this->vendorDir) {
//no-op
} elseif ($prepend) {
self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
} else {
unset(self::$registeredLoaders[$this->vendorDir]);
self::$registeredLoaders[$this->vendorDir] = $this;
}
}
/**
* Unregisters this instance as an autoloader.
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
if (null !== $this->vendorDir) {
unset(self::$registeredLoaders[$this->vendorDir]);
}
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return bool|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
includeFile($file);
return true;
}
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
/**
* Returns the currently registered loaders indexed by their corresponding vendor directories.
*
* @return self[]
*/
public static function getRegisteredLoaders()
{
return self::$registeredLoaders;
}
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*/
function includeFile($file)
{
include $file;
}

View File

@@ -0,0 +1,397 @@
<?php
namespace Composer;
use Composer\Autoload\ClassLoader;
use Composer\Semver\VersionParser;
class InstalledVersions
{
private static $installed = array (
'root' =>
array (
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'aliases' =>
array (
),
'reference' => '20e58898db73c504917554bbe5ecf7c60a6499bb',
'name' => 'brizy/brizy',
),
'versions' =>
array (
'bagrinsergiu/brizy-merge-page-assets' =>
array (
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'aliases' =>
array (
0 => '9999999-dev',
),
'reference' => '883490c9302aa2da9ccfd71b74c4e216ce1cd6f2',
),
'bagrinsergiu/brizy-migration-utils' =>
array (
'pretty_version' => '1.4.2',
'version' => '1.4.2.0',
'aliases' =>
array (
),
'reference' => '6af1f8e3e181d1d262bd32cb96bf08ef9ead59df',
),
'bagrinsergiu/content-placeholder' =>
array (
'pretty_version' => '2.0.5',
'version' => '2.0.5.0',
'aliases' =>
array (
),
'reference' => '3be1d4e2033c6c074f12391fc796e5ab9a9bc72d',
),
'brizy/brizy' =>
array (
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'aliases' =>
array (
),
'reference' => '20e58898db73c504917554bbe5ecf7c60a6499bb',
),
'enshrined/svg-sanitize' =>
array (
'pretty_version' => '0.13.3',
'version' => '0.13.3.0',
'aliases' =>
array (
),
'reference' => 'bc66593f255b7d2613d8f22041180036979b6403',
),
'knplabs/gaufrette' =>
array (
'pretty_version' => 'v0.7.0',
'version' => '0.7.0.0',
'aliases' =>
array (
),
'reference' => 'a0627e91e8753f442eea6560cb347151cd306b2c',
),
'select2/select2' =>
array (
'pretty_version' => '4.1.0-rc.0',
'version' => '4.1.0.0-RC0',
'aliases' =>
array (
),
'reference' => '9ce61fd297fd2922fe771debea8b24dfd219a49a',
),
'shortpixel/shortpixel-php' =>
array (
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'aliases' =>
array (
0 => '9999999-dev',
),
'reference' => '940c299b7a449d6621103c195d7094b1976861a7',
),
'symfony/deprecation-contracts' =>
array (
'pretty_version' => 'dev-main',
'version' => 'dev-main',
'aliases' =>
array (
0 => '2.5.x-dev',
),
'reference' => '6f981ee24cf69ee7ce9736146d1c57c2780598a8',
),
'symfony/dotenv' =>
array (
'pretty_version' => '5.4.x-dev',
'version' => '5.4.9999999.9999999-dev',
'aliases' =>
array (
),
'reference' => '7189ac0d3f99c7526950f13ff337d2b9a2bedf21',
),
'symfony/polyfill-ctype' =>
array (
'pretty_version' => 'dev-main',
'version' => 'dev-main',
'aliases' =>
array (
0 => '1.23.x-dev',
),
'reference' => '46cd95797e9df938fdd2b03693b5fca5e64b01ce',
),
'tburry/pquery' =>
array (
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'aliases' =>
array (
0 => '9999999-dev',
),
'reference' => 'c28159447f4cec57f2a016c2ec15f5b754b58052',
),
'twig/twig' =>
array (
'pretty_version' => 'v1.42.5',
'version' => '1.42.5.0',
'aliases' =>
array (
),
'reference' => '87b2ea9d8f6fd014d0621ca089bb1b3769ea3f8e',
),
),
);
private static $canGetVendors;
private static $installedByVendor = array();
public static function getInstalledPackages()
{
$packages = array();
foreach (self::getInstalled() as $installed) {
$packages[] = array_keys($installed['versions']);
}
if (1 === \count($packages)) {
return $packages[0];
}
return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
}
public static function isInstalled($packageName)
{
foreach (self::getInstalled() as $installed) {
if (isset($installed['versions'][$packageName])) {
return true;
}
}
return false;
}
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
$constraint = $parser->parseConstraints($constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
return $provided->matches($constraint);
}
public static function getVersionRanges($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
$ranges = array();
if (isset($installed['versions'][$packageName]['pretty_version'])) {
$ranges[] = $installed['versions'][$packageName]['pretty_version'];
}
if (array_key_exists('aliases', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
}
if (array_key_exists('replaced', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
}
if (array_key_exists('provided', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
}
return implode(' || ', $ranges);
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
public static function getVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['version'])) {
return null;
}
return $installed['versions'][$packageName]['version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
public static function getPrettyVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['pretty_version'])) {
return null;
}
return $installed['versions'][$packageName]['pretty_version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
public static function getReference($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['reference'])) {
return null;
}
return $installed['versions'][$packageName]['reference'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
public static function getRootPackage()
{
$installed = self::getInstalled();
return $installed[0]['root'];
}
public static function getRawData()
{
return self::$installed;
}
public static function reload($data)
{
self::$installed = $data;
self::$installedByVendor = array();
}
private static function getInstalled()
{
if (null === self::$canGetVendors) {
self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
}
$installed = array();
if (self::$canGetVendors) {
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
$installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php';
}
}
}
$installed[] = self::$installed;
return $installed;
}
}

View File

@@ -0,0 +1,21 @@
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,29 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
'pQuery' => $vendorDir . '/tburry/pquery/pQuery.php',
'pQuery\\AspEmbeddedNode' => $vendorDir . '/tburry/pquery/gan_node_html.php',
'pQuery\\CSSQueryTokenizer' => $vendorDir . '/tburry/pquery/gan_selector_html.php',
'pQuery\\CdataNode' => $vendorDir . '/tburry/pquery/gan_node_html.php',
'pQuery\\CommentNode' => $vendorDir . '/tburry/pquery/gan_node_html.php',
'pQuery\\ConditionalTagNode' => $vendorDir . '/tburry/pquery/gan_node_html.php',
'pQuery\\DoctypeNode' => $vendorDir . '/tburry/pquery/gan_node_html.php',
'pQuery\\DomNode' => $vendorDir . '/tburry/pquery/gan_node_html.php',
'pQuery\\EmbeddedNode' => $vendorDir . '/tburry/pquery/gan_node_html.php',
'pQuery\\Html5Parser' => $vendorDir . '/tburry/pquery/gan_parser_html.php',
'pQuery\\HtmlFormatter' => $vendorDir . '/tburry/pquery/gan_formatter.php',
'pQuery\\HtmlParser' => $vendorDir . '/tburry/pquery/gan_parser_html.php',
'pQuery\\HtmlParserBase' => $vendorDir . '/tburry/pquery/gan_parser_html.php',
'pQuery\\HtmlSelector' => $vendorDir . '/tburry/pquery/gan_selector_html.php',
'pQuery\\IQuery' => $vendorDir . '/tburry/pquery/IQuery.php',
'pQuery\\TextNode' => $vendorDir . '/tburry/pquery/gan_node_html.php',
'pQuery\\TokenizerBase' => $vendorDir . '/tburry/pquery/gan_tokenizer.php',
'pQuery\\XML2ArrayParser' => $vendorDir . '/tburry/pquery/gan_xml2array.php',
'pQuery\\XmlNode' => $vendorDir . '/tburry/pquery/gan_node_html.php',
);

View File

@@ -0,0 +1,13 @@
<?php
// autoload_files.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
'8ec4222c68e580a23520eef4abe4380f' => $vendorDir . '/shortpixel/shortpixel-php/lib/ShortPixel.php',
'c93afce03290e70ec0d051b69a50edb0' => $vendorDir . '/shortpixel/shortpixel-php/lib/ShortPixel/Exception.php',
);

View File

@@ -0,0 +1,12 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Twig_' => array($vendorDir . '/twig/twig/lib'),
'Gaufrette' => array($vendorDir . '/knplabs/gaufrette/src'),
'Brizy' => array($vendorDir . '/bagrinsergiu/brizy-migration-utils/src'),
);

View File

@@ -0,0 +1,18 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'enshrined\\svgSanitize\\' => array($vendorDir . '/enshrined/svg-sanitize/src'),
'Twig\\' => array($vendorDir . '/twig/twig/src'),
'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'),
'Symfony\\Component\\Dotenv\\' => array($vendorDir . '/symfony/dotenv'),
'ShortPixel\\' => array($vendorDir . '/shortpixel/shortpixel-php/lib/ShortPixel'),
'BrizyPlaceholders\\' => array($vendorDir . '/bagrinsergiu/content-placeholder/lib'),
'BrizyPlaceholdersTests\\' => array($vendorDir . '/bagrinsergiu/content-placeholder/tests'),
'BrizyMerge\\' => array($vendorDir . '/bagrinsergiu/brizy-merge-page-assets/lib'),
'BrizyMergeTests\\' => array($vendorDir . '/bagrinsergiu/brizy-merge-page-assets/tests'),
);

View File

@@ -0,0 +1,73 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit8f26576b30ceed4ca5a9626b6c5b70d5
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
/**
* @return \Composer\Autoload\ClassLoader
*/
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit8f26576b30ceed4ca5a9626b6c5b70d5', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(\dirname(__FILE__)));
spl_autoload_unregister(array('ComposerAutoloaderInit8f26576b30ceed4ca5a9626b6c5b70d5', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit8f26576b30ceed4ca5a9626b6c5b70d5::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInit8f26576b30ceed4ca5a9626b6c5b70d5::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequire8f26576b30ceed4ca5a9626b6c5b70d5($fileIdentifier, $file);
}
return $loader;
}
}
function composerRequire8f26576b30ceed4ca5a9626b6c5b70d5($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
}
}

View File

@@ -0,0 +1,136 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInit8f26576b30ceed4ca5a9626b6c5b70d5
{
public static $files = array (
'6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php',
'8ec4222c68e580a23520eef4abe4380f' => __DIR__ . '/..' . '/shortpixel/shortpixel-php/lib/ShortPixel.php',
'c93afce03290e70ec0d051b69a50edb0' => __DIR__ . '/..' . '/shortpixel/shortpixel-php/lib/ShortPixel/Exception.php',
);
public static $prefixLengthsPsr4 = array (
'e' =>
array (
'enshrined\\svgSanitize\\' => 22,
),
'T' =>
array (
'Twig\\' => 5,
),
'S' =>
array (
'Symfony\\Polyfill\\Ctype\\' => 23,
'Symfony\\Component\\Dotenv\\' => 25,
'ShortPixel\\' => 11,
),
'B' =>
array (
'BrizyPlaceholders\\' => 18,
'BrizyPlaceholdersTests\\' => 23,
'BrizyMerge\\' => 11,
'BrizyMergeTests\\' => 16,
),
);
public static $prefixDirsPsr4 = array (
'enshrined\\svgSanitize\\' =>
array (
0 => __DIR__ . '/..' . '/enshrined/svg-sanitize/src',
),
'Twig\\' =>
array (
0 => __DIR__ . '/..' . '/twig/twig/src',
),
'Symfony\\Polyfill\\Ctype\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-ctype',
),
'Symfony\\Component\\Dotenv\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/dotenv',
),
'ShortPixel\\' =>
array (
0 => __DIR__ . '/..' . '/shortpixel/shortpixel-php/lib/ShortPixel',
),
'BrizyPlaceholders\\' =>
array (
0 => __DIR__ . '/..' . '/bagrinsergiu/content-placeholder/lib',
),
'BrizyPlaceholdersTests\\' =>
array (
0 => __DIR__ . '/..' . '/bagrinsergiu/content-placeholder/tests',
),
'BrizyMerge\\' =>
array (
0 => __DIR__ . '/..' . '/bagrinsergiu/brizy-merge-page-assets/lib',
),
'BrizyMergeTests\\' =>
array (
0 => __DIR__ . '/..' . '/bagrinsergiu/brizy-merge-page-assets/tests',
),
);
public static $prefixesPsr0 = array (
'T' =>
array (
'Twig_' =>
array (
0 => __DIR__ . '/..' . '/twig/twig/lib',
),
),
'G' =>
array (
'Gaufrette' =>
array (
0 => __DIR__ . '/..' . '/knplabs/gaufrette/src',
),
),
'B' =>
array (
'Brizy' =>
array (
0 => __DIR__ . '/..' . '/bagrinsergiu/brizy-migration-utils/src',
),
),
);
public static $classMap = array (
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
'pQuery' => __DIR__ . '/..' . '/tburry/pquery/pQuery.php',
'pQuery\\AspEmbeddedNode' => __DIR__ . '/..' . '/tburry/pquery/gan_node_html.php',
'pQuery\\CSSQueryTokenizer' => __DIR__ . '/..' . '/tburry/pquery/gan_selector_html.php',
'pQuery\\CdataNode' => __DIR__ . '/..' . '/tburry/pquery/gan_node_html.php',
'pQuery\\CommentNode' => __DIR__ . '/..' . '/tburry/pquery/gan_node_html.php',
'pQuery\\ConditionalTagNode' => __DIR__ . '/..' . '/tburry/pquery/gan_node_html.php',
'pQuery\\DoctypeNode' => __DIR__ . '/..' . '/tburry/pquery/gan_node_html.php',
'pQuery\\DomNode' => __DIR__ . '/..' . '/tburry/pquery/gan_node_html.php',
'pQuery\\EmbeddedNode' => __DIR__ . '/..' . '/tburry/pquery/gan_node_html.php',
'pQuery\\Html5Parser' => __DIR__ . '/..' . '/tburry/pquery/gan_parser_html.php',
'pQuery\\HtmlFormatter' => __DIR__ . '/..' . '/tburry/pquery/gan_formatter.php',
'pQuery\\HtmlParser' => __DIR__ . '/..' . '/tburry/pquery/gan_parser_html.php',
'pQuery\\HtmlParserBase' => __DIR__ . '/..' . '/tburry/pquery/gan_parser_html.php',
'pQuery\\HtmlSelector' => __DIR__ . '/..' . '/tburry/pquery/gan_selector_html.php',
'pQuery\\IQuery' => __DIR__ . '/..' . '/tburry/pquery/IQuery.php',
'pQuery\\TextNode' => __DIR__ . '/..' . '/tburry/pquery/gan_node_html.php',
'pQuery\\TokenizerBase' => __DIR__ . '/..' . '/tburry/pquery/gan_tokenizer.php',
'pQuery\\XML2ArrayParser' => __DIR__ . '/..' . '/tburry/pquery/gan_xml2array.php',
'pQuery\\XmlNode' => __DIR__ . '/..' . '/tburry/pquery/gan_node_html.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit8f26576b30ceed4ca5a9626b6c5b70d5::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit8f26576b30ceed4ca5a9626b6c5b70d5::$prefixDirsPsr4;
$loader->prefixesPsr0 = ComposerStaticInit8f26576b30ceed4ca5a9626b6c5b70d5::$prefixesPsr0;
$loader->classMap = ComposerStaticInit8f26576b30ceed4ca5a9626b6c5b70d5::$classMap;
}, null, ClassLoader::class);
}
}

View File

@@ -0,0 +1,743 @@
{
"packages": [
{
"name": "bagrinsergiu/brizy-merge-page-assets",
"version": "dev-master",
"version_normalized": "dev-master",
"source": {
"type": "git",
"url": "https://github.com/bagrinsergiu/brizy-merge-page-assets.git",
"reference": "883490c9302aa2da9ccfd71b74c4e216ce1cd6f2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/bagrinsergiu/brizy-merge-page-assets/zipball/883490c9302aa2da9ccfd71b74c4e216ce1cd6f2",
"reference": "883490c9302aa2da9ccfd71b74c4e216ce1cd6f2",
"shasum": ""
},
"require": {
"ext-json": "*",
"php": ">=5.6.0"
},
"require-dev": {
"phpunit/phpunit": "^9.4"
},
"time": "2021-08-16T09:11:29+00:00",
"default-branch": true,
"type": "library",
"installation-source": "source",
"autoload": {
"psr-4": {
"BrizyMerge\\": "lib/",
"BrizyMergeTests\\": "tests/"
}
},
"description": "Merge page assets compiled by Brizy compiler",
"keywords": [
"brizy",
"brizy merge assets"
],
"support": {
"source": "https://github.com/bagrinsergiu/brizy-merge-page-assets/tree/1.0.16",
"issues": "https://github.com/bagrinsergiu/brizy-merge-page-assets/issues"
},
"install-path": "../bagrinsergiu/brizy-merge-page-assets"
},
{
"name": "bagrinsergiu/brizy-migration-utils",
"version": "1.4.2",
"version_normalized": "1.4.2.0",
"source": {
"type": "git",
"url": "https://github.com/bagrinsergiu/brizy-migration-utils.git",
"reference": "6af1f8e3e181d1d262bd32cb96bf08ef9ead59df"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/bagrinsergiu/brizy-migration-utils/zipball/6af1f8e3e181d1d262bd32cb96bf08ef9ead59df",
"reference": "6af1f8e3e181d1d262bd32cb96bf08ef9ead59df",
"shasum": ""
},
"require-dev": {
"phpunit/phpunit": "8.2.1"
},
"time": "2020-05-12T15:14:00+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-0": {
"Brizy": "src/"
}
},
"autoload-dev": {
"classmap": [
"tests/"
]
},
"authors": [
{
"name": "Alex Zaharia",
"email": "alecszaharia@gmail.com"
}
],
"description": "Data migration utils",
"support": {
"source": "https://github.com/bagrinsergiu/brizy-migration-utils/tree/1.4.2",
"issues": "https://github.com/bagrinsergiu/brizy-migration-utils/issues"
},
"install-path": "../bagrinsergiu/brizy-migration-utils"
},
{
"name": "bagrinsergiu/content-placeholder",
"version": "2.0.5",
"version_normalized": "2.0.5.0",
"source": {
"type": "git",
"url": "https://github.com/bagrinsergiu/brizy-content-placeholder.git",
"reference": "3be1d4e2033c6c074f12391fc796e5ab9a9bc72d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/bagrinsergiu/brizy-content-placeholder/zipball/3be1d4e2033c6c074f12391fc796e5ab9a9bc72d",
"reference": "3be1d4e2033c6c074f12391fc796e5ab9a9bc72d",
"shasum": ""
},
"require": {
"php": ">=5.4.0"
},
"require-dev": {
"phpspec/prophecy-phpunit": "^2.0",
"phpunit/phpunit": "^9.4"
},
"time": "2021-07-29T08:06:01+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"BrizyPlaceholders\\": "lib/",
"BrizyPlaceholdersTests\\": "tests/"
}
},
"description": "Brizy content placeholders SDK",
"keywords": [
"brizy",
"content",
"placeholders"
],
"support": {
"source": "https://github.com/bagrinsergiu/brizy-content-placeholder/tree/2.0.5",
"issues": "https://github.com/bagrinsergiu/brizy-content-placeholder/issues"
},
"install-path": "../bagrinsergiu/content-placeholder"
},
{
"name": "enshrined/svg-sanitize",
"version": "0.13.3",
"version_normalized": "0.13.3.0",
"source": {
"type": "git",
"url": "https://github.com/darylldoyle/svg-sanitizer.git",
"reference": "bc66593f255b7d2613d8f22041180036979b6403"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/darylldoyle/svg-sanitizer/zipball/bc66593f255b7d2613d8f22041180036979b6403",
"reference": "bc66593f255b7d2613d8f22041180036979b6403",
"shasum": ""
},
"require": {
"ext-dom": "*",
"ext-libxml": "*"
},
"require-dev": {
"codeclimate/php-test-reporter": "^0.1.2",
"phpunit/phpunit": "^6"
},
"time": "2020-01-20T01:34:17+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"enshrined\\svgSanitize\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"GPL-2.0-or-later"
],
"authors": [
{
"name": "Daryll Doyle",
"email": "daryll@enshrined.co.uk"
}
],
"description": "An SVG sanitizer for PHP",
"support": {
"issues": "https://github.com/darylldoyle/svg-sanitizer/issues",
"source": "https://github.com/darylldoyle/svg-sanitizer/tree/develop"
},
"install-path": "../enshrined/svg-sanitize"
},
{
"name": "knplabs/gaufrette",
"version": "v0.7.0",
"version_normalized": "0.7.0.0",
"source": {
"type": "git",
"url": "https://github.com/KnpLabs/Gaufrette.git",
"reference": "a0627e91e8753f442eea6560cb347151cd306b2c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/KnpLabs/Gaufrette/zipball/a0627e91e8753f442eea6560cb347151cd306b2c",
"reference": "a0627e91e8753f442eea6560cb347151cd306b2c",
"shasum": ""
},
"require": {
"php": ">=5.6"
},
"conflict": {
"microsoft/windowsazure": "<0.4.3"
},
"require-dev": {
"akeneo/phpspec-skip-example-extension": "~1.2",
"amazonwebservices/aws-sdk-for-php": "1.5.*",
"aws/aws-sdk-php": "^2.4.12||~3",
"doctrine/dbal": ">=2.3",
"dropbox-php/dropbox-php": "*",
"google/apiclient": "~1.1.3",
"league/flysystem": "~1.0",
"microsoft/azure-storage-blob": "^1.0",
"mikey179/vfsstream": "~1.2.0",
"mongodb/mongodb": "^1.1",
"phpseclib/phpseclib": "^2.0",
"phpspec/phpspec": "~2.4",
"phpunit/phpunit": "^5.6.8",
"rackspace/php-opencloud": "^1.9.2"
},
"suggest": {
"ext-curl": "*",
"ext-fileinfo": "This extension is used to automatically detect the content-type of a file in the AwsS3, OpenCloud, AzureBlogStorage and GoogleCloudStorage adapters",
"ext-mbstring": "*",
"gaufrette/aws-s3-adapter": "to use AwsS3 adapter (supports SDK v2 and v3)",
"gaufrette/azure-blob-storage-adapter": "to use AzureBlobStorage adapter",
"gaufrette/doctrine-dbal-adapter": "to use DBAL adapter",
"gaufrette/flysystem-adapter": "to use Flysystem adapter",
"gaufrette/ftp-adapter": "to use Ftp adapter",
"gaufrette/gridfs-adapter": "to use GridFS adapter",
"gaufrette/in-memory-adapter": "to use InMemory adapter",
"gaufrette/local-adapter": "to use Local adapter",
"gaufrette/opencloud-adapter": "to use Opencloud adapter",
"gaufrette/phpseclib-sftp-adapter": "to use PhpseclibSftp adapter",
"gaufrette/zip-adapter": "to use Zip adapter",
"google/apiclient": "to use GoogleCloudStorage adapter",
"knplabs/knp-gaufrette-bundle": "to use with Symfony2"
},
"time": "2018-08-30T13:26:15+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "0.7.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-0": {
"Gaufrette": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "The contributors",
"homepage": "http://github.com/knplabs/Gaufrette/contributors"
},
{
"name": "KnpLabs Team",
"homepage": "http://knplabs.com"
}
],
"description": "PHP library that provides a filesystem abstraction layer",
"homepage": "http://knplabs.com",
"keywords": [
"abstraction",
"file",
"filesystem",
"media"
],
"support": {
"issues": "https://github.com/KnpLabs/Gaufrette/issues",
"source": "https://github.com/KnpLabs/Gaufrette/tree/v0.7.0"
},
"install-path": "../knplabs/gaufrette"
},
{
"name": "select2/select2",
"version": "4.1.0-rc.0",
"version_normalized": "4.1.0.0-RC0",
"source": {
"type": "git",
"url": "git@github.com:select2/select2.git",
"reference": "9ce61fd297fd2922fe771debea8b24dfd219a49a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/select2/select2/zipball/9ce61fd297fd2922fe771debea8b24dfd219a49a",
"reference": "9ce61fd297fd2922fe771debea8b24dfd219a49a",
"shasum": ""
},
"time": "2021-01-23T04:36:25+00:00",
"type": "component",
"extra": {
"component": {
"scripts": [
"dist/js/select2.js"
],
"styles": [
"dist/css/select2.css"
],
"files": [
"dist/js/select2.js",
"dist/js/i18n/*.js",
"dist/css/select2.css"
]
}
},
"installation-source": "dist",
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "Select2 is a jQuery based replacement for select boxes.",
"homepage": "https://select2.org/",
"install-path": "../select2/select2"
},
{
"name": "shortpixel/shortpixel-php",
"version": "dev-master",
"version_normalized": "dev-master",
"source": {
"type": "git",
"url": "https://github.com/short-pixel-optimizer/shortpixel-php.git",
"reference": "940c299b7a449d6621103c195d7094b1976861a7"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/short-pixel-optimizer/shortpixel-php/zipball/940c299b7a449d6621103c195d7094b1976861a7",
"reference": "940c299b7a449d6621103c195d7094b1976861a7",
"shasum": ""
},
"require": {
"ext-curl": "*",
"ext-json": "*",
"lib-curl": ">=7.20.0",
"php": ">=5.3.0"
},
"require-dev": {
"phpunit/phpunit": "~4.0",
"symfony/yaml": "~2.0"
},
"time": "2021-08-29T05:07:47+00:00",
"default-branch": true,
"type": "library",
"installation-source": "source",
"autoload": {
"files": [
"lib/ShortPixel.php",
"lib/ShortPixel/Exception.php"
],
"psr-4": {
"ShortPixel\\": "lib/ShortPixel/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Simon Duduica",
"email": "simon@shortpixel.com"
}
],
"description": "ShortPixel PHP SDK. Read more at https://shortpixel.com/api-tools",
"homepage": "https://shortpixel.com/api",
"keywords": [
"api",
"compress",
"images",
"optimize",
"shortpixel"
],
"support": {
"email": "support@shortpixel.com",
"issues": "https://github.com/short-pixel-optimizer/shortpixel-php/issues",
"source": "https://github.com/short-pixel-optimizer/shortpixel-php/tree/master"
},
"install-path": "../shortpixel/shortpixel-php"
},
{
"name": "symfony/deprecation-contracts",
"version": "dev-main",
"version_normalized": "dev-main",
"source": {
"type": "git",
"url": "https://github.com/symfony/deprecation-contracts.git",
"reference": "6f981ee24cf69ee7ce9736146d1c57c2780598a8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/6f981ee24cf69ee7ce9736146d1c57c2780598a8",
"reference": "6f981ee24cf69ee7ce9736146d1c57c2780598a8",
"shasum": ""
},
"require": {
"php": ">=7.1"
},
"time": "2021-07-12T14:48:14+00:00",
"default-branch": true,
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "2.5-dev"
},
"thanks": {
"name": "symfony/contracts",
"url": "https://github.com/symfony/contracts"
}
},
"installation-source": "source",
"autoload": {
"files": [
"function.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "A generic function and convention to trigger deprecation notices",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/deprecation-contracts/tree/main"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"install-path": "../symfony/deprecation-contracts"
},
{
"name": "symfony/dotenv",
"version": "5.4.x-dev",
"version_normalized": "5.4.9999999.9999999-dev",
"source": {
"type": "git",
"url": "https://github.com/symfony/dotenv.git",
"reference": "7189ac0d3f99c7526950f13ff337d2b9a2bedf21"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/dotenv/zipball/7189ac0d3f99c7526950f13ff337d2b9a2bedf21",
"reference": "7189ac0d3f99c7526950f13ff337d2b9a2bedf21",
"shasum": ""
},
"require": {
"php": ">=7.2.5",
"symfony/deprecation-contracts": "^2.1"
},
"require-dev": {
"symfony/process": "^4.4|^5.0|^6.0"
},
"time": "2021-08-17T14:20:01+00:00",
"type": "library",
"installation-source": "source",
"autoload": {
"psr-4": {
"Symfony\\Component\\Dotenv\\": ""
},
"exclude-from-classmap": [
"/Tests/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Registers environment variables from a .env file",
"homepage": "https://symfony.com",
"keywords": [
"dotenv",
"env",
"environment"
],
"support": {
"source": "https://github.com/symfony/dotenv/tree/5.4"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"install-path": "../symfony/dotenv"
},
{
"name": "symfony/polyfill-ctype",
"version": "dev-main",
"version_normalized": "dev-main",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-ctype.git",
"reference": "46cd95797e9df938fdd2b03693b5fca5e64b01ce"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/46cd95797e9df938fdd2b03693b5fca5e64b01ce",
"reference": "46cd95797e9df938fdd2b03693b5fca5e64b01ce",
"shasum": ""
},
"require": {
"php": ">=7.1"
},
"suggest": {
"ext-ctype": "For best performance"
},
"time": "2021-02-19T12:13:01+00:00",
"default-branch": true,
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "1.23-dev"
},
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
}
},
"installation-source": "source",
"autoload": {
"psr-4": {
"Symfony\\Polyfill\\Ctype\\": ""
},
"files": [
"bootstrap.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Gert de Pagter",
"email": "BackEndTea@gmail.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for ctype functions",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"ctype",
"polyfill",
"portable"
],
"support": {
"source": "https://github.com/symfony/polyfill-ctype/tree/v1.23.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"install-path": "../symfony/polyfill-ctype"
},
{
"name": "tburry/pquery",
"version": "dev-master",
"version_normalized": "dev-master",
"source": {
"type": "git",
"url": "https://github.com/tburry/pquery.git",
"reference": "c28159447f4cec57f2a016c2ec15f5b754b58052"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/tburry/pquery/zipball/c28159447f4cec57f2a016c2ec15f5b754b58052",
"reference": "c28159447f4cec57f2a016c2ec15f5b754b58052",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"require-dev": {
"htmlawed/htmlawed": "dev-master"
},
"time": "2016-03-23T18:57:26+00:00",
"default-branch": true,
"type": "library",
"installation-source": "source",
"autoload": {
"classmap": [
"IQuery.php",
"gan_formatter.php",
"gan_node_html.php",
"gan_parser_html.php",
"gan_selector_html.php",
"gan_tokenizer.php",
"gan_xml2array.php",
"pQuery.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"LGPL-2.1"
],
"authors": [
{
"name": "Todd Burry",
"email": "todd@vanillaforums.com",
"role": "Developer"
}
],
"description": "A jQuery like html dom parser written in php.",
"keywords": [
"dom",
"ganon",
"php"
],
"support": {
"issues": "https://github.com/tburry/pquery/issues",
"source": "https://github.com/tburry/pquery/tree/master"
},
"install-path": "../tburry/pquery"
},
{
"name": "twig/twig",
"version": "v1.42.5",
"version_normalized": "1.42.5.0",
"source": {
"type": "git",
"url": "https://github.com/twigphp/Twig.git",
"reference": "87b2ea9d8f6fd014d0621ca089bb1b3769ea3f8e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/twigphp/Twig/zipball/87b2ea9d8f6fd014d0621ca089bb1b3769ea3f8e",
"reference": "87b2ea9d8f6fd014d0621ca089bb1b3769ea3f8e",
"shasum": ""
},
"require": {
"php": ">=5.5.0",
"symfony/polyfill-ctype": "^1.8"
},
"require-dev": {
"psr/container": "^1.0",
"symfony/phpunit-bridge": "^4.4|^5.0"
},
"time": "2020-02-11T05:59:23+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.42-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-0": {
"Twig_": "lib/"
},
"psr-4": {
"Twig\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com",
"homepage": "http://fabien.potencier.org",
"role": "Lead Developer"
},
{
"name": "Twig Team",
"role": "Contributors"
},
{
"name": "Armin Ronacher",
"email": "armin.ronacher@active-4.com",
"role": "Project Founder"
}
],
"description": "Twig, the flexible, fast, and secure template language for PHP",
"homepage": "https://twig.symfony.com",
"keywords": [
"templating"
],
"support": {
"issues": "https://github.com/twigphp/Twig/issues",
"source": "https://github.com/twigphp/Twig/tree/1.x"
},
"install-path": "../twig/twig"
}
],
"dev": false,
"dev-package-names": []
}

View File

@@ -0,0 +1,137 @@
<?php return array (
'root' =>
array (
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'aliases' =>
array (
),
'reference' => '20e58898db73c504917554bbe5ecf7c60a6499bb',
'name' => 'brizy/brizy',
),
'versions' =>
array (
'bagrinsergiu/brizy-merge-page-assets' =>
array (
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'aliases' =>
array (
0 => '9999999-dev',
),
'reference' => '883490c9302aa2da9ccfd71b74c4e216ce1cd6f2',
),
'bagrinsergiu/brizy-migration-utils' =>
array (
'pretty_version' => '1.4.2',
'version' => '1.4.2.0',
'aliases' =>
array (
),
'reference' => '6af1f8e3e181d1d262bd32cb96bf08ef9ead59df',
),
'bagrinsergiu/content-placeholder' =>
array (
'pretty_version' => '2.0.5',
'version' => '2.0.5.0',
'aliases' =>
array (
),
'reference' => '3be1d4e2033c6c074f12391fc796e5ab9a9bc72d',
),
'brizy/brizy' =>
array (
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'aliases' =>
array (
),
'reference' => '20e58898db73c504917554bbe5ecf7c60a6499bb',
),
'enshrined/svg-sanitize' =>
array (
'pretty_version' => '0.13.3',
'version' => '0.13.3.0',
'aliases' =>
array (
),
'reference' => 'bc66593f255b7d2613d8f22041180036979b6403',
),
'knplabs/gaufrette' =>
array (
'pretty_version' => 'v0.7.0',
'version' => '0.7.0.0',
'aliases' =>
array (
),
'reference' => 'a0627e91e8753f442eea6560cb347151cd306b2c',
),
'select2/select2' =>
array (
'pretty_version' => '4.1.0-rc.0',
'version' => '4.1.0.0-RC0',
'aliases' =>
array (
),
'reference' => '9ce61fd297fd2922fe771debea8b24dfd219a49a',
),
'shortpixel/shortpixel-php' =>
array (
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'aliases' =>
array (
0 => '9999999-dev',
),
'reference' => '940c299b7a449d6621103c195d7094b1976861a7',
),
'symfony/deprecation-contracts' =>
array (
'pretty_version' => 'dev-main',
'version' => 'dev-main',
'aliases' =>
array (
0 => '2.5.x-dev',
),
'reference' => '6f981ee24cf69ee7ce9736146d1c57c2780598a8',
),
'symfony/dotenv' =>
array (
'pretty_version' => '5.4.x-dev',
'version' => '5.4.9999999.9999999-dev',
'aliases' =>
array (
),
'reference' => '7189ac0d3f99c7526950f13ff337d2b9a2bedf21',
),
'symfony/polyfill-ctype' =>
array (
'pretty_version' => 'dev-main',
'version' => 'dev-main',
'aliases' =>
array (
0 => '1.23.x-dev',
),
'reference' => '46cd95797e9df938fdd2b03693b5fca5e64b01ce',
),
'tburry/pquery' =>
array (
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'aliases' =>
array (
0 => '9999999-dev',
),
'reference' => 'c28159447f4cec57f2a016c2ec15f5b754b58052',
),
'twig/twig' =>
array (
'pretty_version' => 'v1.42.5',
'version' => '1.42.5.0',
'aliases' =>
array (
),
'reference' => '87b2ea9d8f6fd014d0621ca089bb1b3769ea3f8e',
),
),
);

View File

@@ -0,0 +1,340 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
colors="true"
stopOnFailure="false"
syntaxCheck="false">
<testsuites>
<testsuite name="The project's test suite">
<directory>./tests</directory>
</testsuite>
</testsuites>
<logging>
<log type="coverage-clover" target="./build/logs/clover.xml"/>
</logging>
<filter>
<whitelist addUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src</directory>
</whitelist>
</filter>
</phpunit>

View File

@@ -0,0 +1,169 @@
<?php
namespace enshrined\svgSanitize\ElementReference;
use enshrined\svgSanitize\data\XPath;
use enshrined\svgSanitize\Exceptions\NestingException;
use enshrined\svgSanitize\Helper;
class Resolver
{
/**
* @var XPath
*/
protected $xPath;
/**
* @var Subject[]
*/
protected $subjects = [];
/**
* @var array DOMElement[]
*/
protected $elementsToRemove = [];
/**
* @var int
*/
protected $useNestingLimit;
public function __construct(XPath $xPath, $useNestingLimit)
{
$this->xPath = $xPath;
$this->useNestingLimit = $useNestingLimit;
}
public function collect()
{
$this->collectIdentifiedElements();
$this->processReferences();
$this->determineInvalidSubjects();
}
/**
* Resolves one subject by element.
*
* @param \DOMElement $element
* @param bool $considerChildren Whether to search in Subject's children as well
* @return Subject|null
*/
public function findByElement(\DOMElement $element, $considerChildren = false)
{
foreach ($this->subjects as $subject) {
if (
$element === $subject->getElement()
|| $considerChildren && Helper::isElementContainedIn($element, $subject->getElement())
) {
return $subject;
}
}
return null;
}
/**
* Resolves subjects (plural!) by element id - in theory malformed
* DOM might have same ids assigned to different elements and leaving
* it to client/browser implementation which element to actually use.
*
* @param string $elementId
* @return Subject[]
*/
public function findByElementId($elementId)
{
return array_filter(
$this->subjects,
function (Subject $subject) use ($elementId) {
return $elementId === $subject->getElementId();
}
);
}
/**
* Collects elements having `id` attribute (those that can be referenced).
*/
protected function collectIdentifiedElements()
{
/** @var \DOMNodeList|\DOMElement[] $elements */
$elements = $this->xPath->query('//*[@id]');
foreach ($elements as $element) {
$this->subjects[$element->getAttribute('id')] = new Subject($element, $this->useNestingLimit);
}
}
/**
* Processes references from and to elements having `id` attribute concerning
* their occurrence in `<use ... xlink:href="#identifier">` statements.
*/
protected function processReferences()
{
$useNodeName = $this->xPath->createNodeName('use');
foreach ($this->subjects as $subject) {
$useElements = $this->xPath->query(
$useNodeName . '[@href or @xlink:href]',
$subject->getElement()
);
/** @var \DOMElement $useElement */
foreach ($useElements as $useElement) {
$useId = Helper::extractIdReferenceFromHref(
Helper::getElementHref($useElement)
);
if ($useId === null || !isset($this->subjects[$useId])) {
continue;
}
$subject->addUse($this->subjects[$useId]);
$this->subjects[$useId]->addUsedIn($subject);
}
}
}
/**
* Determines and tags infinite loops.
*/
protected function determineInvalidSubjects()
{
foreach ($this->subjects as $subject) {
if (in_array($subject->getElement(), $this->elementsToRemove)) {
continue;
}
$useId = Helper::extractIdReferenceFromHref(
Helper::getElementHref($subject->getElement())
);
try {
if ($useId === $subject->getElementId()) {
$this->markSubjectAsInvalid($subject);
} elseif ($subject->hasInfiniteLoop()) {
$this->markSubjectAsInvalid($subject);
}
} catch (NestingException $e) {
$this->elementsToRemove[] = $e->getElement();
$this->markSubjectAsInvalid($subject);
}
}
}
/**
* Get all the elements that caused a nesting exception.
*
* @return array
*/
public function getElementsToRemove() {
return $this->elementsToRemove;
}
/**
* The Subject is invalid for some reason, therefore we should
* remove it and all it's child usages.
*
* @param Subject $subject
*/
protected function markSubjectAsInvalid(Subject $subject) {
$this->elementsToRemove = array_merge(
$this->elementsToRemove,
$subject->clearInternalAndGetAffectedElements()
);
}
}

View File

@@ -0,0 +1,153 @@
<?php
namespace enshrined\svgSanitize\ElementReference;
class Subject
{
/**
* @var \DOMElement
*/
protected $element;
/**
* @var Usage[]
*/
protected $useCollection = [];
/**
* @var Usage[]
*/
protected $usedInCollection = [];
/**
* @var int
*/
protected $useNestingLimit;
/**
* Subject constructor.
*
* @param \DOMElement $element
* @param int $useNestingLimit
*/
public function __construct(\DOMElement $element, $useNestingLimit)
{
$this->element = $element;
$this->useNestingLimit = $useNestingLimit;
}
/**
* @return \DOMElement
*/
public function getElement()
{
return $this->element;
}
/**
* @return string
*/
public function getElementId()
{
return $this->element->getAttribute('id');
}
/**
* @param array $subjects Previously processed subjects
* @param int $level The current level of nesting.
* @return bool
* @throws \enshrined\svgSanitize\Exceptions\NestingException
*/
public function hasInfiniteLoop(array $subjects = [], $level = 1)
{
if ($level > $this->useNestingLimit) {
throw new \enshrined\svgSanitize\Exceptions\NestingException('Nesting level too high, aborting', 1570713498, null, $this->getElement());
}
if (in_array($this, $subjects, true)) {
return true;
}
$subjects[] = $this;
foreach ($this->useCollection as $usage) {
if ($usage->getSubject()->hasInfiniteLoop($subjects, $level + 1)) {
return true;
}
}
return false;
}
/**
* @param Subject $subject
*/
public function addUse(Subject $subject)
{
if ($subject === $this) {
throw new \LogicException('Cannot add self usage', 1570713416);
}
$identifier = $subject->getElementId();
if (isset($this->useCollection[$identifier])) {
$this->useCollection[$identifier]->increment();
return;
}
$this->useCollection[$identifier] = new Usage($subject);
}
/**
* @param Subject $subject
*/
public function addUsedIn(Subject $subject)
{
if ($subject === $this) {
throw new \LogicException('Cannot add self as usage', 1570713417);
}
$identifier = $subject->getElementId();
if (isset($this->usedInCollection[$identifier])) {
$this->usedInCollection[$identifier]->increment();
return;
}
$this->usedInCollection[$identifier] = new Usage($subject);
}
/**
* @param bool $accumulated
* @return int
*/
public function countUse($accumulated = false)
{
$count = 0;
foreach ($this->useCollection as $use) {
$useCount = $use->getSubject()->countUse();
$count += $use->getCount() * ($accumulated ? 1 + $useCount : max(1, $useCount));
}
return $count;
}
/**
* @return int
*/
public function countUsedIn()
{
$count = 0;
foreach ($this->usedInCollection as $usedIn) {
$count += $usedIn->getCount() * max(1, $usedIn->getSubject()->countUsedIn());
}
return $count;
}
/**
* Clear the internal arrays (to free up memory as they can get big)
* and return all the child usages DOMElement's
*
* @return array
*/
public function clearInternalAndGetAffectedElements()
{
$elements = array_map(function(Usage $usage) {
return $usage->getSubject()->getElement();
}, $this->useCollection);
$this->usedInCollection = [];
$this->useCollection = [];
return $elements;
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace enshrined\svgSanitize\ElementReference;
class Usage
{
/**
* @var Subject
*/
protected $subject;
/**
* @var int
*/
protected $count;
/**
* @param Subject $subject
* @param int $count
*/
public function __construct(Subject $subject, $count = 1)
{
$this->subject = $subject;
$this->count = (int)$count;
}
/**
* @param int $by
*/
public function increment($by = 1)
{
$this->count += (int)$by;
}
/**
* @return Subject
*/
public function getSubject()
{
return $this->subject;
}
/**
* @return int
*/
public function getCount()
{
return $this->count;
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace enshrined\svgSanitize\Exceptions;
use Exception;
class NestingException extends \Exception
{
/**
* @var \DOMElement
*/
protected $element;
/**
* NestingException constructor.
*
* @param string $message
* @param int $code
* @param Exception|null $previous
* @param \DOMElement|null $element
*/
public function __construct($message = "", $code = 0, Exception $previous = null, \DOMElement $element = null)
{
$this->element = $element;
parent::__construct($message, $code, $previous);
}
/**
* Get the element that caused the exception.
*
* @return \DOMElement
*/
public function getElement()
{
return $this->element;
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace enshrined\svgSanitize;
class Helper
{
/**
* @param \DOMElement $element
* @return string|null
*/
public static function getElementHref(\DOMElement $element)
{
if ($element->hasAttribute('href')) {
return $element->getAttribute('href');
}
if ($element->hasAttributeNS('http://www.w3.org/1999/xlink', 'href')) {
return $element->getAttributeNS('http://www.w3.org/1999/xlink', 'href');
}
return null;
}
/**
* @param string $href
* @return string|null
*/
public static function extractIdReferenceFromHref($href)
{
if (!is_string($href) || strpos($href, '#') !== 0) {
return null;
}
return substr($href, 1);
}
/**
* @param \DOMElement $needle
* @param \DOMElement $haystack
* @return bool
*/
public static function isElementContainedIn(\DOMElement $needle, \DOMElement $haystack)
{
if ($needle === $haystack) {
return true;
}
foreach ($haystack->childNodes as $childNode) {
if (!$childNode instanceof \DOMElement) {
continue;
}
if (self::isElementContainedIn($needle, $childNode)) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,617 @@
<?php
namespace enshrined\svgSanitize;
use enshrined\svgSanitize\data\AllowedAttributes;
use enshrined\svgSanitize\data\AllowedTags;
use enshrined\svgSanitize\data\AttributeInterface;
use enshrined\svgSanitize\data\TagInterface;
use enshrined\svgSanitize\data\XPath;
use enshrined\svgSanitize\ElementReference\Resolver;
use enshrined\svgSanitize\ElementReference\Subject;
/**
* Class Sanitizer
*
* @package enshrined\svgSanitize
*/
class Sanitizer
{
/**
* @var \DOMDocument
*/
protected $xmlDocument;
/**
* @var array
*/
protected $allowedTags;
/**
* @var array
*/
protected $allowedAttrs;
/**
* @var
*/
protected $xmlLoaderValue;
/**
* @var bool
*/
protected $minifyXML = false;
/**
* @var bool
*/
protected $removeRemoteReferences = false;
/**
* @var int
*/
protected $useThreshold = 1000;
/**
* @var bool
*/
protected $removeXMLTag = false;
/**
* @var int
*/
protected $xmlOptions = LIBXML_NOEMPTYTAG;
/**
* @var array
*/
protected $xmlIssues = array();
/**
* @var Resolver
*/
protected $elementReferenceResolver;
/**
* @var int
*/
protected $useNestingLimit = 15;
/**
*
*/
function __construct()
{
// Load default tags/attributes
$this->allowedAttrs = array_map('strtolower', AllowedAttributes::getAttributes());
$this->allowedTags = array_map('strtolower', AllowedTags::getTags());
}
/**
* Set up the DOMDocument
*/
protected function resetInternal()
{
$this->xmlDocument = new \DOMDocument();
$this->xmlDocument->preserveWhiteSpace = false;
$this->xmlDocument->strictErrorChecking = false;
$this->xmlDocument->formatOutput = !$this->minifyXML;
}
/**
* Set XML options to use when saving XML
* See: DOMDocument::saveXML
*
* @param int $xmlOptions
*/
public function setXMLOptions($xmlOptions)
{
$this->xmlOptions = $xmlOptions;
}
/**
* Get XML options to use when saving XML
* See: DOMDocument::saveXML
*
* @return int
*/
public function getXMLOptions()
{
return $this->xmlOptions;
}
/**
* Get the array of allowed tags
*
* @return array
*/
public function getAllowedTags()
{
return $this->allowedTags;
}
/**
* Set custom allowed tags
*
* @param TagInterface $allowedTags
*/
public function setAllowedTags(TagInterface $allowedTags)
{
$this->allowedTags = array_map('strtolower', $allowedTags::getTags());
}
/**
* Get the array of allowed attributes
*
* @return array
*/
public function getAllowedAttrs()
{
return $this->allowedAttrs;
}
/**
* Set custom allowed attributes
*
* @param AttributeInterface $allowedAttrs
*/
public function setAllowedAttrs(AttributeInterface $allowedAttrs)
{
$this->allowedAttrs = array_map('strtolower', $allowedAttrs::getAttributes());
}
/**
* Should we remove references to remote files?
*
* @param bool $removeRemoteRefs
*/
public function removeRemoteReferences($removeRemoteRefs = false)
{
$this->removeRemoteReferences = $removeRemoteRefs;
}
/**
* Get XML issues.
*
* @return array
*/
public function getXmlIssues() {
return $this->xmlIssues;
}
/**
* Sanitize the passed string
*
* @param string $dirty
* @return string
*/
public function sanitize($dirty)
{
// Don't run on an empty string
if (empty($dirty)) {
return '';
}
// Strip php tags
$dirty = preg_replace('/<\?(=|php)(.+?)\?>/i', '', $dirty);
$this->resetInternal();
$this->setUpBefore();
$loaded = $this->xmlDocument->loadXML($dirty);
// If we couldn't parse the XML then we go no further. Reset and return false
if (!$loaded) {
$this->resetAfter();
return false;
}
$this->removeDoctype();
// Pre-process all identified elements
$xPath = new XPath($this->xmlDocument);
$this->elementReferenceResolver = new Resolver($xPath, $this->useNestingLimit);
$this->elementReferenceResolver->collect();
$elementsToRemove = $this->elementReferenceResolver->getElementsToRemove();
// Grab all the elements
$allElements = $this->xmlDocument->getElementsByTagName("*");
// Start the cleaning proccess
$this->startClean($allElements, $elementsToRemove);
// Save cleaned XML to a variable
if ($this->removeXMLTag) {
$clean = $this->xmlDocument->saveXML($this->xmlDocument->documentElement, $this->xmlOptions);
} else {
$clean = $this->xmlDocument->saveXML($this->xmlDocument, $this->xmlOptions);
}
$this->resetAfter();
// Remove any extra whitespaces when minifying
if ($this->minifyXML) {
$clean = preg_replace('/\s+/', ' ', $clean);
}
// Return result
return $clean;
}
/**
* Set up libXML before we start
*/
protected function setUpBefore()
{
// Turn off the entity loader
$this->xmlLoaderValue = libxml_disable_entity_loader(true);
// Suppress the errors because we don't really have to worry about formation before cleansing
libxml_use_internal_errors(true);
// Reset array of altered XML
$this->xmlIssues = array();
}
/**
* Reset the class after use
*/
protected function resetAfter()
{
// Reset the entity loader
libxml_disable_entity_loader($this->xmlLoaderValue);
}
/**
* Remove the XML Doctype
* It may be caught later on output but that seems to be buggy, so we need to make sure it's gone
*/
protected function removeDoctype()
{
foreach ($this->xmlDocument->childNodes as $child) {
if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
$child->parentNode->removeChild($child);
}
}
}
/**
* Start the cleaning with tags, then we move onto attributes and hrefs later
*
* @param \DOMNodeList $elements
* @param array $elementsToRemove
*/
protected function startClean(\DOMNodeList $elements, array $elementsToRemove)
{
// loop through all elements
// we do this backwards so we don't skip anything if we delete a node
// see comments at: http://php.net/manual/en/class.domnamednodemap.php
for ($i = $elements->length - 1; $i >= 0; $i--) {
/** @var \DOMElement $currentElement */
$currentElement = $elements->item($i);
/**
* If the element has exceeded the nesting limit, we should remove it.
*
* As it's only <use> elements that cause us issues with nesting DOS attacks
* we should check what the element is before removing it. For now we'll only
* remove <use> elements.
*/
if (in_array($currentElement, $elementsToRemove) && 'use' === $currentElement->nodeName) {
$currentElement->parentNode->removeChild($currentElement);
$this->xmlIssues[] = array(
'message' => 'Invalid \'' . $currentElement->tagName . '\'',
'line' => $currentElement->getLineNo(),
);
continue;
}
// If the tag isn't in the whitelist, remove it and continue with next iteration
if (!in_array(strtolower($currentElement->tagName), $this->allowedTags)) {
$currentElement->parentNode->removeChild($currentElement);
$this->xmlIssues[] = array(
'message' => 'Suspicious tag \'' . $currentElement->tagName . '\'',
'line' => $currentElement->getLineNo(),
);
continue;
}
$this->cleanHrefs($currentElement);
$this->cleanXlinkHrefs($currentElement);
$this->cleanAttributesOnWhitelist($currentElement);
if (strtolower($currentElement->tagName) === 'use') {
if ($this->isUseTagDirty($currentElement)
|| $this->isUseTagExceedingThreshold($currentElement)
) {
$currentElement->parentNode->removeChild($currentElement);
$this->xmlIssues[] = array(
'message' => 'Suspicious \'' . $currentElement->tagName . '\'',
'line' => $currentElement->getLineNo(),
);
continue;
}
}
}
}
/**
* Only allow attributes that are on the whitelist
*
* @param \DOMElement $element
*/
protected function cleanAttributesOnWhitelist(\DOMElement $element)
{
for ($x = $element->attributes->length - 1; $x >= 0; $x--) {
// get attribute name
$attrName = $element->attributes->item($x)->name;
// Remove attribute if not in whitelist
if (!in_array(strtolower($attrName), $this->allowedAttrs) && !$this->isAriaAttribute(strtolower($attrName)) && !$this->isDataAttribute(strtolower($attrName))) {
$element->removeAttribute($attrName);
$this->xmlIssues[] = array(
'message' => 'Suspicious attribute \'' . $attrName . '\'',
'line' => $element->getLineNo(),
);
}
/**
* This is used for when a namespace isn't imported properly.
* Such as xlink:href when the xlink namespace isn't imported.
* We have to do this as the link is still ran in this case.
*/
if (false !== strpos($attrName, 'href')) {
$href = $element->getAttribute($attrName);
if (false === $this->isHrefSafeValue($href)) {
$element->removeAttribute($attrName);
$this->xmlIssues[] = array(
'message' => 'Suspicious attribute \'href\'',
'line' => $element->getLineNo(),
);
}
}
// Do we want to strip remote references?
if($this->removeRemoteReferences) {
// Remove attribute if it has a remote reference
if (isset($element->attributes->item($x)->value) && $this->hasRemoteReference($element->attributes->item($x)->value)) {
$element->removeAttribute($attrName);
$this->xmlIssues[] = array(
'message' => 'Suspicious attribute \'' . $attrName . '\'',
'line' => $element->getLineNo(),
);
}
}
}
}
/**
* Clean the xlink:hrefs of script and data embeds
*
* @param \DOMElement $element
*/
protected function cleanXlinkHrefs(\DOMElement $element)
{
$xlinks = $element->getAttributeNS('http://www.w3.org/1999/xlink', 'href');
if (false === $this->isHrefSafeValue($xlinks)) {
$element->removeAttributeNS( 'http://www.w3.org/1999/xlink', 'href' );
$this->xmlIssues[] = array(
'message' => 'Suspicious attribute \'href\'',
'line' => $element->getLineNo(),
);
}
}
/**
* Clean the hrefs of script and data embeds
*
* @param \DOMElement $element
*/
protected function cleanHrefs(\DOMElement $element)
{
$href = $element->getAttribute('href');
if (false === $this->isHrefSafeValue($href)) {
$element->removeAttribute('href');
$this->xmlIssues[] = array(
'message' => 'Suspicious attribute \'href\'',
'line' => $element->getLineNo(),
);
}
}
/**
* Only allow whitelisted starts to be within the href.
*
* This will stop scripts etc from being passed through, with or without attempting to hide bypasses.
* This stops the need for us to use a complicated script regex.
*
* @param $value
* @return bool
*/
protected function isHrefSafeValue($value) {
// Allow fragment identifiers.
if ('#' === substr($value, 0, 1)) {
return true;
}
// Allow relative URIs.
if ('/' === substr($value, 0, 1)) {
return true;
}
// Allow HTTPS domains.
if ('https://' === substr($value, 0, 8)) {
return true;
}
// Allow HTTP domains.
if ('http://' === substr($value, 0, 7)) {
return true;
}
// Allow known data URIs.
if (in_array(substr($value, 0, 14), array(
'data:image/png', // PNG
'data:image/gif', // GIF
'data:image/jpg', // JPG
'data:image/jpe', // JPEG
'data:image/pjp', // PJPEG
))) {
return true;
}
// Allow known short data URIs.
if (in_array(substr($value, 0, 12), array(
'data:img/png', // PNG
'data:img/gif', // GIF
'data:img/jpg', // JPG
'data:img/jpe', // JPEG
'data:img/pjp', // PJPEG
))) {
return true;
}
return false;
}
/**
* Removes non-printable ASCII characters from string & trims it
*
* @param string $value
* @return bool
*/
protected function removeNonPrintableCharacters($value)
{
return trim(preg_replace('/[^ -~]/xu','',$value));
}
/**
* Does this attribute value have a remote reference?
*
* @param $value
* @return bool
*/
protected function hasRemoteReference($value)
{
$value = $this->removeNonPrintableCharacters($value);
$wrapped_in_url = preg_match('~^url\(\s*[\'"]\s*(.*)\s*[\'"]\s*\)$~xi', $value, $match);
if (!$wrapped_in_url){
return false;
}
$value = trim($match[1], '\'"');
return preg_match('~^((https?|ftp|file):)?//~xi', $value);
}
/**
* Should we minify the output?
*
* @param bool $shouldMinify
*/
public function minify($shouldMinify = false)
{
$this->minifyXML = (bool) $shouldMinify;
}
/**
* Should we remove the XML tag in the header?
*
* @param bool $removeXMLTag
*/
public function removeXMLTag($removeXMLTag = false)
{
$this->removeXMLTag = (bool) $removeXMLTag;
}
/**
* Whether `<use ... xlink:href="#identifier">` elements shall be
* removed in case expansion would exceed this threshold.
*
* @param int $useThreshold
*/
public function useThreshold($useThreshold = 1000)
{
$this->useThreshold = (int)$useThreshold;
}
/**
* Check to see if an attribute is an aria attribute or not
*
* @param $attributeName
*
* @return bool
*/
protected function isAriaAttribute($attributeName)
{
return strpos($attributeName, 'aria-') === 0;
}
/**
* Check to see if an attribute is an data attribute or not
*
* @param $attributeName
*
* @return bool
*/
protected function isDataAttribute($attributeName)
{
return strpos($attributeName, 'data-') === 0;
}
/**
* Make sure our use tag is only referencing internal resources
*
* @param \DOMElement $element
* @return bool
*/
protected function isUseTagDirty(\DOMElement $element)
{
$href = Helper::getElementHref($element);
return $href && strpos($href, '#') !== 0;
}
/**
* Determines whether `<use ... xlink:href="#identifier">` is expanded
* recursively in order to create DoS scenarios. The amount of a actually
* used element needs to be below `$this->useThreshold`.
*
* @param \DOMElement $element
* @return bool
*/
protected function isUseTagExceedingThreshold(\DOMElement $element)
{
if ($this->useThreshold <= 0) {
return false;
}
$useId = Helper::extractIdReferenceFromHref(
Helper::getElementHref($element)
);
if ($useId === null) {
return false;
}
foreach ($this->elementReferenceResolver->findByElementId($useId) as $subject) {
if ($subject->countUse() >= $this->useThreshold) {
return true;
}
}
return false;
}
/**
* Set the nesting limit for <use> tags.
*
* @param $limit
*/
public function setUseNestingLimit($limit)
{
$this->useNestingLimit = (int) $limit;
}
}

View File

@@ -0,0 +1,357 @@
<?php
namespace enshrined\svgSanitize\data;
/**
* Class AllowedAttributes
*
* @package enshrined\svgSanitize\data
*/
class AllowedAttributes implements AttributeInterface
{
/**
* Returns an array of attributes
*
* @return array
*/
public static function getAttributes()
{
return array(
// HTML
'about',
'accept',
'action',
'align',
'alt',
'autocomplete',
'background',
'bgcolor',
'border',
'cellpadding',
'cellspacing',
'checked',
'cite',
'class',
'clear',
'color',
'cols',
'colspan',
'coords',
'crossorigin',
'datetime',
'default',
'dir',
'disabled',
'download',
'enctype',
'encoding',
'face',
'for',
'headers',
'height',
'hidden',
'high',
'href',
'hreflang',
'id',
'integrity',
'ismap',
'label',
'lang',
'list',
'loop',
'low',
'max',
'maxlength',
'media',
'method',
'min',
'multiple',
'name',
'noshade',
'novalidate',
'nowrap',
'open',
'optimum',
'pattern',
'placeholder',
'poster',
'preload',
'pubdate',
'radiogroup',
'readonly',
'rel',
'required',
'rev',
'reversed',
'role',
'rows',
'rowspan',
'spellcheck',
'scope',
'selected',
'shape',
'size',
'sizes',
'span',
'srclang',
'start',
'src',
'srcset',
'step',
'style',
'summary',
'tabindex',
'title',
'type',
'usemap',
'valign',
'value',
'version',
'width',
'xmlns',
// SVG
'accent-height',
'accumulate',
'additivive',
'alignment-baseline',
'ascent',
'attributename',
'attributetype',
'azimuth',
'basefrequency',
'baseline-shift',
'begin',
'bias',
'by',
'class',
'clip',
'clip-path',
'clip-rule',
'color',
'color-interpolation',
'color-interpolation-filters',
'color-profile',
'color-rendering',
'cx',
'cy',
'd',
'dx',
'dy',
'diffuseconstant',
'direction',
'display',
'divisor',
'dur',
'edgemode',
'elevation',
'end',
'fill',
'fill-opacity',
'fill-rule',
'filter',
'flood-color',
'flood-opacity',
'font-family',
'font-size',
'font-size-adjust',
'font-stretch',
'font-style',
'font-variant',
'font-weight',
'fx',
'fy',
'g1',
'g2',
'glyph-name',
'glyphref',
'gradientunits',
'gradienttransform',
'height',
'href',
'id',
'image-rendering',
'in',
'in2',
'k',
'k1',
'k2',
'k3',
'k4',
'kerning',
'keypoints',
'keysplines',
'keytimes',
'lang',
'lengthadjust',
'letter-spacing',
'kernelmatrix',
'kernelunitlength',
'lighting-color',
'local',
'marker-end',
'marker-mid',
'marker-start',
'markerheight',
'markerunits',
'markerwidth',
'maskcontentunits',
'maskunits',
'max',
'mask',
'media',
'method',
'mode',
'min',
'name',
'numoctaves',
'offset',
'operator',
'opacity',
'order',
'orient',
'orientation',
'origin',
'overflow',
'paint-order',
'path',
'pathlength',
'patterncontentunits',
'patterntransform',
'patternunits',
'points',
'preservealpha',
'preserveaspectratio',
'r',
'rx',
'ry',
'radius',
'refx',
'refy',
'repeatcount',
'repeatdur',
'restart',
'result',
'rotate',
'scale',
'seed',
'shape-rendering',
'specularconstant',
'specularexponent',
'spreadmethod',
'stddeviation',
'stitchtiles',
'stop-color',
'stop-opacity',
'stroke-dasharray',
'stroke-dashoffset',
'stroke-linecap',
'stroke-linejoin',
'stroke-miterlimit',
'stroke-opacity',
'stroke',
'stroke-width',
'style',
'surfacescale',
'tabindex',
'targetx',
'targety',
'transform',
'text-anchor',
'text-decoration',
'text-rendering',
'textlength',
'type',
'u1',
'u2',
'unicode',
'values',
'viewbox',
'visibility',
'vert-adv-y',
'vert-origin-x',
'vert-origin-y',
'width',
'word-spacing',
'wrap',
'writing-mode',
'xchannelselector',
'ychannelselector',
'x',
'x1',
'x2',
'xmlns',
'y',
'y1',
'y2',
'z',
'zoomandpan',
// MathML
'accent',
'accentunder',
'align',
'bevelled',
'close',
'columnsalign',
'columnlines',
'columnspan',
'denomalign',
'depth',
'dir',
'display',
'displaystyle',
'fence',
'frame',
'height',
'href',
'id',
'largeop',
'length',
'linethickness',
'lspace',
'lquote',
'mathbackground',
'mathcolor',
'mathsize',
'mathvariant',
'maxsize',
'minsize',
'movablelimits',
'notation',
'numalign',
'open',
'rowalign',
'rowlines',
'rowspacing',
'rowspan',
'rspace',
'rquote',
'scriptlevel',
'scriptminsize',
'scriptsizemultiplier',
'selection',
'separator',
'separators',
'slope',
'stretchy',
'subscriptshift',
'supscriptshift',
'symmetric',
'voffset',
'width',
'xmlns',
// XML
'xlink:href',
'xml:id',
'xlink:title',
'xml:space',
'xmlns:xlink',
);
}
}

View File

@@ -0,0 +1,245 @@
<?php
namespace enshrined\svgSanitize\data;
/**
* Class AllowedTags
*
* @package enshrined\svgSanitize\data
*/
class AllowedTags implements TagInterface
{
/**
* Returns an array of tags
*
* @return array
*/
public static function getTags()
{
return array (
// HTML
'a',
'abbr',
'acronym',
'address',
'area',
'article',
'aside',
'audio',
'b',
'bdi',
'bdo',
'big',
'blink',
'blockquote',
'body',
'br',
'button',
'canvas',
'caption',
'center',
'cite',
'code',
'col',
'colgroup',
'content',
'data',
'datalist',
'dd',
'decorator',
'del',
'details',
'dfn',
'dir',
'div',
'dl',
'dt',
'element',
'em',
'fieldset',
'figcaption',
'figure',
'font',
'footer',
'form',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'head',
'header',
'hgroup',
'hr',
'html',
'i',
'image',
'img',
'input',
'ins',
'kbd',
'label',
'legend',
'li',
'main',
'map',
'mark',
'marquee',
'menu',
'menuitem',
'meter',
'nav',
'nobr',
'ol',
'optgroup',
'option',
'output',
'p',
'pre',
'progress',
'q',
'rp',
'rt',
'ruby',
's',
'samp',
'section',
'select',
'shadow',
'small',
'source',
'spacer',
'span',
'strike',
'strong',
'style',
'sub',
'summary',
'sup',
'table',
'tbody',
'td',
'template',
'textarea',
'tfoot',
'th',
'thead',
'time',
'tr',
'track',
'tt',
'u',
'ul',
'var',
'video',
'wbr',
// SVG
'svg',
'altglyph',
'altglyphdef',
'altglyphitem',
'animatecolor',
'animatemotion',
'animatetransform',
'circle',
'clippath',
'defs',
'desc',
'ellipse',
'filter',
'font',
'g',
'glyph',
'glyphref',
'hkern',
'image',
'line',
'lineargradient',
'marker',
'mask',
'metadata',
'mpath',
'path',
'pattern',
'polygon',
'polyline',
'radialgradient',
'rect',
'stop',
'switch',
'symbol',
'text',
'textpath',
'title',
'tref',
'tspan',
'use',
'view',
'vkern',
// SVG Filters
'feBlend',
'feColorMatrix',
'feComponentTransfer',
'feComposite',
'feConvolveMatrix',
'feDiffuseLighting',
'feDisplacementMap',
'feDistantLight',
'feFlood',
'feFuncA',
'feFuncB',
'feFuncG',
'feFuncR',
'feGaussianBlur',
'feMerge',
'feMergeNode',
'feMorphology',
'feOffset',
'fePointLight',
'feSpecularLighting',
'feSpotLight',
'feTile',
'feTurbulence',
//MathML
'math',
'menclose',
'merror',
'mfenced',
'mfrac',
'mglyph',
'mi',
'mlabeledtr',
'mmuliscripts',
'mn',
'mo',
'mover',
'mpadded',
'mphantom',
'mroot',
'mrow',
'ms',
'mpspace',
'msqrt',
'mystyle',
'msub',
'msup',
'msubsup',
'mtable',
'mtd',
'mtext',
'mtr',
'munder',
'munderover',
//text
'#text'
);
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace enshrined\svgSanitize\data;
/**
* Class AttributeInterface
*
* @package enshrined\svgSanitize\data
*/
interface AttributeInterface
{
/**
* Returns an array of attributes
*
* @return array
*/
public static function getAttributes();
}

View File

@@ -0,0 +1,19 @@
<?php
namespace enshrined\svgSanitize\data;
/**
* Interface TagInterface
*
* @package enshrined\svgSanitize\tags
*/
interface TagInterface
{
/**
* Returns an array of tags
*
* @return array
*/
public static function getTags();
}

View File

@@ -0,0 +1,64 @@
<?php
namespace enshrined\svgSanitize\data;
class XPath extends \DOMXPath
{
const DEFAULT_NAMESPACE_PREFIX = 'svg';
/**
* @var string
*/
protected $defaultNamespaceURI;
public function __construct(\DOMDocument $doc)
{
parent::__construct($doc);
$this->handleDefaultNamespace();
}
/**
* @param string $nodeName
* @return string
*/
public function createNodeName($nodeName)
{
if (empty($this->defaultNamespaceURI)) {
return $nodeName;
}
return self::DEFAULT_NAMESPACE_PREFIX . ':' . $nodeName;
}
protected function handleDefaultNamespace()
{
$rootElements = $this->getRootElements();
if (count($rootElements) !== 1) {
throw new \LogicException(
sprintf('Got %d svg elements, expected exactly one', count($rootElements)),
1570870568
);
}
$this->defaultNamespaceURI = (string)$rootElements[0]->namespaceURI;
if ($this->defaultNamespaceURI !== '') {
$this->registerNamespace(self::DEFAULT_NAMESPACE_PREFIX, $this->defaultNamespaceURI);
}
}
/**
* @return \DOMElement[]
*/
protected function getRootElements()
{
$rootElements = [];
$elements = $this->document->getElementsByTagName('svg');
/** @var \DOMElement $element */
foreach ($elements as $element) {
if ($element->parentNode !== $this->document) {
continue;
}
$rootElements[] = $element;
}
return $rootElements;
}
}

View File

@@ -0,0 +1,187 @@
#!/usr/bin/env php
<?php
/*
* Simple program that uses svg-sanitizer
* to find issues in files specified on the
* command line, and prints a JSON output with
* the issues found on exit.
*/
require_once( __DIR__ . '/data/AttributeInterface.php' );
require_once( __DIR__ . '/data/TagInterface.php' );
require_once( __DIR__ . '/data/AllowedAttributes.php' );
require_once( __DIR__ . '/data/AllowedTags.php' );
require_once( __DIR__ . '/Sanitizer.php' );
/*
* Print array as JSON and then
* exit program with a particular
* exit-code.
*/
function sysexit(
$results,
$status
) {
echo json_encode(
$results,
JSON_PRETTY_PRINT
);
exit( $status );
}
/*
* Main part begins
*/
global $argv;
/*
* Set up results array, to
* be printed on exit.
*/
$results = array(
'totals' => array(
'errors' => 0,
),
'files' => array(
),
);
/*
* Catch files to scan from $argv.
*/
$files_to_scan = $argv;
unset( $files_to_scan[0] );
$files_to_scan = array_values(
$files_to_scan
);
/*
* Catch no file specified.
*/
if ( empty( $files_to_scan ) ) {
$results['totals']['errors']++;
$results['messages'] = array(
array( 'No files to scan specified' ),
);
sysexit(
$results,
1
);
}
/*
* Initialize the SVG scanner.
*
* Make sure to allow custom attributes,
* and to remove remote references.
*/
$sanitizer = new enshrined\svgSanitize\Sanitizer();
$sanitizer->removeRemoteReferences( true );
/*
* Scan each file specified to be scanned.
*/
foreach( $files_to_scan as $file_name ) {
/*
* Read SVG file.
*/
$svg_file = @file_get_contents( $file_name );
/*
* If not found, report that and continue.
*/
if ( false === $svg_file ) {
$results['totals']['errors']++;
$results['files'][ $file_name ][] = array(
'errors' => 1,
'messages' => array(
array(
'message' => 'File specified could not be read (' . $file_name . ')',
'line' => null,
),
),
);
continue;
}
/*
* Sanitize file and get issues found.
*/
$sanitize_status = $sanitizer->sanitize( $svg_file );
$xml_issues = $sanitizer->getXmlIssues();
/*
* If we find no issues, simply note that.
*/
if ( empty( $xml_issues ) && ( false !== $sanitize_status ) ) {
$results['files'][ $file_name ] = array(
'errors' => 0,
'messages' => array()
);
}
/*
* Could not sanitize the file.
*/
else if (
( '' === $sanitize_status ) ||
( false === $sanitize_status )
) {
$results['totals']['errors']++;
$results['files'][ $file_name ] = array(
'errors' => 1,
'messages' => array(
array(
'message' => 'Unable to sanitize file \'' . $file_name . '\'' ,
'line' => null,
)
),
);
}
/*
* If we find issues, note it and update statistics.
*/
else {
$results['totals']['errors'] += count( $xml_issues );
$results['files'][ $file_name ] = array(
'errors' => count( $xml_issues ),
'messages' => $xml_issues,
);
}
unset( $svg_file );
unset( $xml_issues );
unset( $sanitize_status );
}
/*
* Exit with a status
* that reflects what issues
* we found.
*/
sysexit(
$results,
( $results['totals']['errors'] === 0 ? 0 : 1 )
);

View File

@@ -0,0 +1,15 @@
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[*.yml]
indent_size = 2

View File

@@ -0,0 +1,56 @@
FROM php:5.6-alpine
ENV SRC_DIR /usr/src/gaufrette
RUN apk add --no-cache --virtual .persistent-deps \
git \
zlib
# PHP extensions
ENV MONGODB_VERSION="1.2.11" \
SSH2_VERSION="0.13"
RUN set -xe \
&& apk add --no-cache --virtual .build-deps \
$PHPIZE_DEPS \
libssh2-dev \
zlib-dev \
&& docker-php-ext-install \
zip \
&& pecl install \
mongodb-${MONGODB_VERSION} \
ssh2-${SSH2_VERSION} \
&& docker-php-ext-enable --ini-name 05-opcache.ini opcache \
&& docker-php-ext-enable \
mongodb \
ssh2 \
&& apk del .build-deps
COPY docker/php.ini /usr/local/etc/php/php.ini
COPY docker/install-composer.sh /usr/local/bin/install-composer
RUN chmod +x /usr/local/bin/install-composer
RUN set -xe \
&& install-composer \
&& mv composer.phar /usr/local/bin/composer
ENV COMPOSER_ALLOW_SUPERUSER 1
RUN composer global require "hirak/prestissimo" --prefer-dist --no-progress --no-suggest --optimize-autoloader --apcu-autoloader \
&& composer clear-cache
WORKDIR ${SRC_DIR}
COPY composer.json ./
RUN composer update --prefer-dist --no-autoloader --no-scripts --no-progress --no-suggest \
&& composer clear-cache
COPY spec spec/
COPY src src/
COPY tests tests/
COPY bin/tests bin/tests
RUN composer dump-autoload
CMD ["bin/tests"]

View File

@@ -0,0 +1,68 @@
FROM php:7.0-alpine
ENV SRC_DIR /usr/src/gaufrette
RUN apk add --no-cache --virtual .persistent-deps \
git \
zlib
# PHP extensions
ENV MONGODB_VERSION="1.2.11" \
SSH2_VERSION="1.1.2"
RUN set -xe \
&& apk add --no-cache --virtual .build-deps \
$PHPIZE_DEPS \
libssh2-dev \
zlib-dev \
&& docker-php-ext-install \
zip \
&& pecl install \
mongodb-${MONGODB_VERSION} \
ssh2-${SSH2_VERSION} \
&& docker-php-ext-enable --ini-name 05-opcache.ini opcache \
&& docker-php-ext-enable \
mongodb \
ssh2 \
&& apk del .build-deps
COPY docker/php.ini /usr/local/etc/php/php.ini
COPY docker/install-composer.sh /usr/local/bin/docker-gaufrette-install-composer
RUN chmod +x /usr/local/bin/docker-gaufrette-install-composer
RUN set -xe \
&& apk add --no-cache --virtual .fetch-deps \
openssl \
&& docker-gaufrette-install-composer \
&& mv composer.phar /usr/local/bin/composer \
&& apk del .fetch-deps
COPY docker/php.ini /usr/local/etc/php/php.ini
COPY docker/install-composer.sh /usr/local/bin/install-composer
RUN chmod +x /usr/local/bin/install-composer
RUN set -xe \
&& install-composer \
&& mv composer.phar /usr/local/bin/composer
ENV COMPOSER_ALLOW_SUPERUSER 1
RUN composer global require "hirak/prestissimo" --prefer-dist --no-progress --no-suggest --optimize-autoloader --apcu-autoloader \
&& composer clear-cache
WORKDIR ${SRC_DIR}
COPY composer.json ./
RUN composer update --prefer-dist --no-autoloader --no-scripts --no-progress --no-suggest \
&& composer clear-cache
COPY spec spec/
COPY src src/
COPY tests tests/
COPY bin/tests bin/tests
RUN composer dump-autoload
CMD ["bin/tests"]

View File

@@ -0,0 +1,56 @@
FROM php:7.1-alpine
ENV SRC_DIR /usr/src/gaufrette
RUN apk add --no-cache --virtual .persistent-deps \
git \
zlib
# PHP extensions
ENV MONGODB_VERSION="1.2.11" \
SSH2_VERSION="1.1.2"
RUN set -xe \
&& apk add --no-cache --virtual .build-deps \
$PHPIZE_DEPS \
libssh2-dev \
zlib-dev \
&& docker-php-ext-install \
zip \
&& pecl install \
mongodb-${MONGODB_VERSION} \
ssh2-${SSH2_VERSION} \
&& docker-php-ext-enable --ini-name 05-opcache.ini opcache \
&& docker-php-ext-enable \
mongodb \
ssh2 \
&& apk del .build-deps
COPY docker/php.ini /usr/local/etc/php/php.ini
COPY docker/install-composer.sh /usr/local/bin/install-composer
RUN chmod +x /usr/local/bin/install-composer
RUN set -xe \
&& install-composer \
&& mv composer.phar /usr/local/bin/composer
ENV COMPOSER_ALLOW_SUPERUSER 1
RUN composer global require "hirak/prestissimo" --prefer-dist --no-progress --no-suggest --optimize-autoloader --apcu-autoloader \
&& composer clear-cache
WORKDIR ${SRC_DIR}
COPY composer.json ./
RUN composer update --prefer-dist --no-autoloader --no-scripts --no-progress --no-suggest \
&& composer clear-cache
COPY spec spec/
COPY src src/
COPY tests tests/
COPY bin/tests bin/tests
RUN composer dump-autoload
CMD ["bin/tests"]

View File

@@ -0,0 +1,22 @@
Copyright (c) 2010 Antoine Hérault
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,68 @@
build: false
platform: 'x86'
clone_folder: C:\projects\gaufrette
branches:
except:
- gh-pages
cache:
- '%LOCALAPPDATA%\Composer\files'
- c:\php -> appveyor.yml
environment:
AWS_KEY:
secure: nMVfvhojgVc9VBlrYXeddaYIQHlVAlupWmxNjXMlsB0=
AWS_SECRET:
secure: MiAf2q7mnqSIZSoChd9v3pwUrXHeAEpZP8Zc0E0qjiOBXPvplzJVtrkWRwTNlQl3
AWS_BUCKET: gaufretteci
RACKSPACE_USER:
secure: aEIZdm+IXe9dGLOnSmgu8A==
RACKSPACE_APIKEY:
secure: CqBlB4EVIM2FMaYxBdplTaQzw8JgKElxYvKYpXUXPHpOdwJcnYy0gk2KdjF4fXDM
RACKSPACE_CONTAINER: gaufretteci
AZURE_ACCOUNT:
secure: s6JCZ8ztVGvVYprceONZOg==
AZURE_KEY:
secure: 6+9kd9n/BO65LI8ZCJJXOwo9v5QmMULKWExHgECe+rnflaw+ZiQ8jFfHwxxjOfUF1qulAyxHQmDj7M3Cfvbe/DAASjk52ngEMvHC6wv2/Eo0cBMQiUlS9vPeUlvkUy1L
AZURE_CONTAINER: gaufretteci
MONGO_URI: "mongodb://127.0.0.1:27017"
MONGO_DBNAME: "gridfs_test"
services:
- mongodb
init:
- SET PATH=C:\Program Files\OpenSSL;c:\php;%PATH%
- SET PHP=1
install:
- IF EXIST c:\php (SET PHP=0) ELSE (mkdir c:\php)
- cd c:\php
- IF %PHP%==1 cinst -y OpenSSL.Light
- IF %PHP%==1 curl -fsSL -o php-5.6.33-Win32-VC11-x86.zip https://windows.php.net/downloads/releases/archives/php-5.6.33-Win32-VC11-x86.zip
- IF %PHP%==1 7z x php-5.6.33-Win32-VC11-x86.zip -y >nul
- IF %PHP%==1 del /Q *.zip
- IF %PHP%==1 curl -fsSL -o cacert.pem https://curl.haxx.se/ca/cacert.pem
- IF %PHP%==1 cd ext
- IF %PHP%==1 curl -fsSL -o php_mongodb-1.2.9-5.6-ts-vc11-x86.zip https://windows.php.net/downloads/pecl/releases/mongodb/1.2.9/php_mongodb-1.2.9-5.6-ts-vc11-x86.zip
- IF %PHP%==1 7z x php_mongodb-1.2.9-5.6-ts-vc11-x86.zip php_mongodb.dll -y >nul
- IF %PHP%==1 del /Q *.zip
- IF %PHP%==1 cd ..
- IF %PHP%==1 copy php.ini-production php.ini /Y
- IF %PHP%==1 echo extension_dir=ext >> php.ini
- IF %PHP%==1 echo date.timezone="UTC" >> php.ini
- IF %PHP%==1 echo extension=php_mbstring.dll >> php.ini
- IF %PHP%==1 echo extension=php_openssl.dll >> php.ini
- IF %PHP%==1 echo extension=php_mongodb.dll >> php.ini
- IF %PHP%==1 echo extension=php_pdo_sqlite.dll >> php.ini
- IF %PHP%==1 echo extension=php_fileinfo.dll >> php.ini
- IF %PHP%==1 echo extension=php_curl.dll >> php.ini
- IF %PHP%==1 echo openssl.cafile=c:\php\cacert.pem >> php.ini
- cd C:\projects\gaufrette
- curl -fsSL -o composer.phar https://getcomposer.org/composer.phar
- php composer.phar update --prefer-dist --no-interaction --no-progress --no-suggest --ansi
test_script:
- cd C:\projects\gaufrette
- vendor\bin\phpspec run -fpretty --verbose
- vendor\bin\phpunit --verbose -c phpunit.xml.dist

View File

@@ -0,0 +1,10 @@
#!/bin/sh
set -o nounset
set -o errexit
set -o xtrace
DIR=$(dirname $0)/..
${DIR}/vendor/bin/phpunit tests
${DIR}/vendor/bin/phpspec run --format=pretty --no-code-generation

View File

@@ -0,0 +1,7 @@
#!/bin/sh
set -o xtrace
docker-compose run --rm php56
docker-compose run --rm php70
docker-compose run --rm php71

View File

@@ -0,0 +1,3 @@
FROM stilliard/pure-ftpd
RUN (echo gaufrette; echo gaufrette) | pure-pw useradd gaufrette -f /etc/pure-ftpd/passwd/pureftpd.passwd -m -u ftpuser -d /home/ftpusers/gaufrette

View File

@@ -0,0 +1,21 @@
#!/bin/sh
# Copyright (c) Nils Adermann, Jordi Boggiano
# Origin: https://github.com/composer/composer/blob/master/doc/faqs/how-to-install-composer-programmatically.md
# Licence: MIT
EXPECTED_SIGNATURE=$(wget -q -O - https://composer.github.io/installer.sig)
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
ACTUAL_SIGNATURE=$(php -r "echo hash_file('SHA384', 'composer-setup.php');")
if [ "$EXPECTED_SIGNATURE" != "$ACTUAL_SIGNATURE" ]
then
>&2 echo 'ERROR: Invalid installer signature'
rm composer-setup.php
exit 1
fi
php composer-setup.php --quiet
RESULT=$?
rm composer-setup.php
exit $RESULT

View File

@@ -0,0 +1,2 @@
apc.enable_cli = 1
date.timezone = UTC

View File

@@ -0,0 +1,2 @@
extensions:
Akeneo\SkipExampleExtension: Akeneo\SkipExampleExtension

View File

@@ -0,0 +1,238 @@
<?php
namespace spec\Gaufrette\Adapter;
use PhpSpec\ObjectBehavior;
class AclAwareAmazonS3Spec extends ObjectBehavior
{
/**
* @param \Gaufrette\Adapter $adapter
* @param \AmazonS3 $service
*/
function let($adapter, $service)
{
$this->beConstructedWith($adapter, $service, 'bucketName');
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
function it_supports_metadata()
{
$this->shouldHaveType('Gaufrette\Adapter\MetadataSupporter');
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_delegates_read($adapter)
{
$adapter->read('filename')->willReturn('some content');
$adapter->read('filename2')->willReturn('other content');
$this->read('filename')->shouldReturn('some content');
$this->read('filename2')->shouldReturn('other content');
}
/**
* @param \Gaufrette\Adapter $adapter
* @param \AmazonS3 $service
*/
function it_delegates_rename_and_update_acl($adapter, $service)
{
$service
->set_object_acl('bucketName', 'filename2', \AmazonS3::ACL_PRIVATE)
->shouldBeCalled()
->willReturn(new \CFResponse(array(), '', 200))
;
$adapter
->rename('filename', 'filename2')
->shouldBeCalled()
->willReturn(true)
;
$adapter
->delete('filename')
->shouldNotBeCalled()
;
$this->rename('filename', 'filename2')->shouldReturn(true);
}
/**
* @param \Gaufrette\Adapter $adapter
* @param \AmazonS3 $service
*/
function it_does_not_rename_when_cannot_update_acl($adapter, $service)
{
$service
->set_object_acl('bucketName', 'filename2', \AmazonS3::ACL_PRIVATE)
->shouldBeCalled()
->willReturn(new \CFResponse(array(), '', 500));
$adapter
->rename('filename', 'filename2')
->shouldBeCalled()
->willReturn(true);
$adapter
->delete('filename2')
->shouldBeCalled();
$this->rename('filename', 'filename2')->shouldReturn(false);
}
/**
* @param \Gaufrette\Adapter $adapter
* @param \AmazonS3 $service
*/
function it_updates_acl_with_users_array_when_rename($adapter, $service)
{
$service
->set_object_acl('bucketName', 'filename2', array(array('id' => 'someId', 'permission' => \AmazonS3::GRANT_READ)))
->shouldBeCalled()
->willReturn(new \CFResponse(array(), '', 200))
;
$adapter
->rename('filename', 'filename2')
->willReturn(true)
;
$this->setUsers(array(array('id' => 'someId', 'permission' => 'read')));
$this->rename('filename', 'filename2')->shouldReturn(true);
}
/**
* @param \Gaufrette\Adapter $adapter
* @param \AmazonS3 $service
*/
function it_delegates_write_and_update_acl($adapter, $service)
{
$service
->set_object_acl('bucketName', 'filename', \AmazonS3::ACL_PRIVATE)
->shouldBeCalled()
->willReturn(new \CFResponse(array(), '', 200))
;
$adapter
->write('filename', 'some content')
->shouldBeCalled()
->willReturn(12)
;
$adapter
->delete('filename')
->shouldNotBeCalled()
;
$this->write('filename', 'some content')->shouldReturn(12);
}
/**
* @param \Gaufrette\Adapter $adapter
* @param \AmazonS3 $service
*/
function it_does_not_write_when_cannot_update_acl($adapter, $service)
{
$service
->set_object_acl('bucketName', 'filename', \AmazonS3::ACL_PRIVATE)
->shouldBeCalled()
->willReturn(new \CFResponse(array(), '', 500))
;
$adapter
->write('filename', 'some content')
->shouldBeCalled()
->willReturn(12)
;
$adapter
->delete('filename')
->shouldBeCalled()
;
$this->write('filename', 'some content')->shouldReturn(false);
}
/**
* @param \Gaufrette\Adapter $adapter
* @param \AmazonS3 $service
*/
function it_updates_acl_with_users_array_when_write($adapter, $service)
{
$service
->set_object_acl('bucketName', 'filename', array(array('id' => 'someId', 'permission' => \AmazonS3::GRANT_READ)))
->shouldBeCalled()
->willReturn(new \CFResponse(array(), '', 200))
;
$adapter
->write('filename', 'some content')
->willReturn(12)
;
$this->setUsers(array(array('id' => 'someId', 'permission' => 'read')));
$this->write('filename', 'some content')->shouldReturn(12);
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_delegates_exists($adapter)
{
$adapter->exists('filename')->willReturn(true);
$adapter->exists('filename2')->willReturn(false);
$this->exists('filename')->shouldReturn(true);
$this->exists('filename2')->shouldReturn(false);
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_delegates_mtime($adapter)
{
$adapter->mtime('filename')->willReturn(1234);
$adapter->mtime('filename2')->willReturn(2345);
$this->mtime('filename')->shouldReturn(1234);
$this->mtime('filename2')->shouldReturn(2345);
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_delegates_directory_check($adapter)
{
$adapter->isDirectory('filename')->willReturn(true);
$adapter->isDirectory('filename2')->willReturn(false);
$this->isDirectory('filename')->shouldReturn(true);
$this->isDirectory('filename2')->shouldReturn(false);
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_delegates_keys($adapter)
{
$adapter->keys()->willReturn(array('filename', 'filename2'));
$this->keys()->shouldReturn(array('filename', 'filename2'));
}
/**
* @param \spec\Gaufrette\Adapter\TestDelegateAdapter $extendedAdapter
* @param \AmazonS3 $service
*/
function it_delegates_metadata_handling($extendedAdapter, $service)
{
$this->beConstructedWith($extendedAdapter, $service, 'bucketName');
$extendedAdapter->setMetadata('filename', array('some'))->shouldBeCalled();
$extendedAdapter->getMetadata('filename')->shouldBeCalled()->willReturn(array('some2'));
$this->setMetadata('filename', array('some'));
$this->getMetadata('filename')->shouldReturn(array('some2'));
}
}
interface TestDelegateAdapter extends \Gaufrette\Adapter,
\Gaufrette\Adapter\MetadataSupporter
{
}

View File

@@ -0,0 +1,683 @@
<?php
namespace spec\Gaufrette\Adapter;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class AmazonS3Spec extends ObjectBehavior
{
/**
* @param \AmazonS3 $service
*/
function let($service)
{
$this->beConstructedWith($service, 'bucketName');
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
function it_supports_metadata()
{
$this->shouldHaveType('Gaufrette\Adapter\MetadataSupporter');
}
/**
* @param \AmazonS3 $service
*/
function it_reads_file($service)
{
$options = array(
'range' => 12,
'response' => array(
'content-language' => 'pl-pl'
)
);
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->get_object(
'bucketName',
'filename',
$options
)
->shouldBeCalled()
->willReturn(new \CFResponse('header', 'some content', 200))
;
$this->setMetadata('filename', $options);
$this->read('filename')->shouldReturn('some content');
}
/**
* @param \AmazonS3 $service
*/
function it_returns_false_when_cannot_read($service)
{
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->get_object(
'bucketName',
'filename',
array()
)
->shouldBeCalled()
->willReturn(new \CFResponse('header', 'some content', 500))
;
$this->read('filename')->shouldReturn(false);
}
/**
* @param \AmazonS3 $service
*/
function it_is_verbose_and_throws_exceptions_when_read($service)
{
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->get_object(
'bucketName',
'filename',
array()
)
->willThrow(new \RuntimeException('read'))
;
$this->shouldThrow(new \RuntimeException('read'))->duringRead('filename');
}
/**
* @param \AmazonS3 $service
*/
function it_rename_file($service)
{
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->copy_object(
array(
'bucket' => 'bucketName',
'filename' => 'filename1',
),
array(
'bucket' => 'bucketName',
'filename' => 'filename2'
),
array('acl' => \AmazonS3::ACL_OWNER_READ)
)
->shouldBeCalled()
->willReturn(new \CFResponse('header', 'some content', 200))
;
$service
->delete_object(
'bucketName',
'filename1',
Argument::any()
)
->shouldBeCalled()
->willReturn(new \CFResponse(array(), 'some', 200))
;
$this->setMetadata('filename1', array('acl' => \AmazonS3::ACL_OWNER_READ));
$this->rename('filename1', 'filename2')->shouldReturn(true);
}
/**
* @param \AmazonS3 $service
*/
function it_is_verbose_and_throws_exceptions_when_rename($service)
{
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->copy_object(Argument::cetera())
->willThrow(new \RuntimeException('rename'))
;
$this->shouldThrow(new \RuntimeException('rename'))->duringRename('filename', 'filename1');
}
/**
* @param \AmazonS3 $service
*/
function it_returns_false_when_cannot_rename($service)
{
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->copy_object(
array(
'bucket' => 'bucketName',
'filename' => 'filename1',
),
array(
'bucket' => 'bucketName',
'filename' => 'filename2'
),
array()
)
->shouldBeCalled()
->willReturn(new \CFResponse('header', 'some content', 500))
;
$this->rename('filename1', 'filename2')->shouldReturn(false);
}
/**
* @param \AmazonS3 $service
*/
function it_should_write_file($service)
{
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->create_object(
'bucketName',
'filename',
array(
'acl' => \AmazonS3::ACL_PRIVATE,
'body' => 'some content'
)
)
->shouldBeCalled()
->willReturn(new \CFResponse(array('x-aws-requestheaders' => array('Content-Length' => 12)), 'some content', 200))
;
$this->setMetadata('filename', array('acl' => \AmazonS3::ACL_PRIVATE, 'body' => 'other content'));
$this->write('filename', 'some content')->shouldReturn(12);
}
/**
* @param \AmazonS3 $service
*/
function it_returns_false_when_cannot_write($service)
{
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->create_object(
'bucketName',
'filename',
array(
'acl' => \AmazonS3::ACL_PUBLIC,
'body' => 'some content'
)
)
->shouldBeCalled()
->willReturn(new \CFResponse(array('x-aws-requestheaders' => array('Content-Length' => 12)), 'some content', 500))
;
$this->write('filename', 'some content')->shouldReturn(false);
}
/**
* @param \AmazonS3 $service
*/
function it_is_verbose_and_throws_exceptions_when_write($service)
{
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->create_object(Argument::cetera())
->willThrow(new \RuntimeException('write'))
;
$this->shouldThrow(new \RuntimeException('write'))->duringWrite('filename', 'some content');
}
/**
* @param \AmazonS3 $service
*/
function it_should_check_if_file_exists($service)
{
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service->if_object_exists('bucketName', 'filename')->willReturn(true);
$this->exists('filename')->shouldReturn(true);
$service->if_object_exists('bucketName', 'filename')->willReturn(false);
$this->exists('filename')->shouldReturn(false);
}
/**
* @param \AmazonS3 $service
*/
function it_is_verbose_and_throws_exceptions_when_file_exists($service)
{
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->if_object_exists('bucketName', 'filename')
->willThrow(new \RuntimeException('exists'))
;
$this->shouldThrow(new \RuntimeException('exists'))->duringExists('filename');
}
/**
* @param \AmazonS3 $service
*/
function it_should_get_file_mtime($service)
{
$metadata = array('acl' => \AmazonS3::ACL_PUBLIC);
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->get_object_metadata(
'bucketName',
'filename',
$metadata
)
->shouldBeCalled()
->willReturn(array('Headers' => array('last-modified' => '2012-01-01 23:10:10')))
;
$this->setMetadata('filename', $metadata);
$this->mtime('filename')->shouldReturn(strtotime('2012-01-01 23:10:10'));
}
/**
* @param \AmazonS3 $service
*/
function it_returns_false_when_cannot_fetch_mtime($service)
{
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->get_object_metadata(
'bucketName',
'filename',
array()
)
->shouldBeCalled()
->willReturn(array('Headers' => array()))
;
$this->mtime('filename')->shouldReturn(false);
}
/**
* @param \AmazonS3 $service
*/
function it_is_verbose_and_throws_exceptions_when_fetch_mtime($service)
{
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->get_object_metadata('bucketName', 'filename', Argument::any())
->willThrow(new \RuntimeException('mtime'))
;
$this->shouldThrow(new \RuntimeException('mtime'))->duringMtime('filename');
}
/**
* @param \AmazonS3 $service
*/
function it_should_delete_file($service)
{
$metadata = array('acl' => \AmazonS3::ACL_PRIVATE);
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->delete_object(
'bucketName',
'filename',
$metadata
)
->willReturn(new \CFResponse(array(), 'some', 200))
;
$this->setMetadata('filename', $metadata);
$this->delete('filename')->shouldReturn(true);
}
/**
* @param \AmazonS3 $service
*/
function it_is_verbose_and_throws_exceptions_when_fetch_delete($service)
{
$service
->if_bucket_exists('bucketName')
->willReturn(true)
;
$service
->delete_object(
'bucketName',
'filename',
Argument::any()
)
->willThrow(new \RuntimeException('delete'))
;
$this->shouldThrow(new \RuntimeException('delete'))->duringDelete('filename');
}
/**
* @param \AmazonS3 $service
*/
function it_returns_false_when_cannot_delete($service)
{
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->delete_object(
'bucketName',
'filename',
array()
)
->willReturn(new \CFResponse(array(), 'some', 500))
;
$this->delete('filename')->shouldReturn(false);
}
/**
* @param \AmazonS3 $service
*/
function it_should_get_keys($service)
{
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->get_object_list('bucketName')
->shouldBeCalled()
->willReturn(array('filename2', 'aaa/filename', 'filename1'))
;
$this->keys()->shouldReturn(array('aaa', 'aaa/filename', 'filename1', 'filename2'));
}
/**
* @param \AmazonS3 $service
*/
function it_is_verbose_and_throws_exceptions_when_fetch_keys($service)
{
$service
->if_bucket_exists('bucketName')
->willReturn(true)
;
$service
->get_object_list('bucketName')
->willThrow(new \RuntimeException('keys'))
;
$this->shouldThrow(new \RuntimeException('keys'))->duringKeys();
}
/**
* @param \AmazonS3 $service
*/
function it_should_handle_dirs($service)
{
$service
->if_bucket_exists('bucketName')
->willReturn(true)
;
$service
->if_object_exists('bucketName', 'filename')
->shouldNotBeCalled()
;
$service
->if_object_exists('bucketName', 'filename/')
->shouldBeCalled()
->willReturn(false)
;
$service
->if_object_exists('bucketName', 'dirname/')
->willReturn(true)
;
$this->isDirectory('filename')->shouldReturn(false);
$this->isDirectory('dirname')->shouldReturn(true);
}
/**
* @param \AmazonS3 $service
*/
function it_should_fail_when_bucket_does_not_exist($service)
{
$service
->if_bucket_exists('bucketName')
->willReturn(false)
;
$this
->shouldThrow(new \RuntimeException('The configured bucket "bucketName" does not exist.'))
->duringRead('filename')
;
$this
->shouldThrow(new \RuntimeException('The configured bucket "bucketName" does not exist.'))
->duringWrite('filename', 'content')
;
$this
->shouldThrow(new \RuntimeException('The configured bucket "bucketName" does not exist.'))
->duringDelete('filename')
;
$this
->shouldThrow(new \RuntimeException('The configured bucket "bucketName" does not exist.'))
->duringExists('filename')
;
$this
->shouldThrow(new \RuntimeException('The configured bucket "bucketName" does not exist.'))
->duringMtime('filename')
;
$this
->shouldThrow(new \RuntimeException('The configured bucket "bucketName" does not exist.'))
->duringRename('filename', 'filename2')
;
$this
->shouldThrow(new \RuntimeException('The configured bucket "bucketName" does not exist.'))
->duringKeys()
;
}
/**
* @param \AmazonS3 $service
*/
function it_creates_bucket_if_create_mode_is_enabled($service)
{
$service->set_region(Argument::any())->shouldBeCalled();
$service
->if_bucket_exists('bucketName')
->willReturn(false)
;
$service->hostname = \AmazonS3::REGION_US_E1;
$service
->create_bucket('bucketName', \AmazonS3::REGION_US_E1)
->shouldBeCalled()
->willReturn(new \CFResponse(array(), 'created', 201))
;
$service
->if_object_exists('bucketName', 'filename')
->willReturn(false)
;
$this->beConstructedWith($service, 'bucketName', array('create' => true));
$this->exists('filename');
}
/**
* @param \AmazonS3 $service
*/
function it_fails_when_cannot_create_bucket($service)
{
$service
->if_bucket_exists('bucketName')
->willReturn(false)
;
$service
->create_bucket('bucketName', Argument::any())
->shouldBeCalled()
->willReturn(new \CFResponse(array(), 'created', 500))
;
$this->beConstructedWith($service, 'bucketName', array('create' => true));
$this
->shouldThrow(new \RuntimeException('Failed to create the configured bucket "bucketName".'))
->duringExists('filename')
;
}
/**
* @param \AmazonS3 $service
*/
function it_allows_to_configure_reqion($service)
{
$service
->if_bucket_exists('bucketName')
->willReturn(true)
;
$service
->set_region(\AmazonS3::REGION_EU_W1)
->shouldBeCalled()
;
$service
->if_object_exists('bucketName', 'filename')
->willReturn(true)
;
$this->beConstructedWith($service, 'bucketName', array('region' => \AmazonS3::REGION_EU_W1));
$this->exists('filename');
}
/**
* @param \AmazonS3 $service
*/
function it_allows_to_configure_region_for_bucket($service)
{
$service->set_region(Argument::any())->shouldBeCalled();
$service
->if_bucket_exists('bucketName')
->willReturn(false)
;
$service
->create_bucket('bucketName', \AmazonS3::REGION_EU_W1)
->shouldBeCalled()
->willReturn(new \CFResponse(array(), 'created', 201))
;
$service
->if_object_exists('bucketName', 'filename')
->willReturn(false)
;
$this->beConstructedWith($service, 'bucketName', array('create' => true, 'region' => \AmazonS3::REGION_EU_W1));
$this->exists('filename');
}
/**
* @param \AmazonS3 $service
*/
function it_allows_to_configure_acl($service)
{
$this->setAcl('123abc');
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->create_object(
'bucketName',
'filename',
array(
'acl' => '123abc',
'body' => 'some content'
)
)
->shouldBeCalled()
->willReturn(new \CFResponse(array('x-aws-requestheaders' => array('Content-Length' => 12)), 'some content', 200))
;
$this->write('filename', 'some content')->shouldReturn(12);
$this->getAcl()->shouldBe('123abc');
}
/**
* @param \AmazonS3 $service
*/
function its_file_metadata_acl_are_more_important_than_global_acl_config($service)
{
$this->setAcl('123abc');
$service
->if_bucket_exists('bucketName')
->shouldBeCalled()
->willReturn(true)
;
$service
->create_object(
'bucketName',
'filename',
array(
'acl' => 'more important acl',
'body' => 'some content'
)
)
->shouldBeCalled()
->willReturn(new \CFResponse(array('x-aws-requestheaders' => array('Content-Length' => 12)), 'some content', 200))
;
$this->setMetadata('filename', array('acl' => 'more important acl'));
$this->write('filename', 'some content')->shouldReturn(12);
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace spec\Gaufrette\Adapter;
//hack - mock php built-in functions
require_once 'functions.php';
use PhpSpec\ObjectBehavior;
class ApcSpec extends ObjectBehavior
{
function let()
{
global $extensionLoaded;
$extensionLoaded = true;
$this->beConstructedWith('prefix-apc-test/');
}
function letgo()
{
global $extensionLoaded;
$extensionLoaded = null;
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
function it_reads_file()
{
$this->read('filename')->shouldReturn('prefix-apc-test/filename content');
$this->read('filename2')->shouldReturn('prefix-apc-test/filename2 content');
}
function it_writes_file()
{
$this->write('filename', 'some content')->shouldReturn(12);
$this->write('invalid', 'some content')->shouldReturn(false);
}
function it_deletes_file()
{
$this->delete('filename')->shouldReturn(true);
$this->delete('invalid')->shouldReturn(false);
}
function it_rename_file()
{
$this->rename('filename', 'aaa/filename2')->shouldReturn(true);
$this->rename('filename', 'invalid')->shouldReturn(false);
$this->rename('invalid', 'somename')->shouldReturn(false);
}
function it_checks_if_file_exists()
{
$this->exists('filename')->shouldReturn(true);
$this->exists('invalid')->shouldReturn(false);
}
function it_does_not_handles_directory()
{
$this->isDirectory('filename')->shouldReturn(false);
$this->isDirectory('invalid')->shouldReturn(false);
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace spec\Gaufrette\Adapter;
use Gaufrette\Adapter\MimeTypeProvider;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class AwsS3Spec extends ObjectBehavior
{
/**
* @param \Aws\S3\S3Client $service
*/
function let($service)
{
$this->beConstructedWith($service, 'bucketName');
}
function it_is_initializable()
{
$this->shouldHaveType('Gaufrette\Adapter\AwsS3');
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
function it_supports_metadata()
{
$this->shouldHaveType('Gaufrette\Adapter\MetadataSupporter');
}
function it_supports_sizecalculator()
{
$this->shouldHaveType('Gaufrette\Adapter\SizeCalculator');
}
function it_provides_mime_type()
{
$this->shouldHaveType(MimeTypeProvider::class);
}
}

View File

@@ -0,0 +1,494 @@
<?php
namespace spec\Gaufrette\Adapter;
use PHPSpec2\ObjectBehavior;
use WindowsAzure\Blob\Models\Blob;
use WindowsAzure\Common\ServiceException;
class AzureBlobStorage extends ObjectBehavior
{
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
*/
public function let($blobProxyFactory)
{
$this->beConstructedWith($blobProxyFactory, 'containerName');
}
public function it_should_be_initializable()
{
$this->shouldHaveType('Gaufrette\Adapter\AzureBlobStorage');
$this->shouldHaveType('Gaufrette\Adapter');
$this->shouldHaveType('Gaufrette\Adapter\MetadataSupporter');
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
* @param \WindowsAzure\Blob\Models\GetBlobResult $getBlobResult
*/
public function it_should_read_file($blobProxyFactory, $blobProxy, $getBlobResult)
{
$getBlobResult
->getContentStream()
->shouldBeCalled()
//azure blob content is handled as stream so we need to fake it
->willReturn(fopen('data://text/plain,some content','r'));
$blobProxy
->getBlob('containerName', 'filename')
->shouldBeCalled()
->willReturn($getBlobResult);
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$this->read('filename')->shouldReturn('some content');
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_return_false_when_cannot_read($blobProxyFactory, $blobProxy)
{
$blobProxy
->getBlob('containerName', 'filename')
->shouldBeCalled()
->willThrow(new ServiceException(500));
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$this->read('filename')->shouldReturn(false);
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_not_mask_exception_when_read($blobProxyFactory, $blobProxy)
{
$blobProxy
->getBlob('containerName', 'filename')
->shouldBeCalled()
->willThrow(new \RuntimeException('read'));
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$this->shouldThrow(new \RuntimeException('read'))->duringRead('filename');
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_rename_file($blobProxyFactory, $blobProxy)
{
$blobProxy
->copyBlob('containerName', 'filename2', 'containerName', 'filename1')
->shouldBeCalled();
$blobProxy
->deleteBlob('containerName', 'filename1')
->shouldBeCalled();
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$this->rename('filename1', 'filename2')->shouldReturn(true);
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_return_false_when_cannot_rename($blobProxyFactory, $blobProxy)
{
$blobProxy
->copyBlob('containerName', 'filename2', 'containerName', 'filename1')
->shouldBeCalled()
->willThrow(new ServiceException(500));
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$this->rename('filename1', 'filename2')->shouldReturn(false);
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_not_mask_exception_when_rename($blobProxyFactory, $blobProxy)
{
$blobProxy
->copyBlob('containerName', 'filename2', 'containerName', 'filename1')
->shouldBeCalled()
->willThrow(new \RuntimeException('rename'));
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$this->shouldThrow(new \RuntimeException('rename'))->duringRename('filename1', 'filename2');
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_write_file($blobProxyFactory, $blobProxy)
{
$blobProxy
->createBlockBlob('containerName', 'filename', 'some content',
\Mockery::type('\WindowsAzure\Blob\Models\CreateBlobOptions'))
->shouldBeCalled();
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$this->write('filename', 'some content')->shouldReturn(12);
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_return_false_when_cannot_write($blobProxyFactory, $blobProxy)
{
$blobProxy
->createBlockBlob('containerName', 'filename', 'some content',
\Mockery::type('\WindowsAzure\Blob\Models\CreateBlobOptions'))
->willThrow(new ServiceException(500));
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$this->write('filename', 'some content')->shouldReturn(false);
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_not_mask_exception_when_write($blobProxyFactory, $blobProxy)
{
$blobProxy
->createBlockBlob('containerName', 'filename', 'some content',
\Mockery::type('\WindowsAzure\Blob\Models\CreateBlobOptions'))
->willThrow(new \RuntimeException('write'));
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$this->shouldThrow(new \RuntimeException('write'))->duringWrite('filename', 'some content');
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
* @param \WindowsAzure\Blob\Models\GetBlobResult $getBlobResult
*/
public function it_should_check_if_file_exists($blobProxyFactory, $blobProxy, $getBlobResult)
{
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$blobProxy
->getBlob('containerName', 'filename')
->shouldBeCalled()
->willThrow(new ServiceException(404));
$this->exists('filename')->shouldReturn(false);
$blobProxy
->getBlob('containerName', 'filename2')
->shouldBeCalled()
->willReturn($getBlobResult);
$this->exists('filename2')->shouldReturn(true);
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_not_mask_exception_when_check_if_file_exists($blobProxyFactory, $blobProxy)
{
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$blobProxy
->getBlob('containerName', 'filename')
->shouldBeCalled()
->willThrow(new \RuntimeException('exists'));
$this->shouldThrow(new \RuntimeException('exists'))->duringExists('filename');
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
* @param \WindowsAzure\Blob\Models\GetBlobPropertiesResult $getBlobPropertiesResult
* @param \WindowsAzure\Blob\Models\BlobProperties $blobProperties
*/
public function it_should_get_file_mtime($blobProxyFactory, $blobProxy, $getBlobPropertiesResult, $blobProperties)
{
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$blobProxy
->getBlobProperties('containerName', 'filename')
->shouldBeCalled()
->willReturn($getBlobPropertiesResult);
$getBlobPropertiesResult
->getProperties()
->shouldBeCalled()
->willReturn($blobProperties);
$blobProperties
->getLastModified()
->shouldBeCalled()
->willReturn(new \DateTime('1987-12-28 20:00:00'));
$this->mtime('filename')->shouldReturn(strtotime('1987-12-28 20:00:00'));
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_return_false_when_cannot_mtime($blobProxyFactory, $blobProxy)
{
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$blobProxy
->getBlobProperties('containerName', 'filename')
->shouldBeCalled()
->willThrow(new ServiceException(500));
$this->mtime('filename')->shouldReturn(false);
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_not_mask_exception_when_get_mtime($blobProxyFactory, $blobProxy)
{
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$blobProxy
->getBlobProperties('containerName', 'filename')
->shouldBeCalled()
->willThrow(new \RuntimeException('mtime'));
$this->shouldThrow(new \RuntimeException('mtime'))->duringMtime('filename');
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_delete_file($blobProxyFactory, $blobProxy)
{
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$blobProxy
->deleteBlob('containerName', 'filename')
->shouldBeCalled();
$this->delete('filename')->shouldReturn(true);
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_return_false_when_cannot_delete_file($blobProxyFactory, $blobProxy)
{
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$blobProxy
->deleteBlob('containerName', 'filename')
->shouldBeCalled()
->willThrow(new ServiceException(500));
$this->delete('filename')->shouldReturn(false);
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_not_mask_exception_when_delete($blobProxyFactory, $blobProxy)
{
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$blobProxy
->deleteBlob('containerName', 'filename')
->shouldBeCalled()
->willThrow(new \RuntimeException('delete'));
$this->shouldThrow(new \RuntimeException('delete'))->duringDelete('filename');
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
* @param \WindowsAzure\Blob\Models\ListBlobsResult $listBlobResult
*/
public function it_should_get_keys($blobProxyFactory, $blobProxy, $listBlobResult)
{
$fileNames = array('aaa', 'aaa/filename', 'filename1', 'filename2');
$blobs = array();
foreach ($fileNames as $fileName) {
$blob = new Blob();
$blob->setName($fileName);
$blobs[] = $blob;
}
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$blobProxy
->listBlobs('containerName')
->shouldBeCalled()
->willReturn($listBlobResult);
$listBlobResult
->getBlobs()
->shouldBeCalled()
->willReturn($blobs);
$this->keys()->shouldReturn(array('aaa', 'aaa/filename', 'filename1', 'filename2'));
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_not_mask_exception_when_get_keys($blobProxyFactory, $blobProxy)
{
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$blobProxy
->listBlobs('containerName')
->shouldBeCalled()
->willThrow(new \RuntimeException('keys'));
$this->shouldThrow(new \RuntimeException('keys'))->duringKeys();
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_handle_dirs($blobProxyFactory, $blobProxy)
{
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$blobProxy
->getBlob('containerName', 'filename')
->shouldNotBeCalled();
$blobProxy
->getBlob('containerName', 'filename/')
->shouldBeCalled()
->willThrow(new ServiceException(404));
$blobProxy
->getBlob('containerName', 'dirname/')
->shouldBeCalled();
$this->isDirectory('filename')->shouldReturn(false);
$this->isDirectory('dirname')->shouldReturn(true);
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_create_container($blobProxyFactory, $blobProxy)
{
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$blobProxy
->createContainer('containerName', null)
->shouldBeCalled();
$this->createContainer('containerName');
}
/**
* @param \Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface $blobProxyFactory
* @param \WindowsAzure\Blob\Internal\IBlob $blobProxy
*/
public function it_should_fail_when_cannot_create_container($blobProxyFactory, $blobProxy)
{
$blobProxyFactory
->create()
->shouldBeCalled()
->willReturn($blobProxy);
$blobProxy
->createContainer('containerName', null)
->shouldBeCalled()
->willThrow(new ServiceException(500));
$this->shouldThrow(new \RuntimeException('Failed to create the configured container "containerName": 0 ().', null))->duringCreateContainer('containerName');
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace spec\Gaufrette\Adapter\AzureBlobStorage;
use PHPSpec2\ObjectBehavior;
class BlobProxyFactory extends ObjectBehavior
{
/**
* @param string $connectionString
*/
public function let($connectionString)
{
$this->beConstructedWith($connectionString);
}
public function it_should_be_initializable()
{
$this->shouldHaveType('Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactory');
$this->shouldHaveType('Gaufrette\Adapter\AzureBlobStorage\BlobProxyFactoryInterface');
}
}

View File

@@ -0,0 +1,156 @@
<?php
namespace spec\Gaufrette\Adapter;
use PhpSpec\ObjectBehavior;
class CacheSpec extends ObjectBehavior
{
/**
* @param \Gaufrette\Adapter $source
* @param \Gaufrette\Adapter $cache
*/
function let($source, $cache)
{
$this->beConstructedWith($source, $cache);
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
function it_supports_metadata()
{
$this->shouldHaveType('Gaufrette\Adapter\MetadataSupporter');
}
/**
* @param \spec\Gaufrette\Adapter\CacheTestExtendedAdapter $extendedSource
* @param \spec\Gaufrette\Adapter\CacheTestExtendedAdapter $extendedCache
*/
function it_handles_metadata_when_cached_adapters_supports_metadata($extendedSource, $extendedCache)
{
$extendedSource->setMetadata('filename', array('metadata'))->shouldBeCalled();
$extendedCache->setMetadata('filename', array('metadata'))->shouldBeCalled();
$extendedSource->getMetadata('filename')->shouldBeCalled()->willReturn(array('someMetadata'));
$this->beConstructedWith($extendedSource, $extendedCache);
$this->setMetadata('filename', array('metadata'));
$this->getMetadata('filename')->shouldReturn(array('someMetadata'));
}
/**
* @param \Gaufrette\Adapter $source
*/
function it_delegates_is_directory_check_to_source($source)
{
$source->isDirectory('filename')->shouldBeCalled()->willReturn(true);
$this->isDirectory('filename')->shouldReturn(true);
}
/**
* @param \Gaufrette\Adapter $source
* @param \Gaufrette\Adapter $cache
*/
function it_reads_from_cache_adapter($source, $cache)
{
$source->read('filename')->shouldNotBeCalled();
$cache->read('filename')->shouldBeCalled()->willReturn('some content');
$source->mtime('filename')->willReturn(strtotime('2010-10-11'));
$cache->mtime('filename')->willReturn(strtotime('2010-10-12'));
$cache->exists('filename')->willReturn(true);
$this->read('filename')->shouldReturn('some content');
}
/**
* @param \Gaufrette\Adapter $source
* @param \Gaufrette\Adapter $cache
*/
function it_update_cache_adapter_when_source_file_is_modified($source, $cache)
{
$source->read('filename')->shouldBeCalled()->willReturn('some other content');
$cache->read('filename')->shouldNotBeCalled();
$cache->write('filename', 'some other content')->shouldBeCalled();
$source->mtime('filename')->willReturn(strtotime('2010-10-11'));
$cache->mtime('filename')->willReturn(strtotime('2010-10-10'));
$cache->exists('filename')->willReturn(true);
$this->read('filename')->shouldReturn('some other content');
}
/**
* @param \Gaufrette\Adapter $source
* @param \Gaufrette\Adapter $cache
*/
function it_rename_file_in_source_and_cache($source, $cache)
{
$source->rename('filename', 'filename2')->shouldBeCalled()->willReturn(true);
$cache->rename('filename', 'filename2')->shouldBeCalled()->willReturn(true);
$this->rename('filename', 'filename2')->shouldReturn(true);
}
/**
* @param \Gaufrette\Adapter $source
* @param \Gaufrette\Adapter $cache
*/
function it_writes_file_to_source_and_cache($source, $cache)
{
$source->write('filename', 'some content')->shouldBeCalled()->willReturn(12);
$cache->write('filename', 'some content')->shouldBeCalled()->willReturn(12);
$this->write('filename', 'some content')->shouldReturn(12);
}
/**
* @param \Gaufrette\Adapter $source
* @param \Gaufrette\Adapter $cache
*/
function it_deletes_file_from_source_and_cache($source, $cache)
{
$source->delete('filename')->shouldBeCalled()->willReturn(true);
$cache->delete('filename')->shouldBeCalled()->willReturn(true);
$this->delete('filename')->shouldReturn(true);
}
/**
* @param \Gaufrette\Adapter $source
*/
function it_check_if_exists_in_source($source)
{
$source->exists('filename')->shouldBeCalled()->willReturn(true);
$this->exists('filename')->shouldReturn(true);
}
/**
* @param \Gaufrette\Adapter $source
*/
function it_get_mtime_from_source($source)
{
$source->mtime('filename')->shouldBeCalled()->willReturn(1234);
$this->mtime('filename')->shouldReturn(1234);
}
/**
* @param \Gaufrette\Adapter $source
*/
function it_get_keys_from_source($source)
{
$source->keys()->willReturn(array('filename2', 'filename1', 'filename'));
$this->keys()->shouldReturn(array('filename', 'filename1', 'filename2'));
}
}
interface CacheTestExtendedAdapter extends \Gaufrette\Adapter,
\Gaufrette\Adapter\ChecksumCalculator,
\Gaufrette\Adapter\MetadataSupporter
{
}

View File

@@ -0,0 +1,208 @@
<?php
namespace spec\Gaufrette\Adapter;
//hack - mock php built-in functions
require_once 'functions.php';
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class DoctrineDbalSpec extends ObjectBehavior
{
/**
* @param \Doctrine\DBAL\Connection $connection
*/
function let($connection)
{
$this->beConstructedWith($connection, 'someTableName');
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
function it_is_checksum_calculator()
{
$this->shouldHaveType('Gaufrette\Adapter\ChecksumCalculator');
}
function it_does_not_handle_directories()
{
$this->isDirectory('filename')->shouldReturn(false);
}
/**
* @param \Doctrine\DBAL\Connection $connection
*/
function it_checks_if_file_exists($connection)
{
$connection
->quoteIdentifier(Argument::any())
->will(function ($argument) { return sprintf('"%s"', $argument[0]); });
$connection
->fetchColumn('SELECT COUNT("key") FROM "someTableName" WHERE "key" = :key', array('key' => 'filename'))
->willReturn(12);
$this->exists('filename')->shouldReturn(true);
$connection
->fetchColumn('SELECT COUNT("key") FROM "someTableName" WHERE "key" = :key', array('key' => 'filename'))
->willReturn(0);
$this->exists('filename')->shouldReturn(false);
}
/**
* @param \Doctrine\DBAL\Connection $connection
*/
function it_writes_to_new_file($connection)
{
$connection
->quoteIdentifier(Argument::any())
->will(function ($argument) { return sprintf('"%s"', $argument[0]); });
$connection
->fetchColumn('SELECT COUNT("key") FROM "someTableName" WHERE "key" = :key', array('key' => 'filename'))
->willReturn(false);
$connection
->insert(
'someTableName',
array(
'"content"' => 'some content',
'"mtime"' => strtotime('2012-10-10 23:10:10'),
'"checksum"' => '9893532233caff98cd083a116b013c0b',
'"key"' => 'filename'
))
->shouldBeCalled();
$this->write('filename', 'some content')->shouldReturn(12);
}
/**
* @param \Doctrine\DBAL\Connection $connection
*/
function it_write_file($connection)
{
$connection
->quoteIdentifier(Argument::any())
->will(function ($argument) { return sprintf('"%s"', $argument[0]); });
$connection
->fetchColumn('SELECT COUNT("key") FROM "someTableName" WHERE "key" = :key', array('key' => 'filename'))
->willReturn(true);
$connection
->update(
'someTableName',
array(
'"content"' => 'some content',
'"mtime"' => strtotime('2012-10-10 23:10:10'),
'"checksum"' => '9893532233caff98cd083a116b013c0b',
),
array(
'"key"' => 'filename'
))
->shouldBeCalled();
$this->write('filename', 'some content')->shouldReturn(12);
}
/**
* @param \Doctrine\DBAL\Connection $connection
*/
function it_reads_file($connection)
{
$connection
->quoteIdentifier(Argument::any())
->will(function ($argument) { return sprintf('"%s"', $argument[0]); });
$connection
->fetchColumn('SELECT "content" FROM "someTableName" WHERE "key" = :key', array('key' => 'filename'))
->willReturn('some content');
$this->read('filename')->shouldReturn('some content');
}
/**
* @param \Doctrine\DBAL\Connection $connection
*/
function it_calculates_checksum($connection)
{
$connection
->quoteIdentifier(Argument::any())
->will(function ($argument) { return sprintf('"%s"', $argument[0]); });
$connection
->fetchColumn('SELECT "checksum" FROM "someTableName" WHERE "key" = :key', array('key' => 'filename'))
->willReturn(1234);
$this->checksum('filename')->shouldReturn(1234);
}
/**
* @param \Doctrine\DBAL\Connection $connection
*/
function it_gets_mtime($connection)
{
$connection
->quoteIdentifier(Argument::any())
->will(function ($argument) { return sprintf('"%s"', $argument[0]); });
$connection
->fetchColumn('SELECT "mtime" FROM "someTableName" WHERE "key" = :key', array('key' => 'filename'))
->willReturn(1234);
$this->mtime('filename')->shouldReturn(1234);
}
/**
* @param \Doctrine\DBAL\Connection $connection
*/
function it_renames_file($connection)
{
$connection
->quoteIdentifier(Argument::any())
->will(function ($argument) { return sprintf('"%s"', $argument[0]); });
$connection
->update(
'someTableName',
array(
'"key"' => 'newFile',
),
array(
'"key"' => 'filename'
))
->shouldBeCalled()
->willReturn(1);
$this->rename('filename', 'newFile')->shouldReturn(true);
}
/**
* @param \Doctrine\DBAL\Connection $connection
* @param \Doctrine\DBAL\Statement $stmt
*/
function it_get_keys($connection, $stmt)
{
$stmt->fetchAll(\PDO::FETCH_COLUMN)->willReturn(array('filename', 'filename1', 'filename2'));
$connection
->quoteIdentifier(Argument::any())
->will(function ($argument) { return sprintf('"%s"', $argument[0]); });
$connection
->executeQuery('SELECT "key" FROM "someTableName"')
->willReturn($stmt);
$this->keys()->shouldReturn(array('filename', 'filename1', 'filename2'));
}
/**
* @param \Doctrine\DBAL\Connection $connection
*/
function it_deletes_file($connection)
{
$connection
->quoteIdentifier(Argument::any())
->will(function ($argument) { return sprintf('"%s"', $argument[0]); });
$connection
->delete('someTableName', array('"key"' => 'filename'))
->shouldBeCalled()
->willReturn(1);
$this->delete('filename')->shouldReturn(true);
}
}

View File

@@ -0,0 +1,288 @@
<?php
namespace spec\Gaufrette\Adapter;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class DropboxSpec extends ObjectBehavior
{
/**
* @param \Dropbox_API $dropbox
*/
function let($dropbox)
{
$this->beConstructedWith($dropbox);
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
/**
* @param \Dropbox_API $dropbox
*/
function it_reads_file($dropbox)
{
$dropbox->getFile('filename')->willReturn('some content');
$this->read('filename')->shouldReturn('some content');
}
/**
* @param \Dropbox_API $dropbox
*/
function it_does_not_mask_exception_from_client_during_read($dropbox)
{
$dropbox->getFile('filename')->willThrow(new \RuntimeException('read'));
$this->shouldThrow(new \RuntimeException('read'))->duringRead('filename');
}
/**
* @param \Dropbox_API $dropbox
*/
function it_does_not_read_file($dropbox)
{
$dropbox
->getFile('filename')
->willThrow(new \Dropbox_Exception_NotFound());
$this->read('filename')->shouldReturn(false);
}
/**
* @param \Dropbox_API $dropbox
*/
function it_checks_if_file_exists($dropbox)
{
$dropbox
->getMetaData('filename', false)
->willReturn(array(
"size" => "225.4KB",
"rev" => "35e97029684fe",
"thumb_exists" => false,
"bytes" => 230783,
"modified" => "Tue, 19 Jul 2011 21:55:38 +0000",
"client_mtime" => "Mon, 18 Jul 2011 18:04:35 +0000",
"path" => "/filename",
"is_dir" => false,
"icon" => "page_white_acrobat",
"root" => "dropbox",
"mime_type" => "application/pdf",
"revision" => 220823
));
$this->exists('filename')->shouldReturn(true);
$dropbox
->getMetaData('filename', false)
->willThrow(new \Dropbox_Exception_NotFound);
$this->exists('filename')->shouldReturn(false);
$dropbox
->getMetaData('filename', false)
->willReturn(array("is_deleted" => true));
$this->exists('filename')->shouldReturn(false);
}
/**
* @param \Dropbox_API $dropbox
*/
function it_does_not_mask_exception_from_client_during_check_if_exists($dropbox)
{
$dropbox
->getMetaData('filename', false)
->willThrow(new \RuntimeException('exists'));
$this->shouldThrow(new \RuntimeException('exists'))->duringExists('filename');
}
/**
* @param \Dropbox_API $dropbox
*/
function it_gets_keys($dropbox)
{
$dropbox
->getMetaData('/', true)
->willReturn(array(
'contents' => array(
array('path' => '/filename'),
array('path' => '/aaa/filename')
)
));
$this->keys()->shouldReturn(array('aaa', 'aaa/filename', 'filename'));
}
/**
* @param \Dropbox_API $dropbox
*/
function it_does_not_mask_exception_from_client_during_getting_keys($dropbox)
{
$dropbox
->getMetaData('/', true)
->willThrow(new \RuntimeException('keys'))
;
$this->shouldThrow(new \RuntimeException('keys'))->duringKeys();
}
/**
* @param \Dropbox_API $dropbox
*/
function it_checks_if_given_key_is_directory($dropbox)
{
$dropbox
->getMetaData('filename', false)
->willReturn(array(
"is_dir" => true
))
;
$this->isDirectory('filename')->shouldReturn(true);
$dropbox
->getMetaData('filename', false)
->willReturn(array(
"is_dir" => false
));
$this->isDirectory('filename')->shouldReturn(false);
}
/**
* @param \Dropbox_API $dropbox
*/
function it_writes_file($dropbox)
{
$dropbox
->putFile('filename', Argument::any())
->shouldBeCalled()
;
$this->write('filename', 'some content')->shouldReturn(12);
}
/**
* @param \Dropbox_API $dropbox
*/
function it_does_not_mask_exception_from_client_during_write($dropbox)
{
$dropbox
->putFile('filename', Argument::any())
->willThrow(new \RuntimeException('write'))
;
$this->shouldThrow(new \RuntimeException('write'))->duringWrite('filename', 'some content');
}
/**
* @param \Dropbox_API $dropbox
*/
function it_deletes_file($dropbox)
{
$dropbox
->delete('filename')
->shouldBeCalled()
;
$this->delete('filename')->shouldReturn(true);
}
/**
* @param \Dropbox_API $dropbox
*/
function it_does_not_delete_file($dropbox)
{
$dropbox
->delete('filename')
->willThrow(new \Dropbox_Exception_NotFound())
;
$this->delete('filename')->shouldReturn(false);
}
/**
* @param \Dropbox_API $dropbox
*/
function it_renames_file($dropbox)
{
$dropbox
->move('filename', 'filename2')
->shouldBeCalled()
;
$this->rename('filename', 'filename2')->shouldReturn(true);
}
/**
* @param \Dropbox_API $dropbox
*/
function it_does_not_rename_file($dropbox)
{
$dropbox
->move('filename', 'filename2')
->willThrow(new \Dropbox_Exception_NotFound())
;
$this->rename('filename', 'filename2')->shouldReturn(false);
}
/**
* @param \Dropbox_API $dropbox
*/
function it_fetches_mtime($dropbox)
{
$dropbox
->getMetaData('filename', false)
->willReturn(array(
"modified" => "Tue, 19 Jul 2011 21:55:38 +0000",
))
;
$this->mtime('filename')->shouldReturn(1311112538);
}
/**
* @param \Dropbox_API $dropbox
*/
function it_does_not_fetch_mtime_when_file_not_found($dropbox)
{
$dropbox
->getMetaData('filename', false)
->willThrow(new \Dropbox_Exception_NotFound())
;
$this->mtime('filename')->shouldReturn(false);
}
/**
* @param \Dropbox_API $dropbox
*/
function it_does_not_check_if_key_is_dir_when_file_not_found($dropbox)
{
$dropbox
->getMetaData('filename', false)
->willThrow(new \Dropbox_Exception_NotFound())
;
$this->isDirectory('filename')->shouldReturn(false);
}
/**
* @param \Dropbox_API $dropbox
*/
function it_fails_checking_if_key_is_dir_when_dropbox_throws_exception($dropbox)
{
$dropbox
->getMetaData('filename', false)
->willThrow(new \RuntimeException('some exception'))
;
$this->shouldThrow(new \RuntimeException('some exception'))->duringIsDirectory('filename');
}
}

View File

@@ -0,0 +1,107 @@
<?php
namespace spec\Gaufrette\Adapter;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use League\Flysystem\AdapterInterface;
use League\Flysystem\Config;
class FlysystemSpec extends ObjectBehavior
{
function let(AdapterInterface $adapter, Config $config)
{
$this->beConstructedWith($adapter, $config);
}
function it_is_adapter()
{
$this->shouldImplement('Gaufrette\Adapter');
}
function it_is_list_keys_aware()
{
$this->shouldImplement('Gaufrette\Adapter\ListKeysAware');
}
function it_reads_file(AdapterInterface $adapter)
{
$adapter->read('filename')->willReturn(['contents' => 'Hello.']);
$this->read('filename')->shouldReturn('Hello.');
}
function it_writes_file(AdapterInterface $adapter, Config $config)
{
$adapter->write('filename', 'Hello.', $config)->willReturn(array());
$this->write('filename', 'Hello.')->shouldReturn(array());
}
function it_checks_if_file_exists(AdapterInterface $adapter)
{
$adapter->has('filename')->willReturn(true);
$this->exists('filename')->shouldReturn(true);
}
function it_checks_if_file_exists_when_flysystem_returns_array(AdapterInterface $adapter)
{
$adapter->has('filename')->willReturn(['type' => 'file']);
$this->exists('filename')->shouldReturn(true);
}
function it_fetches_keys(AdapterInterface $adapter)
{
$adapter->listContents()->willReturn([[
'path' => 'folder',
'timestamp' => 1457104978,
'size' => 22,
'type' => 'dir',
]]);
$this->keys()->shouldReturn(['folder']);
}
function it_lists_keys(AdapterInterface $adapter)
{
$adapter->listContents()->willReturn([[
'path' => 'folder',
'timestamp' => 1457104978,
'size' => 22,
'type' => 'dir',
]]);
$this->listKeys()->shouldReturn([
'keys' => [],
'dirs' => ['folder'],
]);
}
function it_fetches_mtime(AdapterInterface $adapter)
{
$adapter->getTimestamp('filename')->willReturn(1457104978);
$this->mtime('filename')->shouldReturn(1457104978);
}
function it_deletes_file(AdapterInterface $adapter)
{
$adapter->delete('filename')->willReturn(true);
$this->delete('filename')->shouldReturn(true);
}
function it_renames_file(AdapterInterface $adapter)
{
$adapter->rename('oldfilename', 'newfilename')->willReturn(true);
$this->rename('oldfilename', 'newfilename')->shouldReturn(true);
}
function it_does_not_support_is_directory(AdapterInterface $adapter)
{
$this->shouldThrow('Gaufrette\Exception\UnsupportedAdapterMethodException')->duringisDirectory('folder');
}
}

View File

@@ -0,0 +1,228 @@
<?php
namespace spec\Gaufrette\Adapter;
//hack - mock php built-in functions
require_once 'functions.php';
use PhpSpec\ObjectBehavior;
class FtpSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('/home/l3l0', 'localhost');
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
function it_supports_native_list_keys()
{
$this->shouldHaveType('Gaufrette\Adapter\ListKeysAware');
}
function it_checks_if_file_exists_for_absolute_path()
{
$this->exists('filename')->shouldReturn(true);
$this->exists('aa/filename')->shouldReturn(false);
}
function it_checks_if_file_exists_for_relative_path()
{
$this->beConstructedWith('/home/l3l0/relative', 'localhost');
$this->exists('filename')->shouldReturn(true);
$this->exists('filename2')->shouldReturn(false);
$this->exists('aa/filename')->shouldReturn(false);
$this->exists('some/otherfilename')->shouldReturn(true);
}
function it_checks_if_dir_exists_for_symlink()
{
$this->exists('www')->shouldReturn(true);
$this->exists('vendor')->shouldReturn(true);
$this->exists('bbb')->shouldReturn(false);
}
function it_checks_if_dir_exists_with_special_and_unicode_chars_in_name()
{
$this->beConstructedWith('/home/l3l2', 'localhost');
$this->exists('a b c d -> žežulička')->shouldReturn(true);
}
function it_reads_file()
{
$this->read('filename')->shouldReturn('some content');
}
function it_does_not_read_file()
{
$this->read('filename2')->shouldReturn(false);
}
function it_writes_file()
{
$this->write('filename', 'some content')->shouldReturn(12);
}
function it_does_not_write_file()
{
$this->write('filename2', 'some content')->shouldReturn(false);
}
function it_renames_file()
{
$this->rename('filename', 'filename2')->shouldReturn(true);
}
function it_does_not_not_rename_file_when_target_file_is_invalid()
{
$this->rename('filename', 'invalid')->shouldReturn(false);
}
function it_fetches_keys_without_directories_dots()
{
$this->keys()->shouldReturn(array('filename', 'filename.exe', '.htaccess', 'aaa', 'aaa/filename'));
}
function it_fetches_keys_with_spaces_and_unicode_chars()
{
$this->beConstructedWith('/home/l3l2', 'localhost');
$this->keys()->shouldReturn(array('Žľuťoučký kůň.pdf', 'a b c d -> žežulička', 'a b c d -> žežulička/do re mi.pdf'));
}
function it_fetches_keys_recursive()
{
$this->beConstructedWith('/home/l3l3', 'localhost');
$this->keys()->shouldReturn(array('filename', 'filename.exe', '.htaccess', 'aaa', 'www', 'aaa/filename', 'www/filename', 'www/some', 'www/some/otherfilename'));
}
function it_lists_keys()
{
$this->listKeys()->shouldReturn(array(
'keys' => array('filename', 'filename.exe', '.htaccess', 'aaa/filename'),
'dirs' => array('aaa')
));
$this->listKeys('file')->shouldReturn(array(
'keys' => array('filename', 'filename.exe'),
'dirs' => array()
));
$this->listKeys('name')->shouldReturn(array(
'keys' => array(),
'dirs' => array()
));
$this->listKeys('aaa')->shouldReturn(array(
'keys' => array('aaa/filename'),
'dirs' => array('aaa')
));
$this->listKeys('aaa/')->shouldReturn(array(
'keys' => array('aaa/filename'),
'dirs' => array()
));
}
function it_fetches_mtime()
{
$this->mtime('filename')->shouldReturn(strtotime('2010-10-10 23:10:10'));
}
function it_throws_exception_when_mtime_is_not_supported_by_server()
{
$this->shouldThrow(new \RuntimeException('Server does not support ftp_mdtm function.'))->duringMtime('invalid');
}
function it_deletes_file()
{
$this->delete('filename')->shouldReturn(true);
}
function it_does_not_delete_file()
{
$this->delete('invalid')->shouldReturn(false);
}
/**
* @param \Gaufrette\Filesystem $filesystem
*/
function it_creates_file($filesystem)
{
$this->createFile('filename', $filesystem)->shouldReturnAnInstanceOf('\Gaufrette\File');
}
/**
* @param \Gaufrette\Filesystem $filesystem
*/
function it_creates_file_in_not_existing_directory($filesystem)
{
$this->createFile('bb/cc/dd/filename', $filesystem)->shouldReturnAnInstanceOf('\Gaufrette\File');
}
function it_checks_if_given_key_is_directory()
{
$this->isDirectory('aaa')->shouldReturn(true);
$this->isDirectory('filename')->shouldReturn(false);
}
function it_fetches_keys_with_hidden_files()
{
$this->beConstructedWith('/home/l3l1', 'localhost');
$this->keys()->shouldReturn(array('filename', '.htaccess'));
}
function it_checks_if_hidden_file_exists()
{
$this->beConstructedWith('/home/l3l1', 'localhost');
$this->exists('.htaccess')->shouldReturn(true);
}
function it_creates_base_directory_without_warning()
{
global $createdDirectory;
$createdDirectory = '';
$this->beConstructedWith('/home/l3l0/new', 'localhost', array('create' => true));
$this->listDirectory()->shouldReturn(array('keys' => array(), 'dirs' => array()));
}
function it_does_not_create_base_directory_and_should_throw_exception()
{
global $createdDirectory;
$createdDirectory = '';
$this->beConstructedWith('/home/l3l0/new', 'localhost', array('create' => false));
$this->shouldThrow(new \RuntimeException("The directory '/home/l3l0/new' does not exist."))->during('listDirectory', array());
}
function it_fetches_keys_for_windows()
{
$this->beConstructedWith('C:\Ftp', 'localhost');
$this->keys()->shouldReturn(array('archive', 'file1.zip', 'file2.zip'));
}
function it_supports_sizecalculator()
{
$this->shouldImplement('Gaufrette\Adapter\SizeCalculator');
$this->size('/path')->shouldReturn(5000);
}
function it_throws_an_exception_when_size_cant_be_fetched()
{
$this->shouldThrow('RuntimeException')->during('size', ['/erroneous']);
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace spec\Gaufrette\Adapter;
use PhpSpec\ObjectBehavior;
class GoogleCloudStorageSpec extends ObjectBehavior
{
public function let(\Google_Service_Storage $service)
{
$this->beConstructedWith($service, 'bucketName');
}
public function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
public function it_supports_metadata()
{
$this->shouldHaveType('Gaufrette\Adapter\MetadataSupporter');
}
public function it_is_list_keys_aware()
{
$this->shouldHaveType('Gaufrette\Adapter\ListKeysAware');
}
}

View File

@@ -0,0 +1,168 @@
<?php
namespace spec\Gaufrette\Adapter;
use MongoDB\BSON\UTCDateTime;
use MongoDB\GridFS\Bucket;
use MongoDB\GridFS\Exception\FileNotFoundException;
use MongoDB\Model\BSONDocument;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class GridFSSpec extends ObjectBehavior
{
private $resources = [];
function let(Bucket $bucket)
{
$this->beConstructedWith($bucket);
}
function letGo()
{
array_map(function ($res) {
@fclose($res);
}, $this->resources);
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
function it_is_checksum_calculator()
{
$this->shouldHaveType('Gaufrette\Adapter\ChecksumCalculator');
}
function it_supports_metadata()
{
$this->shouldHaveType('Gaufrette\Adapter\MetadataSupporter');
}
function it_supports_native_list_keys()
{
$this->shouldHaveType('Gaufrette\Adapter\ListKeysAware');
}
function it_reads_file($bucket)
{
$this->resources[] = $readable = fopen('php://memory', 'rw');
fwrite($readable, 'some content');
fseek($readable, 0);
$bucket
->openDownloadStreamByName('filename')
->shouldBeCalled()
->willReturn($readable)
;
$this->read('filename')->shouldReturn('some content');
}
function it_does_not_fail_when_cannot_read($bucket)
{
$bucket->openDownloadStreamByName('filename')->willThrow(FileNotFoundException::class);
$this->read('filename')->shouldReturn(false);
}
function it_checks_if_file_exists($bucket, BSONDocument $file)
{
$bucket
->findOne(['filename' => 'filename'])
->willReturn($file)
;
$bucket
->findOne(['filename' => 'filename2'])
->willReturn(null)
;
$this->exists('filename')->shouldReturn(true);
$this->exists('filename2')->shouldReturn(false);
}
function it_deletes_file($bucket)
{
$bucket
->findOne(['filename' => 'filename'], ['projection' => ['_id' => 1]])
->willReturn($file = new BSONDocument(['_id' => 123]))
;
$bucket->delete(123)->shouldBeCalled();
$this->delete('filename')->shouldReturn(true);
}
function it_does_not_delete_file($bucket)
{
$bucket->findOne(['filename' => 'filename'], ['projection' => ['_id' => 1]])->willReturn(null);
$this->delete('filename')->shouldReturn(false);
}
function it_writes_file($bucket)
{
$this->resources[] = $writable = fopen('php://memory', 'rw');
$bucket
->openUploadStream('filename', ['metadata' => ['someother' => 'metadata']])
->willReturn($writable)
;
$this->setMetadata('filename', ['someother' => 'metadata']);
$this
->write('filename', 'some content')
->shouldReturn(12)
;
}
function it_renames_file($bucket)
{
$this->resources[] = $writable = fopen('php://memory', 'rw');
$this->resources[] = $readable = fopen('php://memory', 'rw');
fwrite($readable, 'some content');
fseek($readable, 0);
$bucket->openUploadStream('otherFilename', ['metadata' => ['some' => 'metadata']])->willReturn($writable);
$bucket->downloadToStreamByName('filename', $writable)->shouldBeCalled();
$bucket
->findOne(['filename' => 'filename'], ['projection' => ['_id' => 1]])
->willReturn($toDelete = new BSONDocument(['_id' => 1234]))
;
$bucket->delete(1234)->shouldBeCalled();
$this->setMetadata('filename', ['some' => 'metadata']);
$this->rename('filename', 'otherFilename')->shouldReturn(true);
}
function it_fetches_keys($bucket)
{
$bucket
->find([], ['projection' => ['filename' => 1]])
->willReturn([new BSONDocument(['filename' => 'filename']), new BSONDocument(['filename' => 'otherFilename'])])
;
$this->keys()->shouldReturn(['filename', 'otherFilename']);
}
function it_fetches_mtime($bucket)
{
$bucket
->findOne(['filename' => 'filename'], ['projection' => ['uploadDate' => 1]])
->willReturn(new BSONDocument(['uploadDate' => new UTCDateTime(12345000)]))
;
$this->mtime('filename')->shouldReturn(12345);
}
function it_calculates_checksum($bucket)
{
$bucket
->findOne(['filename' => 'filename'], ['projection' => ['md5' => 1]])
->willReturn(new BSONDocument(['md5' => 'md5123']))
;
$this->checksum('filename')->shouldReturn('md5123');
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace spec\Gaufrette\Adapter;
use PhpSpec\ObjectBehavior;
class InMemorySpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith(array(
'filename' => array('mtime' => 12345, 'content' => 'content'),
'filename2' => 'other content'
));
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
function it_is_a_mime_type_provider()
{
$this->shouldHaveType('Gaufrette\Adapter\MimeTypeProvider');
}
function it_gets_the_file_mime_type()
{
$this->mimeType('filename')->shouldReturn('text/plain');
}
function it_reads_file()
{
$this->read('filename')->shouldReturn('content');
}
function it_writes_file()
{
$this->write('filename', 'some content')->shouldReturn(12);
}
function it_renames_file()
{
$this->rename('filename', 'aaa/filename2')->shouldReturn(true);
$this->exists('filename')->shouldReturn(false);
$this->exists('aaa/filename2')->shouldReturn(true);
}
function it_checks_if_file_exists()
{
$this->exists('filename')->shouldReturn(true);
$this->exists('filenameTest')->shouldReturn(false);
}
function it_fetches_keys()
{
$this->keys()->shouldReturn(array('filename', 'filename2'));
}
function it_fetches_mtime()
{
$this->mtime('filename')->shouldReturn(12345);
}
function it_deletes_file()
{
$this->delete('filename')->shouldReturn(true);
$this->exists('filename')->shouldReturn(false);
}
function it_does_not_handle_dirs()
{
$this->isDirectory('filename')->shouldReturn(false);
$this->isDirectory('filename2')->shouldReturn(false);
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace spec\Gaufrette\Adapter;
use OpenCloud\ObjectStore\Exception\ObjectNotFoundException;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
/**
* LazyOpenCloudSpec
*
* @author Daniel Richter <nexyz9@gmail.com>
*/
class LazyOpenCloudSpec extends ObjectBehavior
{
/**
* @param \Gaufrette\Adapter\OpenStackCloudFiles\ObjectStoreFactoryInterface $objectStoreFactory
*/
function let($objectStoreFactory)
{
$this->beConstructedWith($objectStoreFactory, 'test-container-name');
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
/**
* @param \Gaufrette\Adapter\OpenStackCloudFiles\ObjectStoreFactoryInterface $objectStoreFactory
* @param \OpenCloud\ObjectStore\Service $objectStore
* @param \OpenCloud\ObjectStore\Resource\Container $container
*/
function it_initializes_object_store($objectStoreFactory, $objectStore, $container)
{
$objectStoreFactory->getObjectStore()->shouldBeCalled()->willReturn($objectStore);
$objectStore->getContainer("test-container-name")->shouldBeCalled()->willReturn($container);
$container->getObject("test-file-name")->willThrow(new ObjectNotFoundException());
$this->read("test-file-name");
}
}

View File

@@ -0,0 +1,161 @@
<?php
namespace spec\Gaufrette\Adapter;
use org\bovigo\vfs\vfsStream;
use PhpSpec\ObjectBehavior;
class LocalSpec extends ObjectBehavior
{
function let()
{
vfsStream::setup('test');
vfsStream::copyFromFileSystem(__DIR__.'/MockFilesystem');
$this->beConstructedWith(vfsStream::url('test'));
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
function it_is_checksum_calculator()
{
$this->shouldHaveType('Gaufrette\Adapter\ChecksumCalculator');
}
function it_is_a_mime_type_provider()
{
$this->shouldHaveType('Gaufrette\Adapter\MimeTypeProvider');
}
function it_gets_the_file_mime_type()
{
$this->mimeType('filename')->shouldReturn('text/plain');
}
function it_is_stream_factory()
{
$this->shouldHaveType('Gaufrette\Adapter\StreamFactory');
}
function it_reads_file()
{
$this->read('filename')->shouldReturn("content\n");
}
function it_writes_file()
{
$this->write('filename', 'some content')->shouldReturn(12);
}
function it_renames_file()
{
$this->rename('filename', 'aaa/filename2')->shouldReturn(true);
}
function it_checks_if_file_exists()
{
$this->exists('filename')->shouldReturn(true);
$this->exists('filename1')->shouldReturn(false);
}
function it_fetches_keys()
{
$expectedKeys = array('filename', 'dir', 'dir/file');
sort($expectedKeys);
$this->keys()->shouldReturn($expectedKeys);
}
function it_fetches_mtime()
{
$mtime = filemtime(vfsStream::url('test/filename'));
$this->mtime('filename')->shouldReturn($mtime);
}
function it_deletes_file()
{
$this->delete('filename')->shouldReturn(true);
$this->delete('filename1')->shouldReturn(false);
}
function it_checks_if_given_key_is_directory()
{
$this->isDirectory('dir')->shouldReturn(true);
$this->isDirectory('filename')->shouldReturn(false);
}
function it_creates_local_stream()
{
$this->createStream('filename')->shouldReturnAnInstanceOf('Gaufrette\Stream\Local');
}
function it_does_not_allow_to_read_path_above_main_file_directory()
{
$this
->shouldThrow(new \OutOfBoundsException(sprintf('The path "%s" is out of the filesystem.', vfsStream::url('filename'))))
->duringRead('../filename')
;
$this
->shouldThrow(new \OutOfBoundsException(sprintf('The path "%s" is out of the filesystem.', vfsStream::url('filename'))))
->duringExists('../filename')
;
}
function it_fails_when_directory_does_not_exists()
{
$this->beConstructedWith(vfsStream::url('other'));
$this
->shouldThrow(new \RuntimeException(sprintf('The directory "%s" does not exist.', vfsStream::url('other'))))
->duringRead('filename')
;
$this
->shouldThrow(new \RuntimeException(sprintf('The directory "%s" does not exist.', vfsStream::url('other'))))
->duringWrite('filename', 'some content')
;
$this
->shouldThrow(new \RuntimeException(sprintf('The directory "%s" does not exist.', vfsStream::url('other'))))
->duringRename('filename', 'otherFilename')
;
$this
->shouldThrow(new \RuntimeException(sprintf('The directory "%s" does not exist.', vfsStream::url('other'))))
->duringExists('filename')
;
$this
->shouldThrow(new \RuntimeException(sprintf('The directory "%s" does not exist.', vfsStream::url('other'))))
->duringKeys()
;
$this
->shouldThrow(new \RuntimeException(sprintf('The directory "%s" does not exist.', vfsStream::url('other'))))
->duringMtime('filename')
;
$this
->shouldThrow(new \RuntimeException(sprintf('The directory "%s" does not exist.', vfsStream::url('other'))))
->duringDelete('filename')
;
$this
->shouldThrow(new \RuntimeException(sprintf('The directory "%s" does not exist.', vfsStream::url('other'))))
->duringIsDirectory('filename')
;
$this
->shouldThrow(new \RuntimeException(sprintf('The directory "%s" does not exist.', vfsStream::url('other'))))
->duringCreateStream('filename')
;
$this
->shouldThrow(new \RuntimeException(sprintf('The directory "%s" does not exist.', vfsStream::url('other'))))
->duringChecksum('filename')
;
$this
->shouldThrow(new \RuntimeException(sprintf('The directory "%s" does not exist.', vfsStream::url('other'))))
->duringMimeType('filename')
;
}
function it_creates_directory_when_does_not_exists()
{
$this->beConstructedWith(vfsStream::url('test/other'), true);
$this->isDirectory('/')->shouldReturn(true);
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace spec\Gaufrette\Adapter;
use PhpSpec\ObjectBehavior;
class MogileFSSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('http://domain.com', array('localhost'));
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
function it_does_not_handle_mtime()
{
$this->mtime('filename')->shouldReturn(false);
$this->mtime('filename2')->shouldReturn(false);
}
}

View File

@@ -0,0 +1,255 @@
<?php
namespace spec\Gaufrette\Adapter;
use Guzzle\Http\Exception\BadResponseException;
use OpenCloud\Common\Exceptions\CreateUpdateError;
use OpenCloud\Common\Exceptions\DeleteError;
use OpenCloud\ObjectStore\Exception\ObjectNotFoundException;
use OpenCloud\ObjectStore\Resource\DataObject;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
/**
* OpenCloudSpec
*
* @author Chris Warner <cdw.lighting@gmail.com>
* @author Daniel Richter <nexyz9@gmail.com>
*/
class OpenCloudSpec extends ObjectBehavior
{
/**
* @param OpenCloud\ObjectStore\Service $objectStore
* @param OpenCloud\ObjectStore\Resource\Container $container
*/
function let($objectStore, $container)
{
$objectStore->getContainer("test")->willReturn($container);
$this->beConstructedWith($objectStore, 'test', false);
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
/**
* @param OpenCloud\ObjectStore\Resource\Container $container
* @param OpenCloud\ObjectStore\Resource\DataObject $object
*/
function it_reads_file($container, $object)
{
$object->getContent()->willReturn("Hello World");
$container->getObject("test")->willReturn($object);
$this->read('test')->shouldReturn('Hello World');
}
/**
* @param OpenCloud\ObjectStore\Resource\Container $container
*/
function it_reads_file_on_error_returns_false($container)
{
$container->getObject("test")->willThrow(new ObjectNotFoundException());
$this->read('test')->shouldReturn(false);
}
/**
* @param OpenCloud\ObjectStore\Resource\Container $container
* @param OpenCloud\ObjectStore\Resource\DataObject $object
*/
function it_writes_file_returns_size($container, $object)
{
$testData = "Hello World!";
$testDataSize = strlen($testData);
$object->getContentLength()->willReturn($testDataSize);
$container->uploadObject('test', $testData)->willReturn($object);
$this->write('test', $testData)->shouldReturn($testDataSize);
}
/**
* @param OpenCloud\ObjectStore\Resource\Container $container
*/
function it_writes_file_and_write_fails_returns_false($container)
{
$testData = "Hello World!";
$container->uploadObject('test', $testData)->willThrow(new CreateUpdateError());
$this->write('test', $testData)->shouldReturn(false);
}
/**
* @param OpenCloud\ObjectStore\Resource\Container $container
* @param OpenCloud\ObjectStore\Resource\DataObject $object
*/
function it_returns_true_if_key_exists($container, $object)
{
$container->getPartialObject('test')->willReturn($object);
$this->exists('test')->shouldReturn(true);
}
/**
* @param OpenCloud\ObjectStore\Resource\Container $container
*/
function it_returns_false_if_key_does_not_exist($container)
{
$container->getPartialObject('test')->willThrow(new BadResponseException());
$this->exists('test')->shouldReturn(false);
}
/**
* @param OpenCloud\ObjectStore\Resource\Container $container
* @param OpenCloud\ObjectStore\Resource\DataObject $object
*/
function it_deletes_file_on_success_returns_true($container, $object)
{
$object->delete()->willReturn(null);
$container->getObject("test")->willReturn($object);
$this->delete('test')->shouldReturn(true);
}
/**
* @param OpenCloud\ObjectStore\Resource\Container $container
* @param OpenCloud\ObjectStore\Resource\DataObject $object
*/
function it_deletes_file_returns_false_on_failure($container, $object)
{
$object->delete()->willThrow(new DeleteError());
$container->getObject("test")->willReturn($object);
$this->delete('test')->shouldReturn(false);
}
/**
* @param OpenCloud\ObjectStore\Resource\Container $container
*/
function it_deletes_file_if_file_does_not_exist_returns_false($container)
{
$container->getObject("test")->willThrow(new ObjectNotFoundException());
$this->delete('test')->shouldReturn(false);
}
/**
* @param OpenCloud\ObjectStore\Resource\Container $container
* @param OpenCloud\ObjectStore\Resource\DataObject $object
*/
function it_returns_checksum_if_file_exists($container, $object)
{
$object->getEtag()->willReturn("test String");
$container->getObject("test")->willReturn($object);
$this->checksum('test')->shouldReturn("test String");
}
/**
* @param OpenCloud\ObjectStore\Resource\Container $container
*/
function it_returns_false_when_file_does_not_exist($container)
{
$container->getObject("test")->willThrow(new ObjectNotFoundException());
$this->checksum('test')->shouldReturn(false);
}
/**
* @param OpenCloud\ObjectStore\Resource\Container $container
* @param OpenCloud\Common\Collection $objectList
* @param OpenCloud\ObjectStore\Resource\DataObject $object1
* @param OpenCloud\ObjectStore\Resource\DataObject $object2
* @param OpenCloud\ObjectStore\Resource\DataObject $object3
*/
function it_returns_files_as_sorted_array($container, $objectList, $object1, $object2, $object3)
{
$outputArray = array('key1', 'key2', 'key5');
$index = 0;
$object1->getName()->willReturn('key5');
$object2->getName()->willReturn('key2');
$object3->getName()->willReturn('key1');
$objects = array($object1, $object2, $object3);
$objectList->next()->will(
function () use ($objects, &$index) {
if ($index < count($objects)) {
$index++;
return $objects[$index - 1];
}
}
) ->shouldBeCalledTimes(count($objects) + 1);
$container->objectList()->willReturn($objectList);
$this->keys()->shouldReturn($outputArray);
}
/**
* @param OpenCloud\ObjectStore\Service $objectStore
*/
function it_throws_exception_if_container_does_not_exist($objectStore)
{
$containerName = 'container-does-not-exist';
$objectStore->getContainer($containerName)->willThrow(new BadResponseException());
$this->beConstructedWith($objectStore, $containerName);
$this->shouldThrow('\RuntimeException')->duringExists('test');
}
/**
* @param OpenCloud\ObjectStore\Service $objectStore
* @param OpenCloud\ObjectStore\Resource\Container $container
*/
function it_creates_container($objectStore, $container)
{
$containerName = 'container-does-not-yet-exist';
$filename = 'test';
$objectStore->getContainer($containerName)->willThrow(new BadResponseException());
$objectStore->createContainer($containerName)->willReturn($container);
$container->getPartialObject($filename)->willThrow(new BadResponseException());
$this->beConstructedWith($objectStore, $containerName, true);
$this->exists($filename)->shouldReturn(false);
}
/**
* @param OpenCloud\ObjectStore\Service $objectStore
*/
function it_throws_exeption_if_container_creation_fails($objectStore)
{
$containerName = 'container-does-not-yet-exist';
$objectStore->getContainer($containerName)->willThrow(new BadResponseException());
$objectStore->createContainer($containerName)->willReturn(false);
$this->beConstructedWith($objectStore, $containerName, true);
$this->shouldThrow('\RuntimeException')->duringExists('test');
}
function it_returns_false_if_the_object_does_not_exists_when_fetching_mtime($container)
{
$container->getObject('foo')->willThrow(ObjectNotFoundException::class);
$this->mtime('foo')->shouldReturn(false);
}
function it_fetches_file_mtime(DataObject $object, $container)
{
$container->getObject('foo')->willReturn($object);
$object->getLastModified()->willReturn('Tue, 13 Jun 2017 22:02:34 GMT');
$this->mtime('foo')->shouldReturn('1497391354');
}
}

View File

@@ -0,0 +1,156 @@
<?php
namespace spec\Gaufrette\Adapter;
if (!defined('NET_SFTP_TYPE_REGULAR')) {
define('NET_SFTP_TYPE_REGULAR', 1);
}
if (!defined('NET_SFTP_TYPE_DIRECTORY')) {
define('NET_SFTP_TYPE_DIRECTORY', 2);
}
use phpseclib\Net\SFTP as Base;
use PhpSpec\ObjectBehavior;
class PhpseclibSftpSpec extends ObjectBehavior
{
/**
* @param \spec\Gaufrette\Adapter\SFTP $sftp
*/
function let($sftp)
{
$this->beConstructedWith($sftp, '/home/l3l0', false, 'l3lo', 'password');
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
function it_is_file_factory()
{
$this->shouldHaveType('Gaufrette\Adapter\FileFactory');
}
function it_supports_native_list_keys()
{
$this->shouldHaveType('Gaufrette\Adapter\ListKeysAware');
}
/**
* @param \spec\Gaufrette\Adapter\SFTP $sftp
*/
function it_fetches_keys($sftp)
{
$sftp
->file_exists('/home/l3l0/')
->willReturn(true);
$sftp
->rawlist('/home/l3l0/')
->willReturn(array(
'filename' => array('type' => NET_SFTP_TYPE_REGULAR),
'filename1' => array('type' => NET_SFTP_TYPE_REGULAR),
'aaa' => array('type' => NET_SFTP_TYPE_DIRECTORY)
));
$sftp
->file_exists('/home/l3l0/aaa')
->willReturn(true);
$sftp
->rawlist('/home/l3l0/aaa')
->willReturn(array(
'filename' => array('type' => NET_SFTP_TYPE_REGULAR),
));
$this->keys()->shouldReturn(array('filename', 'filename1', 'aaa', 'aaa/filename'));
}
/**
* @param \spec\Gaufrette\Adapter\SFTP $sftp
*/
function it_reads_file($sftp)
{
$sftp->get('/home/l3l0/filename')->willReturn('some content');
$this->read('filename')->shouldReturn('some content');
}
/**
* @param \spec\Gaufrette\Adapter\SFTP $sftp
*/
function it_creates_and_writes_file($sftp)
{
$sftp->pwd()->willReturn('/home/l3l0');
$sftp->chdir('/home/l3l0')->willReturn(true);
$sftp->put('/home/l3l0/filename', 'some content')->willReturn(true);
$sftp->size('/home/l3l0/filename')->willReturn(12);
$this->write('filename', 'some content')->shouldReturn(12);
}
/**
* @param \spec\Gaufrette\Adapter\SFTP $sftp
*/
function it_renames_file($sftp)
{
$sftp->pwd()->willReturn('/home/l3l0');
$sftp->chdir('/home/l3l0')->willReturn(true);
$sftp
->rename('/home/l3l0/filename', '/home/l3l0/filename1')
->willReturn(true)
;
$this->rename('filename', 'filename1')->shouldReturn(true);
}
/**
* @param \spec\Gaufrette\Adapter\SFTP $sftp
*/
function it_should_check_if_file_exists($sftp)
{
$sftp->pwd()->willReturn('/home/l3l0');
$sftp->chdir('/home/l3l0')->willReturn(true);
$sftp->stat('/home/l3l0/filename')->willReturn(array(
'name' => '/home/l3l0/filename'
));
$sftp->stat('/home/l3l0/filename1')->willReturn(false);
$this->exists('filename')->shouldReturn(true);
$this->exists('filename1')->shouldReturn(false);
}
/**
* @param \spec\Gaufrette\Adapter\SFTP $sftp
*/
function it_should_check_is_directory($sftp)
{
$sftp->pwd()->willReturn('/home/l3l0');
$sftp->chdir('/home/l3l0')->willReturn(true);
$sftp->chdir('/home/l3l0/aaa')->willReturn(true);
$sftp->chdir('/home/l3l0/filename')->willReturn(false);
$this->isDirectory('aaa')->shouldReturn(true);
$this->isDirectory('filename')->shouldReturn(false);
}
/**
* @param \spec\Gaufrette\Adapter\SFTP $sftp
* @param \Gaufrette\Filesystem $filesystem
*/
function it_should_create_file($sftp, $filesystem)
{
$sftp->stat('/home/l3l0/filename')->willReturn(array(
'name' => '/home/l3l0/filename',
'size' => '30',
));
$this->createFile('filename', $filesystem)->beAnInstanceOf('Gaufrette\File');
}
}
class SFTP extends Base
{
public function __construct()
{
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace spec\Gaufrette\Adapter;
use org\bovigo\vfs\vfsStream;
use PhpSpec\ObjectBehavior;
class SafeLocalSpec extends ObjectBehavior
{
function let()
{
vfsStream::setup('test');
vfsStream::copyFromFileSystem(__DIR__.'/MockFilesystem');
$this->beConstructedWith(vfsStream::url('test'));
}
function it_is_local_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter\Local');
}
function it_computes_path_using_base64()
{
rename(vfsStream::url('test/filename'), vfsStream::url('test/'.base64_encode('filename')));
$this->read('filename')->shouldReturn("content\n");
}
function it_computes_key_back_using_base64()
{
$this->keys()->shouldReturn(array(base64_decode('dir'), base64_decode('dir/file'), base64_decode('filename')));
}
}

View File

@@ -0,0 +1,127 @@
<?php
namespace spec\Gaufrette\Adapter;
//hack - mock php built-in functions
require_once 'functions.php';
use PhpSpec\ObjectBehavior;
/**
* @require Ssh\Sftp
*/
class SftpSpec extends ObjectBehavior
{
/**
* @param \Ssh\Sftp $sftp
*/
function let($sftp)
{
$this->beConstructedWith($sftp, '/home/l3l0');
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
function it_is_checksum_calculator()
{
$this->shouldHaveType('Gaufrette\Adapter\ChecksumCalculator');
}
/**
* @param \Ssh\Sftp $sftp
*/
function it_fetches_keys($sftp)
{
$sftp
->getUrl('/home/l3l0')
->willReturn('ssh+ssl://localhost/home/l3l0')
;
$sftp
->listDirectory('/home/l3l0', true)
->willReturn(array('files' => array('/home/l3l0/filename', '/home/l3l0/filename1', '/home/l3l0/aaa/filename')))
;
$this->keys()->shouldReturn(array('aaa', 'aaa/filename', 'filename', 'filename1'));
}
/**
* @param \Ssh\Sftp $sftp
*/
function it_reads_file($sftp)
{
$sftp
->getUrl('/home/l3l0')
->willReturn('ssh+ssl://localhost/home/l3l0')
;
$sftp
->read('/home/l3l0/filename')
->shouldBeCalled()
->willReturn('some content')
;
$this->read('filename')->shouldReturn('some content');
}
/**
* @param \Ssh\Sftp $sftp
*/
function it_writes_file($sftp)
{
$sftp
->getUrl('/home/l3l0')
->willReturn('ssh+ssl://localhost/home/l3l0')
;
$sftp
->write('/home/l3l0/filename', 'some content')
->shouldBeCalled()
->willReturn(12)
;
$this->write('filename', 'some content')->shouldReturn(12);
}
/**
* @param \Ssh\Sftp $sftp
*/
function it_renames_file($sftp)
{
$sftp
->getUrl('/home/l3l0')
->willReturn('ssh+ssl://localhost/home/l3l0')
;
$sftp
->rename('/home/l3l0/filename', '/home/l3l0/filename1')
->shouldBeCalled()
->willReturn(true)
;
$this->rename('filename', 'filename1')->shouldReturn(true);
}
/**
* @param \Ssh\Sftp $sftp
*/
function it_checks_if_file_exists($sftp)
{
$sftp
->getUrl('/home/l3l0')
->willReturn('ssh+ssl://localhost/home/l3l0')
;
$sftp
->getUrl('/home/l3l0/filename')
->shouldBeCalled()
->willReturn('ssh+ssl://localhost/home/l3l0/filename')
;
$sftp
->getUrl('/home/l3l0/filename1')
->shouldBeCalled()
->willReturn('ssh+ssl://localhost/home/l3l0/filename1')
;
$this->exists('filename')->shouldReturn(true);
$this->exists('filename1')->shouldReturn(false);
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace spec\Gaufrette\Adapter;
use PhpSpec\ObjectBehavior;
class ZipSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('somefile');
}
function it_is_adapter()
{
$this->shouldHaveType('Gaufrette\Adapter');
}
}

View File

@@ -0,0 +1,295 @@
<?php
namespace Gaufrette\Adapter;
global $createdDirectory;
function ftp_delete($connection, $path)
{
if ($path === '/home/l3l0/invalid') {
return false;
}
return true;
}
function ftp_mdtm($connection, $path)
{
if ($path === '/home/l3l0/invalid') {
return -1;
}
return \strtotime('2010-10-10 23:10:10');
}
function ftp_rename($connection, $from, $to)
{
return ! ('/home/l3l0/invalid' === $from or '/home/l3l0/invalid' === $to);
}
function ftp_fput($connection, $path, $fileResource, $mode)
{
if ('/home/l3l0/filename' === $path) {
return true;
}
return false;
}
function ftp_fget($connection, &$fileResource, $path, $mode)
{
if ('/home/l3l0/filename' === $path) {
$bytes = \fwrite($fileResource, 'some content');
return true;
}
return false;
}
function ftp_chdir($connection, $dirname)
{
if (in_array($dirname, array('/home/l3l0', '/home/l3l0/aaa', '/home/l3l0/relative', '/home/l3l0/relative/some', '/home/l3l1', '/home/l3l2', '/home/l3l2/a b c d -> žežulička', '/home/l3l3', 'C:\Ftp'))) {
return true;
}
global $createdDirectory;
if ($createdDirectory && $createdDirectory === $dirname) {
return true;
}
trigger_error(sprintf('%s: No such file or directory', $dirname), E_USER_WARNING);
return false;
}
function ftp_mkdir($connection, $dirname)
{
if (in_array($dirname, array('/home/l3l0/new'))) {
global $createdDirectory;
$createdDirectory = $dirname;
return true;
}
return false;
}
function ftp_connect($host, $port = 21, $timeout = 90)
{
if ('localhost' !== $host) {
return false;
}
return fopen('php://temp', 'r');
}
function ftp_close($connection)
{
return fclose($connection);
}
function ftp_rawlist($connection, $directory, $recursive = false)
{
$arguments = explode(' ', $directory, 2);
if ('/home/l3l0' === end($arguments))
{
return array(
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 .",
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 ..",
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 aaa",
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 filename",
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 filename.exe",
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 .htaccess",
"lrwxrwxrwx 1 vincent vincent 11 Jul 12 12:16 www -> aaa",
"lrwxrwxrwx 1 vincent vincent 11 Jul 12 12:16 vendor -> bbb",
);
}
if ('/home/l3l0/aaa' === end($arguments))
{
return array(
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 filename",
);
}
if ('/home/l3l0/relative' === end($arguments))
{
return array(
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 filename",
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 some",
);
}
if ('/home/l3l0/relative/some' === end($arguments))
{
return array(
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 otherfilename",
);
}
if ('/home/l3l1' === end($arguments) && 0 === strpos(reset($arguments), '-al'))
{
return array(
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 .",
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 ..",
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 filename",
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 .htaccess",
);
}
if ('/home/l3l1' === end($arguments) && false === strpos(reset($arguments), '-al'))
{
return array(
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 .",
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 ..",
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 filename",
);
}
if ('/home/l3l2' === end($arguments))
{
return array(
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 .",
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 ..",
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 a b c d -> žežulička",
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 Žľuťoučký kůň.pdf",
);
}
if ('/home/l3l2/a b c d -> žežulička' === end($arguments))
{
return array(
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 .",
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 ..",
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 do re mi.pdf",
);
}
if ('/home/l3l3' === end($arguments) && '-alR' === reset($arguments))
{
return array(
"/home/l3l3:",
"total: 12",
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 .",
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 ..",
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 aaa",
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 filename",
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 filename.exe",
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 .htaccess",
"drwxrwxrwx 1 vincent vincent 11 Jul 12 12:16 www",
"lrwxrwxrwx 1 vincent vincent 11 Jul 12 12:16 vendor -> bbb",
"",
"/home/l3l3/aaa:",
"total: 8",
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 filename",
"",
"/home/l3l3/www:",
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 .",
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 ..",
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 filename",
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 some",
"",
"/home/l3l3/www/some:",
"total 5",
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 .",
"drwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 ..",
"-rwxr-x--- 15 vincent vincent 4096 Nov 3 21:31 otherfilename",
);
}
// https://github.com/KnpLabs/Gaufrette/issues/147
if ('C:\Ftp' === end($arguments))
{
return array(
"05-26-12 08:03PM <DIR> archive",
"12-04-12 06:57PM 16142 file1.zip",
"12-05-12 04:01PM 16142 file2.zip",
);
}
return array();
}
function ftp_login($connection, $username, $password)
{
if ('invalid' === $username) {
return false;
}
return true;
}
function time()
{
return \strtotime('2012-10-10 23:10:10');
}
function file_exists($path)
{
//fake it for ssh+ssl: protocol for SFTP testing, otherwise delegate to global
if (strpos($path, 'ssh+ssl:') === 0) {
return in_array($path, array('/home/l3l0/filename', '/home/somedir/filename', 'ssh+ssl://localhost/home/l3l0/filename')) ? true : false;
}
return \file_exists($path);
}
function extension_loaded($name)
{
global $extensionLoaded;
if (is_null($extensionLoaded)) {
return true;
}
return $extensionLoaded;
}
function opendir($url)
{
return true;
}
function apc_fetch($path)
{
return sprintf('%s content', $path);
}
function apc_store($path, $content, $ttl)
{
if ('prefix-apc-test/invalid' === $path) {
return false;
}
return sprintf('%s content', $path);
}
function apc_delete($path)
{
if ('prefix-apc-test/invalid' === $path) {
return false;
}
return true;
}
function apc_exists($path)
{
if ('prefix-apc-test/invalid' === $path) {
return false;
}
return true;
}
function ftp_size($connection, $path)
{
if ($path === '/erroneous') {
return -1;
}
return 5000;
}

View File

@@ -0,0 +1,186 @@
<?php
namespace spec\Gaufrette;
use PhpSpec\ObjectBehavior;
class FileSpec extends ObjectBehavior
{
/**
* @param \Gaufrette\Filesystem $filesystem
*/
function let($filesystem)
{
$this->beConstructedWith('filename', $filesystem);
}
function it_is_initializable()
{
$this->shouldHaveType('Gaufrette\File');
}
function it_gives_access_to_key()
{
$this->getKey()->shouldReturn('filename');
}
/**
* @param \Gaufrette\Filesystem $filesystem
*/
function it_gets_content($filesystem)
{
$filesystem->read('filename')->shouldBeCalled()->willReturn('Some content');
$this->getContent()->shouldReturn('Some content');
}
/**
* @param \Gaufrette\Filesystem $filesystem
*/
function it_gets_mtime($filesystem)
{
$filesystem->mtime('filename')->shouldBeCalled()->willReturn(1358797854);
$this->getMtime()->shouldReturn(1358797854);
}
/**
* @param \Gaufrette\Filesystem $filesystem
* @param \spec\Gaufrette\MetadataAdapter $adapter
*/
function it_pass_metadata_when_write_content($filesystem, $adapter)
{
$metadata = array('id' => '123');
$adapter->setMetadata('filename', $metadata)->shouldBeCalled();
$filesystem->write('filename', 'some content', true)->willReturn(12);
$filesystem->getAdapter()->willReturn($adapter);
$this->setContent('some content', $metadata);
}
/**
* @param \Gaufrette\Filesystem $filesystem
* @param \spec\Gaufrette\MetadataAdapter $adapter
*/
function it_pass_metadata_when_read_content($filesystem, $adapter)
{
$metadata = array('id' => '123');
$adapter->setMetadata('filename', $metadata)->shouldBeCalled();
$filesystem->read('filename')->willReturn('some content');
$filesystem->getAdapter()->willReturn($adapter);
$this->getContent($metadata);
}
/**
* @param \Gaufrette\Filesystem $filesystem
* @param \spec\Gaufrette\MetadataAdapter $adapter
*/
function it_pass_metadata_when_delete_content($filesystem, $adapter)
{
$metadata = array('id' => '123');
$adapter->setMetadata('filename', $metadata)->shouldBeCalled();
$filesystem->delete('filename')->willReturn(true);
$filesystem->getAdapter()->willReturn($adapter);
$this->delete($metadata);
}
/**
* @param \Gaufrette\Filesystem $filesystem
* @param \spec\Gaufrette\MetadataAdapter $adapter
*/
function it_sets_content_of_file($filesystem, $adapter)
{
$adapter->setMetadata('filename', array())->shouldNotBeCalled();
$filesystem->getAdapter()->willReturn($adapter);
$filesystem->write('filename', 'some content', true)->shouldBeCalled()->willReturn(21);
$this->setContent('some content')->shouldReturn(21);
$this->getContent('filename')->shouldReturn('some content');
}
function it_sets_key_as_name_by_default()
{
$this->getName()->shouldReturn('filename');
}
function it_sets_name()
{
$this->setName('name');
$this->getName()->shouldReturn('name');
}
/**
* @param \Gaufrette\Filesystem $filesystem
*/
function it_sets_size_for_new_file($filesystem)
{
$filesystem->write('filename', 'some content', true)->shouldBeCalled()->willReturn(21);
$this->setContent('some content');
$this->getSize()->shouldReturn(21);
}
/**
* @param \Gaufrette\Filesystem $filesystem
*/
function it_calculates_size_from_filesystem($filesystem)
{
$filesystem->size('filename')->shouldBeCalled()->willReturn(12);
$this->getSize()->shouldReturn(12);
}
/**
* @param \Gaufrette\Filesystem $filesystem
*/
function it_allows_to_set_size($filesystem)
{
$filesystem->read('filename')->shouldNotBeCalled();
$this->setSize(21);
$this->getSize()->shouldReturn(21);
}
/**
* @param \Gaufrette\Filesystem $filesystem
*/
function it_gets_zero_size_when_file_not_found($filesystem)
{
$filesystem->size('filename')->willThrow(new \Gaufrette\Exception\FileNotFound('filename'));
$this->getSize()->shouldReturn(0);
}
/**
* @param \Gaufrette\Filesystem $filesystem
*/
function it_check_if_file_with_key_exists_in_filesystem($filesystem)
{
$filesystem->has('filename')->willReturn(true);
$this->exists()->shouldReturn(true);
$filesystem->has('filename')->willReturn(false);
$this->exists()->shouldReturn(false);
}
/**
* @param \Gaufrette\Filesystem $filesystem
*/
function it_deletes_file_from_filesystem($filesystem)
{
$filesystem->delete('filename')->shouldBeCalled()->willReturn(true);
$this->delete()->shouldReturn(true);
}
function it_renames_file_from_filesystem($filesystem)
{
$filesystem->rename('filename', 'newname')->shouldBeCalled();
$this->rename('newname');
}
}
interface MetadataAdapter extends \Gaufrette\Adapter,
\Gaufrette\Adapter\MetadataSupporter
{}

View File

@@ -0,0 +1,73 @@
<?php
namespace spec\Gaufrette;
use PhpSpec\ObjectBehavior;
class FilesystemMapSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Gaufrette\FilesystemMap');
}
/**
* @param Gaufrette\Filesystem $filesystem
*/
function it_checks_if_has_mapped_filesystem($filesystem)
{
$this->set('some', $filesystem);
$this->has('some')->shouldReturn(true);
$this->has('other')->shouldReturn(false);
}
/**
* @param Gaufrette\Filesystem $filesystem
*/
function it_sets_mapped_filesystem($filesystem)
{
$this->set('some', $filesystem);
$this->get('some')->shouldReturn($filesystem);
}
function it_fails_when_get_filesystem_which_was_not_mapped()
{
$this
->shouldThrow(new \InvalidArgumentException('There is no filesystem defined for the "some" domain.'))
->duringGet('some')
;
}
/**
* @param Gaufrette\Filesystem $filesystem
*/
function it_removes_mapped_filesystem($filesystem)
{
$this->set('some', $filesystem);
$this->remove('some');
$this->has('some')->shouldReturn(false);
}
function it_fails_when_try_to_remove_filesystem_which_was_not_mapped()
{
$this
->shouldThrow(new \InvalidArgumentException('Cannot remove the "some" filesystem as it is not defined.'))
->duringRemove('some')
;
}
/**
* @param Gaufrette\Filesystem $filesystem
*/
function it_removes_all_filesystems($filesystem)
{
$this->set('some', $filesystem);
$this->set('other', $filesystem);
$this->clear();
$this->has('some')->shouldReturn(false);
$this->has('other')->shouldReturn(false);
$this->all()->shouldReturn(array());
}
}

View File

@@ -0,0 +1,432 @@
<?php
namespace spec\Gaufrette;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class FilesystemSpec extends ObjectBehavior
{
/**
* @param \Gaufrette\Adapter $adapter
*/
function let($adapter)
{
$this->beConstructedWith($adapter);
}
function it_is_initializable()
{
$this->shouldBeAnInstanceOf('Gaufrette\Filesystem');
$this->shouldBeAnInstanceOf('Gaufrette\FilesystemInterface');
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_gives_access_to_adapter($adapter)
{
$this->getAdapter()->shouldBe($adapter);
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_check_if_file_exists_using_adapter($adapter)
{
$adapter->exists('filename')->willReturn(true);
$adapter->exists('otherFilename')->willReturn(false);
$this->has('filename')->shouldReturn(true);
$this->has('otherFilename')->shouldReturn(false);
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_renames_file($adapter)
{
$adapter->exists('filename')->shouldBeCalled()->willReturn(true);
$adapter->exists('otherFilename')->shouldBeCalled()->willReturn(false);
$adapter->rename('filename', 'otherFilename')->shouldBeCalled()->willReturn(true);
$this->rename('filename', 'otherFilename')->shouldReturn(true);
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_fails_when_renamed_source_file_does_not_exist($adapter)
{
$adapter->exists('filename')->willReturn(false);
$this
->shouldThrow(new \Gaufrette\Exception\FileNotFound('filename'))
->duringRename('filename', 'otherFilename')
;
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_fails_when_renamed_target_file_exists($adapter)
{
$adapter->exists('filename')->willReturn(true);
$adapter->exists('otherFilename')->willReturn(true);
$this
->shouldThrow(new \Gaufrette\Exception\UnexpectedFile('otherFilename'))
->duringRename('filename', 'otherFilename')
;
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_fails_when_rename_is_not_successful($adapter)
{
$adapter->exists('filename')->willReturn(true);
$adapter->exists('otherFilename')->willReturn(false);
$adapter->rename('filename', 'otherFilename')->willReturn(false);
$this
->shouldThrow(new \RuntimeException('Could not rename the "filename" key to "otherFilename".'))
->duringRename('filename', 'otherFilename')
;
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_creates_file_object_for_key($adapter)
{
$adapter->exists('filename')->willReturn(true);
$this->get('filename')->shouldBeAnInstanceOf('Gaufrette\File');
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_does_not_get_file_object_when_file_with_key_does_not_exist($adapter)
{
$adapter->exists('filename')->willReturn(false);
$this
->shouldThrow(new \Gaufrette\Exception\FileNotFound('filename'))
->duringGet('filename')
;
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_gets_file_object_when_file_does_not_exist_but_can_be_created($adapter)
{
$adapter->exists('filename')->willReturn(false);
$this->get('filename', true)->shouldBeAnInstanceOf('Gaufrette\File');
}
/**
* @param \spec\Gaufrette\Adapter $extendedAdapter
* @param \Gaufrette\File $file
*/
function it_delegates_file_creation_to_adapter_when_adapter_is_file_factory($extendedAdapter, $file)
{
$this->beConstructedWith($extendedAdapter);
$extendedAdapter->exists('filename')->willReturn(true);
$extendedAdapter->createFile('filename', $this)->willReturn($file);
$this->get('filename')->shouldBe($file);
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_writes_content_to_new_file($adapter)
{
$adapter->exists('filename')->shouldBeCalled()->willReturn(false);
$adapter->write('filename', 'some content to write')->shouldBeCalled()->willReturn(21);
$this->write('filename', 'some content to write')->shouldReturn(21);
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_updates_content_of_file($adapter)
{
$adapter->write('filename', 'some content to write')->shouldBeCalled()->willReturn(21);
$this->write('filename', 'some content to write', true)->shouldReturn(21);
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_does_not_update_content_of_file_when_file_cannot_be_overwriten($adapter)
{
$adapter->exists('filename')->willReturn(true);
$adapter->write('filename', 'some content to write')->shouldNotBeCalled();
$this
->shouldThrow(new \Gaufrette\Exception\FileAlreadyExists('filename'))
->duringWrite('filename', 'some content to write')
;
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_fails_when_write_is_not_successful($adapter)
{
$adapter->exists('filename')->willReturn(false);
$adapter->write('filename', 'some content to write')->shouldBeCalled()->willReturn(false);
$this
->shouldThrow(new \RuntimeException('Could not write the "filename" key content.'))
->duringWrite('filename', 'some content to write')
;
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_read_file($adapter)
{
$adapter->exists('filename')->shouldBeCalled()->willReturn(true);
$adapter->read('filename')->shouldBeCalled()->willReturn('Some content');
$this->read('filename')->shouldReturn('Some content');
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_does_not_read_file_which_does_not_exist($adapter)
{
$adapter->exists('filename')->willReturn(false);
$this
->shouldThrow(new \Gaufrette\Exception\FileNotFound('filename'))
->duringRead('filename');
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_fails_when_read_is_not_successful($adapter)
{
$adapter->exists('filename')->willReturn(true);
$adapter->read('filename')->willReturn(false);
$this
->shouldThrow(new \RuntimeException('Could not read the "filename" key content.'))
->duringRead('filename')
;
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_deletes_file($adapter)
{
$adapter->exists('filename')->shouldBeCalled()->willReturn(true);
$adapter->delete('filename')->shouldBeCalled()->willReturn(true);
$this->delete('filename')->shouldReturn(true);
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_does_not_delete_file_which_does_not_exist($adapter)
{
$adapter->exists('filename')->willReturn(false);
$this
->shouldThrow(new \Gaufrette\Exception\FileNotFound('filename'))
->duringDelete('filename')
;
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_fails_when_delete_is_not_successful($adapter)
{
$adapter->exists('filename')->willReturn(true);
$adapter->delete('filename')->willReturn(false);
$this
->shouldThrow(new \RuntimeException('Could not remove the "filename" key.'))
->duringDelete('filename')
;
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_should_get_all_keys($adapter)
{
$keys = array('filename', 'filename1', 'filename2');
$adapter->keys()->willReturn($keys);
$this->keys()->shouldReturn($keys);
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_match_listed_keys_using_specified_pattern($adapter)
{
$keys = array('filename', 'filename1', 'filename2', 'testKey', 'KeyTest', 'testkey');
$adapter->keys()->willReturn($keys);
$adapter->isDirectory(Argument::any())->willReturn(false);
$this->listKeys()->shouldReturn(
array(
'keys' => array('filename', 'filename1', 'filename2', 'testKey', 'KeyTest', 'testkey'),
'dirs' => array()
)
);
$this->listKeys('filename')->shouldReturn(
array(
'keys' => array('filename', 'filename1', 'filename2'),
'dirs' => array()
)
);
$this->listKeys('Key')->shouldReturn(
array(
'keys' => array('KeyTest'),
'dirs' => array()
)
);
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_listing_directories_using_adapter_is_directory_method($adapter)
{
$keys = array('filename', 'filename1', 'filename2', 'testKey', 'KeyTest', 'testkey');
$adapter->keys()->willReturn($keys);
$adapter->isDirectory('filename')->willReturn(false);
$adapter->isDirectory('filename2')->willReturn(false);
$adapter->isDirectory('KeyTest')->willReturn(false);
$adapter->isDirectory('testkey')->willReturn(false);
$adapter->isDirectory('filename1')->willReturn(true);
$adapter->isDirectory('testKey')->willReturn(true);
$this->listKeys()->shouldReturn(
array(
'keys' => array('filename', 'filename2', 'KeyTest', 'testkey'),
'dirs' => array('filename1', 'testKey')
)
);
$this->listKeys('filename')->shouldReturn(
array(
'keys' => array('filename', 'filename2'),
'dirs' => array('filename1')
)
);
$this->listKeys('Key')->shouldReturn(
array(
'keys' => array('KeyTest'),
'dirs' => array()
)
);
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_gets_mtime_of_file_using_adapter($adapter)
{
$adapter->exists('filename')->willReturn(true);
$adapter->mtime('filename')->willReturn(1234567);
$this->mtime('filename')->shouldReturn(1234567);
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_does_not_get_mtime_of_file_which_does_not_exist($adapter)
{
$adapter->exists('filename')->willReturn(false);
$this
->shouldThrow(new \Gaufrette\Exception\FileNotFound('filename'))
->duringMtime('filename')
;
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_calculates_file_checksum($adapter)
{
$adapter->exists('filename')->shouldBeCalled()->willReturn(true);
$adapter->read('filename')->willReturn('some content');
$this->checksum('filename')->shouldReturn(md5('some content'));
}
/**
* @param \Gaufrette\Adapter $adapter
*/
function it_does_not_calculate_checksum_of_file_which_does_not_exist($adapter)
{
$adapter->exists('filename')->shouldBeCalled()->willReturn(false);
$this
->shouldThrow(new \Gaufrette\Exception\FileNotFound('filename'))
->duringChecksum('filename');
}
/**
* @param \spec\Gaufrette\Adapter $extendedAdapter
*/
function it_delegates_checksum_calculation_to_adapter_when_adapter_is_checksum_calculator($extendedAdapter)
{
$this->beConstructedWith($extendedAdapter);
$extendedAdapter->exists('filename')->shouldBeCalled()->willReturn(true);
$extendedAdapter->read('filename')->shouldNotBeCalled();
$extendedAdapter->checksum('filename')->shouldBeCalled()->willReturn(12);
$this->checksum('filename')->shouldReturn(12);
}
/**
* @param \spec\Gaufrette\Adapter $extendedAdapter
*/
function it_delegates_mime_type_resolution_to_adapter_when_adapter_is_mime_type_provider($extendedAdapter)
{
$this->beConstructedWith($extendedAdapter);
$extendedAdapter->exists('filename')->willReturn(true);
$extendedAdapter->mimeType('filename')->willReturn('text/plain');
$this->mimeType('filename')->shouldReturn('text/plain');
}
function it_cannot_resolve_mime_type_if_the_adapter_cannot_provide_it($adapter)
{
$adapter->exists('filename')->willReturn(true);
$this
->shouldThrow(new \LogicException(sprintf('Adapter "%s" cannot provide MIME type', get_class($adapter->getWrappedObject()))))
->duringMimeType('filename');
}
}
interface Adapter extends \Gaufrette\Adapter,
\Gaufrette\Adapter\FileFactory,
\Gaufrette\Adapter\StreamFactory,
\Gaufrette\Adapter\ChecksumCalculator,
\Gaufrette\Adapter\MetadataSupporter,
\Gaufrette\Adapter\MimeTypeProvider
{}

View File

@@ -0,0 +1,29 @@
<?php
namespace spec\Gaufrette\Stream;
use PhpSpec\ObjectBehavior;
use Gaufrette\StreamMode;
use org\bovigo\vfs\vfsStream;
class LocalSpec extends ObjectBehavior
{
function it_throws_runtime_exception_when_file_doesnt_exists()
{
$this->beConstructedWith(vfsStream::url('other'));
$this->shouldThrow('\RuntimeException')->duringOpen(new StreamMode('r'));
}
function it_throws_runtime_exception_when_file_doesnt_exists_and_custom_error_handler_specified()
{
$custom_error_handler = function ($errno, $errstr, $errfile, $errline) {
throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
};
set_error_handler($custom_error_handler);
$this->beConstructedWith(vfsStream::url('other'));
$this->shouldThrow('\RuntimeException')->duringOpen(new StreamMode('r'));
restore_error_handler();
}
}

View File

@@ -0,0 +1,142 @@
<?php
namespace spec\Gaufrette;
use PhpSpec\ObjectBehavior;
class StreamModeSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->beConstructedWith('r');
$this->shouldHaveType('Gaufrette\StreamMode');
}
function it_gives_access_to_mode()
{
$this->beConstructedWith('r+');
$this->getMode()->shouldReturn('r+');
}
function it_allows_write_only()
{
$this->beConstructedWith('w');
$this->allowsWrite()->shouldReturn(true);
$this->allowsRead()->shouldReturn(false);
}
function it_allows_write_and_read()
{
$this->beConstructedWith('w+');
$this->allowsWrite()->shouldReturn(true);
$this->allowsRead()->shouldReturn(true);
}
function it_allows_read_only()
{
$this->beConstructedWith('r');
$this->allowsWrite()->shouldReturn(false);
$this->allowsRead()->shouldReturn(true);
}
function it_allows_to_existing_file_opening()
{
$this->beConstructedWith('r');
$this->allowsExistingFileOpening()->shouldReturn(true);
}
function it_does_not_allow_to_existing_file_opening()
{
$this->beConstructedWith('x');
$this->allowsExistingFileOpening()->shouldReturn(false);
}
function it_allows_new_file_opening()
{
$this->beConstructedWith('w');
$this->allowsNewFileOpening()->shouldReturn(true);
}
function it_does_not_allow_new_file_opening()
{
$this->beConstructedWith('r');
$this->allowsNewFileOpening()->shouldReturn(false);
}
function it_implies_existing_content_deletion()
{
$this->beConstructedWith('w+');
$this->allowsNewFileOpening()->shouldReturn(true);
}
function it_does_not_implies_existing_content_deletion()
{
$this->beConstructedWith('r+');
$this->allowsNewFileOpening()->shouldReturn(false);
}
function it_implies_positioning_cursor_at_the_beginning()
{
$this->beConstructedWith('r+');
$this->impliesPositioningCursorAtTheBeginning()->shouldReturn(true);
}
function it_does_no_implies_positioning_cursor_at_the_beginning()
{
$this->beConstructedWith('a');
$this->impliesPositioningCursorAtTheBeginning()->shouldReturn(false);
}
function it_implies_positioning_cursor_at_the_end()
{
$this->beConstructedWith('a');
$this->impliesPositioningCursorAtTheEnd()->shouldReturn(true);
}
function it_does_no_implies_positioning_cursor_at_the_end()
{
$this->beConstructedWith('w');
$this->impliesPositioningCursorAtTheEnd()->shouldReturn(false);
}
function it_should_be_binary()
{
$this->beConstructedWith('wb+');
$this->isBinary()->shouldReturn(true);
}
function it_should_not_be_binary()
{
$this->beConstructedWith('w+');
$this->isBinary()->shouldReturn(false);
}
function it_should_not_be_text()
{
$this->beConstructedWith('wb+');
$this->isText()->shouldReturn(false);
}
function it_should_be_text()
{
$this->beConstructedWith('w+');
$this->isText()->shouldReturn(true);
}
}

View File

@@ -0,0 +1,295 @@
<?php
namespace spec\Gaufrette;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class StreamWrapperSpec extends ObjectBehavior
{
/**
* @param \Gaufrette\FilesystemMap $map
* @param \Gaufrette\Filesystem $filesystem
* @param \Gaufrette\Stream $stream
*/
function let($map, $filesystem, $stream)
{
$filesystem->createStream('filename')->willReturn($stream);
$map->get('some')->willReturn($filesystem);
$this->setFilesystemMap($map);
}
function it_is_initializable()
{
$this->shouldHaveType('Gaufrette\StreamWrapper');
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_opens_stream($stream)
{
$stream->open(Argument::any())->willReturn(true);
$this->stream_open('gaufrette://some/filename', 'r+')->shouldReturn(true);
}
function it_does_not_open_stream_when_key_is_not_defined()
{
$this
->shouldThrow(new \InvalidArgumentException('The specified path (gaufrette://some) is invalid.'))
->duringStream_open('gaufrette://some', 'r+');
}
function it_does_not_open_stream_when_host_is_not_defined()
{
$this
->shouldThrow(new \InvalidArgumentException('The specified path (gaufrette:///somefile) is invalid.'))
->duringStream_open('gaufrette:///somefile', 'r+')
;
}
function it_does_not_read_from_stream_when_is_not_opened()
{
$this->stream_read(10)->shouldReturn(false);
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_does_not_read_from_stream($stream)
{
$stream->open(Argument::any())->willReturn(true);
$stream->read(4)->willReturn('some');
$this->stream_open('gaufrette://some/filename', 'r+');
$this->stream_read(4)->shouldReturn('some');
}
function it_does_not_write_to_stream_when_is_not_opened()
{
$this->stream_write('some content')->shouldReturn(0);
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_writes_to_stream($stream)
{
$stream->open(Argument::any())->willReturn(true);
$stream->write('some content')->shouldBeCalled()->willReturn(12);
$this->stream_open('gaufrette://some/filename', 'w+');
$this->stream_write('some content')->shouldReturn(12);
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_does_not_close_stream_when_is_not_opened($stream)
{
$stream->close()->shouldNotBeCalled();
$this->stream_close();
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_closes_stream($stream)
{
$stream->open(Argument::any())->willReturn(true);
$stream->close()->shouldBeCalled();
$this->stream_open('gaufrette://some/filename', 'w+');
$this->stream_close();
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_does_not_flush_stream_when_is_not_opened($stream)
{
$stream->flush()->shouldNotBeCalled();
$this->stream_flush();
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_flushes_stream($stream)
{
$stream->open(Argument::any())->willReturn(true);
$stream->flush()->shouldBeCalled();
$this->stream_open('gaufrette://some/filename', 'w+');
$this->stream_flush();
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_does_not_seek_in_stream_when_is_not_opened($stream)
{
$stream->seek(12, SEEK_SET)->shouldNotBeCalled();
$this->stream_seek(12, SEEK_SET);
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_seeks_in_stream($stream)
{
$stream->open(Argument::any())->willReturn(true);
$stream->seek(12, SEEK_SET)->shouldBeCalled()->willReturn(true);
$this->stream_open('gaufrette://some/filename', 'w+');
$this->stream_seek(12, SEEK_SET)->shouldReturn(true);
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_does_not_tell_about_position_in_stream_when_is_not_opened($stream)
{
$stream->tell()->shouldNotBeCalled();
$this->stream_tell();
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_does_tell_about_position_in_stream($stream)
{
$stream->open(Argument::any())->willReturn(true);
$stream->tell()->shouldBeCalled()->willReturn(12);
$this->stream_open('gaufrette://some/filename', 'w+');
$this->stream_tell()->shouldReturn(12);
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_does_not_mark_as_eof_if_stream_is_not_opened($stream)
{
$stream->eof()->shouldNotBeCalled();
$this->stream_eof();
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_checks_if_eof($stream)
{
$stream->open(Argument::any())->willReturn(true);
$this->stream_open('gaufrette://some/filename', 'w+');
$stream->eof()->willReturn(false);
$this->stream_eof()->shouldReturn(false);
$stream->eof()->willReturn(true);
$this->stream_eof()->shouldReturn(true);
}
function it_does_not_get_stat_when_is_not_open()
{
$this->stream_stat()->shouldReturn(false);
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_stats_file($stream)
{
$stat = array(
'dev' => 1,
'ino' => 12,
'mode' => 0777,
'nlink' => 0,
'uid' => 123,
'gid' => 1,
'rdev' => 0,
'size' => 666,
'atime' => 1348030800,
'mtime' => 1348030800,
'ctime' => 1348030800,
'blksize' => 5,
'blocks' => 1,
);
$stream->open(Argument::any())->willReturn(true);
$stream->stat()->willReturn($stat);
$this->stream_open('gaufrette://some/filename', 'w+');
$this->stream_stat()->shouldReturn($stat);
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_should_stat_from_url($stream)
{
$stat = array(
'dev' => 1,
'ino' => 12,
'mode' => 0777,
'nlink' => 0,
'uid' => 123,
'gid' => 1,
'rdev' => 0,
'size' => 666,
'atime' => 1348030800,
'mtime' => 1348030800,
'ctime' => 1348030800,
'blksize' => 5,
'blocks' => 1,
);
$stream->open(Argument::any())->willReturn(true);
$stream->stat()->willReturn($stat);
$this->url_stat('gaufrette://some/filename', STREAM_URL_STAT_LINK)->shouldReturn($stat);
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_stats_even_if_it_cannot_be_open($filesystem, $stream)
{
$filesystem->createStream('dir/')->willReturn($stream);
$stream->open(Argument::any())->willThrow(new \RuntimeException);
$stream->stat(Argument::any())->willReturn(array('mode' => 16893));
$this->url_stat('gaufrette://some/dir/', STREAM_URL_STAT_LINK)->shouldReturn(array('mode' => 16893));
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_does_not_unlink_when_cannot_open($stream)
{
$stream->open(Argument::any())->willThrow(new \RuntimeException);
$this->unlink('gaufrette://some/filename')->shouldReturn(false);
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_unlinks_file($stream)
{
$stream->open(Argument::any())->willReturn(true);
$stream->unlink()->willReturn(true);
$this->unlink('gaufrette://some/filename')->shouldReturn(true);
}
function it_does_not_cast_stream_if_is_not_opened()
{
$this->stream_cast(STREAM_CAST_FOR_SELECT)->shouldReturn(false);
}
/**
* @param \Gaufrette\Stream $stream
*/
function it_casts_stream($stream)
{
$stream->open(Argument::any())->willReturn(true);
$stream->cast(STREAM_CAST_FOR_SELECT)->willReturn('resource');
$this->stream_open('gaufrette://some/filename', 'w+');
$this->stream_cast(STREAM_CAST_FOR_SELECT)->shouldReturn('resource');
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace spec\Gaufrette\Util;
use PHPSpec\ObjectBehavior;
class ChecksumSpec extends ObjectBehavior
{
function let()
{
$path = __DIR__.DIRECTORY_SEPARATOR.'testFile';
file_put_contents($path, 'some other content');
}
function it_calculates_checksum_from_content()
{
$this->fromContent('some content')->shouldReturn(md5('some content'));
}
function it_calculates_checksum_from_filepath()
{
$path = __DIR__.DIRECTORY_SEPARATOR.'testFile';
$this->fromFile($path)->shouldReturn(md5('some other content'));
}
function letgo()
{
$path = __DIR__.DIRECTORY_SEPARATOR.'testFile';
@unlink(__DIR__.DIRECTORY_SEPARATOR.'testFile');
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace spec\Gaufrette\Util;
use PhpSpec\ObjectBehavior;
class PathSpec extends ObjectBehavior
{
function it_checks_if_path_is_absolute()
{
$this->isAbsolute('/home/path')->shouldBe(true);
$this->isAbsolute('home/path')->shouldBe(false);
$this->isAbsolute('../home/path')->shouldBe(false);
$this->isAbsolute('protocol://home/path')->shouldBe(true);
}
function it_normalizes_file_path()
{
$this->normalize('C:\\some\other.txt')->shouldReturn('c:/some/other.txt');
$this->normalize('..\other.txt')->shouldReturn('../other.txt');
$this->normalize('..\other.txt')->shouldReturn('../other.txt');
$this->normalize('/home/other/../new')->shouldReturn('/home/new');
$this->normalize('/home/other/./new')->shouldReturn('/home/other/new');
$this->normalize('protocol://home/other.txt')->shouldReturn('protocol://home/other.txt');
}
function it_returns_unix_style_dirname()
{
$this->dirname('a/test/path')->shouldReturn('a/test');
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace spec\Gaufrette\Util;
use PhpSpec\ObjectBehavior;
class SizeSpec extends ObjectBehavior
{
function it_calculates_size_of_content()
{
$this->fromContent('some content')->shouldReturn(12);
$this->fromContent('some other content')->shouldReturn(18);
$this->fromContent('some')->shouldReturn(4);
}
}

View File

@@ -0,0 +1,84 @@
<?php
namespace Gaufrette;
/**
* Interface for the filesystem adapters.
*
* @author Antoine Hérault <antoine.herault@gmail.com>
* @author Leszek Prabucki <leszek.prabucki@gmail.com>
*/
interface Adapter
{
/**
* Reads the content of the file.
*
* @param string $key
*
* @return string|bool if cannot read content
*/
public function read($key);
/**
* Writes the given content into the file.
*
* @param string $key
* @param string $content
*
* @return int|bool The number of bytes that were written into the file
*/
public function write($key, $content);
/**
* Indicates whether the file exists.
*
* @param string $key
*
* @return bool
*/
public function exists($key);
/**
* Returns an array of all keys (files and directories).
*
* @return array
*/
public function keys();
/**
* Returns the last modified time.
*
* @param string $key
*
* @return int|bool An UNIX like timestamp or false
*/
public function mtime($key);
/**
* Deletes the file.
*
* @param string $key
*
* @return bool
*/
public function delete($key);
/**
* Renames a file.
*
* @param string $sourceKey
* @param string $targetKey
*
* @return bool
*/
public function rename($sourceKey, $targetKey);
/**
* Check if key is directory.
*
* @param string $key
*
* @return bool
*/
public function isDirectory($key);
}

Some files were not shown because too many files have changed in this diff Show More