public static function load($classes, $cacheDir, $name, $autoReload, $adaptive = false, $extension = '.php')
    {
        // each $name can only be loaded once per PHP process
        if (isset(self::$loaded[$name])) {
            return;
        }

        self::$loaded[$name] = true;

        if ($adaptive) {
            $declared = array_merge(get_declared_classes(), get_declared_interfaces(), get_declared_traits());

            // don't include already declared classes
            $classes = array_diff($classes, $declared);

            // the cache is different depending on which classes are already declared
            $name = $name.'-'.substr(hash('sha256', implode('|', $classes)), 0, 5);
        }

        $classes = array_unique($classes);

        // cache the core classes
        if (!is_dir($cacheDir) && !@mkdir($cacheDir, 0777, true) && !is_dir($cacheDir)) {
            throw new \RuntimeException(sprintf('Class Collection Loader was not able to create directory "%s"', $cacheDir));
        }
        $cacheDir = rtrim(realpath($cacheDir) ?: $cacheDir, '/'.DIRECTORY_SEPARATOR);
        $cache = $cacheDir.'/'.$name.$extension;

        // auto-reload
        $reload = false;
        if ($autoReload) {
            $metadata = $cache.'.meta';
            if (!is_file($metadata) || !is_file($cache)) {
                $reload = true;
            } else {
                $time = filemtime($cache);
                $meta = unserialize(file_get_contents($metadata));

                sort($meta[1]);
                sort($classes);

                if ($meta[1] != $classes) {
                    $reload = true;
                } else {
                    foreach ($meta[0] as $resource) {
                        if (!is_file($resource) || filemtime($resource) > $time) {
                            $reload = true;

                            break;
                        }
                    }
                }
            }
        }

        if (!$reload && file_exists($cache)) {
            require_once $cache;

            return;
        }
        if (!$adaptive) {
            $declared = array_merge(get_declared_classes(), get_declared_interfaces(), get_declared_traits());
        }

        $files = self::inline($classes, $cache, $declared);

        if ($autoReload) {
            // save the resources
            self::writeCacheFile($metadata, serialize(array(array_values($files), $classes)));
        }
    }

Loads a list of classes and caches them in one big file.

@param array  $classes    An array of classes to load
@param string $cacheDir   A cache directory
@param string $name       The cache name prefix
@param bool   $autoReload Whether to flush the cache when the cache is stale or not
@param bool   $adaptive   Whether to remove already declared classes or not
@param string $extension  File extension of the resulting file

@throws \InvalidArgumentException When class can't be loaded

Loads a list of classes and caches them in one big file .


public static function fixNamespaceDeclarations($source)
    {
        if (!function_exists('token_get_all') || !self::$useTokenizer) {
            if (preg_match('/(^|\s)namespace(.*?)\s*;/', $source)) {
                $source = preg_replace('/(^|\s)namespace(.*?)\s*;/', "$1namespace$2\n{", $source)."}\n";
            }

            return $source;
        }

        $rawChunk = '';
        $output = '';
        $inNamespace = false;
        $tokens = token_get_all($source);

        for ($i = 0; isset($tokens[$i]); ++$i) {
            $token = $tokens[$i];
            if (!isset($token[1]) || 'b"' === $token) {
                $rawChunk .= $token;
            } elseif (in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
                // strip comments
                continue;
            } elseif (T_NAMESPACE === $token[0]) {
                if ($inNamespace) {
                    $rawChunk .= "}\n";
                }
                $rawChunk .= $token[1];

                // namespace name and whitespaces
                while (isset($tokens[++$i][1]) && in_array($tokens[$i][0], array(T_WHITESPACE, T_NS_SEPARATOR, T_STRING))) {
                    $rawChunk .= $tokens[$i][1];
                }
                if ('{' === $tokens[$i]) {
                    $inNamespace = false;
                    --$i;
                } else {
                    $rawChunk = rtrim($rawChunk)."\n{";
                    $inNamespace = true;
                }
            } elseif (T_START_HEREDOC === $token[0]) {
                $output .= self::compressCode($rawChunk).$token[1];
                do {
                    $token = $tokens[++$i];
                    $output .= isset($token[1]) && 'b"' !== $token ? $token[1] : $token;
                } while (T_END_HEREDOC !== $token[0]);
                $output .= "\n";
                $rawChunk = '';
            } elseif (T_CONSTANT_ENCAPSED_STRING === $token[0]) {
                $output .= self::compressCode($rawChunk).$token[1];
                $rawChunk = '';
            } else {
                $rawChunk .= $token[1];
            }
        }

        if ($inNamespace) {
            $rawChunk .= "}\n";
        }

        $output .= self::compressCode($rawChunk);

        if (\PHP_VERSION_ID >= 70000) {
            // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098
            unset($tokens, $rawChunk);
            gc_mem_caches();
        }

        return $output;
    }

Adds brackets around each namespace if it's not already the case.

@param string $source Namespace string

@return string Namespaces with brackets

Adds brackets around each namespace if it s not already the case .


private static function writeCacheFile($file, $content)
    {
        $dir = dirname($file);
        if (!is_writable($dir)) {
            throw new \RuntimeException(sprintf('Cache directory "%s" is not writable.', $dir));
        }

        $tmpFile = tempnam($dir, basename($file));

        if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $file)) {
            @chmod($file, 0666 & ~umask());

            return;
        }

        throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $file));
    }

private
static
function
writeCacheFile
(
$
file
,
$
content
)
{
$
dir
=
dirname
(
$
file
)
;
if
(
!
is_writable
(
$
dir
)
)
{
throw
new
\
RuntimeException
(
sprintf
(
'Cache directory "%s" is not writable.'
,
$
dir
)
)
;
}
$
tmpFile
=
tempnam
(
$
dir
,
basename
(
$
file
)
)
;
if
(
false
!==
@
file_put_contents
(
$
tmpFile
,
$
content
)
&&
@
rename
(
$
tmpFile
,
$
file
)
)
{
@
chmod
(
$
file
,
0666
&
~
umask
(
)
)
;
return
;
}
throw
new
\
RuntimeException
(
sprintf
(
'Failed to write cache file "%s".'
,
$
file
)
)
;
}

Writes a cache file.

@param string $file    Filename
@param string $content Temporary file content

@throws \RuntimeException when a cache file cannot be written


private static function getOrderedClasses(array $classes)
    {
        $map = array();
        self::$seen = array();
        foreach ($classes as $class) {
            try {
                $reflectionClass = new \ReflectionClass($class);
            } catch (\ReflectionException $e) {
                throw new \InvalidArgumentException(sprintf('Unable to load class "%s"', $class));
            }

            $map = array_merge($map, self::getClassHierarchy($reflectionClass));
        }

        return $map;
    }

private
static
function
getOrderedClasses
(
array
$
classes
)
{
$
map
=
array
(
)
;
self
::
$
seen
=
array
(
)
;
foreach
(
$
classes
as
$
class
)
{
try
{
$
reflectionClass
=
new
\
ReflectionClass
(
$
class
)
;
}
catch
(
\
ReflectionException
$
e
)
{
throw
new
\
InvalidArgumentException
(
sprintf
(
'Unable to load class "%s"'
,
$
class
)
)
;
}
$
map
=
array_merge
(
$
map
,
self
::
getClassHierarchy
(
$
reflectionClass
)
)
;
}
return
$
map
;
}

Gets an ordered array of passed classes including all their dependencies.

@param array $classes

@return \ReflectionClass[] An array of sorted \ReflectionClass instances (dependencies added if needed)

@throws \InvalidArgumentException When a class can't be loaded

Gets an ordered array of passed classes including all their dependencies .


public function addPrefixes(array $prefixes)
    {
        foreach ($prefixes as $prefix => $path) {
            $this->addPrefix($prefix, $path);
        }
    }

public function addPrefixes ( array $ prefixes ) { foreach ( $ prefixes as $ prefix => $ path ) { $ this -> addPrefix ( $ prefix , $ path ) ; } }

Adds prefixes.

@param array $prefixes Prefixes to add


public function addPrefix($prefix, $paths)
    {
        if (!$prefix) {
            foreach ((array) $paths as $path) {
                $this->fallbackDirs[] = $path;
            }

            return;
        }
        if (isset($this->prefixes[$prefix])) {
            if (is_array($paths)) {
                $this->prefixes[$prefix] = array_unique(array_merge(
                    $this->prefixes[$prefix],
                    $paths
                ));
            } elseif (!in_array($paths, $this->prefixes[$prefix])) {
                $this->prefixes[$prefix][] = $paths;
            }
        } else {
            $this->prefixes[$prefix] = array_unique((array) $paths);
        }
    }

public function addPrefix ( $ prefix , $ paths ) { if ( ! $ prefix ) { foreach ( ( array ) $ paths as $ path ) { $ this -> fallbackDirs [ ] = $ path ; } return ; } if ( isset ( $ this -> prefixes [ $ prefix ] ) ) { if ( is_array ( $ paths ) ) { $ this -> prefixes [ $ prefix ] = array_unique ( array_merge ( $ this -> prefixes [ $ prefix ] , $ paths ) ) ; } elseif ( ! in_array ( $ paths , $ this -> prefixes [ $ prefix ] ) ) { $ this -> prefixes [ $ prefix ] [ ] = $ paths ; } } else { $ this -> prefixes [ $ prefix ] = array_unique ( ( array ) $ paths ) ; } }

Registers a set of classes.

@param string       $prefix The classes prefix
@param array|string $paths  The location(s) of the classes


public function findFile($class)
    {
        if (xcache_isset($this->prefix.$class)) {
            $file = xcache_get($this->prefix.$class);
        } else {
            $file = $this->decorated->findFile($class) ?: null;
            xcache_set($this->prefix.$class, $file);
        }

        return $file;
    }

public function findFile ( $ class ) { if ( xcache_isset ( $ this -> prefix . $ class ) ) { $ file = xcache_get ( $ this -> prefix . $ class ) ; } else { $ file = $ this -> decorated -> findFile ( $ class ) ? : null ; xcache_set ( $ this -> prefix . $ class , $ file ) ; } return $ file ; }

Finds a file by class name while caching lookups to Xcache.

@param string $class A class name to resolve to file

@return string|null

Finds a file by class name while caching lookups to Xcache .


public function parse($text)
	{
		$this->prepare();

		if (ltrim($text) === '') {
			return '';
		}

		$text = str_replace(["\r\n", "\n\r", "\r"], "\n", $text);

		$this->prepareMarkers($text);

		$absy = $this->parseBlocks(explode("\n", $text));
		$markup = $this->renderAbsy($absy);

		$this->cleanup();
		return $markup;
	}

public function parse ( $ text ) { $ this -> prepare ( ) ; if ( ltrim ( $ text ) === '' ) { return '' ; } $ text = str_replace ( [ "\r\n" , "\n\r" , "\r" ] , "\n" , $ text ) ; $ this -> prepareMarkers ( $ text ) ; $ absy = $ this -> parseBlocks ( explode ( "\n" , $ text ) ) ; $ markup = $ this -> renderAbsy ( $ absy ) ; $ this -> cleanup ( ) ; return $ markup ; }

Parses the given text considering the full language.

This includes parsing block elements as well as inline elements.

@param string $text the text to parse
@return string parsed markup

Parses the given text considering the full language .


protected function detectLineType($lines, $current)
	{
		$line = $lines[$current];
		$blockTypes = $this->blockTypes();
		foreach($blockTypes as $blockType) {
			if ($this->{'identify' . $blockType}($line, $lines, $current)) {
				return $blockType;
			}
		}
		// consider the line a normal paragraph if no other block type matches
		return 'paragraph';
	}

Given a set of lines and an index of a current line it uses the registed block types to
detect the type of this line.
@param array $lines
@param integer $current
@return string name of the block type in lower case

Given a set of lines and an index of a current line it uses the registed block types to detect the type of this line .


protected function parseBlock($lines, $current)
	{
		// identify block type for this line
		$blockType = $this->detectLineType($lines, $current);

		// call consume method for the detected block type to consume further lines
		return $this->{'consume' . $blockType}($lines, $current);
	}

Parses the block at current line by identifying the block type and parsing the content
@param $lines
@param $current
@return array Array of two elements, the first element contains the block,
the second contains the next line index to be parsed.


protected function inlineMarkers()
	{
		$markers = [];
		// detect "parse" functions
		$reflection = new \ReflectionClass($this);
		foreach($reflection->getMethods(ReflectionMethod::IS_PROTECTED) as $method) {
			$methodName = $method->getName();
			if (strncmp($methodName, 'parse', 5) === 0) {
				preg_match_all('/@marker ([^\s]+)/', $method->getDocComment(), $matches);
				foreach($matches[1] as $match) {
					$markers[$match] = $methodName;
				}
			}
		}
		return $markers;
	}

