private function getSupportedLoader($data)
    {
        $loaders = $this->vars->loader->getLoaders();

        foreach ($loaders as $loader) {
            $class_loader = new \ReflectionClass($loader);
            $class_loader = $class_loader->newInstanceArgs(array($data));

            if ($class_loader->supports()) {
                return $class_loader;
            }
        }
        return false;
    }

private function getSupportedLoader ( $ data ) { $ loaders = $ this -> vars -> loader -> getLoaders ( ) ; foreach ( $ loaders as $ loader ) { $ class_loader = new \ ReflectionClass ( $ loader ) ; $ class_loader = $ class_loader -> newInstanceArgs ( array ( $ data ) ) ; if ( $ class_loader -> supports ( ) ) { return $ class_loader ; } } return false ; }

Gets the supported loader for the passed file

@see \M1\Vars\Vars::getLoaders() \M1\Vars\Vars::getLoaders()

@param string $data The passed file

@return mixed Returns the loader class or false if no loader calls was found


private function loadContent($data)
    {
        $loader = $this->getSupportedLoader($data);

        if (!$loader) {
            throw new \InvalidArgumentException(sprintf("'%s' is not supported by the current loaders", $this->file));
        }

        $loader->load();
        return $loader->getContent();
    }

Loads raw content from the file

@param string $data The passed file

@throws \InvalidArugmentException If the file passed is not supported by the current loaders

@return mixed The content from the file via the loader


private function createOptions($app)
    {
        $options = array();

        if (isset($app['vars.path'])) {
            $options['path'] = $app['vars.path'];
        }

        if (isset($app['vars.options'])) {
            $options = $this->createKeyedOptions($options, $app['vars.options']);
        }

        if (!isset($options['merge_globals']) || is_null($options['merge_globals'])) {
            $options['merge_globals'] = false;
        }

        if (isset($app['debug']) && $app['debug']) {
            $options['cache'] = false;
        }

        return $options;
    }

private function createOptions ( $ app ) { $ options = array ( ) ; if ( isset ( $ app [ 'vars.path' ] ) ) { $ options [ 'path' ] = $ app [ 'vars.path' ] ; } if ( isset ( $ app [ 'vars.options' ] ) ) { $ options = $ this -> createKeyedOptions ( $ options , $ app [ 'vars.options' ] ) ; } if ( ! isset ( $ options [ 'merge_globals' ] ) || is_null ( $ options [ 'merge_globals' ] ) ) { $ options [ 'merge_globals' ] = false ; } if ( isset ( $ app [ 'debug' ] ) && $ app [ 'debug' ] ) { $ options [ 'cache' ] = false ; } return $ options ; }

Creates the defined options into a way that Vars can use

@param \Silex\Application $app The silex app

@return array The created options


public static function get_allowed_tags() {
		$tags = array(
			'a',
			'altGlyph',
			'altGlyphDef',
			'altGlyphItem',
			'animate',
			'animateColor',
			'animateMotion',
			'animateTransform',
			'audio',
			'canvas',
			'circle',
			'clipPath',
			'color-profile',
			'cursor',
			'defs',
			'desc',
			'discard',
			'ellipse',
			'feBlend',
			'feColorMatrix',
			'feComponentTransfer',
			'feComposite',
			'feConvolveMatrix',
			'feDiffuseLighting',
			'feDisplacementMap',
			'feDistantLight',
			'feDropShadow',
			'feFlood',
			'feFuncA',
			'feFuncB',
			'feFuncG',
			'feFuncR',
			'feGaussianBlur',
			'feImage',
			'feMerge',
			'feMergeNode',
			'feMorphology',
			'feOffset',
			'fePointLight',
			'feSpecularLighting',
			'feSpotLight',
			'feTile',
			'feTurbulence',
			'filter',
			'font',
			'font-face',
			'font-face-format',
			'font-face-name',
			'font-face-src',
			'font-face-uri',
			'g',
			'glyph',
			'glyphRef',
			'hatch',
			'hatchpath',
			'hkern',
			'image',
			'line',
			'linearGradient',
			'marker',
			'mask',
			'mesh',
			'meshgradient',
			'meshpatch',
			'meshrow',
			'metadata',
			'missing-glyph',
			'mpath',
			'path',
			'pattern',
			'polygon',
			'polyline',
			'radialGradient',
			'rect',
			'set',
			'solidcolor',
			'stop',
			'style',
			'svg',
			'switch',
			'symbol',
			'text',
			'textPath',
			'title',
			'tref',
			'tspan',
			'unknown',
			'use',
			'video',
			'view',
			'vkern',
		);

		$tags = apply_filters('blobmimes_svg_allowed_tags', $tags);
		if (!is_array($tags) || !count($tags)) {
			return array();
		}

		// Convert to lowercase for easier comparison.
		foreach ($tags as $k=>$v) {
			$tags[$k] = mb::strtolower(trim($v));
			if (!strlen($tags[$k])) {
				unset($tags[$k]);
			}
		}

		// Pre-sorting will speed up looped checks.
		$tags = array_unique($tags);
		sort($tags);
		return $tags;
	}

Return whitelisted tags

Based on SVG spec, minus anything scripty.

@see { https://developer.mozilla.org/en-US/docs/Web/SVG/Element }

@return array Array of valid tags.


public static function get_allowed_protocols() {
		$protocols = array(
			'http',
			'https',
		);

		$protocols = apply_filters('blobmimes_svg_allowed_protocols', $protocols);
		if (!is_array($protocols) || !count($protocols)) {
			return array();
		}

		// Convert to lowercase for easier comparison.
		foreach ($protocols as $k=>$v) {
			$protocols[$k] = mb::strtolower(trim($v));
			if (!strlen($protocols[$k])) {
				unset($protocols[$k]);
			}
		}

		// Pre-sorting will speed up looped checks.
		$protocols = array_unique($protocols);
		sort($protocols);
		return $protocols;
	}

Return whitelisted protocols

@see { http://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml }

@return array Array of valid protocols.


public static function get_allowed_domains() {
		$domains = array(
			site_url(),
			'creativecommons.org',
			'inkscape.org',
			'sodipodi.sourceforge.net',
			'w3.org',
		);

		$domains = apply_filters('blobmimes_svg_allowed_domains', $domains);
		if (!is_array($domains) || !count($domains)) {
			return array();
		}

		// Sanitize the list before moving on.
		foreach ($domains as $k=>$domain) {
			if (false === ($domains[$k] = static::sanitize_domain($domain))) {
				unset($domains[$k]);
			}
		}

		// Pre-sorting will speed up looped checks.
		$domains = array_unique($domains);
		sort($domains);
		return $domains;
	}

Return whitelisted domains

@return array Domains.


public static function sanitize_domain($domain = '') {
		if (!is_string($domain)) {
			return false;
		}

		$domain = mb::strtolower(trim($domain));

		// Try to parse a full URL.
		$host = wp_parse_url($domain, PHP_URL_HOST);
		if (!$host) {
			// Strip path?
			if (false !== ($start = mb::strpos($domain, '/'))) {
				$domain = mb::substr($domain, 0, $start);
			}

			// Strip query?
			if (false !== ($start = mb::strpos($domain, '?'))) {
				$domain = mb::substr($domain, 0, $start);
			}

			// Strip port?
			if (
				!filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) &&
				false !== ($start = mb::strpos($domain, ':'))
			) {
				$domain = mb::substr($domain, 0, $start);
			}

			// Bail if invalid characters at this point.
			if (filter_var($domain, FILTER_SANITIZE_URL) !== $domain) {
				return false;
			}
		} else {
			$domain = $host;
		}

		if (is_string($domain)) {
			$domain = preg_replace('/^www\./u', '', $domain);
		}

		return $domain ? $domain : false;
	}

Sanitize a domain-like string for more
level comparison.

@param string $domain Domain.
@return string|bool Domain. False on failure.

Sanitize a domain - like string for more level comparison .


protected static function sanitize_attribute_value($str = '') {
		$str = wp_kses_no_null($str);

		// Decode all entities.
		$old_value = '';
		while ($old_value !== $str) {
			$old_value = $str;
			$str = wp_kses_decode_entities($str);
			$str = html_entity_decode($str, ENT_QUOTES, 'UTF-8');

			// And (full) trim while we're here.
			$str = preg_replace('/^\s+/u', '', $str);
			$str = preg_replace('/\s+$/u', '', $str);
		}

		return $str;
	}

protected
static
function
sanitize_attribute_value
(
$
str
=
''
)
{
$
str
=
wp_kses_no_null
(
$
str
)
;
// Decode all entities.
$
old_value
=
''
;
while
(
$
old_value
!==
$
str
)
{
$
old_value
=
$
str
;
$
str
=
wp_kses_decode_entities
(
$
str
)
;
$
str
=
html_entity_decode
(
$
str
,
ENT_QUOTES
,
'UTF-8'
)
;
// And (full) trim while we're here.
$
str
=
preg_replace
(
'/^\s+/u'
,
''
,
$
str
)
;
$
str
=
preg_replace
(
'/\s+$/u'
,
''
,
$
str
)
;
}
return
$
str
;
}

Sanitize attribute value

@param string $str Attribute value.
@return string Attribute value.


protected static function sanitize_iri_value($str = '') {
		$allowed_protocols = static::get_allowed_protocols();
		$allowed_domains = static::get_allowed_domains();

		if (wp_kses_bad_protocol($str, $allowed_protocols) !== $str) {
			return '';
		}

		// Assign a protocol.
		$str = preg_replace('/^\/\//', 'https://', $str);

		// Is this a URLish thing?
		if (filter_var($str, FILTER_SANITIZE_URL) !== $str) {
			return '';
		}

		// Check the domain, if applicable.
		if (preg_match('/^[\w\d]+:\/\//i', $str)) {
			if (false !== ($domain = static::sanitize_domain($str))) {
				if (!in_array($domain, $allowed_domains, true)) {
					return '';
				}
			} else {
				return '';
			}
		}

		return $str;
	}

protected
static
function
sanitize_iri_value
(
$
str
=
''
)
{
$
allowed_protocols
=
static
::
get_allowed_protocols
(
)
;
$
allowed_domains
=
static
::
get_allowed_domains
(
)
;
if
(
wp_kses_bad_protocol
(
$
str
,
$
allowed_protocols
)
!==
$
str
)
{
return
''
;
}
// Assign a protocol.
$
str
=
preg_replace
(
'/^\/\//'
,
'https://'
,
$
str
)
;
// Is this a URLish thing?
if
(
filter_var
(
$
str
,
FILTER_SANITIZE_URL
)
!==
$
str
)
{
return
''
;
}
// Check the domain, if applicable.
if
(
preg_match
(
'/^[\w\d]+:\/\//i'
,
$
str
)
)
{
if
(
false
!==
(
$
domain
=
static
::
sanitize_domain
(
$
str
)
)
)
{
if
(
!
in_array
(
$
domain
,
$
allowed_domains
,
true
)
)
{
return
''
;
}
}
else
{
return
''
;
}
}
return
$
str
;
}

Sanitize IRI value

@param string $str IRI value.
@return string IRI value.


protected static function callback_sanitize_css_iri($match) {
		$str = static::sanitize_attribute_value($match[1]);

		// Strip quotes.
		$str = ltrim($str, "'\"");
		$str = rtrim($str, "'\"");

		$str = static::sanitize_iri_value($str);

		if (strlen($str)) {
			return "url('$str')";
		}

		return 'none';
	}

protected
static
function
callback_sanitize_css_iri
(
$
match
)
{
$
str
=
static
::
sanitize_attribute_value
(
$
match
[
1
]
)
;
// Strip quotes.
$
str
=
ltrim
(
$
str
,
"'\""
)
;
$
str
=
rtrim
(
$
str
,
"'\""
)
;
$
str
=
static
::
sanitize_iri_value
(
$
str
)
;
if
(
strlen
(
$
str
)
)
{
return
"url('$str')"
;
}
return
'none'
;
}

Callback handler for sanitizing CSS URLs

@param array $match Match.
@return string Sanitized URL.


protected static function load_svg($svg = '') {
		// Early bail.
		if (!is_string($svg) || !strlen($svg)) {
			return false;
		}

		// Maybe a path?
		if (
			false === mb::strpos(mb::strtolower($svg), '<svg') ||
			false === mb::strrpos(mb::strtolower($svg), '</svg>')
		) {
			try {
				// @codingStandardsIgnoreStart
				$svg = @file_get_contents($svg);
				// @codingStandardsIgnoreEnd
				if (!is_string($svg) || !strlen($svg)) {
					return false;
				}
			} catch (\Throwable $e) {
				return false;
			} catch (\Exception $e) {
				return false;
			}
		}

		// Lowercase the tags.
		$svg = preg_replace('/<svg/ui', '<svg', $svg);
		$svg = preg_replace('/<\/svg>/ui', '</svg>', $svg);

		if (
			false === ($start = mb::strpos($svg, '<svg')) ||
			false === ($end = mb::strrpos($svg, '</svg>'))
		) {
			return false;
		}
		$svg = mb::substr($svg, $start, ($end - $start + 6));

		// Remove comments.
		$svg = static::strip_comments($svg);

		return $svg;
	}

protected
static
function
load_svg
(
$
svg
=
''
)
{
// Early bail.
if
(
!
is_string
(
$
svg
)
||
!
strlen
(
$
svg
)
)
{
return
false
;
}
// Maybe a path?
if
(
false
===
mb
::
strpos
(
mb
::
strtolower
(
$
svg
)
,
'<svg'
)
||
false
===
mb
::
strrpos
(
mb
::
strtolower
(
$
svg
)
,
'</svg>'
)
)
{
try
{
// @codingStandardsIgnoreStart
$
svg
=
@
file_get_contents
(
$
svg
)
;
// @codingStandardsIgnoreEnd
if
(
!
is_string
(
$
svg
)
||
!
strlen
(
$
svg
)
)
{
return
false
;
}
}
catch
(
\
Throwable
$
e
)
{
return
false
;
}
catch
(
\
Exception
$
e
)
{
return
false
;
}
}
// Lowercase the tags.
$
svg
=
preg_replace
(
'/<svg/ui'
,
'<svg'
,
$
svg
)
;
$
svg
=
preg_replace
(
'/<\/svg>/ui'
,
'</svg>'
,
$
svg
)
;
if
(
false
===
(
$
start
=
mb
::
strpos
(
$
svg
,
'<svg'
)
)
||
false
===
(
$
end
=
mb
::
strrpos
(
$
svg
,
'</svg>'
)
)
)
{
return
false
;
}
$
svg
=
mb
::
substr
(
$
svg
,
$
start
,
(
$
end
$
start
+
6
)
)
;
// Remove comments.
$
svg
=
static
::
strip_comments
(
$
svg
)
;
return
$
svg
;
}

Read an SVG file as contents or path.

@param string $svg SVG code or path.
@return string|bool SVG code. False on failure.


protected static function strip_comments($svg = '') {
		if (!is_string($svg)) {
			return false;
		}

		// Remove XML, PHP, ASP, etc.
		$svg = preg_replace('/<\?(.*)\?>/Us', '', $svg);
		$svg = preg_replace('/<\%(.*)\%>/Us', '', $svg);

		if (
			false !== mb::strpos($svg, '<?') ||
			false !== mb::strpos($svg, '<%')
		) {
			return false;
		}

		// Remove comments.
		$svg = preg_replace('/<!--(.*)-->/Us', '', $svg);
		$svg = preg_replace('/\/\*(.*)\*\//Us', '', $svg);

		if (
			false !== mb::strpos($svg, '<!--') ||
			false !== mb::strpos($svg, '/*')
		) {
			return false;
		}

		return $svg;
	}

protected
static
function
strip_comments
(
$
svg
=
''
)
{
if
(
!
is_string
(
$
svg
)
)
{
return
false
;
}
// Remove XML, PHP, ASP, etc.
$
svg
=
preg_replace
(
'/<\?(.*)\?>/Us'
,
''
,
$
svg
)
;
$
svg
=
preg_replace
(
'/<\%(.*)\%>/Us'
,
''
,
$
svg
)
;
if
(
false
!==
mb
::
strpos
(
$
svg
,
'<?'
)
||
false
!==
mb
::
strpos
(
$
svg
,
'<%'
)
)
{
return
false
;
}
// Remove comments.
$
svg
=
preg_replace
(
'/<!--(.*)-->/Us'
,
''
,
$
svg
)
;
$
svg
=
preg_replace
(
'/\/\*(.*)\*\//Us'
,
''
,
$
svg
)
;
if
(
false
!==
mb
::
strpos
(
$
svg
,
'<!--'
)
||
false
!==
mb
::
strpos
(
$
svg
,
'/*'
)
)
{
return
false
;
}
return
$
svg
;
}

Remove comments and interpreter tags from an SVG file

@param string $svg SVG code or path.
@return string|bool SVG code. False on failure.


protected function replicateFlags($resource, $original_resource)
    {
        return sprintf(
            '%s%s%s',
            ($this->checkSuppression($original_resource)) ? '@' : null,
            $resource,
            ($this->checkRecursive($original_resource)) ? '*' : null
        );
    }

protected function replicateFlags ( $ resource , $ original_resource ) { return sprintf ( '%s%s%s' , ( $ this -> checkSuppression ( $ original_resource ) ) ? '@' : null , $ resource , ( $ this -> checkRecursive ( $ original_resource ) ) ? '*' : null ) ; }

Duplicates the flags from one string to another

@param string $resource The resource to add the flags to
@param string $resource The resource to duplicate the flags from

@return string The parsed string resource


private function makeLoaders($options, $default_loaders)
    {
        $loaders = $this->preParseLoaders($options, $default_loaders);
        $parsed_loaders = array();

        foreach ($loaders as $loader) {
            if ($loader === 'default') {
                $parsed_loaders = array_merge($parsed_loaders, $default_loaders);
            } else {
                $parsed_loaders[] = $loader;
            }
        }

        $parsed_loaders = array_unique($parsed_loaders);

        $this->loaders = $this->makeNameSpaceLoaders($parsed_loaders, $default_loaders);
        $this->extensions = $this->makeExtensions($this->loaders);
    }

private function makeLoaders ( $ options , $ default_loaders ) { $ loaders = $ this -> preParseLoaders ( $ options , $ default_loaders ) ; $ parsed_loaders = array ( ) ; foreach ( $ loaders as $ loader ) { if ( $ loader === 'default' ) { $ parsed_loaders = array_merge ( $ parsed_loaders , $ default_loaders ) ; } else { $ parsed_loaders [ ] = $ loader ; } } $ parsed_loaders = array_unique ( $ parsed_loaders ) ; $ this -> loaders = $ this -> makeNameSpaceLoaders ( $ parsed_loaders , $ default_loaders ) ; $ this -> extensions = $ this -> makeExtensions ( $ this -> loaders ) ; }

Get loaders and make extensions for the loaders

@param array|null $options           The options being used for Vars
@param array      $default_loaders   The default loaders for Vars


private function preParseLoaders($options, $default_loaders)
    {
        $loaders = array();

        if (is_array($options['loaders']) && !empty($options['loaders'])) {
            $loaders = $options['loaders'];
        } elseif (is_string($options['loaders'])) {
            $loaders[] = $options['loaders'];
        } else {
            $loaders = $default_loaders;
        }

        return $loaders;
    }

private function preParseLoaders ( $ options , $ default_loaders ) { $ loaders = array ( ) ; if ( is_array ( $ options [ 'loaders' ] ) && ! empty ( $ options [ 'loaders' ] ) ) { $ loaders = $ options [ 'loaders' ] ; } elseif ( is_string ( $ options [ 'loaders' ] ) ) { $ loaders [ ] = $ options [ 'loaders' ] ; } else { $ loaders = $ default_loaders ; } return $ loaders ; }

Pre parse the loaders for use in make loaders

@param array|null $options           The options being used for Vars
@param array      $default_loaders   The default loaders for Vars

@return array The pre parsed loaders


private function makeNameSpaceLoaders($loaders, $default_loaders)
    {
        $parsed_loaders = array();

        foreach ($loaders as $loader) {
            if (in_array($loader, $default_loaders)) {
                $loader = sprintf('%s\%sLoader', __NAMESPACE__, ucfirst(strtolower($loader)));
            }

            if (!class_exists($loader)) {
                throw new \InvalidArgumentException(sprintf("'%s' loader class does not exist", $loader));
            }

            $parsed_loaders[] = $loader;
        }

        return $parsed_loaders;
    }

private
function
makeNameSpaceLoaders
(
$
loaders
,
$
default_loaders
)
{
$
parsed_loaders
=
array
(
)
;
foreach
(
$
loaders
as
$
loader
)
{
if
(
in_array
(
$
loader
,
$
default_loaders
)
)
{
$
loader
=
sprintf
(
'%s\%sLoader'
,
__NAMESPACE__
,
ucfirst
(
strtolower
(
$
loader
)
)
)
;
}
if
(
!
class_exists
(
$
loader
)
)
{
throw
new
\
InvalidArgumentException
(
sprintf
(
"'%s' loader class does not exist"
,
$
loader
)
)
;
}
$
parsed_loaders
[
]
=
$
loader
;
}
return
$
parsed_loaders
;
}

Makes namespace loaders from loader strings

@param array $loaders The options being used for Vars
@param array      $default_loaders   The default loaders for Vars

@throws \InvalidArgumentException If a loader from options isn't found

@return array The namespace loaders


private function parseOptions(array $options)
    {
        $parsed_options = array_merge($this->default_options, $options);
        $parsed_options['loaders'] = (isset($options['loaders'])) ?
            $options['loaders'] : $this->default_options['loaders'];

        return $parsed_options;
    }

private function parseOptions ( array $ options ) { $ parsed_options = array_merge ( $ this -> default_options , $ options ) ; $ parsed_options [ 'loaders' ] = ( isset ( $ options [ 'loaders' ] ) ) ? $ options [ 'loaders' ] : $ this -> default_options [ 'loaders' ] ; return $ parsed_options ; }

Parses the options so Vars can use them

@param array $options  The options being used for Vars

@return array The parsed options


private function makeCache($options, $resource)
    {
        $cache = new CacheProvider($resource, $options);
        $this->cache = $cache;
    }

private function makeCache ( $ options , $ resource ) { $ cache = new CacheProvider ( $ resource , $ options ) ; $ this -> cache = $ cache ; }

Makes the CacheProvider with the options

@param array        $options  The options being used for Vars
@param array|string $resource The main configuration resource


private function makePaths($options)
    {
        $this->setPath($options['path']);

        if (is_null($options['cache_path']) && !is_null($options['path'])) {
            $this->cache->setPath($options['path']);
            $this->paths_loaded = true;
        }
    }

private function makePaths ( $ options ) { $ this -> setPath ( $ options [ 'path' ] ) ; if ( is_null ( $ options [ 'cache_path' ] ) && ! is_null ( $ options [ 'path' ] ) ) { $ this -> cache -> setPath ( $ options [ 'path' ] ) ; $ this -> paths_loaded = true ; } }

Sets the base path if the options have been set and the cache path if the cache path has not been set but the
base path has

@param array $options The options being used for Vars


private function makeLoader($options)
    {
        $loader = new LoaderProvider($options, $this->default_options['loaders']);
        $this->loader = $loader;
    }

private function makeLoader ( $ options ) { $ loader = new LoaderProvider ( $ options , $ this -> default_options [ 'loaders' ] ) ; $ this -> loader = $ loader ; }

Makes the LoaderProvider with the options

@param array $options  The options being used for Vars


private function makeVariables($options)
    {
        $this->variables = new VariableProvider($this);

        if (isset($options['replacements'])) {
            $this->variables->rstore->load($options['replacements']);
        }
    }

private function makeVariables ( $ options ) { $ this -> variables = new VariableProvider ( $ this ) ; if ( isset ( $ options [ 'replacements' ] ) ) { $ this -> variables -> rstore -> load ( $ options [ 'replacements' ] ) ; } }

Sets the replacement variables if the option has been set

@param array|null $options The options being used for Vars


private function loadFromCache()
    {
        $this->cache->load();

        $passed_keys = array(
            'path',
            'content',
            'extensions',
            'loaders',
            'resources',
            'replacements',
            'globals',
        );

        $loaded_vars = get_object_vars($this->cache->getLoadedVars());

        foreach ($loaded_vars as $key => $value) {
            if (in_array($key, $passed_keys)) {
                $this->$key = $value;
            }
        }

        $this->cache->setTime($loaded_vars['cache']->getTime());
    }

private function loadFromCache ( ) { $ this -> cache -> load ( ) ; $ passed_keys = array ( 'path' , 'content' , 'extensions' , 'loaders' , 'resources' , 'replacements' , 'globals' , ) ; $ loaded_vars = get_object_vars ( $ this -> cache -> getLoadedVars ( ) ) ; foreach ( $ loaded_vars as $ key => $ value ) { if ( in_array ( $ key , $ passed_keys ) ) { $ this -> $ key = $ value ; } } $ this -> cache -> setTime ( $ loaded_vars [ 'cache' ] -> getTime ( ) ) ; }

Loads the cached file into the current class


private function mergeGlobals($content, $options)
    {
        if (array_key_exists('_globals', $content)) {
            $this->globals = $content['_globals'];

            if ($options['merge_globals']) {
                $content = array_replace_recursive($content, $content['_globals']);
            }

            unset($content['_globals']);
        }

        return $content;
    }

private function mergeGlobals ( $ content , $ options ) { if ( array_key_exists ( '_globals' , $ content ) ) { $ this -> globals = $ content [ '_globals' ] ; if ( $ options [ 'merge_globals' ] ) { $ content = array_replace_recursive ( $ content , $ content [ '_globals' ] ) ; } unset ( $ content [ '_globals' ] ) ; } return $ content ; }

Gets the _globals from the file and merges them if merge_globals is true

@param array $content The unparsed content
@param array $options  The options being used for Vars

@return array $content The parsed content


public function getResource($resource)
    {
        foreach ($this->getResources() as $r) {
            if ($resource === $r->getFilename()) {
                return $r;
            }
        }

        return false;
    }

public function getResource ( $ resource ) { foreach ( $ this -> getResources ( ) as $ r ) { if ( $ resource === $ r -> getFilename ( ) ) { return $ r ; } } return false ; }

Searches the resource stack for a certain resource

@param string $resource The resource to search for

@return \M1\Vars\Resource\FileResource|bool Returns the resource if found


public function createPrefix($relative)
    {
        if ($relative) {
            $this->prefix = (empty($this->current_prefix)) ? '' : $this->current_prefix;
            return;
        }

        $this->prefix = '';
    }

public function createPrefix ( $ relative ) { if ( $ relative ) { $ this -> prefix = ( empty ( $ this -> current_prefix ) ) ? '' : $ this -> current_prefix ; return ; } $ this -> prefix = '' ; }

Creates a relative prefix for the store

@param bool $relative Is the prefix relative


private function createResources(array $resources, $type)
    {
        foreach ($resources as $resource) {
            if ($type === "string") {
                $this->vars->pathsLoadedCheck($resource);

                if ($this->vars->cache->checkCache()) {
                    return;
                }

                if ($this->vars->resourceImported($resource)) {
                    continue;
                }

                $pos = $this->vars->addResource($resource);
                $resource = new FileResource($this, $resource);
                $this->vars->updateResource($resource, $pos);
            } else {
                $resource = new ResourceProvider($this->vars, $resource);
            }

            $this->addContent($resource->getContent());
        }
    }

private function createResources ( array $ resources , $ type ) { foreach ( $ resources as $ resource ) { if ( $ type === "string" ) { $ this -> vars -> pathsLoadedCheck ( $ resource ) ; if ( $ this -> vars -> cache -> checkCache ( ) ) { return ; } if ( $ this -> vars -> resourceImported ( $ resource ) ) { continue ; } $ pos = $ this -> vars -> addResource ( $ resource ) ; $ resource = new FileResource ( $ this , $ resource ) ; $ this -> vars -> updateResource ( $ resource , $ pos ) ; } else { $ resource = new ResourceProvider ( $ this -> vars , $ resource ) ; } $ this -> addContent ( $ resource -> getContent ( ) ) ; } }

Creates the FileResource|ResourceProvider from the resource

@param array  $resources The array of resources
@param string $type      The type of the resource


private function addContent($content)
    {
        if ($this->relative) {
            $this->content = $this->mergeContents($this->content, $content);
        } else {
            $this->parent_content = $this->mergeContents($this->parent_content, $content);
        }
    }

private function addContent ( $ content ) { if ( $ this -> relative ) { $ this -> content = $ this -> mergeContents ( $ this -> content , $ content ) ; } else { $ this -> parent_content = $ this -> mergeContents ( $ this -> parent_content , $ content ) ; } }

Adds content to the parent contents

@param array $content The content from the resource


private function getSupportedFilesInDir($entity)
    {
        $dir_loader = new DirectoryLoader($entity, $this->recursive);
        $dir_loader->setSupports($this->vars->loader->getExtensions());
        $dir_loader->load();

        return $dir_loader->getContent();
    }

private function getSupportedFilesInDir ( $ entity ) { $ dir_loader = new DirectoryLoader ( $ entity , $ this -> recursive ) ; $ dir_loader -> setSupports ( $ this -> vars -> loader -> getExtensions ( ) ) ; $ dir_loader -> load ( ) ; return $ dir_loader -> getContent ( ) ; }

Returns the supported files using the extensions from the loaders in the entity which is a directory

@see \M1\Vars\Loader\LoaderProvider::getExtensions() \M1\Vars\Loader\LoaderProvider::getExtensions()
@see \M1\Vars\Loader\LoaderProvider::makeLoaders() \M1\Vars\Loader\LoaderProvider::makeLoaders()

@param string $entity The resource entity

@return array|bool Returns the supported files or false if no files were found


public function mergeParentContent()
    {
        $this->content = $this->mergeContents($this->content, $this->parent_content);

        return $this;
    }

public function mergeParentContent ( ) { $ this -> content = $ this -> mergeContents ( $ this -> content , $ this -> parent_content ) ; return $ this ; }

Merges the content and the parent content together

@return \M1\Vars\Resource\ResourceProvider


private function internalGet(array $array, $key, $exists = false)
    {
        if (isset($array[$key])) {
            return (!$exists) ? $array[$key] : true;
        }

        $parts = explode('.', $key);

        foreach ($parts as $part) {
            if (!is_array($array) || !isset($array[$part])) {
                return (!$exists) ? null : false;
            }

            $array = $array[$part];
        }

        return (!$exists) ? $array : true;
    }

private function internalGet ( array $ array , $ key , $ exists = false ) { if ( isset ( $ array [ $ key ] ) ) { return ( ! $ exists ) ? $ array [ $ key ] : true ; } $ parts = explode ( '.' , $ key ) ; foreach ( $ parts as $ part ) { if ( ! is_array ( $ array ) || ! isset ( $ array [ $ part ] ) ) { return ( ! $ exists ) ? null : false ; } $ array = $ array [ $ part ] ; } return ( ! $ exists ) ? $ array : true ; }

The internal get function for getting values by their key

@param array $array  The array to use -- will always be $this->content
@param mixed $key    The key to find the value for
@param bool  $exists Whether to return null or false dependant on the calling function

@return array|bool|null The resource key value


public function arrayKeyExists($key)
    {
        if (array_key_exists($key, $this->content)) {
            return true;
        }

        $parts = explode('.', $key);
        $arr = $this->content;
        foreach ($parts as $part) {
            if (!is_array($arr) || !array_key_exists($part, $arr)) {
                return false;
            }

            $arr = $arr[$part];
        }

        return true;
    }

public function arrayKeyExists ( $ key ) { if ( array_key_exists ( $ key , $ this -> content ) ) { return true ; } $ parts = explode ( '.' , $ key ) ; $ arr = $ this -> content ; foreach ( $ parts as $ part ) { if ( ! is_array ( $ arr ) || ! array_key_exists ( $ part , $ arr ) ) { return false ; } $ arr = $ arr [ $ part ] ; } return true ; }

Port of array_key_exists to \ArrayAccess

@param mixed $key The key to check if exists

@return bool Does the key exist

Port of array_key_exists to \ ArrayAccess


public function parse($value)
    {
        foreach (self::$variable_types as $variable_type) {
            $value = $this->typeParse($value, $variable_type);
        }

        return $value;
    }

public function parse ( $ value ) { foreach ( self :: $ variable_types as $ variable_type ) { $ value = $ this -> typeParse ( $ value , $ variable_type ) ; } return $ value ; }

Parses the string for the types of variables

@param string $value The string to parse

@return string The parsed variable


private function typeParse($value, $type)
    {
        $const_str = sprintf('REGEX_%s_SYNTAX', strtoupper($type));
        $regex = constant('\M1\Vars\Variables\VariableProvider::'.$const_str);

        $matches = $this->fetchVariableMatches($value, $regex);

        if (is_array($matches)) {
            if (count($matches[0]) === 1 && $value === $matches[0][0]) {
                return $this->fetchVariable(trim($matches[1][0]), $type);
            }

            $value = $this->doReplacements($value, $matches, $type);
        }
        return $value;
    }

private function typeParse ( $ value , $ type ) { $ const_str = sprintf ( 'REGEX_%s_SYNTAX' , strtoupper ( $ type ) ) ; $ regex = constant ( '\M1\Vars\Variables\VariableProvider::' . $ const_str ) ; $ matches = $ this -> fetchVariableMatches ( $ value , $ regex ) ; if ( is_array ( $ matches ) ) { if ( count ( $ matches [ 0 ] ) === 1 && $ value === $ matches [ 0 ] [ 0 ] ) { return $ this -> fetchVariable ( trim ( $ matches [ 1 ] [ 0 ] ) , $ type ) ; } $ value = $ this -> doReplacements ( $ value , $ matches , $ type ) ; } return $ value ; }

Parses the string based on the type of variable

@param string $value The string to parse
@param string $type  The variable type

@return string The parsed variable


private function fetchVariableMatches($value, $regex)
    {
        preg_match_all('/' . $regex . '/', $value, $matches);

        if (!is_array($matches) || !isset($matches[0]) || empty($matches[0])) {
            return false;
        }

        return $matches;
    }

private function fetchVariableMatches ( $ value , $ regex ) { preg_match_all ( '/' . $ regex . '/' , $ value , $ matches ) ; if ( ! is_array ( $ matches ) || ! isset ( $ matches [ 0 ] ) || empty ( $ matches [ 0 ] ) ) { return false ; } return $ matches ; }

Fetches the variable matches in the string

@param string $value The string to fetch matches for
@param string $regex The variable type regex

@return array The matches


private function fetchVariable($variable_name, $type)
    {
        $this->checkVariableExists($variable_name, $type);

        if ($type === 'env') {
            return getenv($variable_name);
        } elseif ($type === 'replacement') {
            return $this->rstore->get($variable_name);
        }

        return $this->vstore->get($variable_name);
    }

private function fetchVariable ( $ variable_name , $ type ) { $ this -> checkVariableExists ( $ variable_name , $ type ) ; if ( $ type === 'env' ) { return getenv ( $ variable_name ) ; } elseif ( $ type === 'replacement' ) { return $ this -> rstore -> get ( $ variable_name ) ; } return $ this -> vstore -> get ( $ variable_name ) ; }

Fetches the variable from the stores

@param string $variable_name The variable to fetch
@param string $type          The variable type

@return string The fetches value for the variable


private function checkVariableExists($variable, $type)
    {
        if (($type === 'env'         && !getenv($variable)) ||
            ($type === 'replacement' && !$this->rstore->arrayKeyExists($variable)) ||
            ($type === 'variable'    && !$this->vstore->arrayKeyExists($variable))
        ) {
            throw new \InvalidArgumentException(
                sprintf('Variable has not been defined as a `%s`: %s', $variable, $type)
            );
        }

        return true;
    }

Checks to see if the variable exists

@param string $variable The variable to check
@param string $type     The variable type

@throws \InvalidArgumentException If the variable does not exist

@return bool Does the variable exist


public function doReplacements($value, $matches, $type)
    {
        $replacements = array();
        for ($i = 0; $i <= (count($matches[0]) - 1); $i++) {
            $replacement = $this->fetchVariable($matches[1][$i], $type);
            $replacements[$matches[0][$i]] = $replacement;
        }

        if (!empty($replacements)) {
            $value = strtr($value, $replacements);
        }

        return $value;
    }

public function doReplacements ( $ value , $ matches , $ type ) { $ replacements = array ( ) ; for ( $ i = 0 ; $ i <= ( count ( $ matches [ 0 ] ) - 1 ) ; $ i ++ ) { $ replacement = $ this -> fetchVariable ( $ matches [ 1 ] [ $ i ] , $ type ) ; $ replacements [ $ matches [ 0 ] [ $ i ] ] = $ replacement ; } if ( ! empty ( $ replacements ) ) { $ value = strtr ( $ value , $ replacements ) ; } return $ value ; }

Does the replacements in the string for the variable

@param string $value   The string to parse
@param array  $matches The matches
@param string $type    The variable type

@return string The parsed variable


protected static function export($dom = null) {
		if (!is_a($dom, 'DOMDocument')) {
			return false;
		}

		try {
			$svgs = $dom->getElementsByTagName('svg');
			if (!$svgs->length) {
				return false;
			}
			$svg = $svgs->item(0)->ownerDocument->saveXML($svgs->item(0), LIBXML_NOBLANKS);

			// Remove comments.
			$svg = static::strip_comments($svg);

			return $svg;
		} catch (\Throwable $e) {
			error_log($e->getMessage());
			return false;
		} catch (\Exception $e) {
			return false;
		}

		return false;
	}

protected
static
function
export
(
$
dom
=
)
{
if
(
!
is_a
(
$
dom
,
'DOMDocument'
)
)
{
return
false
;
}
try
{
$
svgs
=
$
dom
->
getElementsByTagName
(
'svg'
)
;
if
(
!
$
svgs
->
length
)
{
return
false
;
}
$
svg
=
$
svgs
->
item
(
0
)
->
ownerDocument
->
saveXML
(
$
svgs
->
item
(
0
)
,
LIBXML_NOBLANKS
)
;
// Remove comments.
$
svg
=
static
::
strip_comments
(
$
svg
)
;
return
$
svg
;
}
catch
(
\
Throwable
$
e
)
{
error_log
(
$
e
->
getMessage
(
)
)
;
return
false
;
}
catch
(
\
Exception
$
e
)
{
return
false
;
}
return
false
;
}

Export from a DOMDocument object.

@param DOMDocument $dom XML object.
@return string|bool Sanitized SVG code. False on failure.


protected static function remove_nodes($nodes) {
		if (!is_a($nodes, 'DOMNodeList')) {
			return false;
		}

		try {
			while ($nodes->length) {
				static::remove_node($nodes->item(0));
			}
			return true;
		} catch (\Throwable $e) {
			error_log($e->getMessage());
			return false;
		} catch (\Exception $e) {
			return false;
		}

		return false;
	}

protected static function remove_nodes ( $ nodes ) { if ( ! is_a ( $ nodes , 'DOMNodeList' ) ) { return false ; } try { while ( $ nodes -> length ) { static :: remove_node ( $ nodes -> item ( 0 ) ) ; } return true ; } catch ( \ Throwable $ e ) { error_log ( $ e -> getMessage ( ) ) ; return false ; } catch ( \ Exception $ e ) { return false ; } return false ; }

Remove nodes from a DOMNodeList

@param DOMNodeList $nodes Nodes.
@return bool True/False.


protected static function remove_node($node) {
		if (
			!is_a($node, 'DOMElement') &&
			!is_a($node, 'DOMNode')
		) {
			return false;
		}

		try {
			// @codingStandardsIgnoreStart
			$node->parentNode->removeChild($node);
			// @codingStandardsIgnoreEnd
			return true;
		} catch (\Throwable $e) {
			error_log($e->getMessage());
			return false;
		} catch (\Exception $e) {
			return false;
		}

		return false;
	}

protected
static
function
remove_node
(
$
node
)
{
if
(
!
is_a
(
$
node
,
'DOMElement'
)
&&
!
is_a
(
$
node
,
'DOMNode'
)
)
{
return
false
;
}
try
{
// @codingStandardsIgnoreStart
$
node
->
parentNode
->
removeChild
(
$
node
)
;
// @codingStandardsIgnoreEnd
return
true
;
}
catch
(
\
Throwable
$
e
)
{
error_log
(
$
e
->
getMessage
(
)
)
;
return
false
;
}
catch
(
\
Exception
$
e
)
{
return
false
;
}
return
false
;
}

Remove node from a DOMDocument

@param DOMElement $node Node.
@return bool True/False.


public function setPath($path, $check_writeable = false)
    {
        if (is_null($path)) {
            return;
        }

        if (!is_dir($path) || ($check_writeable && !is_writable($path))) {
            throw new \InvalidArgumentException(sprintf(
                "'%s' base path does not exist or is not writable",
                $path
            ));
        }

        $this->path = realpath($path);
        return $this;
    }

Set the Vars base path

@param string  $path            The  path to set
@param boolean $check_writeable Check whether dir is writeable

@throws \InvalidArgumentException If the path does not exist or is not writable

@return \M1\Vars\Vars


private function makePaths($file)
    {
        $file = realpath($file);

        $base_path = $this->provider->vars->getPath();

        $filesystem = new Filesystem();
        $abs_path = $filesystem->makePathRelative(
            $file,
            $base_path
        );

        $this->file = $file;
        $this->filename = rtrim($abs_path, "/");
    }

private function makePaths ( $ file ) { $ file = realpath ( $ file ) ; $ base_path = $ this -> provider -> vars -> getPath ( ) ; $ filesystem = new Filesystem ( ) ; $ abs_path = $ filesystem -> makePathRelative ( $ file , $ base_path ) ; $ this -> file = $ file ; $ this -> filename = rtrim ( $ abs_path , "/" ) ; }

Make the paths used for the filename variable

@param string $file The passed file


private function searchForResources($content = array(), $prefix = '')
    {
        $returned_content = array();

        foreach ($content as $ck => $cv) {
            $this->variables->vstore->setCurrentPrefix($prefix);
            $returned_content = $this->parseContent($ck, $cv, $returned_content, $prefix);
        }

        return $returned_content;
    }

private function searchForResources ( $ content = array ( ) , $ prefix = '' ) { $ returned_content = array ( ) ; foreach ( $ content as $ ck => $ cv ) { $ this -> variables -> vstore -> setCurrentPrefix ( $ prefix ) ; $ returned_content = $ this -> parseContent ( $ ck , $ cv , $ returned_content , $ prefix ) ; } return $ returned_content ; }

Search for imports in the files and does the replacement variables

@param mixed  $content The file content received from the loader
@param string $prefix  The array prefix for the entity

@return array Returns the parsed content


private function parseContent($key, $value, $returned_content, $prefix)
    {
        if ($key === 'imports' && !is_null($value) && !empty($value)) {
            $imported_resource = $this->useImports($value);

            if ($imported_resource) {
                $returned_content = array_replace_recursive($returned_content, $imported_resource);
            }
        } elseif (is_array($value)) {
            $returned_content[$key] = $this->searchForResources(
                $value,
                $this->variables->vstore->createPrefixName($prefix, $key)
            );
        } else {
            $value = $this->parseText($value);
            $this->variables->vstore->set($prefix.$key, $value);
            $returned_content[$key] = $value;
        }

        return $returned_content;
    }

private function parseContent ( $ key , $ value , $ returned_content , $ prefix ) { if ( $ key === 'imports' && ! is_null ( $ value ) && ! empty ( $ value ) ) { $ imported_resource = $ this -> useImports ( $ value ) ; if ( $ imported_resource ) { $ returned_content = array_replace_recursive ( $ returned_content , $ imported_resource ) ; } } elseif ( is_array ( $ value ) ) { $ returned_content [ $ key ] = $ this -> searchForResources ( $ value , $ this -> variables -> vstore -> createPrefixName ( $ prefix , $ key ) ) ; } else { $ value = $ this -> parseText ( $ value ) ; $ this -> variables -> vstore -> set ( $ prefix . $ key , $ value ) ; $ returned_content [ $ key ] = $ value ; } return $ returned_content ; }

Parses the contents inside the content array

@param mixed  $key              The key of the content array
@param mixed  $value            The value of the key
@param array  $returned_content The modified content array to return
@param string $prefix           The array prefix for the entity

@return array Returns the modified content array


private function useImports($imports)
    {
        $imported_resources = array();

        if ((is_array($imports) && $this->isAssoc($imports)) || is_string($imports)) {
            $imports = array($imports);
        }

        foreach ($imports as $import) {
            $imported_resources = $this->processImport($this->parseText($import), $imported_resources);
        }

        return $imported_resources;
    }

private function useImports ( $ imports ) { $ imported_resources = array ( ) ; if ( ( is_array ( $ imports ) && $ this -> isAssoc ( $ imports ) ) || is_string ( $ imports ) ) { $ imports = array ( $ imports ) ; } foreach ( $ imports as $ import ) { $ imported_resources = $ this -> processImport ( $ this -> parseText ( $ import ) , $ imported_resources ) ; } return $ imported_resources ; }

Use the import arrays to import resources

@param mixed $imports The resources wanting to be imported

@return array The parsed imported resources


private function import2Resource($import, array $imported_resources)
    {
        $resource = $this->createResource($import);

        if ($resource) {
            $imported_resources = $this->importResource($resource, $imported_resources);
        }

        return $imported_resources;
    }

private function import2Resource ( $ import , array $ imported_resources ) { $ resource = $ this -> createResource ( $ import ) ; if ( $ resource ) { $ imported_resources = $ this -> importResource ( $ resource , $ imported_resources ) ; } return $ imported_resources ; }

Creates the resource from the import then imports it

@param array|string $import The string|array to be converted to a resource
@param array $imported_resources The array of imported resources

@return array The imported resources


private function createResource($import)
    {
        if (is_array($import) && array_key_exists('resource', $import)) {
            $import_resource = $import;
            $import_resource['relative'] = $this->checkBooleanValue('relative', $import_resource);
            $import_resource['recursive'] = $this->checkBooleanValue('recursive', $import_resource);
        } elseif (is_string($import)) {
            $import_resource = array('resource' => $import, 'relative' => true, 'recursive' => true);
        }

        $import_resource = new ResourceProvider(
            $this->provider->vars,
            $this->createImportName($import_resource['resource']),
            $import_resource['relative'],
            $import_resource['recursive']
        );

        return $import_resource;
    }

private function createResource ( $ import ) { if ( is_array ( $ import ) && array_key_exists ( 'resource' , $ import ) ) { $ import_resource = $ import ; $ import_resource [ 'relative' ] = $ this -> checkBooleanValue ( 'relative' , $ import_resource ) ; $ import_resource [ 'recursive' ] = $ this -> checkBooleanValue ( 'recursive' , $ import_resource ) ; } elseif ( is_string ( $ import ) ) { $ import_resource = array ( 'resource' => $ import , 'relative' => true , 'recursive' => true ) ; } $ import_resource = new ResourceProvider ( $ this -> provider -> vars , $ this -> createImportName ( $ import_resource [ 'resource' ] ) , $ import_resource [ 'relative' ] , $ import_resource [ 'recursive' ] ) ; return $ import_resource ; }

Creates resource from the import

@param array|string $import The import to create a resource from

@return \M1\Vars\Resource\ResourceProvider The resource of the import


private function createImportName($resource)
    {
        $resource = $this->explodeResourceIfElse($resource);
        $resource_pieces = array();

        foreach ($resource as $r) {
            $parsed_r = $this->trimFlags($r);
            $parsed_r = sprintf('%s/%s', dirname($this->file), $parsed_r);
            $parsed_r = $this->replicateFlags($parsed_r, $r);

            $resource_pieces[] = $parsed_r;
        }

        return $this->implodeResourceIfElse($resource_pieces);
    }

private function createImportName ( $ resource ) { $ resource = $ this -> explodeResourceIfElse ( $ resource ) ; $ resource_pieces = array ( ) ; foreach ( $ resource as $ r ) { $ parsed_r = $ this -> trimFlags ( $ r ) ; $ parsed_r = sprintf ( '%s/%s' , dirname ( $ this -> file ) , $ parsed_r ) ; $ parsed_r = $ this -> replicateFlags ( $ parsed_r , $ r ) ; $ resource_pieces [ ] = $ parsed_r ; } return $ this -> implodeResourceIfElse ( $ resource_pieces ) ; }

Creates the correctly formatted resource name with paths

@param string $resource The resource to create the import name for

@return string The parsed resource


private function importResource(ResourceProvider $provider, $imported_resources)
    {
        $content = $provider->getContent();
        $parent_content = $provider->getParentContent();

        if (!empty($content)) {
            $imported_resources = array_replace_recursive($imported_resources, $content);
        }

        if (!empty($parent_content)) {
            $this->provider->addParentContent($parent_content);
        }

        return $imported_resources;
    }

private function importResource ( ResourceProvider $ provider , $ imported_resources ) { $ content = $ provider -> getContent ( ) ; $ parent_content = $ provider -> getParentContent ( ) ; if ( ! empty ( $ content ) ) { $ imported_resources = array_replace_recursive ( $ imported_resources , $ content ) ; } if ( ! empty ( $ parent_content ) ) { $ this -> provider -> addParentContent ( $ parent_content ) ; } return $ imported_resources ; }

Import resource into the imported resources and merge contents

@param ResourceProvider $provider The new imported resource
@param array            $imported_resources The imported resources

@return array The modified imported resources


public function checkBooleanValue($value, $import)
    {
        $default = false;

        if ($value === 'relative') {
            $default = true;
        }

        $value = (isset($import[$value])) ? $import[$value] : $default;

        return $this->getBooleanValue($value);
    }

public function checkBooleanValue ( $ value , $ import ) { $ default = false ; if ( $ value === 'relative' ) { $ default = true ; } $ value = ( isset ( $ import [ $ value ] ) ) ? $ import [ $ value ] : $ default ; return $ this -> getBooleanValue ( $ value ) ; }

Checks if the passed boolean value is true or false

@param string $value  The value to check
@param mixed  $import The passed import

@return bool Returns the value of the boolean


private function getBooleanValue($value)
    {
        $value = strtolower($value);

        if (!$value || $value === "false" || $value === "no") {
            return false;
        }

        return true;
    }

private function getBooleanValue ( $ value ) { $ value = strtolower ( $ value ) ; if ( ! $ value || $ value === "false" || $ value === "no" ) { return false ; } return true ; }

Gets the boolean value from the string

@param string $value  The value to check

@return bool Returns the value of the boolean


public static function get_aliases($ext='') {
		$ext = trim(strtolower($ext));
		$ext = ltrim($ext, '.');
		if (strlen($ext) && array_key_exists($ext, mime\aliases::$data)) {
			$match = mime\aliases::$data[$ext];
		} else {
			$match = false;
		}

		// Filter.
		return apply_filters('blobmimes_get_mime_aliases', $match, $ext);
	}

public
static
function
get_aliases
(
$
ext
=
''
)
{
$
ext
=
trim
(
strtolower
(
$
ext
)
)
;
$
ext
=
ltrim
(
$
ext
,
'.'
)
;
if
(
strlen
(
$
ext
)
&&
array_key_exists
(
$
ext
,
mime
\
aliases
::
$
data
)
)
{
$
match
=
mime
\
aliases
::
$
data
[
$
ext
]
;
}
else
{
$
match
=
false
;
}
// Filter.
return
apply_filters
(
'blobmimes_get_mime_aliases'
,
$
match
,
$
ext
)
;
}

Return MIME aliases for a particular file extension.

@see {https://www.iana.org/assignments/media-types}
@see {https://raw.githubusercontent.com/apache/httpd/trunk/docs/conf/mime.types}
@see {http://hg.nginx.org/nginx/raw-file/default/conf/mime.types}
@see {https://cgit.freedesktop.org/xdg/shared-mime-info/plain/freedesktop.org.xml.in}
@see {https://raw.githubusercontent.com/apache/tika/master/tika-core/src/main/resources/org/apache/tika/mime/tika-mimetypes.xml}
@see {https://github.com/Blobfolio/blob-mimes}

@param string $ext File extension.
@return array|bool MIME types or false.

Return MIME aliases for a particular file extension .


public static function update_filename_extension($filename, $ext) {
		$ext = strtolower($ext);
		$ext = rtrim($ext, '.');
		$ext = ltrim($ext, '.');

		$filename_parts = explode('.', $filename);

		// Remove the old extension.
		if (count($filename_parts) > 1) {
			array_pop($filename_parts);
		}

		// Add the new extension.
		if (strlen($ext)) {
			$filename_parts[] = $ext;
		}

		return implode('.', $filename_parts);
	}

public
static
function
update_filename_extension
(
$
filename
,
$
ext
)
{
$
ext
=
strtolower
(
$
ext
)
;
$
ext
=
rtrim
(
$
ext
,
'.'
)
;
$
ext
=
ltrim
(
$
ext
,
'.'
)
;
$
filename_parts
=
explode
(
'.'
,
$
filename
)
;
// Remove the old extension.
if
(
count
(
$
filename_parts
)
>
1
)
{
array_pop
(
$
filename_parts
)
;
}
// Add the new extension.
if
(
strlen
(
$
ext
)
)
{
$
filename_parts
[
]
=
$
ext
;
}
return
implode
(
'.'
,
$
filename_parts
)
;
}

Assign a new extension to a filename.

@param string $filename The original filename.
@param string $ext The new extension.
@return string The renamed file.


public static function check_alias($ext='', $mime='') {
		// Standardize inputs.
		$mime = strtolower(sanitize_mime_type($mime));
		$ext = trim(strtolower($ext));
		$ext = ltrim($ext, '.');

		// Can't continue if the extension is not in the database.
		if (false === ($mimes = static::get_aliases($ext))) {
			// Filter.
			return apply_filters('blobmimes_check_mime_alias', false, $ext, $mime);
		}

		// Before looking for matches, convert any generic CDFV2
		// types into an equally generic, but less variable type.
		if (0 === strpos($mime, 'application/cdfv2')) {
			$mime = 'application/vnd.ms-office';
		}

		// "Default" MIME might not need to trigger a failure.
		if ('application/octet-stream' === $mime) {
			// Filter.
			if (false === apply_filters('blobmimes_check_application_octet_stream', false)) {
				return apply_filters('blobmimes_check_mime_alias', true, $ext, $mime);
			}
		}
		// An empty file doesn't really have a type.
		elseif ('inode/x-empty' === $mime) {
			return apply_filters('blobmimes_check_mime_alias', true, $ext, $mime);
		}

		// Test for the literal MIME, but also certain generic
		// variations like x-subtype and vnd.subtype.
		$test = array($mime);

		$parts = explode('/', $mime);
		$subtype = count($parts) - 1;
		if ('x-' === substr($parts[$subtype], 0, 2)) {
			$parts[$subtype] = substr($parts[$subtype], 2);
		} else {
			$parts[$subtype] = 'x-' . $parts[$subtype];
		}
		$test[] = implode('/', $parts);

		$parts = explode('/', $mime);
		$subtype = count($parts) - 1;
		if ('vnd.' === substr($parts[$subtype], 0, 4)) {
			$parts[$subtype] = substr($parts[$subtype], 4);
		} else {
			$parts[$subtype] = 'vnd.' . $parts[$subtype];
		}
		$test[] = implode('/', $parts);

		// Overlap is success!
		$found = array_intersect($test, $mimes);
		$match = count($found) > 0;

		// Filter.
		return apply_filters('blobmimes_check_mime_alias', $match, $ext, $mime);
	}

Check extension and MIME pairing.

@see { https://github.com/php/php-src/blob/3ef069d26c7863b059325b9a0d26cac31c97fe4b/ext/fileinfo/libmagic/readcdf.c }

@param string $ext File extension.
@param string $mime MIME type.
@return bool True/false.


public static function check_allowed_aliases($alias, $mimes=null) {
		// Default MIMEs.
		if (empty($mimes)) {
			$mimes = get_allowed_mime_types();
		}

		$alias = strtolower(sanitize_mime_type($alias));

		$ext = $type = false;

		// Early bail opportunity.
		if (!$alias || !count($mimes)) {
			return false;
		}

		// Direct hit!
		if (false !== $extensions = array_search($alias, $mimes, true)) {
			$extensions = explode('|', $extensions);
			$ext = $extensions[0];
			$type = $alias;

			return compact('ext', 'type');
		}

		// Try all extensions.
		foreach ($mimes as $extensions=>$mime) {
			$extensions = explode('|', $extensions);
			foreach ($extensions as $extension) {
				if (static::check_alias($extension, $alias)) {
					$ext = $extension;
					$type = $mime;

					return compact('ext', 'type');
				}
			}
		}

		return false;
	}

public
static
function
check_allowed_aliases
(
$
alias
,
$
mimes
=
)
{
// Default MIMEs.
if
(
empty
(
$
mimes
)
)
{
$
mimes
=
get_allowed_mime_types
(
)
;
}
$
alias
=
strtolower
(
sanitize_mime_type
(
$
alias
)
)
;
$
ext
=
$
type
=
false
;
// Early bail opportunity.
if
(
!
$
alias
||
!
count
(
$
mimes
)
)
{
return
false
;
}
// Direct hit!
if
(
false
!==
$
extensions
=
array_search
(
$
alias
,
$
mimes
,
true
)
)
{
$
extensions
=
explode
(
'|'
,
$
extensions
)
;
$
ext
=
$
extensions
[
0
]
;
$
type
=
$
alias
;
return
compact
(
'ext'
,
'type'
)
;
}
// Try all extensions.
foreach
(
$
mimes
as
$
extensions
=>
$
mime
)
{
$
extensions
=
explode
(
'|'
,
$
extensions
)
;
foreach
(
$
extensions
as
$
extension
)
{
if
(
static
::
check_alias
(
$
extension
,
$
alias
)
)
{
$
ext
=
$
extension
;
$
type
=
$
mime
;
return
compact
(
'ext'
,
'type'
)
;
}
}
}
return
false
;
}

Check Allowed Aliases

This will cycle through each allowed ext/MIME pair to see if an
alias matches anything.

@param string $alias MIME alias.
@param array $mimes Allowed MIME types.
@return array|bool Array containing ext and type keys or false.


public function load($replacements)
    {
        if (is_array($replacements)) {
            $variables = $replacements;
        } elseif (is_file($replacements)) {
            $variables = $this->loadContent($replacements);
        } else {
            throw new \RuntimeException('Config replacements must be a array or a file');
        }

        $this->content = $variables;
    }

Creates the replacement variable content from a file or array

@param array $replacements The replacements

@throws \RuntimeException If variable data is not array or a file

@return  array The replacement variables


private function getSupportedFilesRecursively()
    {
        $dir_it = new \RecursiveDirectoryIterator($this->entity, \RecursiveDirectoryIterator::SKIP_DOTS);

        $files = new \RecursiveIteratorIterator(
            $dir_it,
            \RecursiveIteratorIterator::LEAVES_ONLY,
            \RecursiveIteratorIterator::CATCH_GET_CHILD
        );

        return $this->createRegexIterator($files);
    }

private function getSupportedFilesRecursively ( ) { $ dir_it = new \ RecursiveDirectoryIterator ( $ this -> entity , \ RecursiveDirectoryIterator :: SKIP_DOTS ) ; $ files = new \ RecursiveIteratorIterator ( $ dir_it , \ RecursiveIteratorIterator :: LEAVES_ONLY , \ RecursiveIteratorIterator :: CATCH_GET_CHILD ) ; return $ this -> createRegexIterator ( $ files ) ; }

Returns the supported files in the directory recursively

@return \RegexIterator The supported files in the directories


private function makeResources($paths)
    {
        if ($paths && !empty($paths)) {
            $resources = array();

            foreach ($paths as $path) {
                $resources[] = $path;
            }

            return $resources;
        }

        return false;
    }

private function makeResources ( $ paths ) { if ( $ paths && ! empty ( $ paths ) ) { $ resources = array ( ) ; foreach ( $ paths as $ path ) { $ resources [ ] = $ path ; } return $ resources ; } return false ; }

Makes usable resource paths from path strings

@param array $paths The path strings

@return array|bool  The usable resources if any, else false


public function checkCache()
    {
        if ($this->provide && $this->path && !$this->getAttempted()) {
            $file = sprintf('%s/vars/%s.php', $this->path, $this->name);
            $this->attempted = true;

            if (is_file($file) &&
                filemtime($file) >= (time() - $this->expire)) {
                $this->hit = true;
                return true;
            }
        }
        return false;
    }

public function checkCache ( ) { if ( $ this -> provide && $ this -> path && ! $ this -> getAttempted ( ) ) { $ file = sprintf ( '%s/vars/%s.php' , $ this -> path , $ this -> name ) ; $ this -> attempted = true ; if ( is_file ( $ file ) && filemtime ( $ file ) >= ( time ( ) - $ this -> expire ) ) { $ this -> hit = true ; return true ; } } return false ; }

Checks the cache to see if there is a valid cache available

@return bool Returns true if has the cached resource


public function makeCache(Vars $vars)
    {
        if ($this->provide) {
            $cache_folder = sprintf("%s/vars", $this->path);
            if (!file_exists($cache_folder)) {
                mkdir($cache_folder, 0777, true);
            }

            $cache_file = sprintf('%s/%s.php', $cache_folder, $this->name);
            file_put_contents($cache_file, serialize($vars));
        }
    }

public function makeCache ( Vars $ vars ) { if ( $ this -> provide ) { $ cache_folder = sprintf ( "%s/vars" , $ this -> path ) ; if ( ! file_exists ( $ cache_folder ) ) { mkdir ( $ cache_folder , 0777 , true ) ; } $ cache_file = sprintf ( '%s/%s.php' , $ cache_folder , $ this -> name ) ; file_put_contents ( $ cache_file , serialize ( $ vars ) ) ; } }

Transfer the contents of the parent Vars object into a file for cache

@param \M1\Vars\Vars $vars Parent vars object

@codeCoverageIgnore


public function setVersion($value)
    {
        if (!is_string($value) && !is_numeric($value)) {
            throw new \InvalidArgumentException(sprintf(
                    'Wrong value for assets version: %s - it must be string or numeric',
                    var_export($value, true)
                ));
        }

        if (!preg_match('/^' . static::$versionValueMask . '$/', $value)) {
            throw new \InvalidArgumentException(sprintf(
                    'Wrong value for assets version: %s - it must be empty or consist only of letters, numbers and the following characters: .-_',
                    var_export($value, true)
                ));
        }

        $this->fileContents = substr_replace(
                $this->fileContents,
                $value,
                $this->versionStartPos,
                strlen($this->versionValue)
            );
        $this->versionValue = $value;

        try {
            file_put_contents($this->filePath, $this->fileContents);
        } catch (\Exception $e) {
            throw new FileException(sprintf(
                    'Could not write to write "%s"; make sure it exists and you have enough permissions',
                    $this->filePath
                ));
        }
    }

Sets a new value for the assets version parameter

Assets version must consist only of letters, numbers and the following characters: .-_


protected function readFile()
    {

        $fileExtension = pathinfo($this->filePath, PATHINFO_EXTENSION);
        if ($fileExtension != 'yml' && $fileExtension != 'yaml')
            throw new InvalidConfigurationException(sprintf(
                    'Could not use "%s" - only yml files are supported by AssetsVersionManager',
                    var_export($this->versionValue, true)
                ));

        try {
            $this->fileContents = file_get_contents($this->filePath);
        } catch (\Exception $e) {
            throw new FileException(sprintf(
                    'Could not read file "%s"; make sure it exists and you have enough permissions',
                    $this->filePath
                ));
        }

        // Find a row with the parameter
        preg_match(
                '/(\s+' . $this->parameterName . '\:[^\S\n]*)(' . static::$versionValueMask . ')\s*(\n|#)/',
                $this->fileContents . "\n",
                $matches
            );

        if (array_key_exists(2, $matches)) {
            $this->versionValue = $matches[2];
            $this->versionStartPos = strpos($this->fileContents."\n", $matches[0]) + strlen($matches[1]);
            return;
        }

        throw new \Exception(sprintf(
                'Could not find definition of parameter "%s"; make sure it exists in "%s"',
                $this->parameterName,
                $this->filePath
            ));
    }

Reads and parses file with parameters

@throws InvalidConfigurationException
@throws FileException
@throws \Exception


public function send($request)
    {

        $this->request = $request;

        switch (strtoupper($request->getVerb())) {
            case 'GET':
                $this->response = $this->get($request);
                break;
            case 'PUT':
                $this->response = $this->put($request);
                break;
            case 'DELETE':
                $this->response = $this->delete($request);
                break;
            case 'POST':
                $this->response = $this->post($request);
                break;
            case 'HEAD':
                $this->response = $this->head($request);
                break;
            default:
                throw new \Exception($verb . ' is an invalid or unsupported REST verb.');
        }
        return $this->response;
    }

Send a REST request.

@param RESTRequest request A RESTRequest object
@return RESTResponse A RESTResponse object.


protected function setOptions(&$ch, $urlStr, $headers)
    {
        $url = $this->prefix . $urlStr; // Build full URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPAUTH, $this->auth);
        curl_setopt($ch, CURLOPT_USERPWD, $this->username . ':' . $this->password);

        curl_setopt($ch, CURLINFO_HEADER_OUT, true); // For debugging; TODO otherwise disable

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt($ch, CURLOPT_MAXREDIRS, 10); // Expose ?
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Expose ?

        $headerArr = array();
        foreach ($headers as $key => $val) {
            $headerArr[] = $key . ':' . $val;
        }
        // If headers exist, add them
        if (count($headerArr) > 0) {
          curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
        }

    }

Set cURL options common to all requests

@param resource ch The cURL handle.
@param string url The REST URL string (example: 'documents').
@param array headers Optional assoc array of headers.
@return array An array of cURL options.


public function get($request)
    {

        $ch = curl_init();

        $this->setOptions($ch, $request->getUrlStr(), $request->getHeaders());

        // Options specific to GET
        curl_setopt($ch, CURLOPT_HTTPGET, true);

        $this->logger->debug("GET");

        return $this->execute($ch);
    }

public
function
get
(
$
request
)
{
$
ch
=
curl_init
(
)
;
$
this
->
setOptions
(
$
ch
,
$
request
->
getUrlStr
(
)
,
$
request
->
getHeaders
(
)
)
;
// Options specific to GET
curl_setopt
(
$
ch
,
CURLOPT_HTTPGET
,
true
)
;
$
this
->
logger
->
debug
(
"GET"
)
;
return
$
this
->
execute
(
$
ch
)
;
}

Perform a GET request with cURL

@param RESTRequest request A REST request.
@return RESTResponse A REST response.


public function put($request)
    {
        $this->logger->debug("PUT ");

        $ch = curl_init();

        // Handle body
        $body = $request->getBody();
        $requestLength = strlen($body);
        $fh = fopen('php://temp', 'rw');

        fwrite($fh, $body);
        rewind($fh);

        $this->setOptions($ch, $request->getUrlStr(), $request->getHeaders());

        // Options specific to PUT
        curl_setopt($ch, CURLOPT_INFILE, $fh);
        curl_setopt($ch, CURLOPT_INFILESIZE, $requestLength);
        curl_setopt($ch, CURLOPT_PUT, true);

        $ret = $this->execute($ch);

        fclose($fh);

        return $ret;
    }

public
function
put
(
$
request
)
{
$
this
->
logger
->
debug
(
"PUT "
)
;
$
ch
=
curl_init
(
)
;
// Handle body
$
body
=
$
request
->
getBody
(
)
;
$
requestLength
=
strlen
(
$
body
)
;
$
fh
=
fopen
(
'php://temp'
,
'rw'
)
;
fwrite
(
$
fh
,
$
body
)
;
rewind
(
$
fh
)
;
$
this
->
setOptions
(
$
ch
,
$
request
->
getUrlStr
(
)
,
$
request
->
getHeaders
(
)
)
;
// Options specific to PUT
curl_setopt
(
$
ch
,
CURLOPT_INFILE
,
$
fh
)
;
curl_setopt
(
$
ch
,
CURLOPT_INFILESIZE
,
$
requestLength
)
;
curl_setopt
(
$
ch
,
CURLOPT_PUT
,
true
)
;
$
ret
=
$
this
->
execute
(
$
ch
)
;
fclose
(
$
fh
)
;
return
$
ret
;
}

Perform a PUT request with cURL

@param RESTRequest request A REST request.
@return RESTResponse A REST response.


public function delete($request)
    {
        $this->logger->debug("DELETE");

        $ch = curl_init();

        $this->setOptions($ch, $request->getUrlStr(), $request->getHeaders());

        // Options specific to DELETE
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');

        return $this->execute($ch);
    }

public
function
delete
(
$
request
)
{
$
this
->
logger
->
debug
(
"DELETE"
)
;
$
ch
=
curl_init
(
)
;
$
this
->
setOptions
(
$
ch
,
$
request
->
getUrlStr
(
)
,
$
request
->
getHeaders
(
)
)
;
// Options specific to DELETE
curl_setopt
(
$
ch
,
CURLOPT_CUSTOMREQUEST
,
'DELETE'
)
;
return
$
this
->
execute
(
$
ch
)
;
}

Perform a DELETE request with cURL

@param RESTRequest request A REST request.
@return RESTResponse A REST response.


public function post($request)
    {
        $ch = curl_init();

        $this->setOptions($ch, $request->getUrlStr(), $request->getHeaders());

        curl_setopt($ch, CURLOPT_POST, true);

        if ($request->isWWWFormURLEncodedPost()) {

            $this->logger->debug("POST www-form-urlencoded");
            $requestBody = http_build_query($request->getParams());

            curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);

        } else {

            $this->logger->debug("POST ");

            $requestLength = strlen($request->getBody());

            curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getBody());
        }

        return $this->execute($ch);
    }

public
function
post
(
$
request
)
{
$
ch
=
curl_init
(
)
;
$
this
->
setOptions
(
$
ch
,
$
request
->
getUrlStr
(
)
,
$
request
->
getHeaders
(
)
)
;
curl_setopt
(
$
ch
,
CURLOPT_POST
,
true
)
;
if
(
$
request
->
isWWWFormURLEncodedPost
(
)
)
{
$
this
->
logger
->
debug
(
"POST www-form-urlencoded"
)
;
$
requestBody
=
http_build_query
(
$
request
->
getParams
(
)
)
;
curl_setopt
(
$
ch
,
CURLOPT_POSTFIELDS
,
$
requestBody
)
;
}
else
{
$
this
->
logger
->
debug
(
"POST "
)
;
$
requestLength
=
strlen
(
$
request
->
getBody
(
)
)
;
curl_setopt
(
$
ch
,
CURLOPT_POSTFIELDS
,
$
request
->
getBody
(
)
)
;
}
return
$
this
->
execute
(
$
ch
)
;
}

Perform a POST request with cURL

@param RESTRequest request A REST request.
@return RESTResponse A REST response.


public function head($request)
    {
        $ch = curl_init();

        $this->setOptions($ch, $request->getUrlStr(), $request->getHeaders());

        // Options specific to HEAD
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD');

        $this->logger->debug("HEAD");

        return $this->execute($ch);
    }

public
function
head
(
$
request
)
{
$
ch
=
curl_init
(
)
;
$
this
->
setOptions
(
$
ch
,
$
request
->
getUrlStr
(
)
,
$
request
->
getHeaders
(
)
)
;
// Options specific to HEAD
curl_setopt
(
$
ch
,
CURLOPT_NOBODY
,
true
)
;
curl_setopt
(
$
ch
,
CURLOPT_HEADER
,
true
)
;
curl_setopt
(
$
ch
,
CURLOPT_CUSTOMREQUEST
,
'HEAD'
)
;
$
this
->
logger
->
debug
(
"HEAD"
)
;
return
$
this
->
execute
(
$
ch
)
;
}

Perform a HEAD request with cURL

@param RESTRequest request A REST request.
@return RESTResponse A REST response.


protected function execute(&$ch)
    {
        $response = new RESTResponse();
        $curl_exec = curl_exec($ch);
        // print('******* START $curl_exec (body) *******' . PHP_EOL);
        // print_r($curl_exec);
        // print('******* END   $curl_exec (body) *******' . PHP_EOL);
        $response->setBody($curl_exec);
        $curl_getinfo = curl_getinfo($ch);
        // print('******* START $curl_getinfo *******' . PHP_EOL);
        // print_r($curl_getinfo);
        // print('******* END   $curl_getinfo *******' . PHP_EOL);
        $response->setInfo($curl_getinfo);
        //print_r($response);
        $this->logger->debug("Response code: " . $response->getHttpCode());
        if ($response->getHttpCode() === 0) {
            curl_close ($ch);
            throw new \Exception(
              'No connection: ' . $response->getUrl(),
              $response->getHttpCode()
            );
        } else if ($response->getHttpCode() >= 400) {
            curl_close ($ch);
            $this->logger->debug("HTTP Error " . $response->getHttpCode());
            throw new \Exception(
              $response->getErrorMessage(),
              $response->getHttpCode()
            );
        } else {
            curl_close ($ch);
            // print('***** RESPONSE *****' . PHP_EOL);
            // print_r($response);
            return $response;
        }
    }

Execute a cURL request.

@todo Handle more response codes

@param resource ch The REST URL string (example: 'documents')
@return RESTResponse A RESTResponse object.


public function installExtension($resource, $params, $filename)
    {
        if (!isset($params["provider"])) {
            $params["provider"] = 'MLPHP';
        }

        $path = __DIR__ . DIRECTORY_SEPARATOR . "xquery" . DIRECTORY_SEPARATOR . $filename;

        $body = file_get_contents($path);
        $key = serialize(array($this->host, $this->port, $resource, $params, $body));
        if (array_key_exists($key, self::$extension_cache)) {
            return;
        }
        $this->logger->debug("installExtension");
        $method = 'put';
        $headers = array(
            'Content-type' => 'application/xquery'
        );
        $request = new RESTRequest($method, $resource, $params, $body, $headers);
        $this->put($request);
        self::$extension_cache[$key] = 1;
    }

public function installExtension ( $ resource , $ params , $ filename ) { if ( ! isset ( $ params [ "provider" ] ) ) { $ params [ "provider" ] = 'MLPHP' ; } $ path = __DIR__ . DIRECTORY_SEPARATOR . "xquery" . DIRECTORY_SEPARATOR . $ filename ; $ body = file_get_contents ( $ path ) ; $ key = serialize ( array ( $ this -> host , $ this -> port , $ resource , $ params , $ body ) ) ; if ( array_key_exists ( $ key , self :: $ extension_cache ) ) { return ; } $ this -> logger -> debug ( "installExtension" ) ; $ method = 'put' ; $ headers = array ( 'Content-type' => 'application/xquery' ) ; $ request = new RESTRequest ( $ method , $ resource , $ params , $ body , $ headers ) ; $ this -> put ( $ request ) ; self :: $ extension_cache [ $ key ] = 1 ; }

Install a REST API XQuery extension

@param $resource URL
@param $params resource parameters (adds in provider=MLPHP if provider not set)
@param $filename file system name of contents of the XQuery module.


public function addBuckets($buckets) {
        if (is_array($buckets)) {
            $this->buckets = array_merge($this->buckets, $buckets);
        } else {
            $this->buckets[] = $buckets;
        }
    }

public function addBuckets ( $ buckets ) { if ( is_array ( $ buckets ) ) { $ this -> buckets = array_merge ( $ this -> buckets , $ buckets ) ; } else { $ this -> buckets [ ] = $ buckets ; } }

Add bucket objects.

@param array|Bucket $buckets An array of bucket objects or a bucket object.


public function read($uri = null, $params = array())
    {
        $this->uri = (isset($uri)) ? (string)$uri : $this->uri;
        $params = array_merge(array('format' => 'xml'), $params);
        return parent::read($this->uri, $params);
    }

public function read ( $ uri = null , $ params = array ( ) ) { $ this -> uri = ( isset ( $ uri ) ) ? ( string ) $ uri : $ this -> uri ; $ params = array_merge ( array ( 'format' => 'xml' ) , $ params ) ; return parent :: read ( $ this -> uri , $ params ) ; }

Read an XML document from the database.

@param string $uri A document URI.
@param array $params Optional additional parameters to pass when reading.
@return string The document content.

Read an XML document from the database .


public function write($uri = null, $params = array())
    {
        if ($this->isValidXML($this->getContent())) {
            $this->uri = (isset($uri)) ? (string)$uri : $this->uri;
            $params = array_merge(array('format' => 'xml'), $params);
            return parent::write($this->uri, $params);
        } else {
            throw new \Exception('Attempting to write invalid XML content');
        }
    }

Write an XML document to the database.

@param string $uri A document URI.
@param array $params Optional additional parameters to pass when writing.
@return Document $this


public function isValidXML($xml)
    {
        $doc = new \DOMDocument();
        try {
            return $doc->loadXML($xml) === true;
        } catch(\Exception $e) {
            $this->logger->warning('XMLDocument::isValidXML() - ' . $e->getMessage());
            return false;
        }
    }

public
function
isValidXML
(
$
xml
)
{
$
doc
=
new
\
DOMDocument
(
)
;
try
{
return
$
doc
->
loadXML
(
$
xml
)
===
true
;
}
catch
(
\
Exception
$
e
)
{
$
this
->
logger
->
warning
(
'XMLDocument::isValidXML() - '
.
$
e
->
getMessage
(
)
)
;
return
false
;
}
}

Check if XML content is valid.

@return boolean true or false.


public function setUpRange($elem, $ns = '', $attr = '', $attrNs = '', $datatype = 'string')
    {
        $this->type = 'range';
        $this->elem = (string)$elem;
        $this->ns = (string)$ns;
        $this->attr = (string)$attr;
        $this->attrNs = (string)$attrNs;
        $this->datatype = (string)$datatype;
    }

public function setUpRange ( $ elem , $ ns = '' , $ attr = '' , $ attrNs = '' , $ datatype = 'string' ) { $ this -> type = 'range' ; $ this -> elem = ( string ) $ elem ; $ this -> ns = ( string ) $ ns ; $ this -> attr = ( string ) $ attr ; $ this -> attrNs = ( string ) $ attrNs ; $ this -> datatype = ( string ) $ datatype ; }

Set up range values.

@param string $elem Name of the element.
@param string $ns Element namespace.
@param string $attr Attribute name.
@param string $attrNs An attribute namespace.
@param string $datatype Constraint datatype.


public function getValuesAsElem($dom)
    {
        $valsElem = $dom->createElement('values');
        $valsElem->setAttribute('name', $this->name);

        switch ($this->type) {
            case 'range':
                $rangeElem = $dom->createElement('range');
                $rangeElem->setAttribute('type', $this->datatype);
                $elemElem = $dom->createElement('element');
                $elemElem->setAttribute('ns', $this->ns);
                $elemElem->setAttribute('name', $this->elem);
                $rangeElem->appendChild($elemElem);
                if($this->attr) {
                    $attrElem = $dom->createElement('attribute');
                    $attrElem->setAttribute('ns', $this->attrNs);
                    $attrElem->setAttribute('name', $this->attr);
                    $rangeElem->appendChild($attrElem);
                }
                $valsElem->appendChild($rangeElem);
                break;
                /* <values name='example'>
                    <range type='xs:integer'>
                        <element ns='' name='game'/>
                        <attribute ns='' name='runs'/>
                    </range>
                    <aggregate apply='sum'/>
                </values> */
            case 'uri':
                $uriElem = $dom->createElement('uri');
                $valsElem->appendChild($uriElem);

                break;
               /* <values name='uri'>
                      <uri/>
                      <values-option>limit=10</values-option>
                    </values> */
            case 'collection':
                $collectionElem = $dom->createElement('collection');
                $valsElem->appendChild($collectionElem);
                break;
               /* <values name="coll">
                      <collection/>
                      <values-option>limit=10</values-option>
                    </values> */
        }
        $this->addAggregate($dom, $valsElem);
        $this->addValuesOptions($dom, $valsElem);
        return $valsElem;
    }

Get the values setting as a DOMElement object.

@param DOMDocument $dom The DOMDocument object in which to create the element.

Get the values setting as a DOMElement object .


private function addValuesOptions($dom, $elem)
    {
        if (!empty($this->valuesOptions)) {
            foreach($this->valuesOptions as $opt) {
                $valuesElem = $dom->createElement('values-option');
                $valuesElem->nodeValue = $opt;
                $elem->appendChild($valuesElem);
            }
        }
        return $elem;
    }

private function addValuesOptions ( $ dom , $ elem ) { if ( ! empty ( $ this -> valuesOptions ) ) { foreach ( $ this -> valuesOptions as $ opt ) { $ valuesElem = $ dom -> createElement ( 'values-option' ) ; $ valuesElem -> nodeValue = $ opt ; $ elem -> appendChild ( $ valuesElem ) ; } } return $ elem ; }

Add values options to an element.

@param DOMDocument $dom A DOM document.
@param DOMElement $elem A DOM element.
@return DOMElement The updated element.


private function addAggregate($dom, $elem)
    {
        if(!empty($this->aggregate)) {
            $aggregateElem = $dom->createElement('aggregate');
            $aggregateElem->setAttribute('apply', $this->aggregate);
            $elem->appendChild($aggregateElem);
        }
        return $elem;
    }

private function addAggregate ( $ dom , $ elem ) { if ( ! empty ( $ this -> aggregate ) ) { $ aggregateElem = $ dom -> createElement ( 'aggregate' ) ; $ aggregateElem -> setAttribute ( 'apply' , $ this -> aggregate ) ; $ elem -> appendChild ( $ aggregateElem ) ; } return $ elem ; }

Add aggregate setting to an element.

@param DOMDocument $dom A DOM document.
@param DOMElement $elem A DOM element.
@return DOMElement The updated element.


public function getParams()
    {
        $params = array(
            'start' => $this->start, 'pageLength' => $this->pageLength,
            'view' => $this->view, 'format' => $this->format
        );
        if(!empty($this->options)) {
            $params['options'] = $this->options;
        }
        if(!empty($this->collection)) {
            $params['collection'] = $this->collection;
        }
        if(!empty($this->directory)) {
            $params['directory'] = $this->directory;
        }
        return $params;
    }

public function getParams ( ) { $ params = array ( 'start' => $ this -> start , 'pageLength' => $ this -> pageLength , 'view' => $ this -> view , 'format' => $ this -> format ) ; if ( ! empty ( $ this -> options ) ) { $ params [ 'options' ] = $ this -> options ; } if ( ! empty ( $ this -> collection ) ) { $ params [ 'collection' ] = $ this -> collection ; } if ( ! empty ( $ this -> directory ) ) { $ params [ 'directory' ] = $ this -> directory ; } return $ params ; }

Get the common search parameters as an associated array.

@return array An associated array of name/value pairs.

Get the common search parameters as an associated array .


public function retrieve($query, $params = array(), $structured = false)
    {
        $this->query = (string)$query;
        $params = array_merge(array(($structured ? 'structuredQuery' : 'q') =>
            $this->query), $this->getParams(), $params);
        $request = new RESTRequest('GET', 'search', $params);

        try {
            $response = $this->client->send($request);
            //print_r($response);
            $results = new SearchResults($response->getBody());
            return $results;
        } catch(Exception $e) {
            echo $e->getMessage() . ' in ' . $e->getFile() .
                ' on line ' . $e->getLine() . PHP_EOL;
        }
    }

public
function
retrieve
(
$
query
,
$
params
=
array
(
)
,
$
structured
=
false
)
{
$
this
->
query
=
(
string
)
$
query
;
$
params
=
array_merge
(
array
(
(
$
structured
'structuredQuery'
:
'q'
)
=>
$
this
->
query
)
,
$
this
->
getParams
(
)
,
$
params
)
;
$
request
=
new
RESTRequest
(
'GET'
,
'search'
,
$
params
)
;
try
{
$
response
=
$
this
->
client
->
send
(
$
request
)
;
//print_r($response);
$
results
=
new
SearchResults
(
$
response
->
getBody
(
)
)
;
return
$
results
;
}
catch
(
Exception
$
e
)
{
echo
$
e
->
getMessage
(
)
.
' in '
.
$
e
->
getFile
(
)
.
' on line '
.
$
e
->
getLine
(
)
.
PHP_EOL
;
}
}

Retrieve the search results using the REST client.

@param string $query The search query.
@param array $params
@param bool $structured defaults to false
@return SearchResults A search results object.

Retrieve the search results using the REST client .


public function retrieveKeyValue($key, $value, $params = array())
    {
        // /v1/keyvalue is deprecated, use /v1/search with structured
        $this->key = (string)$key;
        $this->value = (string)$value;
        $query = '<query xmlns="http://marklogic.com/appservices/search">
                    <container-query>
                      <json-property name="' . $this->key . '" ns="" />
                      <term-query>
                        <text>' . $this->value . '</text>
                      </term-query>
                    </container-query>
                  </query>';

        try {
            $params = array_merge(
                array('structuredQuery' => $query),
                $this->getParams(), $params
            );
            $request = new RESTRequest('GET', 'search', $params);
            $response = $this->client->send($request);
            $results = new SearchResults($response->getBody());
            return $results;
        } catch(Exception $e) {
            echo $e->getMessage() . ' in ' . $e->getFile() .
            ' on line ' . $e->getLine() . PHP_EOL;
        }
    }

'" ns="" />
                      <term-query>
                        <text>'

Retrieve the key-value search results for JSON content using the
REST client.

@param string $key The key (property name) in JSON content.
@param string $value The value (property value) in JSON content.
@return SearchResults A search results object.

Retrieve the key - value search results for JSON content using the REST client .


public function retrieveKeyValueElement(
        $element, $attribute, $value, $params = array()
    )
    {
        $this->element = (string)$element;
        $this->attribute = (string)$attribute;
        $this->value = (string)$value;
        // /v1/keyvalue is deprecated, use /v1/search with structured
        // $query = '<query xmlns="http://marklogic.com/appservices/search">
        //             <container-query>
        //               <element name="' . $this->element . '" ns="" />';
        // $query .= $this->attribute ?
        //     '<attribute name=' . $this->attribute . ' ns="" />' :
        //     '';
        // $query .= '<term-query>
        //                 <text>' . $this->value . '</text>
        //               </term-query>
        //             </container-query>
        //           </query>';

        try {
            // Only include attribute in final array if it is set
            $array_attr = (!empty($attribute)) ?
                array('attribute' => $this->attribute) : array();
            $params = array_merge(
                array('element' => $this->element, 'value' => $this->value),
                $array_attr, $this->getParams(), $params);
            $request = new RESTRequest('GET', 'keyvalue', $params);

            $params = array_merge(
                array('element' => $this->element, 'value' => $this->value),
                $array_attr, $this->getParams(), $params);
            // $params = array_merge(
            //     array('structuredQuery' => $query),
            //     $this->getParams(), $params
            // );
            $request = new RESTRequest('GET', 'keyvalue', $params);
            $response = $this->client->send($request);
            $results = new SearchResults($response->getBody());
            return $results;
        } catch(Exception $e) {
            echo $e->getMessage() . ' in ' . $e->getFile() .
            ' on line ' . $e->getLine() . PHP_EOL;
        }
    }

//                 <text>' . $this->value . '</text>

//     array('structuredQuery' => $query),

Retrieve the key-value search results, where the key is an element
name, for XML content using the REST client.

@param string $element The element name.
@param string $attribute The attribute for the element, to search for
attribute content.
@param string $value The value for that element (or attribute).
@return SearchResults A search results object.

Retrieve the key - value search results where the key is an element name for XML content using the REST client .


public function highlight(
        $content, $contentType, $class, $query,
        $params = array(), $structured = false
    )
    {
        // Install the API extension
        $resource = "resources/highlight";
        $this->client->installExtension("config/" . $resource, array(
            'method' => 'post',
            'post:q?' => 'string',
            'post:class' => 'string',
            'post:structuredQuery?' => 'string',
            'post:c' => 'string',
            'post:ct' => 'string',
            'post:provider?' => 'string'
        ), "highlight.xqy");

        // Use it
        $this->query = (string)$query;
        $params = array_merge(array(
            ($structured ? 'structuredQuery' : 'q') => $this->query,
            'c' => $content,
            'ct' => $contentType,
            'class' => $class
        ), $this->getParams(), $params);

        $request = new RESTRequest('POST', $resource, $params, "", array(
            'Content-type' => 'application/x-www-form-urlencoded'
        ));

        try {
            $response = $this->client->send($request);
            //print_r($response);
            $results = $response->getBody();
            if ($contentType === "text/plain") {
                return $results;
            } else {
                // Strip off XML decl
                return substr( $results, strpos($results, "\n")+1 );
            }
        } catch(Exception $e) {
            echo $e->getMessage() . ' in ' . $e->getFile() .
            ' on line ' . $e->getLine() . PHP_EOL;
        }
    }

public
function
highlight
(
$
content
,
$
contentType
,
$
class
,
$
query
,
$
params
=
array
(
)
,
$
structured
=
false
)
{
// Install the API extension
$
resource
=
"resources/highlight"
;
$
this
->
client
->
installExtension
(
"config/"
.
$
resource
,
array
(
'method'
=>
'post'
,
'post:q?'
=>
'string'
,
'post:class'
=>
'string'
,
'post:structuredQuery?'
=>
'string'
,
'post:c'
=>
'string'
,
'post:ct'
=>
'string'
,
'post:provider?'
=>
'string'
)
,
"highlight.xqy"
)
;
// Use it
$
this
->
query
=
(
string
)
$
query
;
$
params
=
array_merge
(
array
(
(
$
structured
'structuredQuery'
:
'q'
)
=>
$
this
->
query
,
'c'
=>
$
content
,
'ct'
=>
$
contentType
,
'class'
=>
$
class
)
,
$
this
->
getParams
(
)
,
$
params
)
;
$
request
=
new
RESTRequest
(
'POST'
,
$
resource
,
$
params
,
""
,
array
(
'Content-type'
=>
'application/x-www-form-urlencoded'
)
)
;
try
{
$
response
=
$
this
->
client
->
send
(
$
request
)
;
//print_r($response);
$
results
=
$
response
->
getBody
(
)
;
if
(
$
contentType
===
"text/plain"
)
{
return
$
results
;
}
else
{
// Strip off XML decl
return
substr
(
$
results
,
strpos
(
$
results
,
"\n"
)
+
1
)
;
}
}
catch
(
Exception
$
e
)
{
echo
$
e
->
getMessage
(
)
.
' in '
.
$
e
->
getFile
(
)
.
' on line '
.
$
e
->
getLine
(
)
.
PHP_EOL
;
}
}

Highlight hits in the given content based on the given query

Implemented via a MarkLogic REST API resource extension.

@param string $content
@param string $contentType
- describes content to be highlighted
- support for application/xml and text'plain
@param string $query The search query.
@param array $params
@param bool $structured defaults to false (only false is
supported today)
@return string hit-highlighted content


public function getClient()
    {
        return new RESTClient(
            $this->config['host'],
            $this->config['port'],
            $this->config['path'],
            $this->config['version'],
            $this->config['username'],
            $this->config['password'],
            $this->config['auth'],
            $this->config['logger']
        );
    }

public function getClient ( ) { return new RESTClient ( $ this -> config [ 'host' ] , $ this -> config [ 'port' ] , $ this -> config [ 'path' ] , $ this -> config [ 'version' ] , $ this -> config [ 'username' ] , $ this -> config [ 'password' ] , $ this -> config [ 'auth' ] , $ this -> config [ 'logger' ] ) ; }

Return a REST client based on current configuration.

@return RESTClient

Return a REST client based on current configuration .


public function getManageClient()
    {
        return new RESTClient(
            $this->config['host'],
            $this->config['managePort'],
            $this->config['managePath'],
            $this->config['manageVersion'],
            $this->config['username'],
            $this->config['password'],
            $this->config['auth'],
            $this->config['logger']
        );
    }

public function getManageClient ( ) { return new RESTClient ( $ this -> config [ 'host' ] , $ this -> config [ 'managePort' ] , $ this -> config [ 'managePath' ] , $ this -> config [ 'manageVersion' ] , $ this -> config [ 'username' ] , $ this -> config [ 'password' ] , $ this -> config [ 'auth' ] , $ this -> config [ 'logger' ] ) ; }

Return a REST client to the management API.

@return RESTClient

Return a REST client to the management API .


public function getAdminClient()
    {
        return new RESTClient(
            $this->config['host'],
            $this->config['adminPort'],
            $this->config['adminPath'],
            $this->config['adminVersion'],
            $this->config['username'],
            $this->config['password'],
            $this->config['auth'],
            $this->config['logger']
        );
    }

public function getAdminClient ( ) { return new RESTClient ( $ this -> config [ 'host' ] , $ this -> config [ 'adminPort' ] , $ this -> config [ 'adminPath' ] , $ this -> config [ 'adminVersion' ] , $ this -> config [ 'username' ] , $ this -> config [ 'password' ] , $ this -> config [ 'auth' ] , $ this -> config [ 'logger' ] ) ; }

Return a REST client to the admin API.

@return RESTClient


public function getAPI()
    {
        return new RESTAPI(
            $this->config['api'],
            $this->config['host'],
            $this->config['db'],
            $this->config['port'],
            $this->config['username'],
            $this->config['password']
        );
    }

public function getAPI ( ) { return new RESTAPI ( $ this -> config [ 'api' ] , $ this -> config [ 'host' ] , $ this -> config [ 'db' ] , $ this -> config [ 'port' ] , $ this -> config [ 'username' ] , $ this -> config [ 'password' ] ) ; }

Create and return a REST API based on current configuration.

@return RESTAPI

Create and return a REST API based on current configuration .


public function getDatabase($name = null)
    {
        $name = $name ? $name : $this->config['db'];
        return new Database(
            $this->getManageClient(),
            $name
        );
    }

public function getDatabase ( $ name = null ) { $ name = $ name ? $ name : $ this -> config [ 'db' ] ; return new Database ( $ this -> getManageClient ( ) , $ name ) ; }

Return a Database object.

@return Database


public function getOptions($name = null)
    {
        $name = $name ? $name : $this->config['options'];
        return new Options(
            $this->getClient(),
            $name
        );
    }

public function getOptions ( $ name = null ) { $ name = $ name ? $ name : $ this -> config [ 'options' ] ; return new Options ( $ this -> getClient ( ) , $ name ) ; }

Return an Options object.

@return Options


public static function autoload($className)
    {
        $thisClass = str_replace(__NAMESPACE__ . '\\', '', __CLASS__);

        $baseDir = __DIR__;

        if (substr($baseDir, -strlen($thisClass)) === $thisClass) {
            $baseDir = substr($baseDir, 0, -strlen($thisClass));
        }

        $className = ltrim($className, '\\');
           // echo "class " . $className;
           // echo '
';
        $fileName  = (dirname($baseDir)) . DIRECTORY_SEPARATOR;
                // echo "file " . $fileName;
                // echo '
';
        if ($lastNsPos = strripos($className, '\\')) {
            $namespace = substr($className, 0, $lastNsPos);
               // echo "ns " . $namespace;
               // echo '
';
            $className = substr($className, $lastNsPos + 1);
               // echo "class " . $className;
               // echo '
';
            $fileName .= str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
               // echo "file " . $fileName;
               // echo '
';
        }
        $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

           // echo "FILE: " . $fileName;

        if (file_exists($fileName)) {
            require $fileName;
        }
    }

public
static
function
autoload
(
$
className
)
{
$
thisClass
=
str_replace
(
__NAMESPACE__
.
'\\'
,
''
,
__CLASS__
)
;
$
baseDir
=
__DIR__
;
if
(
substr
(
$
baseDir
,
strlen
(
$
thisClass
)
)
===
$
thisClass
)
{
$
baseDir
=
substr
(
$
baseDir
,
0
,
strlen
(
$
thisClass
)
)
;
}
$
className
=
ltrim
(
$
className
,
'\\'
)
;
// echo "class " . $className;
// echo '
';
$
fileName
=
(
dirname
(
$
baseDir
)
)
.
DIRECTORY_SEPARATOR
;
// echo "file " . $fileName;
// echo '
';
if
(
$
lastNsPos
=
strripos
(
$
className
,
'\\'
)
)
{
$
namespace
=
substr
(
$
className
,
0
,
$
lastNsPos
)
;
// echo "ns " . $namespace;
// echo '
';
$
className
=
substr
(
$
className
,
$
lastNsPos
+
1
)
;
// echo "class " . $className;
// echo '
';
$
fileName
.=
str_replace
(
'\\'
,
DIRECTORY_SEPARATOR
,
$
namespace
)
.
DIRECTORY_SEPARATOR
;
// echo "file " . $fileName;
// echo '
';
}
$
fileName
.=
str_replace
(
'_'
,
DIRECTORY_SEPARATOR
,
$
className
)
.
'.php'
;
// echo "FILE: " . $fileName;
if
(
file_exists
(
$
fileName
)
)
{
require
$
fileName
;
}
}

PSR-0 autoloader.

Do NOT use if you are using Composer to autoload dependencies.

@todo Delete this if we are requiring Composer for MLPHP.

@param $className