protected
function
inlineMarkers
(
)
{
$
markers
=
[
]
;
// detect "parse" functions
$
reflection
=
new
\
ReflectionClass
(
$
this
)
;
foreach
(
$
reflection
->
getMethods
(
ReflectionMethod
::
IS_PROTECTED
)
as
$
method
)
{
$
methodName
=
$
method
->
getName
(
)
;
if
(
strncmp
(
$
methodName
,
'parse'
,
5
)
===
0
)
{
preg_match_all
(
'/@marker ([^\s]+)/'
,
$
method
->
getDocComment
(
)
,
$
matches
)
;
foreach
(
$
matches
[
1
]
as
$
match
)
{
$
markers
[
$
match
]
=
$
methodName
;
}
}
}
return
$
markers
;
}

Returns a map of inline markers to the corresponding parser methods.

This array defines handler methods for inline markdown markers.
When a marker is found in the text, the handler method is called with the text
starting at the position of the marker.

Note that markers starting with whitespace may slow down the parser,
you may want to use [[renderText]] to deal with them.

You may override this method to define a set of markers and parsing methods.
The default implementation looks for protected methods starting with `parse` that
also have an `@marker` annotation in PHPDoc.

@return array a map of markers to parser methods

Returns a map of inline markers to the corresponding parser methods .


protected function prepareMarkers($text)
	{
		$this->_inlineMarkers = [];
		foreach ($this->inlineMarkers() as $marker => $method) {
			if (strpos($text, $marker) !== false) {
				$m = $marker[0];
				// put the longest marker first
				if (isset($this->_inlineMarkers[$m])) {
					reset($this->_inlineMarkers[$m]);
					if (strlen($marker) > strlen(key($this->_inlineMarkers[$m]))) {
						$this->_inlineMarkers[$m] = array_merge([$marker => $method], $this->_inlineMarkers[$m]);
						continue;
					}
				}
				$this->_inlineMarkers[$m][$marker] = $method;
			}
		}
	}

protected
function
prepareMarkers
(
$
text
)
{
$
this
->
_inlineMarkers
=
[
]
;
foreach
(
$
this
->
inlineMarkers
(
)
as
$
marker
=>
$
method
)
{
if
(
strpos
(
$
text
,
$
marker
)
!==
false
)
{
$
m
=
$
marker
[
0
]
;
// put the longest marker first
if
(
isset
(
$
this
->
_inlineMarkers
[
$
m
]
)
)
{
reset
(
$
this
->
_inlineMarkers
[
$
m
]
)
;
if
(
strlen
(
$
marker
)
>
strlen
(
key
(
$
this
->
_inlineMarkers
[
$
m
]
)
)
)
{
$
this
->
_inlineMarkers
[
$
m
]
=
array_merge
(
[
$
marker
=>
$
method
]
,
$
this
->
_inlineMarkers
[
$
m
]
)
;
continue
;
}
}
$
this
->
_inlineMarkers
[
$
m
]
[
$
marker
]
=
$
method
;
}
}
}

Prepare markers that are used in the text to parse

Add all markers that are present in markdown.
Check is done to avoid iterations in parseInline(), good for huge markdown files
@param string $text


protected function parseInline($text)
	{
		if ($this->_depth >= $this->maximumNestingLevel) {
			// maximum depth is reached, do not parse input
			return [['text', $text]];
		}
		$this->_depth++;

		$markers = implode('', array_keys($this->_inlineMarkers));

		$paragraph = [];

		while (!empty($markers) && ($found = strpbrk($text, $markers)) !== false) {

			$pos = strpos($text, $found);

			// add the text up to next marker to the paragraph
			if ($pos !== 0) {
				$paragraph[] = ['text', substr($text, 0, $pos)];
			}
			$text = $found;

			$parsed = false;
			foreach ($this->_inlineMarkers[$text[0]] as $marker => $method) {
				if (strncmp($text, $marker, strlen($marker)) === 0) {
					// parse the marker
					array_unshift($this->context, $method);
					list($output, $offset) = $this->$method($text);
					array_shift($this->context);

					$paragraph[] = $output;
					$text = substr($text, $offset);
					$parsed = true;
					break;
				}
			}
			if (!$parsed) {
				$paragraph[] = ['text', substr($text, 0, 1)];
				$text = substr($text, 1);
			}
		}

		$paragraph[] = ['text', $text];

		$this->_depth--;

		return $paragraph;
	}

Parses inline elements of the language.

@param string $text the inline text to parse.
@return array

Parses inline elements of the language .


protected function parseEmphStrong($text)
	{
		$marker = $text[0];

		if (!isset($text[1])) {
			return [['text', $text[0]], 1];
		}

		if ($marker == $text[1]) { // strong
			// work around a PHP bug that crashes with a segfault on too much regex backtrack
			// check whether the end marker exists in the text
			// https://github.com/erusev/parsedown/issues/443
			// https://bugs.php.net/bug.php?id=45735
			if (strpos($text, $marker . $marker, 2) === false) {
				return [['text', $text[0] . $text[1]], 2];
			}

			if ($marker === '*' && preg_match('/^[*]{2}((?>\\\\[*]|[^*]|[*][^*]*[*])+?)[*]{2}/s', $text, $matches) ||
				$marker === '_' && preg_match('/^__((?>\\\\_|[^_]|_[^_]*_)+?)__/us', $text, $matches)) {

				return [
					[
						'strong',
						$this->parseInline($matches[1]),
					],
					strlen($matches[0])
				];
			}
		} else { // emph
			// work around a PHP bug that crashes with a segfault on too much regex backtrack
			// check whether the end marker exists in the text
			// https://github.com/erusev/parsedown/issues/443
			// https://bugs.php.net/bug.php?id=45735
			if (strpos($text, $marker, 1) === false) {
				return [['text', $text[0]], 1];
			}

			if ($marker === '*' && preg_match('/^[*]((?>\\\\[*]|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*][^*])/s', $text, $matches) ||
				$marker === '_' && preg_match('/^_((?>\\\\_|[^_]|__[^_]*__)+?)_(?!_[^_])\b/us', $text, $matches)) {
				// if only a single whitespace or nothing is contained in an emphasis, do not consider it valid
				if ($matches[1] === '' || $matches[1] === ' ') {
					return [['text', $text[0]], 1];
				}
				return [
					[
						'emph',
						$this->parseInline($matches[1]),
					],
					strlen($matches[0])
				];
			}
		}
		return [['text', $text[0]], 1];
	}

Parses emphasized and strong elements.
@marker _
@marker *


protected function identifyHtml($line, $lines, $current)
	{
		if ($line[0] !== '<' || isset($line[1]) && $line[1] == ' ') {
			return false; // no html tag
		}

		if (strncmp($line, '<!--', 4) === 0) {
			return true; // a html comment
		}

		$gtPos = strpos($lines[$current], '>');
		$spacePos = strpos($lines[$current], ' ');
		if ($gtPos === false && $spacePos === false) {
			return false; // no html tag
		} elseif ($spacePos === false) {
			$tag = rtrim(substr($line, 1, $gtPos - 1), '/');
		} else {
			$tag = rtrim(substr($line, 1, min($gtPos, $spacePos) - 1), '/');
		}

		if (!ctype_alnum($tag) || in_array(strtolower($tag), $this->inlineHtmlElements)) {
			return false; // no html tag or inline html tag
		}
		return true;
	}

protected
function
identifyHtml
(
$
line
,
$
lines
,
$
current
)
{
if
(
$
line
[
0
]
!==
'<'
||
isset
(
$
line
[
1
]
)
&&
$
line
[
1
]
==
' '
)
{
return
false
;
// no html tag
}
if
(
strncmp
(
$
line
,
'<!--'
,
4
)
===
0
)
{
return
true
;
// a html comment
}
$
gtPos
=
strpos
(
$
lines
[
$
current
]
,
'>'
)
;
$
spacePos
=
strpos
(
$
lines
[
$
current
]
,
' '
)
;
if
(
$
gtPos
===
false
&&
$
spacePos
===
false
)
{
return
false
;
// no html tag
}
elseif
(
$
spacePos
===
false
)
{
$
tag
=
rtrim
(
substr
(
$
line
,
1
,
$
gtPos
1
)
,
'/'
)
;
}
else
{
$
tag
=
rtrim
(
substr
(
$
line
,
1
,
min
(
$
gtPos
,
$
spacePos
)
1
)
,
'/'
)
;
}
if
(
!
ctype_alnum
(
$
tag
)
||
in_array
(
strtolower
(
$
tag
)
,
$
this
->
inlineHtmlElements
)
)
{
return
false
;
// no html tag or inline html tag
}
return
true
;
}

identify a line as the beginning of a HTML block.

identify a line as the beginning of a HTML block .


protected function consumeHtml($lines, $current)
	{
		$content = [];
		if (strncmp($lines[$current], '<!--', 4) === 0) { // html comment
			for ($i = $current, $count = count($lines); $i < $count; $i++) {
				$line = $lines[$i];
				$content[] = $line;
				if (strpos($line, '-->') !== false) {
					break;
				}
			}
		} else {
			$tag = rtrim(substr($lines[$current], 1, min(strpos($lines[$current], '>'), strpos($lines[$current] . ' ', ' ')) - 1), '/');
			$level = 0;
			if (in_array($tag, $this->selfClosingHtmlElements)) {
				$level--;
			}
			for ($i = $current, $count = count($lines); $i < $count; $i++) {
				$line = $lines[$i];
				$content[] = $line;
				$level += substr_count($line, "<$tag") - substr_count($line, "</$tag>") - substr_count($line, "/>");
				if ($level <= 0) {
					break;
				}
			}
		}
		$block = [
			'html',
			'content' => implode("\n", $content),
		];
		return [$block, $i];
	}

protected
function
consumeHtml
(
$
lines
,
$
current
)
{
$
content
=
[
]
;
if
(
strncmp
(
$
lines
[
$
current
]
,
'<!--'
,
4
)
===
0
)
{
// html comment
for
(
$
i
=
$
current
,
$
count
=
count
(
$
lines
)
;
$
i
<
$
count
;
$
i
++
)
{
$
line
=
$
lines
[
$
i
]
;
$
content
[
]
=
$
line
;
if
(
strpos
(
$
line
,
'-->'
)
!==
false
)
{
break
;
}
}
}
else
{
$
tag
=
rtrim
(
substr
(
$
lines
[
$
current
]
,
1
,
min
(
strpos
(
$
lines
[
$
current
]
,
'>'
)
,
strpos
(
$
lines
[
$
current
]
.
' '
,
' '
)
)
1
)
,
'/'
)
;
$
level
=
0
;
if
(
in_array
(
$
tag
,
$
this
->
selfClosingHtmlElements
)
)
{
$
level
;
}
for
(
$
i
=
$
current
,
$
count
=
count
(
$
lines
)
;
$
i
<
$
count
;
$
i
++
)
{
$
line
=
$
lines
[
$
i
]
;
$
content
[
]
=
$
line
;
$
level
+=
substr_count
(
$
line
,
"<$tag"
)
substr_count
(
$
line
,
"</$tag>"
)
substr_count
(
$
line
,
"/>"
)
;
if
(
$
level
<=
0
)
{
break
;
}
}
}
$
block
=
[
'html'
,
'content'
=>
implode
(
"\n"
,
$
content
)
,
]
;
return
[
$
block
,
$
i
]
;
}


identify a line as the beginning of a fenced code block.

identify a line as the beginning of a fenced code block .


protected function identifyHeadline($line, $lines, $current)
	{
		return (
			// heading with #
			$line[0] === '#' && !preg_match('/^#\d+/', $line)
			||
			// underlined headline
			!empty($lines[$current + 1]) &&
			(($l = $lines[$current + 1][0]) === '=' || $l === '-') &&
			preg_match('/^(\-+|=+)\s*$/', $lines[$current + 1])
		);
	}

protected
function
identifyHeadline
(
$
line
,
$
lines
,
$
current
)
{
return
(
// heading with #
$
line
[
0
]
===
'#'
&&
!
preg_match
(
'/^#\d+/'
,
$
line
)
||
// underlined headline
!
empty
(
$
lines
[
$
current
+
1
]
)
&&
(
(
$
l
=
$
lines
[
$
current
+
1
]
[
0
]
)
===
'='
||
$
l
===
'-'
)
&&
preg_match
(
'/^(\-+|=+)\s*$/'
,
$
lines
[
$
current
+
1
]
)
)
;
}


protected function consumeHeadline($lines, $current)
	{
		if ($lines[$current][0] === '#') {
			// ATX headline
			$level = 1;
			while (isset($lines[$current][$level]) && $lines[$current][$level] === '#' && $level < 6) {
				$level++;
			}
			$block = [
				'headline',
				'content' => $this->parseInline(trim($lines[$current], "# \t")),
				'level' => $level,
			];
			return [$block, $current];
		} else {
			// underlined headline
			$block = [
				'headline',
				'content' => $this->parseInline($lines[$current]),
				'level' => $lines[$current + 1][0] === '=' ? 1 : 2,
			];
			return [$block, $current + 1];
		}
	}

protected
function
consumeHeadline
(
$
lines
,
$
current
)
{
if
(
$
lines
[
$
current
]
[
0
]
===
'#'
)
{
// ATX headline
$
level
=
1
;
while
(
isset
(
$
lines
[
$
current
]
[
$
level
]
)
&&
$
lines
[
$
current
]
[
$
level
]
===
'#'
&&
$
level
<
6
)
{
$
level
++
;
}
$
block
=
[
'headline'
,
'content'
=>
$
this
->
parseInline
(
trim
(
$
lines
[
$
current
]
,
"# \t"
)
)
,
'level'
=>
$
level
,
]
;
return
[
$
block
,
$
current
]
;
}
else
{
// underlined headline
$
block
=
[
'headline'
,
'content'
=>
$
this
->
parseInline
(
$
lines
[
$
current
]
)
,
'level'
=>
$
lines
[
$
current
+
1
]
[
0
]
===
'='
1
:
2
,
]
;
return
[
$
block
,
$
current
+
1
]
;
}
}


protected function replaceEscape($text)
	{
		$strtr = [];
		foreach($this->escapeCharacters as $char) {
			$strtr["\\$char"] = $char;
		}
		return strtr($text, $strtr);
	}

protected function replaceEscape ( $ text ) { $ strtr = [ ] ; foreach ( $ this -> escapeCharacters as $ char ) { $ strtr [ "\\$char" ] = $ char ; } return strtr ( $ text , $ strtr ) ; }

Remove backslash from escaped characters
@param $text
@return string


protected function parseLink($markdown)
	{
		if (!in_array('parseLink', array_slice($this->context, 1)) && ($parts = $this->parseLinkOrImage($markdown)) !== false) {
			list($text, $url, $title, $offset, $key) = $parts;
			return [
				[
					'link',
					'text' => $this->parseInline($text),
					'url' => $url,
					'title' => $title,
					'refkey' => $key,
					'orig' => substr($markdown, 0, $offset),
				],
				$offset
			];
		} else {
			// remove all starting [ markers to avoid next one to be parsed as link
			$result = '[';
			$i = 1;
			while (isset($markdown[$i]) && $markdown[$i] === '[') {
				$result .= '[';
				$i++;
			}
			return [['text', $result], $i];
		}
	}

Parses a link indicated by `[`.
@marker [


protected function parseImage($markdown)
	{
		if (($parts = $this->parseLinkOrImage(substr($markdown, 1))) !== false) {
			list($text, $url, $title, $offset, $key) = $parts;

			return [
				[
					'image',
					'text' => $text,
					'url' => $url,
					'title' => $title,
					'refkey' => $key,
					'orig' => substr($markdown, 0, $offset + 1),
				],
				$offset + 1
			];
		} else {
			// remove all starting [ markers to avoid next one to be parsed as link
			$result = '!';
			$i = 1;
			while (isset($markdown[$i]) && $markdown[$i] === '[') {
				$result .= '[';
				$i++;
			}
			return [['text', $result], $i];
		}
	}

Parses an image indicated by `![`.
@marker ![


protected function parseInlineCode($text)
	{
		if (preg_match('/^(``+)\s(.+?)\s\1/s', $text, $matches)) { // code with enclosed backtick
			return [
				[
					'inlineCode',
					$matches[2],
				],
				strlen($matches[0])
			];
		} elseif (preg_match('/^`(.+?)`/s', $text, $matches)) {
			return [
				[
					'inlineCode',
					$matches[1],
				],
				strlen($matches[0])
			];
		}
		return [['text', $text[0]], 1];
	}

protected
function
parseInlineCode
(
$
text
)
{
if
(
preg_match
(
'/^(``+)\s(.+?)\s\1/s'
,
$
text
,
$
matches
)
)
{
// code with enclosed backtick
return
[
[
'inlineCode'
,
$
matches
[
2
]
,
]
,
strlen
(
$
matches
[
0
]
)
]
;
}
elseif
(
preg_match
(
'/^`(.+?)`/s'
,
$
text
,
$
matches
)
)
{
return
[
[
'inlineCode'
,
$
matches
[
1
]
,
]
,
strlen
(
$
matches
[
0
]
)
]
;
}
return
[
[
'text'
,
$
text
[
0
]
]
,
1
]
;
}

Parses an inline code span `` ` ``.
@marker `


protected function consumeCode($lines, $current)
	{
		// consume until newline

		$content = [];
		for ($i = $current, $count = count($lines); $i < $count; $i++) {
			$line = $lines[$i];

			// a line is considered to belong to this code block as long as it is intended by 4 spaces or a tab
			if (isset($line[0]) && ($line[0] === "\t" || strncmp($line, '    ', 4) === 0)) {
				$line = $line[0] === "\t" ? substr($line, 1) : substr($line, 4);
				$content[] = $line;
			// but also if it is empty and the next line is intended by 4 spaces or a tab
			} elseif (($line === '' || rtrim($line) === '') && isset($lines[$i + 1][0]) &&
				      ($lines[$i + 1][0] === "\t" || strncmp($lines[$i + 1], '    ', 4) === 0)) {
				if ($line !== '') {
					$line = $line[0] === "\t" ? substr($line, 1) : substr($line, 4);
				}
				$content[] = $line;
			} else {
				break;
			}
		}

		$block = [
			'code',
			'content' => implode("\n", $content),
		];
		return [$block, --$i];
	}


identify a line as the beginning of an unordered list.

identify a line as the beginning of an unordered list .


protected function renderList($block)
	{
		$type = $block['list'];

		if (!empty($block['attr'])) {
			$output = "<$type " . $this->generateHtmlAttributes($block['attr']) . ">\n";
		} else {
			$output = "<$type>\n";
		}

		foreach ($block['items'] as $item => $itemLines) {
			$output .= '<li>' . $this->renderAbsy($itemLines). "</li>\n";
		}
		return $output . "</$type>\n";
	}

protected
function
renderList
(
$
block
)
{
$
type
=
$
block
[
'list'
]
;
if
(
!
empty
(
$
block
[
'attr'
]
)
)
{
$
output
=
"<$type "
.
$
this
->
generateHtmlAttributes
(
$
block
[
'attr'
]
)
.
">\n"
;
}
else
{
$
output
=
"<$type>\n"
;
}
foreach
(
$
block
[
'items'
]
as
$
item
=>
$
itemLines
)
{
$
output
.=
'<li>'
.
$
this
->
renderAbsy
(
$
itemLines
)
.
"</li>\n"
;
}
return
$
output
.
"</$type>\n"
;
}


protected function consumeQuote($lines, $current)
	{
		// consume until newline
		$content = [];
		for ($i = $current, $count = count($lines); $i < $count; $i++) {
			$line = $lines[$i];
			if (ltrim($line) !== '') {
				if ($line[0] == '>' && !isset($line[1])) {
					$line = '';
				} elseif (strncmp($line, '> ', 2) === 0) {
					$line = substr($line, 2);
				}
				$content[] = $line;
			} else {
				break;
			}
		}

		$block = [
			'quote',
			'content' => $this->parseBlocks($content),
			'simple' => true,
		];
		return [$block, $i];
	}

protected
function
consumeQuote
(
$
lines
,
$
current
)
{
// consume until newline
$
content
=
[
]
;
for
(
$
i
=
$
current
,
$
count
=
count
(
$
lines
)
;
$
i
<
$
count
;
$
i
++
)
{
$
line
=
$
lines
[
$
i
]
;
if
(
ltrim
(
$
line
)
!==
''
)
{
if
(
$
line
[
0
]
==
'>'
&&
!
isset
(
$
line
[
1
]
)
)
{
$
line
=
''
;
}
elseif
(
strncmp
(
$
line
,
'> '
,
2
)
===
0
)
{
$
line
=
substr
(
$
line
,
2
)
;
}
$
content
[
]
=
$
line
;
}
else
{
break
;
}
}
$
block
=
[
'quote'
,
'content'
=>
$
this
->
parseBlocks
(
$
content
)
,
'simple'
=>
true
,
]
;
return
[
$
block
,
$
i
]
;
}


protected function consumeReference($lines, $current)
	{
		while (isset($lines[$current]) && preg_match('/^ {0,3}\[(.+?)\]:\s*(.+?)(?:\s+[\(\'"](.+?)[\)\'"])?\s*('.$this->_specialAttributesRegex.')?\s*$/', $lines[$current], $matches)) {
			$label = strtolower($matches[1]);

			$this->references[$label] = [
				'url' => $this->replaceEscape($matches[2]),
			];
			if (isset($matches[3])) {
				$this->references[$label]['title'] = $matches[3];
			} else {
				// title may be on the next line
				if (isset($lines[$current + 1]) && preg_match('/^\s+[\(\'"](.+?)[\)\'"]\s*$/', $lines[$current + 1], $matches)) {
					$this->references[$label]['title'] = $matches[1];
					$current++;
				}
			}
			if (isset($matches[5])) {
				$this->references[$label]['attributes'] = $matches[5];
			}
			$current++;
		}
		return [false, --$current];
	}


protected function renderHeadline($block)
	{
		foreach($block['content'] as $i => $element) {
			if ($element[0] === 'specialAttributes') {
				unset($block['content'][$i]);
				$block['attributes'] = $element[1];
			}
		}
		$tag = 'h' . $block['level'];
		$attributes = $this->renderAttributes($block);
		return "<$tag$attributes>" . rtrim($this->renderAbsy($block['content']), "# \t") . "</$tag>\n";
	}

protected
function
renderHeadline
(
$
block
)
{
foreach
(
$
block
[
'content'
]
as
$
i
=>
$
element
)
{
if
(
$
element
[
0
]
===
'specialAttributes'
)
{
unset
(
$
block
[
'content'
]
[
$
i
]
)
;
$
block
[
'attributes'
]
=
$
element
[
1
]
;
}
}
$
tag
=
'h'
.
$
block
[
'level'
]
;
$
attributes
=
$
this
->
renderAttributes
(
$
block
)
;
return
"<$tag$attributes>"
.
rtrim
(
$
this
->
renderAbsy
(
$
block
[
'content'
]
)
,
"# \t"
)
.
"</$tag>\n"
;
}


protected function parseStrike($markdown)
	{
		if (preg_match('/^~~(.+?)~~/', $markdown, $matches)) {
			return [
				[
					'strike',
					$this->parseInline($matches[1])
				],
				strlen($matches[0])
			];
		}
		return [['text', $markdown[0] . $markdown[1]], 2];
	}

protected function parseStrike ( $ markdown ) { if ( preg_match ( '/^~~(.+?)~~/' , $ markdown , $ matches ) ) { return [ [ 'strike' , $ this -> parseInline ( $ matches [ 1 ] ) ] , strlen ( $ matches [ 0 ] ) ] ; } return [ [ 'text' , $ markdown [ 0 ] . $ markdown [ 1 ] ] , 2 ] ; }

Parses the strikethrough feature.
@marker ~~


protected function identifyTable($line, $lines, $current)
	{
		return strpos($line, '|') !== false && isset($lines[$current + 1])
			&& preg_match('~^\\s*\\|?(\\s*:?-[\\-\\s]*:?\\s*\\|?)*\\s*$~', $lines[$current + 1])
			&& strpos($lines[$current + 1], '|') !== false
			&& isset($lines[$current + 2]) && trim($lines[$current + 1]) !== '';
	}

identify a line as the beginning of a table block.

identify a line as the beginning of a table block .


protected function consumeTable($lines, $current)
	{
		// consume until newline

		$block = [
			'table',
			'cols' => [],
			'rows' => [],
		];
		for ($i = $current, $count = count($lines); $i < $count; $i++) {
			$line = trim($lines[$i]);

			// extract alignment from second line
			if ($i == $current+1) {
				$cols = explode('|', trim($line, ' |'));
				foreach($cols as $col) {
					$col = trim($col);
					if (empty($col)) {
						$block['cols'][] = '';
						continue;
					}
					$l = ($col[0] === ':');
					$r = (substr($col, -1, 1) === ':');
					if ($l && $r) {
						$block['cols'][] = 'center';
					} elseif ($l) {
						$block['cols'][] = 'left';
					} elseif ($r) {
						$block['cols'][] = 'right';
					} else {
						$block['cols'][] = '';
					}
				}

				continue;
			}
			if ($line === '' || substr($lines[$i], 0, 4) === '    ') {
				break;
			}
			if ($line[0] === '|') {
				$line = substr($line, 1);
			}
			if (substr($line, -1, 1) === '|' && (substr($line, -2, 2) !== '\\|' || substr($line, -3, 3) === '\\\\|')) {
				$line = substr($line, 0, -1);
			}

			array_unshift($this->context, 'table');
			$row = $this->parseInline($line);
			array_shift($this->context);

			$r = count($block['rows']);
			$c = 0;
			$block['rows'][] = [];
			foreach ($row as $absy) {
				if (!isset($block['rows'][$r][$c])) {
					$block['rows'][$r][] = [];
				}
				if ($absy[0] === 'tableBoundary') {
					$c++;
				} else {
					$block['rows'][$r][$c][] = $absy;
				}
			}
		}

		return [$block, --$i];
	}

protected
function
consumeTable
(
$
lines
,
$
current
)
{
// consume until newline
$
block
=
[
'table'
,
'cols'
=>
[
]
,
'rows'
=>
[
]
,
]
;
for
(
$
i
=
$
current
,
$
count
=
count
(
$
lines
)
;
$
i
<
$
count
;
$
i
++
)
{
$
line
=
trim
(
$
lines
[
$
i
]
)
;
// extract alignment from second line
if
(
$
i
==
$
current
+
1
)
{
$
cols
=
explode
(
'|'
,
trim
(
$
line
,
' |'
)
)
;
foreach
(
$
cols
as
$
col
)
{
$
col
=
trim
(
$
col
)
;
if
(
empty
(
$
col
)
)
{
$
block
[
'cols'
]
[
]
=
''
;
continue
;
}
$
l
=
(
$
col
[
0
]
===
':'
)
;
$
r
=
(
substr
(
$
col
,
1
,
1
)
===
':'
)
;
if
(
$
l
&&
$
r
)
{
$
block
[
'cols'
]
[
]
=
'center'
;
}
elseif
(
$
l
)
{
$
block
[
'cols'
]
[
]
=
'left'
;
}
elseif
(
$
r
)
{
$
block
[
'cols'
]
[
]
=
'right'
;
}
else
{
$
block
[
'cols'
]
[
]
=
''
;
}
}
continue
;
}
if
(
$
line
===
''
||
substr
(
$
lines
[
$
i
]
,
0
,
4
)
===
'    '
)
{
break
;
}
if
(
$
line
[
0
]
===
'|'
)
{
$
line
=
substr
(
$
line
,
1
)
;
}
if
(
substr
(
$
line
,
1
,
1
)
===
'|'
&&
(
substr
(
$
line
,
2
,
2
)
!==
'\\|'
||
substr
(
$
line
,
3
,
3
)
===
'\\\\|'
)
)
{
$
line
=
substr
(
$
line
,
0
,
1
)
;
}
array_unshift
(
$
this
->
context
,
'table'
)
;
$
row
=
$
this
->
parseInline
(
$
line
)
;
array_shift
(
$
this
->
context
)
;
$
r
=
count
(
$
block
[
'rows'
]
)
;
$
c
=
0
;
$
block
[
'rows'
]
[
]
=
[
]
;
foreach
(
$
row
as
$
absy
)
{
if
(
!
isset
(
$
block
[
'rows'
]
[
$
r
]
[
$
c
]
)
)
{
$
block
[
'rows'
]
[
$
r
]
[
]
=
[
]
;
}
if
(
$
absy
[
0
]
===
'tableBoundary'
)
{
$
c
++
;
}
else
{
$
block
[
'rows'
]
[
$
r
]
[
$
c
]
[
]
=
$
absy
;
}
}
}
return
[
$
block
,
$
i
]
;
}


protected function renderTable($block)
	{
		$head = '';
		$body = '';
		$cols = $block['cols'];
		$first = true;
		foreach($block['rows'] as $row) {
			$cellTag = $first ? 'th' : 'td';
			$tds = '';
			foreach ($row as $c => $cell) {
				$align = empty($cols[$c]) ? '' : ' align="' . $cols[$c] . '"';
				$tds .= "<$cellTag$align>" . trim($this->renderAbsy($cell)) . "</$cellTag>";
			}
			if ($first) {
				$head .= "
$tds
\n";
			} else {
				$body .= "
$tds
\n";
			}
			$first = false;
		}
		return $this->composeTable($head, $body);
	}

protected
function
renderTable
(
$
block
)
{
$
head
=
''
;
$
body
=
''
;
$
cols
=
$
block
[
'cols'
]
;
$
first
=
true
;
foreach
(
$
block
[
'rows'
]
as
$
row
)
{
$
cellTag
=
$
first
'th'
:
'td'
;
$
tds
=
''
;
foreach
(
$
row
as
$
c
=>
$
cell
)
{
$
align
=
empty
(
$
cols
[
$
c
]
)
''
:
' align="'
.
$
cols
[
$
c
]
.
'"'
;
$
tds
.=
"<$cellTag$align>"
.
trim
(
$
this
->
renderAbsy
(
$
cell
)
)
.
"</$cellTag>"
;
}
if
(
$
first
)
{
$
head
.=
"
$tds
\n"
;
}
else
{
$
body
.=
"
$tds
\n"
;
}
$
first
=
false
;
}
return
$
this
->
composeTable
(
$
head
,
$
body
)
;
}


protected function parseUrl($markdown)
	{
		$pattern = <<<REGEXP
			/(?(R) # in case of recursion match parentheses
				 \(((?>[^\s()]+)|(?R))*\)
			|      # else match a link with title
				^(https?|ftp):\/\/(([^\s<>()]+)|(?R))+(?<![\.,:;\'"!\?\s])
			)/x
REGEXP;

		if (!in_array('parseLink', $this->context) && preg_match($pattern, $markdown, $matches)) {
			return [
				['autoUrl', $matches[0]],
				strlen($matches[0])
			];
		}
		return [['text', substr($markdown, 0, 4)], 4];
	}

Parses urls and adds auto linking feature.
@marker http
@marker ftp

Parses urls and adds auto linking feature .


public function equals($nameId, $format)
    {
        if (false == $this->getSubject()) {
            return false;
        }

        if (false == $this->getSubject()->getNameID()) {
            return false;
        }

        if ($this->getSubject()->getNameID()->getValue() != $nameId) {
            return false;
        }

        if ($this->getSubject()->getNameID()->getFormat() != $format) {
            return false;
        }

        return true;
    }

public function equals ( $ nameId , $ format ) { if ( false == $ this -> getSubject ( ) ) { return false ; } if ( false == $ this -> getSubject ( ) -> getNameID ( ) ) { return false ; } if ( $ this -> getSubject ( ) -> getNameID ( ) -> getValue ( ) != $ nameId ) { return false ; } if ( $ this -> getSubject ( ) -> getNameID ( ) -> getFormat ( ) != $ format ) { return false ; } return true ; }

Core 3.3.4 Processing rules.

@param string      $nameId
@param string|null $format

@return bool


public static function createElement(DOMDocument $document, $name, array $attributes = []): DOMElement
    {
        $element = $document->createElement($name);

        foreach ($attributes as $attribName => $attribValue) {
            $element->setAttribute($attribName, $attribValue);
        }

        return $element;
    }

public static function createElement ( DOMDocument $ document , $ name , array $ attributes = [ ] ) : DOMElement { $ element = $ document -> createElement ( $ name ) ; foreach ( $ attributes as $ attribName => $ attribValue ) { $ element -> setAttribute ( $ attribName , $ attribValue ) ; } return $ element ; }

Shortcut for creating an XML element.

@param DOMDocument $document The document used to create the element. It will NOT be modified.
@param string $name Name of the element.
@param array $attributes String-to-string mapping of attributes to set on the element.
@return DOMElement The newly constructed independent DOM element.


public static function createElementWithText(
        DOMDocument $document,
        string $name,
        string $text,
        array $attributes = []
    ): DOMElement {
        $element = self::createElement($document, $name, $attributes);
        $wrappedText = $document->createCDATASection($text);
        $element->appendChild($wrappedText);

        return $element;
    }

public static function createElementWithText ( DOMDocument $ document , string $ name , string $ text , array $ attributes = [ ] ) : DOMElement { $ element = self :: createElement ( $ document , $ name , $ attributes ) ; $ wrappedText = $ document -> createCDATASection ( $ text ) ; $ element -> appendChild ( $ wrappedText ) ; return $ element ; }

Shortcut for creating an XML element that contains CDATA-wrapped text.

@param DOMDocument $document The document used to create the element. It will NOT be modified.
@param string $name Name of the element.
@param string $text The text body of the document.
@param array $attributes String-to-string mapping of attributes to set on the element.
@return DOMElement The newly constructed independent DOM element.

Shortcut for creating an XML element that contains CDATA - wrapped text .


private static function validateImages(array $images): bool
    {
        $valid = false;

        foreach ($images as $image) {
            if ($image->getType() === Image::TYPE_DEFAULT) {
                $valid = true;
                break;
            }
        }

        if (!$valid) {
            throw new BaseImageMissingException();
        }

        return $valid;
    }

private static function validateImages ( array $ images ) : bool { $ valid = false ; foreach ( $ images as $ image ) { if ( $ image -> getType ( ) === Image :: TYPE_DEFAULT ) { $ valid = true ; break ; } } if ( ! $ valid ) { throw new BaseImageMissingException ( ) ; } return $ valid ; }

Checks if there is at least one image of type default

@param array $images The images to validate.
@return boolean Whether the images are valid or not.


public static function checkForEmptyValue(string $valueName, $value): string
    {
        $value = trim($value);

        if ($value === '') {
            throw new EmptyValueNotAllowedException($valueName);
        }

        return $value;
    }

public static function checkForEmptyValue ( string $ valueName , $ value ) : string { $ value = trim ( $ value ) ; if ( $ value === '' ) { throw new EmptyValueNotAllowedException ( $ valueName ) ; } return $ value ; }

Checks if the provided value is empty.

@param string $valueName Name of the value, for better error reporting.
@param string|int|float $value The value to check. Regardless of type, it is coerced into a string.
@return string Returns the value if not empty.


public static function checkForIllegalCsvPropertyKeys(string $propertyKey): void
    {
        if (strpos($propertyKey, "\t") !== false || strpos($propertyKey, "\n") !== false) {
            throw new BadPropertyKeyException($propertyKey);
        }
    }

public static function checkForIllegalCsvPropertyKeys ( string $ propertyKey ) : void { if ( strpos ( $ propertyKey , "\t" ) !== false || strpos ( $ propertyKey , "\n" ) !== false ) { throw new BadPropertyKeyException ( $ propertyKey ) ; } }

Verifies that property keys for use in CSV export don't contain characters that could break the format fatally.

@param string $propertyKey The property key to check.
@throw BadPropertyKeyException In case the property key contains dangerous characters.

Verifies that property keys for use in CSV export don t contain characters that could break the format fatally .


public static function create(int $type, int $itemsPerPage = 20, array $csvProperties = []): Exporter
    {
        if ($itemsPerPage < 1) {
            throw new InvalidArgumentException('At least one item must be exported per page.');
        }

        switch ($type) {
            case self::TYPE_XML:
                $exporter = new XMLExporter($itemsPerPage);
                break;
            case self::TYPE_CSV:
                $exporter = new CSVExporter($itemsPerPage, $csvProperties);
                break;
            default:
                throw new InvalidArgumentException('Unsupported exporter type.');
        }

        return $exporter;
    }

Creates an exporter for the desired output format.

@param int $type The type of export format to choose. Must be either Exporter::TYPE_XML or Exporter::TYPE_CSV.
@param int $itemsPerPage Number of items being exported at once. Respecting this parameter is at the exporter
implementation's discretion.
@param array $csvProperties Properties/extra columns for CSV export. Has no effect for XML export.
@return Exporter The exporter for the desired output format.

Creates an exporter for the desired output format .


public function addValue(string $value, ?string $usergroup = null): void
    {
        if (array_key_exists($usergroup, $this->getAllValues())) {
            throw new DuplicateValueForUsergroupException($this->getKey(), $usergroup);
        }

        $this->values[$usergroup] = DataHelper::checkForEmptyValue('propertyValue', $value);
    }

public function addValue ( string $ value , ? string $ usergroup = null ) : void { if ( array_key_exists ( $ usergroup , $ this -> getAllValues ( ) ) ) { throw new DuplicateValueForUsergroupException ( $ this -> getKey ( ) , $ usergroup ) ; } $ this -> values [ $ usergroup ] = DataHelper :: checkForEmptyValue ( 'propertyValue' , $ value ) ; }

Add a value to the property element.

@SuppressWarnings(PHPMD.StaticAccess)
@param string $value The value to add to the property element.
@param string|null $usergroup The usergroup of the property value.


private function validateWithSchema(DOMDocument $document): void
    {
        $validationErrors = [];
        set_error_handler(function (/** @noinspection PhpUnusedParameterInspection */ $errno, $errstr)
 use (&$validationErrors) {
            array_push($validationErrors, $errstr);
        });

        $isValid = $document->schemaValidate(Constant::$XSD_SCHEMA_PATH);
        restore_error_handler();

        if (!$isValid) {
            throw new XMLSchemaViolationException($validationErrors);
        }
    }

Validates the export page against the schema. In case of violations, an exception is thrown.

@param DOMDocument $document The document to validate.

Validates the export page against the schema . In case of violations an exception is thrown .


public function addName(string $name, string $usergroup = ''): void
    {
        $this->name->setValue($name, $usergroup);
    }

public function addName ( string $ name , string $ usergroup = '' ) : void { $ this -> name -> setValue ( $ name , $ usergroup ) ; }

Shortcut to easily add the name of the item.

@param string $name The name of the item.
@param string $usergroup The usergroup of the name element.

Shortcut to easily add the name of the item .


public function addSummary(string $summary, string $usergroup = ''): void
    {
        $this->summary->setValue($summary, $usergroup);
    }

public function addSummary ( string $ summary , string $ usergroup = '' ) : void { $ this -> summary -> setValue ( $ summary , $ usergroup ) ; }

Shortcut to easily add the summary of the item.

@param string $summary The summary of the item.
@param string $usergroup The usergroup of the summary.

Shortcut to easily add the summary of the item .


public function addDescription(string $description, string $usergroup = ''): void
    {
        $this->description->setValue($description, $usergroup);
    }

public function addDescription ( string $ description , string $ usergroup = '' ) : void { $ this -> description -> setValue ( $ description , $ usergroup ) ; }

Shortcut to easily add the description of the item.

@param string $description The description of the item.
@param string $usergroup The usergroup of the description.

Shortcut to easily add the description of the item .


public function addPrice($price, $usergroup = ''): void
    {
        if ($this->price === null) {
            $this->price = new Price();
        }

        $this->price->setValue($price, $usergroup);
    }

public function addPrice ( $ price , $ usergroup = '' ) : void { if ( $ this -> price === null ) { $ this -> price = new Price ( ) ; } $ this -> price -> setValue ( $ price , $ usergroup ) ; }

Shortcut to easily add the price of the item.

@param string $price The price of the item.
@param string $usergroup The usergroup of the price.

Shortcut to easily add the price of the item .


public function addBonus(float $bonus, string $usergroup = ''): void
    {
        $this->bonus->setValue($bonus, $usergroup);
    }

public function addBonus ( float $ bonus , string $ usergroup = '' ) : void { $ this -> bonus -> setValue ( $ bonus , $ usergroup ) ; }

Shortcut to easily add the bonus of the item. The value must be a numeric.

@param float $bonus The bonus value of the item.
@param string $usergroup The usergroup of the bonus value.

Shortcut to easily add the bonus of the item . The value must be a numeric .


public function addSalesFrequency(int $salesFrequency, string $usergroup = ''): void
    {
        $this->salesFrequency->setValue($salesFrequency, $usergroup);
    }

public function addSalesFrequency ( int $ salesFrequency , string $ usergroup = '' ) : void { $ this -> salesFrequency -> setValue ( $ salesFrequency , $ usergroup ) ; }

Shortcut to easily add the sales frequency of the item. The value must be a positive integer.

@param int $salesFrequency The sales frequency of the item.
@param string $usergroup The usergroup of the sales frequency.

Shortcut to easily add the sales frequency of the item . The value must be a positive integer .


public function addDateAdded(DateTime $dateAdded, string $usergroup = ''): void
    {
        $this->dateAdded->setDateValue($dateAdded, $usergroup);
    }

public function addDateAdded ( DateTime $ dateAdded , string $ usergroup = '' ) : void { $ this -> dateAdded -> setDateValue ( $ dateAdded , $ usergroup ) ; }

Shortcut to easily add the date added value of the item.

@param DateTime $dateAdded The date on which the item was added to the ecommerce system.
@param string $usergroup The usergroup of the date added value.

Shortcut to easily add the date added value of the item .


public function addSort(int $sort, string $usergroup = ''): void
    {
        $this->sort->setValue($sort, $usergroup);
    }

public function addSort ( int $ sort , string $ usergroup = '' ) : void { $ this -> sort -> setValue ( $ sort , $ usergroup ) ; }

Shortcut to easily add the sort value of the item.

@param int $sort The sort value of the item.
@param string $usergroup The usergroup of the sort value.

Shortcut to easily add the sort value of the item .


protected function validate($value)
    {
        $value = trim($value);

        if ($value === '') {
            throw new EmptyValueNotAllowedException($this->getValueName());
        }

        return $value;
    }

protected function validate ( $ value ) { $ value = trim ( $ value ) ; if ( $ value === '' ) { throw new EmptyValueNotAllowedException ( $ this -> getValueName ( ) ) ; } return $ value ; }

Validates given value.
Basic implementation is validating against an empty string,
but is overridden when checking values more specific.

When valid returns given value.
When not valid an exception is thrown.

@param string|int $value Validated value.
@return string
@throws EmptyValueNotAllowedException

Validates given value . Basic implementation is validating against an empty string but is overridden when checking values more specific .


public function get($name)
    {
        if (!$this->has($name)) {
            throw new InvalidArgumentException(sprintf('Hook named "%s" is not present', $name));
        }

        return file_get_contents($this->getPath($name));
    }

public
function
get
(
$
name
)
{
if
(
!
$
this
->
has
(
$
name
)
)
{
throw
new
InvalidArgumentException
(
sprintf
(
'Hook named "%s" is not present'
,
$
name
)
)
;
}
return
file_get_contents
(
$
this
->
getPath
(
$
name
)
)
;
}

Fetches content of a hook.

@param string $name Name of the hook

@return string Content of the hook

@throws InvalidArgumentException Hook does not exist


public function setSymlink($name, $file)
    {
        if ($this->has($name)) {
            throw new LogicException(sprintf('A hook "%s" is already defined', $name));
        }

        $path = $this->getPath($name);
        if (false === symlink($file, $path)) {
            throw new RuntimeException(sprintf('Unable to create hook "%s"', $name, $path));
        }
    }

public
function
setSymlink
(
$
name
,
$
file
)
{
if
(
$
this
->
has
(
$
name
)
)
{
throw
new
LogicException
(
sprintf
(
'A hook "%s" is already defined'
,
$
name
)
)
;
}
$
path
=
$
this
->
getPath
(
$
name
)
;
if
(
false
===
symlink
(
$
file
,
$
path
)
)
{
throw
new
RuntimeException
(
sprintf
(
'Unable to create hook "%s"'
,
$
name
,
$
path
)
)
;
}
}

Insert a hook in repository using a symlink.

@param string $name Name of the hook to insert
@param string $file Target of symlink

@throws LogicException   Hook is already present
@throws RuntimeException Error on symlink creation

Insert a hook in repository using a symlink .


public function set($name, $content)
    {
        if ($this->has($name)) {
            throw new LogicException(sprintf('A hook "%s" is already defined', $name));
        }

        $path = $this->getPath($name);
        file_put_contents($path, $content);
        chmod($path, 0777);
    }

public
function
set
(
$
name
,
$
content
)
{
if
(
$
this
->
has
(
$
name
)
)
{
throw
new
LogicException
(
sprintf
(
'A hook "%s" is already defined'
,
$
name
)
)
;
}
$
path
=
$
this
->
getPath
(
$
name
)
;
file_put_contents
(
$
path
,
$
content
)
;
chmod
(
$
path
,
0777
)
;
}

Set a hook in repository.

@param string $name    Name of the hook
@param string $content Content of the hook

@throws LogicException The hook is already defined


public function remove($name)
    {
        if (!$this->has($name)) {
            throw new LogicException(sprintf('The hook "%s" was not found', $name));
        }

        unlink($this->getPath($name));
    }

public
function
remove
(
$
name
)
{
if
(
!
$
this
->
has
(
$
name
)
)
{
throw
new
LogicException
(
sprintf
(
'The hook "%s" was not found'
,
$
name
)
)
;
}
unlink
(
$
this
->
getPath
(
$
name
)
)
;
}

Removes a hook from repository.

@param string $name Name of the hook

@throws LogicException The hook is not present


public function countCommits()
    {
        if (null !== $this->revisions && count($this->revisions)) {
            $output = $this->repository->run('rev-list', array_merge(array('--count'), $this->revisions->getAsTextArray(), array('--'), $this->paths));
        } else {
            $output = $this->repository->run('rev-list', array_merge(array('--count', '--all', '--'), $this->paths));
        }

        return (int) $output;
    }

public function countCommits ( ) { if ( null !== $ this -> revisions && count ( $ this -> revisions ) ) { $ output = $ this -> repository -> run ( 'rev-list' , array_merge ( array ( '--count' ) , $ this -> revisions -> getAsTextArray ( ) , array ( '--' ) , $ this -> paths ) ) ; } else { $ output = $ this -> repository -> run ( 'rev-list' , array_merge ( array ( '--count' , '--all' , '--' ) , $ this -> paths ) ) ; } return ( int ) $ output ; }

Count commits, without offset or limit.

@return int


public function getReferences()
    {
        if (null === $this->referenceBag) {
            $this->referenceBag = new ReferenceBag($this);
        }

        return $this->referenceBag;
    }

public function getReferences ( ) { if ( null === $ this -> referenceBag ) { $ this -> referenceBag = new ReferenceBag ( $ this ) ; } return $ this -> referenceBag ; }

Returns the reference list associated to the repository.

@return ReferenceBag

Returns the reference list associated to the repository .


public function getCommit($hash)
    {
        if (!isset($this->objects[$hash])) {
            $this->objects[$hash] = new Commit($this, $hash);
        }

        return $this->objects[$hash];
    }

public function getCommit ( $ hash ) { if ( ! isset ( $ this -> objects [ $ hash ] ) ) { $ this -> objects [ $ hash ] = new Commit ( $ this , $ hash ) ; } return $ this -> objects [ $ hash ] ; }

Instanciates a commit object or fetches one from the cache.

@param string $hash A commit hash, with a length of 40

@return Commit

Instanciates a commit object or fetches one from the cache .


public function getTree($hash)
    {
        if (!isset($this->objects[$hash])) {
            $this->objects[$hash] = new Tree($this, $hash);
        }

        return $this->objects[$hash];
    }

public function getTree ( $ hash ) { if ( ! isset ( $ this -> objects [ $ hash ] ) ) { $ this -> objects [ $ hash ] = new Tree ( $ this , $ hash ) ; } return $ this -> objects [ $ hash ] ; }

Instanciates a tree object or fetches one from the cache.

@param string $hash A tree hash, with a length of 40

@return Tree

Instanciates a tree object or fetches one from the cache .


public function getBlob($hash)
    {
        if (!isset($this->objects[$hash])) {
            $this->objects[$hash] = new Blob($this, $hash);
        }

        return $this->objects[$hash];
    }

public function getBlob ( $ hash ) { if ( ! isset ( $ this -> objects [ $ hash ] ) ) { $ this -> objects [ $ hash ] = new Blob ( $ this , $ hash ) ; } return $ this -> objects [ $ hash ] ; }

Instanciates a blob object or fetches one from the cache.

@param string $hash A blob hash, with a length of 40

@return Blob

Instanciates a blob object or fetches one from the cache .


public function getLog($revisions = null, $paths = null, $offset = null, $limit = null)
    {
        return new Log($this, $revisions, $paths, $offset, $limit);
    }

public function getLog ( $ revisions = null , $ paths = null , $ offset = null , $ limit = null ) { return new Log ( $ this , $ revisions , $ paths , $ offset , $ limit ) ; }

Returns log for a given set of revisions and paths.

All those values can be null, meaning everything.

@param array $revisions An array of revisions to show logs from. Can be
any text value type
@param array $paths     Restrict log to modifications occurring on given
paths.
@param int   $offset    Start from a given offset in results.
@param int   $limit     Limit number of total results.

@return Log

Returns log for a given set of revisions and paths .


public function getSize()
    {
        $commandlineArguments = array('du', '-skc', $this->gitDir);
        $commandline = $this->normalizeCommandlineArguments($commandlineArguments);
        $process = new Process($commandline);
        $process->run();

        if (!preg_match('/(\d+)\s+total$/', trim($process->getOutput()), $vars)) {
            $message = sprintf("Unable to parse process output\ncommand: %s\noutput: %s", $process->getCommandLine(), $process->getOutput());

            if (null !== $this->logger) {
                $this->logger->error($message);
            }

            if (true === $this->debug) {
                throw new RuntimeException('unable to parse repository size output');
            }

            return;
        }

        return $vars[1];
    }

Returns the size of repository, in kilobytes.

@return int A sum, in kilobytes

@throws RuntimeException An error occurred while computing size

Returns the size of repository in kilobytes .


public function shell($command, array $env = array())
    {
        $argument = sprintf('%s \'%s\'', $command, $this->gitDir);

        $prefix = '';
        foreach ($env as $name => $value) {
            $prefix .= sprintf('export %s=%s;', escapeshellarg($name), escapeshellarg($value));
        }

        proc_open($prefix.'git shell -c '.escapeshellarg($argument), array(STDIN, STDOUT, STDERR), $pipes);
    }

public
function
shell
(
$
command
,
array
$
env
=
array
(
)
)
{
$
argument
=
sprintf
(
'%s \'%s\''
,
$
command
,
$
this
->
gitDir
)
;
$
prefix
=
''
;
foreach
(
$
env
as
$
name
=>
$
value
)
{
$
prefix
.=
sprintf
(
'export %s=%s;'
,
escapeshellarg
(
$
name
)
,
escapeshellarg
(
$
value
)
)
;
}
proc_open
(
$
prefix
.
'git shell -c '
.
escapeshellarg
(
$
argument
)
,
array
(
STDIN
,
STDOUT
,
STDERR
)
,
$
pipes
)
;
}

Executes a shell command on the repository, using PHP pipes.

@param string $command The command to execute

Executes a shell command on the repository using PHP pipes .


public function getDescription()
    {
        $file = $this->gitDir.'/description';
        $exists = is_file($file);

        if (null !== $this->logger && true === $this->debug) {
            if (false === $exists) {
                $this->logger->debug(sprintf('no description file in repository ("%s")', $file));
            } else {
                $this->logger->debug(sprintf('reading description file in repository ("%s")', $file));
            }
        }

        if (false === $exists) {
            return static::DEFAULT_DESCRIPTION;
        }

        return file_get_contents($this->gitDir.'/description');
    }

Returns description of repository from description file in git directory.

@return string The description

Returns description of repository from description file in git directory .


public function run($command, $args = array())
    {
        $process = $this->getProcess($command, $args);

        if ($this->logger) {
            $this->logger->info(sprintf('run command: %s "%s" ', $command, implode(' ', $args)));
            $before = microtime(true);
        }

        $process->run();

        $output = $process->getOutput();

        if ($this->logger && $this->debug) {
            $duration = microtime(true) - $before;
            $this->logger->debug(sprintf('last command (%s) duration: %sms', $command, sprintf('%.2f', $duration * 1000)));
            $this->logger->debug(sprintf('last command (%s) return code: %s', $command, $process->getExitCode()));
            $this->logger->debug(sprintf('last command (%s) output: %s', $command, $output));
        }

        if (!$process->isSuccessful()) {
            $error = sprintf("error while running %s\n output: \"%s\"", $command, $process->getErrorOutput());

            if ($this->logger) {
                $this->logger->error($error);
            }

            if ($this->debug) {
                throw new ProcessException($process);
            }

            return;
        }

        return $output;
    }

This command is a facility command. You can run any command
directly on git repository.

@param string $command Git command to run (checkout, branch, tag)
@param array  $args    Arguments of git command

@return string Output of a successful process or null if execution failed and debug-mode is disabled.

@throws RuntimeException Error while executing git command (debug-mode only)

This command is a facility command . You can run any command directly on git repository .


public function cloneTo($path, $bare = true, array $options = array())
    {
        return Admin::cloneTo($path, $this->gitDir, $bare, $options);
    }

public function cloneTo ( $ path , $ bare = true , array $ options = array ( ) ) { return Admin :: cloneTo ( $ path , $ this -> gitDir , $ bare , $ options ) ; }

Clones the current repository to a new directory and return instance of new repository.

@param string $path path to the new repository in which current repository will be cloned
@param bool   $bare flag indicating if repository is bare or has a working-copy

@return Repository the newly created repository

Clones the current repository to a new directory and return instance of new repository .


public function getParents()
    {
        $result = array();
        foreach ($this->getData('parentHashes') as $parentHash) {
            $result[] = $this->repository->getCommit($parentHash);
        }

        return $result;
    }

public function getParents ( ) { $ result = array ( ) ; foreach ( $ this -> getData ( 'parentHashes' ) as $ parentHash ) { $ result [ ] = $ this -> repository -> getCommit ( $ parentHash ) ; } return $ result ; }

Returns the parent commits.

@return array An array of Commit objects


public function getShortMessage($length = 50, $preserve = false, $separator = '...')
    {
        $message = $this->getData('subjectMessage');

        if (StringHelper::strlen($message) > $length) {
            if ($preserve && false !== ($breakpoint = StringHelper::strpos($message, ' ', $length))) {
                $length = $breakpoint;
            }

            return rtrim(StringHelper::substr($message, 0, $length)).$separator;
        }

        return $message;
    }

public
function
getShortMessage
(
$
length
=
50
,
$
preserve
=
false
,
$
separator
=
'...'
)
{
$
message
=
$
this
->
getData
(
'subjectMessage'
)
;
if
(
StringHelper
::
strlen
(
$
message
)
>
$
length
)
{
if
(
$
preserve
&&
false
!==
(
$
breakpoint
=
StringHelper
::
strpos
(
$
message
,
' '
,
$
length
)
)
)
{
$
length
=
$
breakpoint
;
}
return
rtrim
(
StringHelper
::
substr
(
$
message
,
0
,
$
length
)
)
.
$
separator
;
}
return
$
message
;
}

Returns the first line of the commit, and the first 50 characters.

Ported from https://github.com/fabpot/Twig-extensions/blob/d67bc7e69788795d7905b52d31188bbc1d390e01/lib/Twig/Extensions/Extension/Text.php#L52-L109

@param int    $length
@param bool   $preserve
@param string $separator

@return string

Returns the first line of the commit and the first 50 characters .


public function getIncludingBranches($local = true, $remote = true)
    {
        $arguments = array('--contains', $this->revision);

        if ($local && $remote) {
            $arguments[] = '-a';
        } elseif (!$local && $remote) {
            $arguments[] = '-r';
        } elseif (!$local && !$remote) {
            throw new InvalidArgumentException('You should a least set one argument to true');
        }

        try {
            $result = $this->repository->run('branch', $arguments);
        } catch (ProcessException $e) {
            return array();
        }

        if (!$result) {
            return array();
        }

        $branchesName = explode("\n", trim(str_replace('*', '', $result)));
        $branchesName = array_filter($branchesName, function ($v) {
            return false === StringHelper::strpos($v, '->');
        });
        $branchesName = array_map('trim', $branchesName);

        $references = $this->repository->getReferences();

        $branches = array();
        foreach ($branchesName as $branchName) {
            if (false === $local) {
                $branches[] = $references->getRemoteBranch($branchName);
            } elseif (0 === StringHelper::strrpos($branchName, 'remotes/')) {
                $branches[] = $references->getRemoteBranch(str_replace('remotes/', '', $branchName));
            } else {
                $branches[] = $references->getBranch($branchName);
            }
        }

        return $branches;
    }

Find branch containing the commit.

@param bool $local  set true to try to locate a commit on local repository
@param bool $remote set true to try to locate a commit on remote repository

@return array An array of Reference\Branch


public static function init($path, $bare = true, array $options = array())
    {
        $process = static::getProcess('init', array_merge(array('-q'), $bare ? array('--bare') : array(), array($path)), $options);

        $process->run();

        if (!$process->isSuccessFul()) {
            throw new RuntimeException(sprintf("Error on repository initialization, command wasn't successful (%s). Error output:\n%s", $process->getCommandLine(), $process->getErrorOutput()));
        }

        return new Repository($path, $options);
    }

Initializes a repository and returns the instance.

@param string $path    path to the repository
@param bool   $bare    indicate to create a bare repository
@param array  $options options for Repository creation

@return Repository

@throws RuntimeException Directory exists or not writable (only if debug=true)

Initializes a repository and returns the instance .


public static function isValidRepository($url, array $options = array())
    {
        $process = static::getProcess('ls-remote', array($url), $options);

        $process->run();

        return $process->isSuccessFul();
    }

public static function isValidRepository ( $ url , array $ options = array ( ) ) { $ process = static :: getProcess ( 'ls-remote' , array ( $ url ) , $ options ) ; $ process -> run ( ) ; return $ process -> isSuccessFul ( ) ; }

Checks the validity of a git repository url without cloning it.

This will use the `ls-remote` command of git against the given url.
Usually, this command returns 0 when successful, and 128 when the
repository is not found.

@param string $url     url of repository to check
@param array  $options options for Repository creation

@return bool true if url is valid

Checks the validity of a git repository url without cloning it .


public static function cloneTo($path, $url, $bare = true, array $options = array())
    {
        $args = $bare ? array('--bare') : array();

        return static::cloneRepository($path, $url, $args, $options);
    }

public static function cloneTo ( $ path , $ url , $ bare = true , array $ options = array ( ) ) { $ args = $ bare ? array ( '--bare' ) : array ( ) ; return static :: cloneRepository ( $ path , $ url , $ args , $ options ) ; }

Clone a repository to a local path.

@param string $path    indicates where to clone repository
@param string $url     url of repository to clone
@param bool   $bare    indicates if repository should be bare or have a working copy
@param array  $options options for Repository creation

@return Repository


public static function cloneBranchTo($path, $url, $branch, $bare = true, $options = array())
    {
        $args = array('--branch', $branch);
        if ($bare) {
            $args[] = '--bare';
        }

        return static::cloneRepository($path, $url, $args, $options);
    }

public static function cloneBranchTo ( $ path , $ url , $ branch , $ bare = true , $ options = array ( ) ) { $ args = array ( '--branch' , $ branch ) ; if ( $ bare ) { $ args [ ] = '--bare' ; } return static :: cloneRepository ( $ path , $ url , $ args , $ options ) ; }

Clone a repository branch to a local path.

@param string $path    indicates where to clone repository
@param string $url     url of repository to clone
@param string $branch  branch to clone
@param bool   $bare    indicates if repository should be bare or have a working copy
@param array  $options options for Repository creation

@return Repository

Clone a repository branch to a local path .


public static function cloneRepository($path, $url, array $args = array(), array $options = array())
    {
        $process = static::getProcess('clone', array_merge(array('-q'), $args, array($url, $path)), $options);

        $process->run();

        if (!$process->isSuccessFul()) {
            throw new RuntimeException(sprintf('Error while initializing repository: %s', $process->getErrorOutput()));
        }

        return new Repository($path, $options);
    }

Internal method to launch effective ``git clone`` command.

@param string $path    indicates where to clone repository
@param string $url     url of repository to clone
@param array  $args    arguments to be added to the command-line
@param array  $options options for Repository creation

@return Repository

Internal method to launch effective git clone command .


public function getGroupedLines()
    {
        $result = array();
        $commit = null;
        $current = array();

        foreach ($this->getLines() as $lineNumber => $line) {
            if ($commit !== $line->getCommit()) {
                if (count($current)) {
                    $result[] = array($commit, $current);
                }
                $commit = $line->getCommit();
                $current = array();
            }

            $current[$lineNumber] = $line;
        }

        if (count($current)) {
            $result[] = array($commit, $current);
        }

        return $result;
    }

public function getGroupedLines ( ) { $ result = array ( ) ; $ commit = null ; $ current = array ( ) ; foreach ( $ this -> getLines ( ) as $ lineNumber => $ line ) { if ( $ commit !== $ line -> getCommit ( ) ) { if ( count ( $ current ) ) { $ result [ ] = array ( $ commit , $ current ) ; } $ commit = $ line -> getCommit ( ) ; $ current = array ( ) ; } $ current [ $ lineNumber ] = $ line ; } if ( count ( $ current ) ) { $ result [ ] = array ( $ commit , $ current ) ; } return $ result ; }

Returns lines grouped by commit.

@return array a list of two-elements array (commit, lines)


public function getLines()
    {
        if (null !== $this->lines) {
            return $this->lines;
        }

        $args = array('-p');

        if (null !== $this->lineRange) {
            $args[] = '-L';
            $args[] = $this->lineRange;
        }

        $args[] = $this->revision->getRevision();
        $args[] = '--';
        $args[] = $this->file;

        $parser = new BlameParser($this->repository);
        $parser->parse($this->repository->run('blame', $args));
        $this->lines = $parser->lines;

        return $this->lines;
    }

public function getLines ( ) { if ( null !== $ this -> lines ) { return $ this -> lines ; } $ args = array ( '-p' ) ; if ( null !== $ this -> lineRange ) { $ args [ ] = '-L' ; $ args [ ] = $ this -> lineRange ; } $ args [ ] = $ this -> revision -> getRevision ( ) ; $ args [ ] = '--' ; $ args [ ] = $ this -> file ; $ parser = new BlameParser ( $ this -> repository ) ; $ parser -> parse ( $ this -> repository -> run ( 'blame' , $ args ) ) ; $ this -> lines = $ parser -> lines ; return $ this -> lines ; }

Returns all lines of the blame.

@return array


public function get($fullname)
    {
        $this->initialize();

        if (!isset($this->references[$fullname])) {
            throw new ReferenceNotFoundException($fullname);
        }

        return $this->references[$fullname];
    }

public function get ( $ fullname ) { $ this -> initialize ( ) ; if ( ! isset ( $ this -> references [ $ fullname ] ) ) { throw new ReferenceNotFoundException ( $ fullname ) ; } return $ this -> references [ $ fullname ] ; }

Returns a reference, by name.

@param string $fullname Fullname of the reference (refs/heads/master, for example).

@return Reference A reference object.


public function getBranches()
    {
        $this->initialize();

        $result = array();
        foreach ($this->references as $reference) {
            if ($reference instanceof Reference\Branch) {
                $result[] = $reference;
            }
        }

        return $result;
    }

public function getBranches ( ) { $ this -> initialize ( ) ; $ result = array ( ) ; foreach ( $ this -> references as $ reference ) { if ( $ reference instanceof Reference \ Branch ) { $ result [ ] = $ reference ; } } return $ result ; }


public function getLocalBranches()
    {
        $result = array();
        foreach ($this->getBranches() as $branch) {
            if ($branch->isLocal()) {
                $result[] = $branch;
            }
        }

        return $result;
    }

public function getLocalBranches ( ) { $ result = array ( ) ; foreach ( $ this -> getBranches ( ) as $ branch ) { if ( $ branch -> isLocal ( ) ) { $ result [ ] = $ branch ; } } return $ result ; }

Returns all locales branches.

@return array


public function getRemoteBranches()
    {
        $result = array();
        foreach ($this->getBranches() as $branch) {
            if ($branch->isRemote()) {
                $result[] = $branch;
            }
        }

        return $result;
    }

public function getRemoteBranches ( ) { $ result = array ( ) ; foreach ( $ this -> getBranches ( ) as $ branch ) { if ( $ branch -> isRemote ( ) ) { $ result [ ] = $ branch ; } } return $ result ; }

Returns all remote branches.

@return array


public function getContent()
    {
        if (null === $this->content) {
            $this->content = $this->repository->run('cat-file', array('-p', $this->hash));
        }

        return $this->content;
    }

public function getContent ( ) { if ( null === $ this -> content ) { $ this -> content = $ this -> repository -> run ( 'cat-file' , array ( '-p' , $ this -> hash ) ) ; } return $ this -> content ; }

Returns content of the blob.

@throws ProcessException Error occurred while getting content of blob


public function getMimetype()
    {
        if (null === $this->mimetype) {
            $finfo = new \finfo(FILEINFO_MIME);
            $this->mimetype = $finfo->buffer($this->getContent());
        }

        return $this->mimetype;
    }

public function getMimetype ( ) { if ( null === $ this -> mimetype ) { $ finfo = new \ finfo ( FILEINFO_MIME ) ; $ this -> mimetype = $ finfo -> buffer ( $ this -> getContent ( ) ) ; } return $ this -> mimetype ; }

Determine the mimetype of the blob.

@return string A mimetype


public function toArray()
    {
        return array(
            'rawDiff' => $this->rawDiff,
            'files' => array_map(
                function (File $file) {
                    return $file->toArray();
                },
                $this->files
            ),
        );
    }

public function toArray ( ) { return array ( 'rawDiff' => $ this -> rawDiff , 'files' => array_map ( function ( File $ file ) { return $ file -> toArray ( ) ; } , $ this -> files ) , ) ; }

Export a diff as array.

@return array The array


public function parse($text)
    {
        $text = str_replace(array("\r\n", "\r"), "\n", $text);

        foreach ($this->quoteHeadersRegex as $regex) {
            if (preg_match($regex, $text, $matches)) {
                $text = str_replace($matches[1], str_replace("\n", ' ', $matches[1]), $text);
            }
        }

        $fragment = null;
        $text_array = explode("\n", $text);
        while (($line = array_pop($text_array)) !== NULL) {
            $line = ltrim($line, "\n");

            if (!$this->isSignature($line)) {
                $line = rtrim($line);
            }

            if ($fragment) {
                $first = reset($fragment->lines);

                if ($this->isSignature($first)) {
                    $fragment->isSignature = true;
                    $this->addFragment($fragment);

                    $fragment = null;
                } elseif (empty($line) && $this->isQuoteHeader($first)) {
                    $fragment->isQuoted = true;
                    $this->addFragment($fragment);

                    $fragment = null;
                }
            }

            $isQuoted = $this->isQuote($line);

            if (null === $fragment || !$this->isFragmentLine($fragment, $line, $isQuoted)) {
                if ($fragment) {
                    $this->addFragment($fragment);
                }

                $fragment = new FragmentDTO();
                $fragment->isQuoted = $isQuoted;
            }

            array_unshift($fragment->lines, $line);
        }

        if ($fragment) {
            $this->addFragment($fragment);
        }

        $email = $this->createEmail($this->fragments);

        $this->fragments = array();

        return $email;
    }

public
function
parse
(
$
text
)
{
$
text
=
str_replace
(
array
(
"\r\n"
,
"\r"
)
,
"\n"
,
$
text
)
;
foreach
(
$
this
->
quoteHeadersRegex
as
$
regex
)
{
if
(
preg_match
(
$
regex
,
$
text
,
$
matches
)
)
{
$
text
=
str_replace
(
$
matches
[
1
]
,
str_replace
(
"\n"
,
' '
,
$
matches
[
1
]
)
,
$
text
)
;
}
}
$
fragment
=
;
$
text_array
=
explode
(
"\n"
,
$
text
)
;
while
(
(
$
line
=
array_pop
(
$
text_array
)
)
!==
)
{
$
line
=
ltrim
(
$
line
,
"\n"
)
;
if
(
!
$
this
->
isSignature
(
$
line
)
)
{
$
line
=
rtrim
(
$
line
)
;
}
if
(
$
fragment
)
{
$
first
=
reset
(
$
fragment
->
lines
)
;
if
(
$
this
->
isSignature
(
$
first
)
)
{
$
fragment
->
isSignature
=
true
;
$
this
->
addFragment
(
$
fragment
)
;
$
fragment
=
;
}
elseif
(
empty
(
$
line
)
&&
$
this
->
isQuoteHeader
(
$
first
)
)
{
$
fragment
->
isQuoted
=
true
;
$
this
->
addFragment
(
$
fragment
)
;
$
fragment
=
;
}
}
$
isQuoted
=
$
this
->
isQuote
(
$
line
)
;
if
(
===
$
fragment
||
!
$
this
->
isFragmentLine
(
$
fragment
,
$
line
,
$
isQuoted
)
)
{
if
(
$
fragment
)
{
$
this
->
addFragment
(
$
fragment
)
;
}
$
fragment
=
new
FragmentDTO
(
)
;
$
fragment
->
isQuoted
=
$
isQuoted
;
}
array_unshift
(
$
fragment
->
lines
,
$
line
)
;
}
if
(
$
fragment
)
{
$
this
->
addFragment
(
$
fragment
)
;
}
$
email
=
$
this
->
createEmail
(
$
this
->
fragments
)
;
$
this
->
fragments
=
array
(
)
;
return
$
email
;
}

Parse a text which represents an email and splits it into fragments.

@param string $text A text.

@return Email

Parse a text which represents an email and splits it into fragments .


public function writeFormatted(QueryInterface $query)
    {
        if (null === $this->sqlFormatter) {
            $this->sqlFormatter = (new \ReflectionClass($this->sqlFormatterClass))->newInstance();
        }

        return $this->sqlFormatter->format($this->write($query));
    }

public function writeFormatted ( QueryInterface $ query ) { if ( null === $ this -> sqlFormatter ) { $ this -> sqlFormatter = ( new \ ReflectionClass ( $ this -> sqlFormatterClass ) ) -> newInstance ( ) ; } return $ this -> sqlFormatter -> format ( $ this -> write ( $ query ) ) ; }

Returns a SQL string in a readable human-friendly format.

@param QueryInterface $query

@return string

Returns a SQL string in a readable human - friendly format .


public function writeColumnName(Column $column)
    {
        $name = $column->getName();

        if ($name === Column::ALL) {
            return $this->writeColumnAll();
        }

        return $name;
    }

public function writeColumnName ( Column $ column ) { $ name = $ column -> getName ( ) ; if ( $ name === Column :: ALL ) { return $ this -> writeColumnAll ( ) ; } return $ name ; }

Returns the column name.

@param Column $column

@return string


public static function createColumns(array &$arguments, $table = null)
    {
        $createdColumns = [];

        foreach ($arguments as $index => $column) {
            if (!is_object($column)) {
                $newColumn = array($column);
                $column = self::createColumn($newColumn, $table);
                if (!is_numeric($index)) {
                    $column->setAlias($index);
                }

                $createdColumns[] = $column;
            } else if ($column instanceof Column) {
                $createdColumns[] = $column;
            }
        }

        return \array_filter($createdColumns);
    }

public static function createColumns ( array & $ arguments , $ table = null ) { $ createdColumns = [ ] ; foreach ( $ arguments as $ index => $ column ) { if ( ! is_object ( $ column ) ) { $ newColumn = array ( $ column ) ; $ column = self :: createColumn ( $ newColumn , $ table ) ; if ( ! is_numeric ( $ index ) ) { $ column -> setAlias ( $ index ) ; } $ createdColumns [ ] = $ column ; } else if ( $ column instanceof Column ) { $ createdColumns [ ] = $ column ; } } return \ array_filter ( $ createdColumns ) ; }

Creates a collection of Column objects.

@param array      $arguments
@param Table|null $table

@return array

Creates a collection of Column objects .


public static function createColumn(array &$argument, $table = null)
    {
        $columnName = \array_values($argument);
        $columnName = $columnName[0];

        $columnAlias = \array_keys($argument);
        $columnAlias = $columnAlias[0];

        if (\is_numeric($columnAlias) || \strpos($columnName, '*') !== false) {
            $columnAlias = null;
        }

        return new Column($columnName, (string) $table, $columnAlias);
    }

public static function createColumn ( array & $ argument , $ table = null ) { $ columnName = \ array_values ( $ argument ) ; $ columnName = $ columnName [ 0 ] ; $ columnAlias = \ array_keys ( $ argument ) ; $ columnAlias = $ columnAlias [ 0 ] ; if ( \ is_numeric ( $ columnAlias ) || \ strpos ( $ columnName , '*' ) !== false ) { $ columnAlias = null ; } return new Column ( $ columnName , ( string ) $ table , $ columnAlias ) ; }

Creates a Column object.

@param array      $argument
@param null|Table $table

@return Column


public static function createTable($table)
    {
        $tableName = $table;
        if (\is_array($table)) {
            $tableName = \current($table);
            $tableAlias = \key($table);
        }

        $newTable = new Table($tableName);

        if (isset($tableAlias) && !is_numeric($tableAlias)) {
            $newTable->setAlias($tableAlias);
        }

        return $newTable;
    }

public static function createTable ( $ table ) { $ tableName = $ table ; if ( \ is_array ( $ table ) ) { $ tableName = \ current ( $ table ) ; $ tableAlias = \ key ( $ table ) ; } $ newTable = new Table ( $ tableName ) ; if ( isset ( $ tableAlias ) && ! is_numeric ( $ tableAlias ) ) { $ newTable -> setAlias ( $ tableAlias ) ; } return $ newTable ; }

Creates a Table object.

@param string[] $table

@return Table


public function getSql($formatted = false)
    {
        if ($formatted) {
            return $this->getBuilder()->writeFormatted($this);
        }

        return $this->getBuilder()->write($this);
    }

public function getSql ( $ formatted = false ) { if ( $ formatted ) { return $ this -> getBuilder ( ) -> writeFormatted ( $ this ) ; } return $ this -> getBuilder ( ) -> write ( $ this ) ; }

Converts this query into an SQL string by using the injected builder.
Optionally can return the SQL with formatted structure.

@param bool $formatted

@return string

Converts this query into an SQL string by using the injected builder . Optionally can return the SQL with formatted structure .


public static function bootCacheableEloquent(): void
    {
        static::updated(function (Model $cachedModel) {
            ! $cachedModel->isCacheClearEnabled() || $cachedModel::forgetCache();
        });

        static::created(function (Model $cachedModel) {
            ! $cachedModel->isCacheClearEnabled() || $cachedModel::forgetCache();
        });

        static::deleted(function (Model $cachedModel) {
            ! $cachedModel->isCacheClearEnabled() || $cachedModel::forgetCache();
        });
    }

public static function bootCacheableEloquent ( ) : void { static :: updated ( function ( Model $ cachedModel ) { ! $ cachedModel -> isCacheClearEnabled ( ) || $ cachedModel :: forgetCache ( ) ; } ) ; static :: created ( function ( Model $ cachedModel ) { ! $ cachedModel -> isCacheClearEnabled ( ) || $ cachedModel :: forgetCache ( ) ; } ) ; static :: deleted ( function ( Model $ cachedModel ) { ! $ cachedModel -> isCacheClearEnabled ( ) || $ cachedModel :: forgetCache ( ) ; } ) ; }

Boot the cacheable eloquent trait for a model.

@return void

Boot the cacheable eloquent trait for a model .


protected static function storeCacheKey(string $modelName, string $cacheKey): void
    {
        $keysFile = storage_path('framework/cache/data/rinvex.cacheable.json');
        $cacheKeys = static::getCacheKeys($keysFile);

        if (! isset($cacheKeys[$modelName]) || ! in_array($cacheKey, $cacheKeys[$modelName])) {
            $cacheKeys[$modelName][] = $cacheKey;
            file_put_contents($keysFile, json_encode($cacheKeys));
        }
    }

Store the given cache key for the given model by mimicking cache tags.

@param string $modelName
@param string $cacheKey

@return void

Store the given cache key for the given model by mimicking cache tags .


protected static function getCacheKeys($file): array
    {
        if (! file_exists($file)) {
            $dir = dirname($file);
            is_dir($dir) || mkdir($dir);
            file_put_contents($file, null);
        }

        return json_decode(file_get_contents($file), true) ?: [];
    }

protected static function getCacheKeys ( $ file ) : array { if ( ! file_exists ( $ file ) ) { $ dir = dirname ( $ file ) ; is_dir ( $ dir ) || mkdir ( $ dir ) ; file_put_contents ( $ file , null ) ; } return json_decode ( file_get_contents ( $ file ) , true ) ? : [ ] ; }

Get cache keys from the given file.

@param string $file

@return array


protected static function flushCacheKeys(string $modelName): array
    {
        $flushedKeys = [];
        $keysFile = storage_path('framework/cache/data/rinvex.cacheable.json');
        $cacheKeys = static::getCacheKeys($keysFile);

        if (isset($cacheKeys[$modelName])) {
            $flushedKeys = $cacheKeys[$modelName];

            unset($cacheKeys[$modelName]);

            file_put_contents($keysFile, json_encode($cacheKeys));
        }

        return $flushedKeys;
    }

Flush cache keys of the given model by mimicking cache tags.

@param string $modelName

@return array

Flush cache keys of the given model by mimicking cache tags .


public static function forgetCache()
    {
        static::fireCacheFlushEvent('cache.flushing');

        // Flush cache tags
        if (method_exists(app('cache')->getStore(), 'tags')) {
            app('cache')->tags(static::class)->flush();
        } else {
            // Flush cache keys, then forget actual cache
            foreach (static::flushCacheKeys(static::class) as $cacheKey) {
                app('cache')->forget($cacheKey);
            }
        }

        static::fireCacheFlushEvent('cache.flushed', false);
    }


public function resetCacheConfig()
    {
        ! $this->cacheDriver || $this->cacheDriver = null;
        ! $this->cacheLifetime || $this->cacheLifetime = -1;

        return $this;
    }

public function resetCacheConfig ( ) { ! $ this -> cacheDriver || $ this -> cacheDriver = null ; ! $ this -> cacheLifetime || $ this -> cacheLifetime = - 1 ; return $ this ; }

Reset cached model to its defaults.

@return $this


protected function generateCacheKey($builder, array $columns): string
    {
        $query = $builder instanceof Builder ? $builder->getQuery() : $builder;
        $vars = [
            'aggregate' => $query->aggregate,
            'columns' => $query->columns,
            'distinct' => $query->distinct,
            'from' => $query->from,
            'joins' => $query->joins,
            'wheres' => $query->wheres,
            'groups' => $query->groups,
            'havings' => $query->havings,
            'orders' => $query->orders,
            'limit' => $query->limit,
            'offset' => $query->offset,
            'unions' => $query->unions,
            'unionLimit' => $query->unionLimit,
            'unionOffset' => $query->unionOffset,
            'unionOrders' => $query->unionOrders,
            'lock' => $query->lock,
        ];

        return md5(json_encode([
            $vars,
            $columns,
            static::class,
            $this->getCacheDriver(),
            $this->getCacheLifetime(),
            $builder instanceof Builder ? $builder->getEagerLoads() : null,
            $builder->getBindings(),
            $builder->toSql(),
        ]));
    }

protected function generateCacheKey ( $ builder , array $ columns ) : string { $ query = $ builder instanceof Builder ? $ builder -> getQuery ( ) : $ builder ; $ vars = [ 'aggregate' => $ query -> aggregate , 'columns' => $ query -> columns , 'distinct' => $ query -> distinct , 'from' => $ query -> from , 'joins' => $ query -> joins , 'wheres' => $ query -> wheres , 'groups' => $ query -> groups , 'havings' => $ query -> havings , 'orders' => $ query -> orders , 'limit' => $ query -> limit , 'offset' => $ query -> offset , 'unions' => $ query -> unions , 'unionLimit' => $ query -> unionLimit , 'unionOffset' => $ query -> unionOffset , 'unionOrders' => $ query -> unionOrders , 'lock' => $ query -> lock , ] ; return md5 ( json_encode ( [ $ vars , $ columns , static :: class , $ this -> getCacheDriver ( ) , $ this -> getCacheLifetime ( ) , $ builder instanceof Builder ? $ builder -> getEagerLoads ( ) : null , $ builder -> getBindings ( ) , $ builder -> toSql ( ) , ] ) ) ; }

Generate unique cache key.

@param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder
@param array                                                                    $columns

@return string


public function cacheQuery($builder, array $columns, Closure $closure)
    {
        $modelName = $this->getMorphClass();
        $lifetime = $this->getCacheLifetime();
        $cacheKey = $this->generateCacheKey($builder, $columns);

        // Switch cache driver on runtime
        if ($driver = $this->getCacheDriver()) {
            app('cache')->setDefaultDriver($driver);
        }

        // We need cache tags, check if default driver supports it
        if (method_exists(app('cache')->getStore(), 'tags')) {
            $result = $lifetime === -1 ? app('cache')->tags($modelName)->rememberForever($cacheKey, $closure) : app('cache')->tags($modelName)->remember($cacheKey, $lifetime, $closure);

            return $result;
        }

        $result = $lifetime === -1 ? app('cache')->rememberForever($cacheKey, $closure) : app('cache')->remember($cacheKey, $lifetime, $closure);

        // Default cache driver doesn't support tags, let's do it manually
        static::storeCacheKey($modelName, $cacheKey);

        // We're done, let's clean up!
        $this->resetCacheConfig();

        return $result;
    }

Cache given callback.

@param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder
@param array                                                                    $columns
@param \Closure                                                                 $closure

@return mixed


public static function validate( HppRequest $hppRequest ) {
		self::Initialise();

		$violations = self::$validator->validate( $hppRequest );

		if ( $violations->count() > 0 ) {
			$validationMessages = array();

			foreach ( $violations as $violation ) {

				/* @var ConstraintViolationInterface $violation */
				$validationMessages[] = $violation->getMessage();
			}

			$message = "HppRequest failed validation with the following errors:";
			foreach ( $validationMessages as $validationMessage ) {
				$message .= $validationMessage . '.';
			}

			self::$logger->info( $message );
			throw new RealexValidationException( "HppRequest failed validation", $validationMessages );
		}

	}

Method validates HPP request object using JSR-303 bean validation.

@param HppRequest|HppResponse $hppRequest

Method validates HPP request object using JSR - 303 bean validation .


public static function validateResponse( HppResponse $hppResponse, $secret ) {
		self::Initialise();

		if ( ! $hppResponse->isHashValid( $secret ) ) {
			self::$logger->error( "HppResponse contains an invalid security hash." );
			throw new RealexValidationException( "HppResponse contains an invalid security hash", array( "HppResponse contains an invalid security hash" ) );
		}
	}

Method validates HPP response hash.

@param HppResponse $hppResponse
@param string $secret


public function addAutoSettleFlag( $autoSettleFlag ) {
		if ( is_bool( $autoSettleFlag ) ) {
			$this->autoSettleFlag = $autoSettleFlag ? Flag::TRUE : Flag::FALSE;
		} else {
			$this->autoSettleFlag = $autoSettleFlag;
		}

		return $this;
	}

public function addAutoSettleFlag ( $ autoSettleFlag ) { if ( is_bool ( $ autoSettleFlag ) ) { $ this -> autoSettleFlag = $ autoSettleFlag ? Flag :: TRUE : Flag :: FALSE ; } else { $ this -> autoSettleFlag = $ autoSettleFlag ; } return $ this ; }

Helper method for adding a autoSettleFlag

@param String|bool $autoSettleFlag

@return HppRequest


public function addReturnTss( $returnTss ) {
		if ( is_bool( $returnTss ) ) {
			$this->returnTss = $returnTss ? Flag::TRUE : Flag::FALSE;
		} else {
			$this->returnTss = $returnTss;
		}

		return $this;
	}

public function addReturnTss ( $ returnTss ) { if ( is_bool ( $ returnTss ) ) { $ this -> returnTss = $ returnTss ? Flag :: TRUE : Flag :: FALSE ; } else { $ this -> returnTss = $ returnTss ; } return $ this ; }

Helper method for adding a returnTss

@param String|bool $returnTss

@return HppRequest


public function addValidateCardOnly( $validateCardOnly ) {
		if ( is_bool( $validateCardOnly ) ) {
			$this->validateCardOnly = $validateCardOnly ? Flag::TRUE : Flag::FALSE;
		} else {
			$this->validateCardOnly = $validateCardOnly;
		}

		return $this;
	}

public function addValidateCardOnly ( $ validateCardOnly ) { if ( is_bool ( $ validateCardOnly ) ) { $ this -> validateCardOnly = $ validateCardOnly ? Flag :: TRUE : Flag :: FALSE ; } else { $ this -> validateCardOnly = $ validateCardOnly ; } return $ this ; }

Helper method for adding a validateCardOnly

@param String|bool $validateCardOnly

@return HppRequest


public function addDccEnable( $dccEnable ) {
		if ( is_bool( $dccEnable ) ) {
			$this->dccEnable = $dccEnable ? Flag::TRUE : Flag::FALSE;
		} else {
			$this->dccEnable = $dccEnable;
		}

		return $this;
	}

public function addDccEnable ( $ dccEnable ) { if ( is_bool ( $ dccEnable ) ) { $ this -> dccEnable = $ dccEnable ? Flag :: TRUE : Flag :: FALSE ; } else { $ this -> dccEnable = $ dccEnable ; } return $ this ; }

Helper method for adding a dccEnable

@param String $dccEnable

@return HppRequest


public function addCardStorageEnable( $cardStorageEnable ) {
		if ( is_bool( $cardStorageEnable ) ) {
			$this->cardStorageEnable = $cardStorageEnable ? Flag::TRUE : Flag::FALSE;
		} else {
			$this->cardStorageEnable = $cardStorageEnable;
		}

		return $this;
	}

public function addCardStorageEnable ( $ cardStorageEnable ) { if ( is_bool ( $ cardStorageEnable ) ) { $ this -> cardStorageEnable = $ cardStorageEnable ? Flag :: TRUE : Flag :: FALSE ; } else { $ this -> cardStorageEnable = $ cardStorageEnable ; } return $ this ; }

Helper method for adding a cardStorageEnable

@param mixed|bool $cardStorageEnable

@return HppRequest


public function addOfferSaveCard( $offerSaveCard ) {
		if ( is_bool( $offerSaveCard ) ) {
			$this->offerSaveCard = $offerSaveCard ? Flag::TRUE : Flag::FALSE;
		} else {
			$this->offerSaveCard = $offerSaveCard;
		}

		return $this;
	}

public function addOfferSaveCard ( $ offerSaveCard ) { if ( is_bool ( $ offerSaveCard ) ) { $ this -> offerSaveCard = $ offerSaveCard ? Flag :: TRUE : Flag :: FALSE ; } else { $ this -> offerSaveCard = $ offerSaveCard ; } return $ this ; }

Helper method for adding a offerSaveCard

@param string|bool $offerSaveCard

@return HppRequest


public function addPayerExists( $payerExists ) {
		if ( is_bool( $payerExists ) ) {
			$this->payerExists = $payerExists ? Flag::TRUE : Flag::FALSE;
		} else {
			$this->payerExists = $payerExists;
		}

		return $this;
	}

public function addPayerExists ( $ payerExists ) { if ( is_bool ( $ payerExists ) ) { $ this -> payerExists = $ payerExists ? Flag :: TRUE : Flag :: FALSE ; } else { $ this -> payerExists = $ payerExists ; } return $ this ; }

Helper method for adding a payerExists

@param string|bool $payerExists

@return HppRequest


public function addHppVersion( $hppVersion ){
		if ( is_bool( $hppVersion ) ) {
			$this->cardStorageEnable = $hppVersion ? Flag::TRUE : Flag::FALSE;
		} else {
			$this->hppVersion = $hppVersion;
		}

		return $this;
	}

public function addHppVersion ( $ hppVersion ) { if ( is_bool ( $ hppVersion ) ) { $ this -> cardStorageEnable = $ hppVersion ? Flag :: TRUE : Flag :: FALSE ; } else { $ this -> hppVersion = $ hppVersion ; } return $ this ; }

Helper method for adding the Hpp Version

@param string $hppVersion

@return HppRequest