function getDependencies(&$pkg)
    {
        if (is_object($pkg)) {
            $channel = strtolower($pkg->getChannel());
            $package = strtolower($pkg->getPackage());
        } else {
            $channel = strtolower($pkg['channel']);
            $package = strtolower($pkg['package']);
        }

        $data = $this->_getDepDB();
        if (isset($data['dependencies'][$channel][$package])) {
            return $data['dependencies'][$channel][$package];
        }

        return false;
    }

function getDependencies ( & $ pkg ) { if ( is_object ( $ pkg ) ) { $ channel = strtolower ( $ pkg -> getChannel ( ) ) ; $ package = strtolower ( $ pkg -> getPackage ( ) ) ; } else { $ channel = strtolower ( $ pkg [ 'channel' ] ) ; $ package = strtolower ( $ pkg [ 'package' ] ) ; } $ data = $ this -> _getDepDB ( ) ; if ( isset ( $ data [ 'dependencies' ] [ $ channel ] [ $ package ] ) ) { return $ data [ 'dependencies' ] [ $ channel ] [ $ package ] ; } return false ; }

Get a list of dependencies of this installed package
@param PEAR_PackageFile_v1|PEAR_PackageFile_v2|array
@return array|false


function installPackage(&$package)
    {
        $data = $this->_getDepDB();
        unset($this->_cache);
        $this->_setPackageDeps($data, $package);
        $this->_writeDepDB($data);
    }

function installPackage ( & $ package ) { $ data = $ this -> _getDepDB ( ) ; unset ( $ this -> _cache ) ; $ this -> _setPackageDeps ( $ data , $ package ) ; $ this -> _writeDepDB ( $ data ) ; }

Register dependencies of a package that is being installed or upgraded
@param PEAR_PackageFile_v2|PEAR_PackageFile_v2


function uninstallPackage(&$pkg)
    {
        $data = $this->_getDepDB();
        unset($this->_cache);
        if (is_object($pkg)) {
            $channel = strtolower($pkg->getChannel());
            $package = strtolower($pkg->getPackage());
        } else {
            $channel = strtolower($pkg['channel']);
            $package = strtolower($pkg['package']);
        }

        if (!isset($data['dependencies'][$channel][$package])) {
            return true;
        }

        foreach ($data['dependencies'][$channel][$package] as $dep) {
            $found      = false;
            $depchannel = isset($dep['dep']['uri']) ? '__uri' : strtolower($dep['dep']['channel']);
            $depname    = strtolower($dep['dep']['name']);
            if (isset($data['packages'][$depchannel][$depname])) {
                foreach ($data['packages'][$depchannel][$depname] as $i => $info) {
                    if ($info['channel'] == $channel && $info['package'] == $package) {
                        $found = true;
                        break;
                    }
                }
            }

            if ($found) {
                unset($data['packages'][$depchannel][$depname][$i]);
                if (!count($data['packages'][$depchannel][$depname])) {
                    unset($data['packages'][$depchannel][$depname]);
                    if (!count($data['packages'][$depchannel])) {
                        unset($data['packages'][$depchannel]);
                    }
                } else {
                    $data['packages'][$depchannel][$depname] =
                        array_values($data['packages'][$depchannel][$depname]);
                }
            }
        }

        unset($data['dependencies'][$channel][$package]);
        if (!count($data['dependencies'][$channel])) {
            unset($data['dependencies'][$channel]);
        }

        if (!count($data['dependencies'])) {
            unset($data['dependencies']);
        }

        if (!count($data['packages'])) {
            unset($data['packages']);
        }

        $this->_writeDepDB($data);
    }

function uninstallPackage ( & $ pkg ) { $ data = $ this -> _getDepDB ( ) ; unset ( $ this -> _cache ) ; if ( is_object ( $ pkg ) ) { $ channel = strtolower ( $ pkg -> getChannel ( ) ) ; $ package = strtolower ( $ pkg -> getPackage ( ) ) ; } else { $ channel = strtolower ( $ pkg [ 'channel' ] ) ; $ package = strtolower ( $ pkg [ 'package' ] ) ; } if ( ! isset ( $ data [ 'dependencies' ] [ $ channel ] [ $ package ] ) ) { return true ; } foreach ( $ data [ 'dependencies' ] [ $ channel ] [ $ package ] as $ dep ) { $ found = false ; $ depchannel = isset ( $ dep [ 'dep' ] [ 'uri' ] ) ? '__uri' : strtolower ( $ dep [ 'dep' ] [ 'channel' ] ) ; $ depname = strtolower ( $ dep [ 'dep' ] [ 'name' ] ) ; if ( isset ( $ data [ 'packages' ] [ $ depchannel ] [ $ depname ] ) ) { foreach ( $ data [ 'packages' ] [ $ depchannel ] [ $ depname ] as $ i => $ info ) { if ( $ info [ 'channel' ] == $ channel && $ info [ 'package' ] == $ package ) { $ found = true ; break ; } } } if ( $ found ) { unset ( $ data [ 'packages' ] [ $ depchannel ] [ $ depname ] [ $ i ] ) ; if ( ! count ( $ data [ 'packages' ] [ $ depchannel ] [ $ depname ] ) ) { unset ( $ data [ 'packages' ] [ $ depchannel ] [ $ depname ] ) ; if ( ! count ( $ data [ 'packages' ] [ $ depchannel ] ) ) { unset ( $ data [ 'packages' ] [ $ depchannel ] ) ; } } else { $ data [ 'packages' ] [ $ depchannel ] [ $ depname ] = array_values ( $ data [ 'packages' ] [ $ depchannel ] [ $ depname ] ) ; } } } unset ( $ data [ 'dependencies' ] [ $ channel ] [ $ package ] ) ; if ( ! count ( $ data [ 'dependencies' ] [ $ channel ] ) ) { unset ( $ data [ 'dependencies' ] [ $ channel ] ) ; } if ( ! count ( $ data [ 'dependencies' ] ) ) { unset ( $ data [ 'dependencies' ] ) ; } if ( ! count ( $ data [ 'packages' ] ) ) { unset ( $ data [ 'packages' ] ) ; } $ this -> _writeDepDB ( $ data ) ; }

Remove dependencies of a package that is being uninstalled, or upgraded.

Upgraded packages first uninstall, then install
@param PEAR_PackageFile_v1|PEAR_PackageFile_v2|array If an array, then it must have
indices 'channel' and 'package'

Remove dependencies of a package that is being uninstalled or upgraded .


function rebuildDB()
    {
        $depdb = array('_version' => $this->_version);
        if (!$this->hasWriteAccess()) {
            // allow startup for read-only with older Registry
            return $depdb;
        }

        $packages = $this->_registry->listAllPackages();
        if (PEAR::isError($packages)) {
            return $packages;
        }

        foreach ($packages as $channel => $ps) {
            foreach ($ps as $package) {
                $package = $this->_registry->getPackage($package, $channel);
                if (PEAR::isError($package)) {
                    return $package;
                }
                $this->_setPackageDeps($depdb, $package);
            }
        }

        $error = $this->_writeDepDB($depdb);
        if (PEAR::isError($error)) {
            return $error;
        }

        $this->_cache = $depdb;
        return true;
    }

Rebuild the dependency DB by reading registry entries.
@return true|PEAR_Error

Rebuild the dependency DB by reading registry entries .


function _lock($mode = LOCK_EX)
    {
        if (stristr(php_uname(), 'Windows 9')) {
            return true;
        }

        if ($mode != LOCK_UN && is_resource($this->_lockFp)) {
            // XXX does not check type of lock (LOCK_SH/LOCK_EX)
            return true;
        }

        $open_mode = 'w';
        // XXX People reported problems with LOCK_SH and 'w'
        if ($mode === LOCK_SH) {
            if (!file_exists($this->_lockfile)) {
                touch($this->_lockfile);
            } elseif (!is_file($this->_lockfile)) {
                return PEAR::raiseError('could not create Dependency lock file, ' .
                    'it exists and is not a regular file');
            }
            $open_mode = 'r';
        }

        if (!is_resource($this->_lockFp)) {
            $this->_lockFp = @fopen($this->_lockfile, $open_mode);
        }

        if (!is_resource($this->_lockFp)) {
            return PEAR::raiseError("could not create Dependency lock file" .
                                     (isset($php_errormsg) ? ": " . $php_errormsg : ""));
        }

        if (!(int)flock($this->_lockFp, $mode)) {
            switch ($mode) {
                case LOCK_SH: $str = 'shared';    break;
                case LOCK_EX: $str = 'exclusive'; break;
                case LOCK_UN: $str = 'unlock';    break;
                default:      $str = 'unknown';   break;
            }

            return PEAR::raiseError("could not acquire $str lock ($this->_lockfile)");
        }

        return true;
    }

Register usage of the dependency DB to prevent race conditions
@param int one of the LOCK_* constants
@return true|PEAR_Error
@access private


function _unlock()
    {
        $ret = $this->_lock(LOCK_UN);
        if (is_resource($this->_lockFp)) {
            fclose($this->_lockFp);
        }
        $this->_lockFp = null;
        return $ret;
    }

function _unlock ( ) { $ ret = $ this -> _lock ( LOCK_UN ) ; if ( is_resource ( $ this -> _lockFp ) ) { fclose ( $ this -> _lockFp ) ; } $ this -> _lockFp = null ; return $ ret ; }

Release usage of dependency DB
@return true|PEAR_Error
@access private


function _getDepDB()
    {
        if (!$this->hasWriteAccess()) {
            return array('_version' => $this->_version);
        }

        if (isset($this->_cache)) {
            return $this->_cache;
        }

        if (!$fp = fopen($this->_depdb, 'r')) {
            $err = PEAR::raiseError("Could not open dependencies file `".$this->_depdb."'");
            return $err;
        }

        $rt = get_magic_quotes_runtime();
        set_magic_quotes_runtime(0);
        clearstatcache();
        fclose($fp);
        $data = unserialize(file_get_contents($this->_depdb));
        set_magic_quotes_runtime($rt);
        $this->_cache = $data;
        return $data;
    }

function
_getDepDB
(
)
{
if
(
!
$
this
->
hasWriteAccess
(
)
)
{
return
array
(
'_version'
=>
$
this
->
_version
)
;
}
if
(
isset
(
$
this
->
_cache
)
)
{
return
$
this
->
_cache
;
}
if
(
!
$
fp
=
fopen
(
$
this
->
_depdb
,
'r'
)
)
{
$
err
=
PEAR
::
raiseError
(
"Could not open dependencies file `"
.
$
this
->
_depdb
.
"'"
)
;
return
$
err
;
}
$
rt
=
get_magic_quotes_runtime
(
)
;
set_magic_quotes_runtime
(
0
)
;
clearstatcache
(
)
;
fclose
(
$
fp
)
;
$
data
=
unserialize
(
file_get_contents
(
$
this
->
_depdb
)
)
;
set_magic_quotes_runtime
(
$
rt
)
;
$
this
->
_cache
=
$
data
;
return
$
data
;
}

Load the dependency database from disk, or return the cache
@return array|PEAR_Error

Load the dependency database from disk or return the cache


function _writeDepDB(&$deps)
    {
        if (PEAR::isError($e = $this->_lock(LOCK_EX))) {
            return $e;
        }

        if (!$fp = fopen($this->_depdb, 'wb')) {
            $this->_unlock();
            return PEAR::raiseError("Could not open dependencies file `".$this->_depdb."' for writing");
        }

        $rt = get_magic_quotes_runtime();
        set_magic_quotes_runtime(0);
        fwrite($fp, serialize($deps));
        set_magic_quotes_runtime($rt);
        fclose($fp);
        $this->_unlock();
        $this->_cache = $deps;
        return true;
    }

function
_writeDepDB
(
&
$
deps
)
{
if
(
PEAR
::
isError
(
$
e
=
$
this
->
_lock
(
LOCK_EX
)
)
)
{
return
$
e
;
}
if
(
!
$
fp
=
fopen
(
$
this
->
_depdb
,
'wb'
)
)
{
$
this
->
_unlock
(
)
;
return
PEAR
::
raiseError
(
"Could not open dependencies file `"
.
$
this
->
_depdb
.
"' for writing"
)
;
}
$
rt
=
get_magic_quotes_runtime
(
)
;
set_magic_quotes_runtime
(
0
)
;
fwrite
(
$
fp
,
serialize
(
$
deps
)
)
;
set_magic_quotes_runtime
(
$
rt
)
;
fclose
(
$
fp
)
;
$
this
->
_unlock
(
)
;
$
this
->
_cache
=
$
deps
;
return
true
;
}

Write out the dependency database to disk
@param array the database
@return true|PEAR_Error
@access private


protected function autoLoadModules()
    {
        $extDirectory = __DIR__ . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR;
        $extDirectories = glob($extDirectory . "*", GLOB_ONLYDIR);

        foreach ($extDirectories as $directory):
            if (basename($directory) === "core"):
                continue;
            endif;

            # Get className and classPath
            $className = substr(basename(glob($directory . "*/Theme*.php")[0]), 0, -4);
            $classPath = '\\NetLimeTheme\\Extensions\\' . $className;
            $this->registerModule($className, new $classPath());
        endforeach;
    }

protected
function
autoLoadModules
(
)
{
$
extDirectory
=
__DIR__
.
DIRECTORY_SEPARATOR
.
".."
.
DIRECTORY_SEPARATOR
;
$
extDirectories
=
glob
(
$
extDirectory
.
"*"
,
GLOB_ONLYDIR
)
;
foreach
(
$
extDirectories
as
$
directory
)
:
if
(
basename
(
$
directory
)
===
"core"
)
:
continue
;
endif
;
# Get className and classPath
$
className
=
substr
(
basename
(
glob
(
$
directory
.
"*/Theme*.php"
)
[
0
]
)
,
0
,
4
)
;
$
classPath
=
'\\NetLimeTheme\\Extensions\\'
.
$
className
;
$
this
->
registerModule
(
$
className
,
new
$
classPath
(
)
)
;
endforeach
;
}


public function registerModule($key, $instance)
    {
        do_action("before_theme_module_register");
        apply_filters("before_theme_module_init", $key, $instance);

        $this->modules[$key] = $instance;
        $this->module($key)->init();

        apply_filters("after_theme_module_init", $key, $instance);
        do_action("after_theme_module_register");
    }

public function registerModule ( $ key , $ instance ) { do_action ( "before_theme_module_register" ) ; apply_filters ( "before_theme_module_init" , $ key , $ instance ) ; $ this -> modules [ $ key ] = $ instance ; $ this -> module ( $ key ) -> init ( ) ; apply_filters ( "after_theme_module_init" , $ key , $ instance ) ; do_action ( "after_theme_module_register" ) ; }

Register theme module

@param $key string Register module under this key
@param $instance


public function getContent($location)
    {
        do_action("before_theme_get_content");
        apply_filters("before_theme_get_content", $location);

        foreach ($this->sections as $section_data):

            # Skip if section is not in given location
            if ($section_data[1] !== $location):
                continue;
            endif;

            # Render it
            $this->renderSection($section_data[0]);

        endforeach;

        apply_filters("after_theme_get_content", $location);
        do_action("after_theme_get_content");
    }

Render sections of given location inside wrapper

@param $location string Render sections on this location


public function actionError(RequestApplicationInterface $app, \Throwable $exception) {
        return $this->render($app, 'view', [
            'exception' => $exception,
            'exceptionName' => $this->getExceptionName($exception),
        ], true);
    }

public function actionError ( RequestApplicationInterface $ app , \ Throwable $ exception ) { return $ this -> render ( $ app , 'view' , [ 'exception' => $ exception , 'exceptionName' => $ this -> getExceptionName ( $ exception ) , ] , true ) ; }

Error action default
@CtrlAction(path="/error")
@param RequestApplicationInterface $app
@param \Throwable                  $exception
@return \Reaction\Web\ResponseBuilderInterface|string


public function setForeground(FormatForeground $foreground = null): void
    {
        if (null === $foreground) {
            $this->foreground = null;

            return;
        }

        $this->foreground = $foreground->getValue();
    }

public function setForeground ( FormatForeground $ foreground = null ) : void { if ( null === $ foreground ) { $ this -> foreground = null ; return ; } $ this -> foreground = $ foreground -> getValue ( ) ; }

Set the foreground.

@param FormatForeground $foreground The foreground color

@return void


public function setBackground(FormatBackground $background = null): void
    {
        if (null === $background) {
            $this->background = null;

            return;
        }

        $this->background = $background->getValue();
    }

public function setBackground ( FormatBackground $ background = null ) : void { if ( null === $ background ) { $ this -> background = null ; return ; } $ this -> background = $ background -> getValue ( ) ; }

Set the background.

@param FormatBackground $background The background

@return void


public function black(bool $background = null): void
    {
        $this->setColor(
            $background ? FormatBackground::BLACK : FormatForeground::BLACK,
            $background
        );
    }

public function black ( bool $ background = null ) : void { $ this -> setColor ( $ background ? FormatBackground :: BLACK : FormatForeground :: BLACK , $ background ) ; }

Set foreground or background to black.

@param bool $background [optional] Whether this is to set the background

@return void


public function red(bool $background = null): void
    {
        $this->setColor(
            $background ? FormatBackground::RED : FormatForeground::RED,
            $background
        );
    }

public function red ( bool $ background = null ) : void { $ this -> setColor ( $ background ? FormatBackground :: RED : FormatForeground :: RED , $ background ) ; }

Set foreground or background to red.

@param bool $background [optional] Whether this is to set the background

@return void


public function green(bool $background = null): void
    {
        $this->setColor(
            $background ? FormatBackground::GREEN : FormatForeground::GREEN,
            $background
        );
    }

public function green ( bool $ background = null ) : void { $ this -> setColor ( $ background ? FormatBackground :: GREEN : FormatForeground :: GREEN , $ background ) ; }

Set foreground or background to green.

@param bool $background [optional] Whether this is to set the background

@return void


public function yellow(bool $background = null): void
    {
        $this->setColor(
            $background ? FormatBackground::YELLOW : FormatForeground::YELLOW,
            $background
        );
    }

public function yellow ( bool $ background = null ) : void { $ this -> setColor ( $ background ? FormatBackground :: YELLOW : FormatForeground :: YELLOW , $ background ) ; }

Set foreground or background to yellow.

@param bool $background [optional] Whether this is to set the background

@return void

Set foreground or background to yellow .


public function blue(bool $background = null): void
    {
        $this->setColor(
            $background ? FormatBackground::BLUE : FormatForeground::BLUE,
            $background
        );
    }

public function blue ( bool $ background = null ) : void { $ this -> setColor ( $ background ? FormatBackground :: BLUE : FormatForeground :: BLUE , $ background ) ; }

Set foreground or background to blue.

@param bool $background [optional] Whether this is to set the background

@return void


public function magenta(bool $background = null): void
    {
        $this->setColor(
            $background ? FormatBackground::MAGENTA : FormatForeground::MAGENTA,
            $background
        );
    }

public function magenta ( bool $ background = null ) : void { $ this -> setColor ( $ background ? FormatBackground :: MAGENTA : FormatForeground :: MAGENTA , $ background ) ; }

Set foreground or background to magenta.

@param bool $background [optional] Whether this is to set the background

@return void

Set foreground or background to magenta .


public function cyan(bool $background = null): void
    {
        $this->setColor(
            $background ? FormatBackground::CYAN : FormatForeground::CYAN,
            $background
        );
    }

public function cyan ( bool $ background = null ) : void { $ this -> setColor ( $ background ? FormatBackground :: CYAN : FormatForeground :: CYAN , $ background ) ; }

Set foreground or background to cyan.

@param bool $background [optional] Whether this is to set the background

@return void


public function white(bool $background = null): void
    {
        $this->setColor(
            $background ? FormatBackground::WHITE : FormatForeground::WHITE,
            $background
        );
    }

public function white ( bool $ background = null ) : void { $ this -> setColor ( $ background ? FormatBackground :: WHITE : FormatForeground :: WHITE , $ background ) ; }

Set foreground or background to white.

@param bool $background [optional] Whether this is to set the background

@return void


public function resetColor(bool $background = null): void
    {
        $this->setColor(
            $background ? FormatBackground::DEFAULT : FormatForeground::DEFAULT,
            $background
        );
    }

public function resetColor ( bool $ background = null ) : void { $ this -> setColor ( $ background ? FormatBackground :: DEFAULT : FormatForeground :: DEFAULT , $ background ) ; }

Set foreground or background to default.

@param bool $background [optional] Whether this is to set the background

@return void

Set foreground or background to default .


protected function setColor(int $color, bool $background = null): void
    {
        if (null !== $background) {
            $this->background = $color;

            return;
        }

        $this->foreground = $color;
    }

protected function setColor ( int $ color , bool $ background = null ) : void { if ( null !== $ background ) { $ this -> background = $ color ; return ; } $ this -> foreground = $ color ; }

Set a color.

@param int  $color      The color
@param bool $background [optional] Whether this is to set the background

@return void


public function removeOption(FormatOption $option): void
    {
        if ($this->hasOption($option)) {
            unset($this->options[$option->getValue()]);
        }
    }

public function removeOption ( FormatOption $ option ) : void { if ( $ this -> hasOption ( $ option ) ) { unset ( $ this -> options [ $ option -> getValue ( ) ] ) ; } }

Remove an option.

@param FormatOption $option The option

@return void


public function format(string $message): string
    {
        $set   = [];
        $unset = [];

        // Check if a foreground was specified
        if (null !== $this->foreground) {
            $set[]   = $this->foreground;
            $unset[] = FormatForeground::DEFAULT;
        }

        // Check if a background was specified
        if (null !== $this->background) {
            $set[]   = $this->background;
            $unset[] = FormatBackground::DEFAULT;
        }

        // Check if options were specified
        if (\count($this->options)) {
            // Iterate through all the options
            foreach ($this->options as $option) {
                $set[]   = $option;
                $unset[] = FormatOption::DEFAULT[$option];
            }
        }

        // No need to format if there's nothing to set
        if (0 === \count($set)) {
            return $message;
        }

        return sprintf(
            "\033[%sm%s\033[%sm",
            implode(';', $set),
            $message,
            implode(';', $unset)
        );
    }

Format a message.

@param string $message The message

@return string


public function logCommand($command, $duration, $connection, $error = false)
    {
        ++$this->commandCount;

        if (null !== $this->logger) {
            $this->commands[] = [
                'cmd' => $command,
                'executionMS' => $duration,
                'conn' => $connection,
                'error' => $error
            ];

            if ($error) {
                $this->logger->error('Command "' . $command . '" failed (' . $error . ')');
            } else {
                $this->logger->debug('Executing command "' . $command . '"');
            }
        }
    }

public
function
logCommand
(
$
command
,
$
duration
,
$
connection
,
$
error
=
false
)
{
++
$
this
->
commandCount
;
if
(
!==
$
this
->
logger
)
{
$
this
->
commands
[
]
=
[
'cmd'
=>
$
command
,
'executionMS'
=>
$
duration
,
'conn'
=>
$
connection
,
'error'
=>
$
error
]
;
if
(
$
error
)
{
$
this
->
logger
->
error
(
'Command "'
.
$
command
.
'" failed ('
.
$
error
.
')'
)
;
}
else
{
$
this
->
logger
->
debug
(
'Executing command "'
.
$
command
.
'"'
)
;
}
}
}

Logs a command

@param string      $command    Redis command
@param float       $duration   Duration in milliseconds
@param string      $connection Connection alias
@param bool|string $error      Error message or false if command was successful


private static function getUploadedFileLeaves(array $uploaded_files)
    {
        $new_file = [];

        if (isset($uploaded_files['tmp_name']) && !is_array($uploaded_files['tmp_name'])) {
            $new_file = new UploadedFile(
                $uploaded_files['name'] ?? null,
                $uploaded_files['type'] ?? null,
                $uploaded_files['tmp_name'] ?? null,
                $uploaded_files['error'] ?? null,
                $uploaded_files['size'] ?? null,
                true
            );
        } elseif (isset($uploaded_files['tmp_name'][0])) {
            foreach ($uploaded_files['tmp_name'] as $key => $value) {
                $new_file[$key] = new UploadedFile(
                    $uploaded_files['name'][$key] ?? null,
                    $uploaded_files['name'][$key] ?? null,
                    $uploaded_files['tmp_name'][$key] ?? null,
                    $uploaded_files['error'][$key] ?? null,
                    $uploaded_files['size'][$key] ?? null,
                    true
                );
            }
        } else {
            foreach (array_keys($uploaded_files['tmp_name']) as $index) {
                $new_array = array_combine(
                    array_keys($uploaded_files),
                    array_column($uploaded_files, $index)
                );

                $new_file[$index] = static::getUploadedFileLeaves($new_array);
            }
        }

        return $new_file;
    }

private static function getUploadedFileLeaves ( array $ uploaded_files ) { $ new_file = [ ] ; if ( isset ( $ uploaded_files [ 'tmp_name' ] ) && ! is_array ( $ uploaded_files [ 'tmp_name' ] ) ) { $ new_file = new UploadedFile ( $ uploaded_files [ 'name' ] ?? null , $ uploaded_files [ 'type' ] ?? null , $ uploaded_files [ 'tmp_name' ] ?? null , $ uploaded_files [ 'error' ] ?? null , $ uploaded_files [ 'size' ] ?? null , true ) ; } elseif ( isset ( $ uploaded_files [ 'tmp_name' ] [ 0 ] ) ) { foreach ( $ uploaded_files [ 'tmp_name' ] as $ key => $ value ) { $ new_file [ $ key ] = new UploadedFile ( $ uploaded_files [ 'name' ] [ $ key ] ?? null , $ uploaded_files [ 'name' ] [ $ key ] ?? null , $ uploaded_files [ 'tmp_name' ] [ $ key ] ?? null , $ uploaded_files [ 'error' ] [ $ key ] ?? null , $ uploaded_files [ 'size' ] [ $ key ] ?? null , true ) ; } } else { foreach ( array_keys ( $ uploaded_files [ 'tmp_name' ] ) as $ index ) { $ new_array = array_combine ( array_keys ( $ uploaded_files ) , array_column ( $ uploaded_files , $ index ) ) ; $ new_file [ $ index ] = static :: getUploadedFileLeaves ( $ new_array ) ; } } return $ new_file ; }

Parse uploaded file.

@param array $uploaded_files The non-normalized tree of uploaded file data.
@return UploadedFile[]|UploadedFile An array of UploadedFile instances or a single instance of UploadedFile.


function setRawState($state)
    {
        if (!isset($this->_packageInfo['stability'])) {
            $this->_packageInfo['stability'] = array();
        }
        $this->_packageInfo['stability']['release'] = $state;
    }

function setRawState ( $ state ) { if ( ! isset ( $ this -> _packageInfo [ 'stability' ] ) ) { $ this -> _packageInfo [ 'stability' ] = array ( ) ; } $ this -> _packageInfo [ 'stability' ] [ 'release' ] = $ state ; }

WARNING - do not use this function unless you know what you're doing

WARNING - do not use this function unless you know what you re doing


function listPostinstallScripts()
    {
        $filelist = $this->getFilelist();
        $contents = $this->getContents();
        $contents = $contents['dir']['file'];
        if (!is_array($contents) || !isset($contents[0])) {
            $contents = array($contents);
        }
        $taskfiles = array();
        foreach ($contents as $file) {
            $atts = $file['attribs'];
            unset($file['attribs']);
            if (count($file)) {
                $taskfiles[$atts['name']] = $file;
            }
        }
        $common = new PEAR_Common;
        $common->debug = $this->_config->get('verbose');
        $this->_scripts = array();
        $ret = array();
        foreach ($taskfiles as $name => $tasks) {
            if (!isset($filelist[$name])) {
                // ignored files will not be in the filelist
                continue;
            }
            $atts = $filelist[$name];
            foreach ($tasks as $tag => $raw) {
                $task = $this->getTask($tag);
                $task = &new $task($this->_config, $common, PEAR_TASK_INSTALL);
                if ($task->isScript()) {
                    $ret[] = $filelist[$name]['installed_as'];
                }
            }
        }
        if (count($ret)) {
            return $ret;
        }
        return false;
    }

Determines whether this package.xml has post-install scripts or not
@return array|false

Determines whether this package . xml has post - install scripts or not


function initPostinstallScripts()
    {
        $filelist = $this->getFilelist();
        $contents = $this->getContents();
        $contents = $contents['dir']['file'];
        if (!is_array($contents) || !isset($contents[0])) {
            $contents = array($contents);
        }
        $taskfiles = array();
        foreach ($contents as $file) {
            $atts = $file['attribs'];
            unset($file['attribs']);
            if (count($file)) {
                $taskfiles[$atts['name']] = $file;
            }
        }
        $common = new PEAR_Common;
        $common->debug = $this->_config->get('verbose');
        $this->_scripts = array();
        foreach ($taskfiles as $name => $tasks) {
            if (!isset($filelist[$name])) {
                // file was not installed due to installconditions
                continue;
            }
            $atts = $filelist[$name];
            foreach ($tasks as $tag => $raw) {
                $taskname = $this->getTask($tag);
                $task = &new $taskname($this->_config, $common, PEAR_TASK_INSTALL);
                if (!$task->isScript()) {
                    continue; // scripts are only handled after installation
                }
                $lastversion = isset($this->_packageInfo['_lastversion']) ?
                    $this->_packageInfo['_lastversion'] : null;
                $task->init($raw, $atts, $lastversion);
                $res = $task->startSession($this, $atts['installed_as']);
                if (!$res) {
                    continue; // skip this file
                }
                if (PEAR::isError($res)) {
                    return $res;
                }
                $assign = &$task;
                $this->_scripts[] = &$assign;
            }
        }
        if (count($this->_scripts)) {
            return true;
        }
        return false;
    }

Initialize post-install scripts for running

This method can be used to detect post-install scripts, as the return value
indicates whether any exist
@return bool

Initialize post - install scripts for running


function fromArray($pinfo)
    {
        unset($pinfo['old']);
        unset($pinfo['xsdversion']);
        // If the changelog isn't an array then it was passed in as an empty tag
        if (isset($pinfo['changelog']) && !is_array($pinfo['changelog'])) {
          unset($pinfo['changelog']);
        }
        $this->_incomplete = false;
        $this->_packageInfo = $pinfo;
    }

Directly set the array that defines this packagefile

WARNING: no validation.  This should only be performed by internal methods
inside PEAR or by inputting an array saved from an existing PEAR_PackageFile_v2
@param array


function getFilelist($preserve = false)
    {
        if (isset($this->_packageInfo['filelist']) && !$preserve) {
            return $this->_packageInfo['filelist'];
        }
        $this->flattenFilelist();
        if ($contents = $this->getContents()) {
            $ret = array();
            if (!isset($contents['dir'])) {
                return false;
            }
            if (!isset($contents['dir']['file'][0])) {
                $contents['dir']['file'] = array($contents['dir']['file']);
            }
            foreach ($contents['dir']['file'] as $file) {
                $name = $file['attribs']['name'];
                if (!$preserve) {
                    $file = $file['attribs'];
                }
                $ret[$name] = $file;
            }
            if (!$preserve) {
                $this->_packageInfo['filelist'] = $ret;
            }
            return $ret;
        }
        return false;
    }

function getFilelist ( $ preserve = false ) { if ( isset ( $ this -> _packageInfo [ 'filelist' ] ) && ! $ preserve ) { return $ this -> _packageInfo [ 'filelist' ] ; } $ this -> flattenFilelist ( ) ; if ( $ contents = $ this -> getContents ( ) ) { $ ret = array ( ) ; if ( ! isset ( $ contents [ 'dir' ] ) ) { return false ; } if ( ! isset ( $ contents [ 'dir' ] [ 'file' ] [ 0 ] ) ) { $ contents [ 'dir' ] [ 'file' ] = array ( $ contents [ 'dir' ] [ 'file' ] ) ; } foreach ( $ contents [ 'dir' ] [ 'file' ] as $ file ) { $ name = $ file [ 'attribs' ] [ 'name' ] ; if ( ! $ preserve ) { $ file = $ file [ 'attribs' ] ; } $ ret [ $ name ] = $ file ; } if ( ! $ preserve ) { $ this -> _packageInfo [ 'filelist' ] = $ ret ; } return $ ret ; } return false ; }

This should only be used to retrieve filenames and install attributes


function getConfigureOptions()
    {
        if ($this->getPackageType() != 'extsrc' && $this->getPackageType() != 'zendextsrc') {
            return false;
        }

        $releases = $this->getReleases();
        if (isset($releases[0])) {
            $releases = $releases[0];
        }

        if (isset($releases['configureoption'])) {
            if (!isset($releases['configureoption'][0])) {
                $releases['configureoption'] = array($releases['configureoption']);
            }

            for ($i = 0; $i < count($releases['configureoption']); $i++) {
                $releases['configureoption'][$i] = $releases['configureoption'][$i]['attribs'];
            }

            return $releases['configureoption'];
        }

        return false;
    }

function getConfigureOptions ( ) { if ( $ this -> getPackageType ( ) != 'extsrc' && $ this -> getPackageType ( ) != 'zendextsrc' ) { return false ; } $ releases = $ this -> getReleases ( ) ; if ( isset ( $ releases [ 0 ] ) ) { $ releases = $ releases [ 0 ] ; } if ( isset ( $ releases [ 'configureoption' ] ) ) { if ( ! isset ( $ releases [ 'configureoption' ] [ 0 ] ) ) { $ releases [ 'configureoption' ] = array ( $ releases [ 'configureoption' ] ) ; } for ( $ i = 0 ; $ i < count ( $ releases [ 'configureoption' ] ) ; $ i ++ ) { $ releases [ 'configureoption' ] [ $ i ] = $ releases [ 'configureoption' ] [ $ i ] [ 'attribs' ] ; } return $ releases [ 'configureoption' ] ; } return false ; }

Return configure options array, if any

@return array|false


function isCompatible($pf)
    {
        if (!isset($this->_packageInfo['compatible'])) {
            return false;
        }
        if (!isset($this->_packageInfo['channel'])) {
            return false;
        }
        $me = $pf->getVersion();
        $compatible = $this->_packageInfo['compatible'];
        if (!isset($compatible[0])) {
            $compatible = array($compatible);
        }
        $found = false;
        foreach ($compatible as $info) {
            if (strtolower($info['name']) == strtolower($pf->getPackage())) {
                if (strtolower($info['channel']) == strtolower($pf->getChannel())) {
                    $found = true;
                    break;
                }
            }
        }
        if (!$found) {
            return false;
        }
        if (isset($info['exclude'])) {
            if (!isset($info['exclude'][0])) {
                $info['exclude'] = array($info['exclude']);
            }
            foreach ($info['exclude'] as $exclude) {
                if (version_compare($me, $exclude, '==')) {
                    return false;
                }
            }
        }
        if (version_compare($me, $info['min'], '>=') && version_compare($me, $info['max'], '<=')) {
            return true;
        }
        return false;
    }

function isCompatible ( $ pf ) { if ( ! isset ( $ this -> _packageInfo [ 'compatible' ] ) ) { return false ; } if ( ! isset ( $ this -> _packageInfo [ 'channel' ] ) ) { return false ; } $ me = $ pf -> getVersion ( ) ; $ compatible = $ this -> _packageInfo [ 'compatible' ] ; if ( ! isset ( $ compatible [ 0 ] ) ) { $ compatible = array ( $ compatible ) ; } $ found = false ; foreach ( $ compatible as $ info ) { if ( strtolower ( $ info [ 'name' ] ) == strtolower ( $ pf -> getPackage ( ) ) ) { if ( strtolower ( $ info [ 'channel' ] ) == strtolower ( $ pf -> getChannel ( ) ) ) { $ found = true ; break ; } } } if ( ! $ found ) { return false ; } if ( isset ( $ info [ 'exclude' ] ) ) { if ( ! isset ( $ info [ 'exclude' ] [ 0 ] ) ) { $ info [ 'exclude' ] = array ( $ info [ 'exclude' ] ) ; } foreach ( $ info [ 'exclude' ] as $ exclude ) { if ( version_compare ( $ me , $ exclude , '==' ) ) { return false ; } } } if ( version_compare ( $ me , $ info [ 'min' ] , '>=' ) && version_compare ( $ me , $ info [ 'max' ] , '<=' ) ) { return true ; } return false ; }

Determines whether this package claims it is compatible with the version of
the package that has a recommended version dependency
@param PEAR_PackageFile_v2|PEAR_PackageFile_v1|PEAR_Downloader_Package
@return boolean


function isSubpackage($p)
    {
        $sub = array();
        if (isset($this->_packageInfo['dependencies']['required']['subpackage'])) {
            $sub = $this->_packageInfo['dependencies']['required']['subpackage'];
            if (!isset($sub[0])) {
                $sub = array($sub);
            }
        }
        if (isset($this->_packageInfo['dependencies']['optional']['subpackage'])) {
            $sub1 = $this->_packageInfo['dependencies']['optional']['subpackage'];
            if (!isset($sub1[0])) {
                $sub1 = array($sub1);
            }
            $sub = array_merge($sub, $sub1);
        }
        if (isset($this->_packageInfo['dependencies']['group'])) {
            $group = $this->_packageInfo['dependencies']['group'];
            if (!isset($group[0])) {
                $group = array($group);
            }
            foreach ($group as $deps) {
                if (isset($deps['subpackage'])) {
                    $sub2 = $deps['subpackage'];
                    if (!isset($sub2[0])) {
                        $sub2 = array($sub2);
                    }
                    $sub = array_merge($sub, $sub2);
                }
            }
        }
        foreach ($sub as $dep) {
            if (strtolower($dep['name']) == strtolower($p->getPackage())) {
                if (isset($dep['channel'])) {
                    if (strtolower($dep['channel']) == strtolower($p->getChannel())) {
                        return true;
                    }
                } else {
                    if ($dep['uri'] == $p->getURI()) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

function isSubpackage ( $ p ) { $ sub = array ( ) ; if ( isset ( $ this -> _packageInfo [ 'dependencies' ] [ 'required' ] [ 'subpackage' ] ) ) { $ sub = $ this -> _packageInfo [ 'dependencies' ] [ 'required' ] [ 'subpackage' ] ; if ( ! isset ( $ sub [ 0 ] ) ) { $ sub = array ( $ sub ) ; } } if ( isset ( $ this -> _packageInfo [ 'dependencies' ] [ 'optional' ] [ 'subpackage' ] ) ) { $ sub1 = $ this -> _packageInfo [ 'dependencies' ] [ 'optional' ] [ 'subpackage' ] ; if ( ! isset ( $ sub1 [ 0 ] ) ) { $ sub1 = array ( $ sub1 ) ; } $ sub = array_merge ( $ sub , $ sub1 ) ; } if ( isset ( $ this -> _packageInfo [ 'dependencies' ] [ 'group' ] ) ) { $ group = $ this -> _packageInfo [ 'dependencies' ] [ 'group' ] ; if ( ! isset ( $ group [ 0 ] ) ) { $ group = array ( $ group ) ; } foreach ( $ group as $ deps ) { if ( isset ( $ deps [ 'subpackage' ] ) ) { $ sub2 = $ deps [ 'subpackage' ] ; if ( ! isset ( $ sub2 [ 0 ] ) ) { $ sub2 = array ( $ sub2 ) ; } $ sub = array_merge ( $ sub , $ sub2 ) ; } } } foreach ( $ sub as $ dep ) { if ( strtolower ( $ dep [ 'name' ] ) == strtolower ( $ p -> getPackage ( ) ) ) { if ( isset ( $ dep [ 'channel' ] ) ) { if ( strtolower ( $ dep [ 'channel' ] ) == strtolower ( $ p -> getChannel ( ) ) ) { return true ; } } else { if ( $ dep [ 'uri' ] == $ p -> getURI ( ) ) { return true ; } } } } return false ; }

Determines whether the passed in package is a subpackage of this package.

No version checking is done, only name verification.
@param PEAR_PackageFile_v1|PEAR_PackageFile_v2
@return bool

Determines whether the passed in package is a subpackage of this package .


function getDependencyGroup($name)
    {
        $name = strtolower($name);
        if (!isset($this->_packageInfo['dependencies']['group'])) {
            return false;
        }
        $groups = $this->_packageInfo['dependencies']['group'];
        if (!isset($groups[0])) {
            $groups = array($groups);
        }
        foreach ($groups as $group) {
            if (strtolower($group['attribs']['name']) == $name) {
                return $group;
            }
        }
        return false;
    }

function getDependencyGroup ( $ name ) { $ name = strtolower ( $ name ) ; if ( ! isset ( $ this -> _packageInfo [ 'dependencies' ] [ 'group' ] ) ) { return false ; } $ groups = $ this -> _packageInfo [ 'dependencies' ] [ 'group' ] ; if ( ! isset ( $ groups [ 0 ] ) ) { $ groups = array ( $ groups ) ; } foreach ( $ groups as $ group ) { if ( strtolower ( $ group [ 'attribs' ] [ 'name' ] ) == $ name ) { return $ group ; } } return false ; }

Get the contents of a dependency group
@param string
@return array|false


function _ksplice($array, $key, $value, $newkey)
    {
        $offset = array_search($key, array_keys($array));
        $after = array_slice($array, $offset);
        $before = array_slice($array, 0, $offset);
        $before[$newkey] = $value;
        return array_merge($before, $after);
    }

function _ksplice ( $ array , $ key , $ value , $ newkey ) { $ offset = array_search ( $ key , array_keys ( $ array ) ) ; $ after = array_slice ( $ array , $ offset ) ; $ before = array_slice ( $ array , 0 , $ offset ) ; $ before [ $ newkey ] = $ value ; return array_merge ( $ before , $ after ) ; }

Key-friendly array_splice
@param tagname to splice a value in before
@param mixed the value to splice in
@param string the new tag name


public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new ManagerCompiler());
        $container->addCompilerPass(new HelperCompiler());
    }

public function build ( ContainerBuilder $ container ) { parent :: build ( $ container ) ; $ container -> addCompilerPass ( new ManagerCompiler ( ) ) ; $ container -> addCompilerPass ( new HelperCompiler ( ) ) ; }

Builds the bundle.

It is only ever called once when the cache is empty.

This method can be overridden to register compilation passes,
other extensions, ...

@param ContainerBuilder $container A ContainerBuilder instance

@return void


public static function modulo($a, $b)
    {
        if (abs($b)>abs($a)) {
            return $a;
        }
        if ($a>0 && $b>0) {
            return ($a%$b);
        }
        return self::getModuloFromEntirePart($a, $b);
    }

public static function modulo ( $ a , $ b ) { if ( abs ( $ b ) > abs ( $ a ) ) { return $ a ; } if ( $ a > 0 && $ b > 0 ) { return ( $ a % $ b ) ; } return self :: getModuloFromEntirePart ( $ a , $ b ) ; }

Try to get the "true" modulo

@param $a
@param $b
@return float|int


public static function getModuloFromEntirePart($a, $b)
    {
        $div = round($a/$b, 0, (($a/$b)>=0 ? PHP_ROUND_HALF_DOWN : PHP_ROUND_HALF_UP));
        $a = round($a, 0, ($a>=0 ? PHP_ROUND_HALF_DOWN : PHP_ROUND_HALF_UP));
        $b = round($b, 0, ($b>=0 ? PHP_ROUND_HALF_DOWN : PHP_ROUND_HALF_UP));
        return ($a - ($div * $b));
    }

public static function getModuloFromEntirePart ( $ a , $ b ) { $ div = round ( $ a / $ b , 0 , ( ( $ a / $ b ) >= 0 ? PHP_ROUND_HALF_DOWN : PHP_ROUND_HALF_UP ) ) ; $ a = round ( $ a , 0 , ( $ a >= 0 ? PHP_ROUND_HALF_DOWN : PHP_ROUND_HALF_UP ) ) ; $ b = round ( $ b , 0 , ( $ b >= 0 ? PHP_ROUND_HALF_DOWN : PHP_ROUND_HALF_UP ) ) ; return ( $ a - ( $ div * $ b ) ) ; }

This method is an alternative to the native `a % b` using the "entire part" method.
The result will always be in range `[0 ; b[` and have the same sign as `b`.

@param $a
@param $b
@return float

This method is an alternative to the native a % b using the entire part method . The result will always be in range [ 0 ; b [ and have the same sign as b .


public function update(SplSubject $subject)
    {
        $event = $subject->getLastEvent();
        if (!in_array($event['name'], $this->events)) {
            return;
        }

        switch ($event['name']) {
        case 'connect':
            $this->log('* Connected to ' . $event['data']);
            break;
        case 'sentHeaders':
            $headers = explode("\r\n", $event['data']);
            array_pop($headers);
            foreach ($headers as $header) {
                $this->log('> ' . $header);
            }
            break;
        case 'sentBody':
            $this->log('> ' . $event['data'] . ' byte(s) sent');
            break;
        case 'receivedHeaders':
            $this->log(sprintf(
                '< HTTP/%s %s %s', $event['data']->getVersion(),
                $event['data']->getStatus(), $event['data']->getReasonPhrase()
            ));
            $headers = $event['data']->getHeader();
            foreach ($headers as $key => $val) {
                $this->log('< ' . $key . ': ' . $val);
            }
            $this->log('< ');
            break;
        case 'receivedBody':
            $this->log($event['data']->getBody());
            break;
        case 'disconnect':
            $this->log('* Disconnected');
            break;
        }
    }

public
function
update
(
SplSubject
$
subject
)
{
$
event
=
$
subject
->
getLastEvent
(
)
;
if
(
!
in_array
(
$
event
[
'name'
]
,
$
this
->
events
)
)
{
return
;
}
switch
(
$
event
[
'name'
]
)
{
case
'connect'
:
$
this
->
log
(
'* Connected to '
.
$
event
[
'data'
]
)
;
break
;
case
'sentHeaders'
:
$
headers
=
explode
(
"\r\n"
,
$
event
[
'data'
]
)
;
array_pop
(
$
headers
)
;
foreach
(
$
headers
as
$
header
)
{
$
this
->
log
(
'> '
.
$
header
)
;
}
break
;
case
'sentBody'
:
$
this
->
log
(
'> '
.
$
event
[
'data'
]
.
' byte(s) sent'
)
;
break
;
case
'receivedHeaders'
:
$
this
->
log
(
sprintf
(
'< HTTP/%s %s %s'
,
$
event
[
'data'
]
->
getVersion
(
)
,
$
event
[
'data'
]
->
getStatus
(
)
,
$
event
[
'data'
]
->
getReasonPhrase
(
)
)
)
;
$
headers
=
$
event
[
'data'
]
->
getHeader
(
)
;
foreach
(
$
headers
as
$
key
=>
$
val
)
{
$
this
->
log
(
'< '
.
$
key
.
': '
.
$
val
)
;
}
$
this
->
log
(
'< '
)
;
break
;
case
'receivedBody'
:
$
this
->
log
(
$
event
[
'data'
]
->
getBody
(
)
)
;
break
;
case
'disconnect'
:
$
this
->
log
(
'* Disconnected'
)
;
break
;
}
}

Called when the request notifies us of an event.

@param HTTP_Request2 $subject The HTTP_Request2 instance

@return void

Called when the request notifies us of an event .


protected function log($message)
    {
        if ($this->target instanceof Log) {
            $this->target->debug($message);
        } elseif (is_resource($this->target)) {
            fwrite($this->target, $message . "\r\n");
        }
    }

protected function log ( $ message ) { if ( $ this -> target instanceof Log ) { $ this -> target -> debug ( $ message ) ; } elseif ( is_resource ( $ this -> target ) ) { fwrite ( $ this -> target , $ message . "\r\n" ) ; } }

Logs the given message to the configured target.

@param string $message Message to display

@return void

Logs the given message to the configured target .


public function selectFromRepositoryEntity($alias = null, $indexBy = null)
    {
        if ($alias) {
            $this->entityAlias = $alias;
        }

        if (!$alias) {
            $alias = $this->getEntityAlias();
        }

        $this->select($alias)->from($this->getEntityClassName(), $alias, $indexBy);

        return $this;
    }

public function selectFromRepositoryEntity ( $ alias = null , $ indexBy = null ) { if ( $ alias ) { $ this -> entityAlias = $ alias ; } if ( ! $ alias ) { $ alias = $ this -> getEntityAlias ( ) ; } $ this -> select ( $ alias ) -> from ( $ this -> getEntityClassName ( ) , $ alias , $ indexBy ) ; return $ this ; }

Configure query to work with repository entity.

@param string $alias
@param string $indexBy The index for the from.

@return $this This QueryBuilder instance.
@throws \ReflectionException

Configure query to work with repository entity .


public function getEntityAlias()
    {
        if (!$this->entityAlias) {
            $className       = $this->getEntityClassName();
            $reflectionCLass = new ReflectionClass($className);

            if (is_string($reflectionCLass->getConstant('ALIAS_NAME'))) {
                $this->entityAlias = $reflectionCLass->getConstant('ALIAS_NAME');
            } else {
                if (method_exists($this->getRepository(), 'getEntityAlias')) {
                    $this->entityAlias = $this->getRepository()->getEntityAlias();
                } else {
                    $this->entityAlias = end(explode('\\', $className));
                }
            }

            $this->entityAlias = str_replace('.', '', $this->entityAlias);
        }

        return $this->entityAlias;
    }

public function getEntityAlias ( ) { if ( ! $ this -> entityAlias ) { $ className = $ this -> getEntityClassName ( ) ; $ reflectionCLass = new ReflectionClass ( $ className ) ; if ( is_string ( $ reflectionCLass -> getConstant ( 'ALIAS_NAME' ) ) ) { $ this -> entityAlias = $ reflectionCLass -> getConstant ( 'ALIAS_NAME' ) ; } else { if ( method_exists ( $ this -> getRepository ( ) , 'getEntityAlias' ) ) { $ this -> entityAlias = $ this -> getRepository ( ) -> getEntityAlias ( ) ; } else { $ this -> entityAlias = end ( explode ( '\\' , $ className ) ) ; } } $ this -> entityAlias = str_replace ( '.' , '' , $ this -> entityAlias ) ; } return $ this -> entityAlias ; }

Get related entity alias used in query. Will be used entity class name without namespace

@return string
@throws \ReflectionException

Get related entity alias used in query . Will be used entity class name without namespace


public function delete($delete = null, $alias = null)
    {
        if ($delete === null) {
            $delete = $this->getEntityClassName();

            if ($alias === null) {
                $alias = $this->getEntityAlias();
            }
        }

        parent::delete($delete, $alias);

        return $this;
    }

public function delete ( $ delete = null , $ alias = null ) { if ( $ delete === null ) { $ delete = $ this -> getEntityClassName ( ) ; if ( $ alias === null ) { $ alias = $ this -> getEntityAlias ( ) ; } } parent :: delete ( $ delete , $ alias ) ; return $ this ; }

Turns the query being built into a bulk delete query that ranges over
a certain entity type.

<code>
$qb = $em->createQueryBuilder()
->delete('User', 'u')
->where('u.id = :user_id')
->setParameter('user_id', 1);
</code>

@param string $delete The class/type whose instances are subject to the deletion.
@param string $alias  The class/type alias used in the constructed query.

@return $this This QueryBuilder instance.
@throws \ReflectionException

Turns the query being built into a bulk delete query that ranges over a certain entity type .


public function update($update = null, $alias = null)
    {
        if ($update === null) {
            $update = $this->getEntityClassName();

            if ($alias === null) {
                $alias = $this->getEntityAlias();
            }
        }

        parent::update($update, $alias);

        return $this;
    }

public function update ( $ update = null , $ alias = null ) { if ( $ update === null ) { $ update = $ this -> getEntityClassName ( ) ; if ( $ alias === null ) { $ alias = $ this -> getEntityAlias ( ) ; } } parent :: update ( $ update , $ alias ) ; return $ this ; }

Turns the query being built into a bulk update query that ranges over
a certain entity type.

<code>
$qb = $em->createQueryBuilder()
->update('User', 'u')
->set('u.password', md5('password'))
->where('u.id = ?');
</code>

@param string $update The class/type whose instances are subject to the update.
@param string $alias  The class/type alias used in the constructed query.

@return $this This QueryBuilder instance.
@throws \ReflectionException

Turns the query being built into a bulk update query that ranges over a certain entity type .


public function from($from = null, $alias = null, $indexBy = null)
    {
        if ($from === null) {
            $from = $this->getEntityClassName();

            if ($alias === null) {
                $alias = $this->getEntityAlias();
            }
        }

        parent::from($from, $alias, $indexBy = null);

        return $this;
    }

public function from ( $ from = null , $ alias = null , $ indexBy = null ) { if ( $ from === null ) { $ from = $ this -> getEntityClassName ( ) ; if ( $ alias === null ) { $ alias = $ this -> getEntityAlias ( ) ; } } parent :: from ( $ from , $ alias , $ indexBy = null ) ; return $ this ; }

Creates and adds a query root corresponding to the entity identified by the given alias,
forming a cartesian product with any existing query roots.

<code>
$qb = $em->createQueryBuilder()
->select('u')
->from('User', 'u');
</code>

@param string $from    The class name.
@param string $alias   The alias of the class.
@param string $indexBy The index for the from.

@return $this This QueryBuilder instance.
@throws \ReflectionException

Creates and adds a query root corresponding to the entity identified by the given alias forming a cartesian product with any existing query roots .


public function set($key, $value)
    {
        parent::set($this->alias($key), $value);

        return $this;
    }

public function set ( $ key , $ value ) { parent :: set ( $ this -> alias ( $ key ) , $ value ) ; return $ this ; }

Sets a new value for a field in a bulk update query.

<code>
$qb = $em->createQueryBuilder()
->update('User', 'u')
->set('u.password', md5('password'))
->where('u.id = ?');
</code>

@param string $key   The key/field to set.
@param string $value The value, expression, placeholder, etc.

@return $this This QueryBuilder instance.
@throws \ReflectionException

Sets a new value for a field in a bulk update query .


public function groupBy($groupBy)
    {
        /** @var array $groupFields */
        $groupFields = func_get_args();

        if (count($groupFields) > 0) {
            parent::groupBy($this->alias(array_shift($groupFields)));

            foreach ($groupFields as $group) {
                $this->addGroupBy($group);
            }
        }

        return $this;
    }

public
function
groupBy
(
$
groupBy
)
{
/** @var array $groupFields */
$
groupFields
=
func_get_args
(
)
;
if
(
count
(
$
groupFields
)
>
0
)
{
parent
::
groupBy
(
$
this
->
alias
(
array_shift
(
$
groupFields
)
)
)
;
foreach
(
$
groupFields
as
$
group
)
{
$
this
->
addGroupBy
(
$
group
)
;
}
}
return
$
this
;
}

Specifies a grouping over the results of the query.
Replaces any previously specified groupings, if any.

<code>
$qb = $em->createQueryBuilder()
->select('u')
->from('User', 'u')
->groupBy('u.id');
</code>

@param string $groupBy The grouping expression.

@return $this This QueryBuilder instance.
@throws \ReflectionException

Specifies a grouping over the results of the query . Replaces any previously specified groupings if any .


public function addGroupBy($groupBy)
    {
        /** @var array $groupFields */
        $groupFields = func_get_args();

        foreach ($groupFields as $group) {
            parent::addGroupBy($this->alias($group));
        }

        return $this;
    }

public
function
addGroupBy
(
$
groupBy
)
{
/** @var array $groupFields */
$
groupFields
=
func_get_args
(
)
;
foreach
(
$
groupFields
as
$
group
)
{
parent
::
addGroupBy
(
$
this
->
alias
(
$
group
)
)
;
}
return
$
this
;
}

Adds a grouping expression to the query.

<code>
$qb = $em->createQueryBuilder()
->select('u')
->from('User', 'u')
->groupBy('u.lastLogin')
->addGroupBy('u.createdAt');
</code>

@param string $groupBy The grouping expression.

@return $this This QueryBuilder instance.
@throws \ReflectionException

Adds a grouping expression to the query .


public function orderBy($sort, $order = null)
    {
        if (is_string($sort)) {
            $sort = $this->alias($sort);
        }

        parent::orderBy($sort, $order);

        return $this;
    }

public function orderBy ( $ sort , $ order = null ) { if ( is_string ( $ sort ) ) { $ sort = $ this -> alias ( $ sort ) ; } parent :: orderBy ( $ sort , $ order ) ; return $ this ; }

Specifies an ordering for the query results.
Replaces any previously specified orderings, if any.

@param string $sort  The ordering expression.
@param string $order The ordering direction.

@return $this This QueryBuilder instance.
@throws \ReflectionException

Specifies an ordering for the query results . Replaces any previously specified orderings if any .


public function addOrderBy($sort, $order = null)
    {
        if (is_string($sort)) {
            $sort = $this->alias($sort);
        }

        parent::addOrderBy($sort, $order);

        return $this;
    }

public function addOrderBy ( $ sort , $ order = null ) { if ( is_string ( $ sort ) ) { $ sort = $ this -> alias ( $ sort ) ; } parent :: addOrderBy ( $ sort , $ order ) ; return $ this ; }

Adds an ordering to the query results.

@param string $sort  The ordering expression.
@param string $order The ordering direction.

@return $this This QueryBuilder instance.
@throws \ReflectionException


public function limit($maxResults, $offset = null)
    {
        if (!is_int($maxResults)) {
            throw new Exception\InvalidArgumentException('Incorrect argument $maxResults. Only number allowed.');
        }

        if ($maxResults < 1) {
            throw new Exception\InvalidArgumentException(
                sprintf('Incorrect maximum results: %d. Only positive number allowed.', $maxResults)
            );
        }

        $this->setMaxResults($maxResults);

        if ($offset !== null) {
            if (!is_int($offset)) {
                throw new Exception\InvalidArgumentException('Incorrect argument $offset. Only number allowed.');
            }

            if ($offset < 0) {
                throw new Exception\InvalidArgumentException(
                    sprintf('Incorrect offset: %d. Only positive number allowed.', $offset)
                );
            }

            $this->setFirstResult($offset);
        }

        return $this;
    }

Limit max number of results

@param int $maxResults
@param int $offset

@return $this This QueryBuilder instance.
@throws Exception\InvalidArgumentException


public function paginate($page = 1, $itemsPerPage = 10)
    {
        if (!is_int($page) || !is_int($itemsPerPage)) {
            throw new Exception\InvalidArgumentException(
                sprintf(
                    'Incorrect argument %s. Only number allowed.', is_int($page) ? '$itemsPerPage' : '$page'
                )
            );
        }

        if ($page < 1) {
            throw new Exception\InvalidArgumentException(
                sprintf('Incorrect page number: %d. Only positive number allowed.', $page)
            );
        }

        if ($itemsPerPage < 1) {
            throw new Exception\InvalidArgumentException(
                sprintf('Incorrect items per page: %d. Only positive number allowed.', $page)
            );
        }

        return $this->limit($itemsPerPage, ($page - 1) * $itemsPerPage);
    }

Limit results with selected page.

@param int $page
@param int $itemsPerPage

@return $this This QueryBuilder instance.
@throws \Xloit\Bridge\Doctrine\ORM\Exception\InvalidArgumentException


public function fetchOne(array $parameters = [], $hydrationMode = null)
    {
        $this->appendParameters($parameters);
        $this->limit(1, 0);

        return $this->getQuery()->getOneOrNullResult($hydrationMode);
    }

public function fetchOne ( array $ parameters = [ ] , $ hydrationMode = null ) { $ this -> appendParameters ( $ parameters ) ; $ this -> limit ( 1 , 0 ) ; return $ this -> getQuery ( ) -> getOneOrNullResult ( $ hydrationMode ) ; }

Fetch first entity.

@param array $parameters
@param int   $hydrationMode

@return mixed|null
@throws \Doctrine\ORM\NonUniqueResultException
@throws \Xloit\Bridge\Doctrine\ORM\Exception\InvalidArgumentException


public function fetchSingle(array $parameters = [], $hydrationMode = null)
    {
        $this->appendParameters($parameters);
        $this->limit(1, 0);

        return $this->getQuery()->getSingleResult($hydrationMode);
    }

public function fetchSingle ( array $ parameters = [ ] , $ hydrationMode = null ) { $ this -> appendParameters ( $ parameters ) ; $ this -> limit ( 1 , 0 ) ; return $ this -> getQuery ( ) -> getSingleResult ( $ hydrationMode ) ; }

Fetch first column of first result row.

@param array $parameters
@param int   $hydrationMode

@return mixed
@throws \Doctrine\ORM\NonUniqueResultException
@throws \Doctrine\ORM\NoResultException
@throws \Xloit\Bridge\Doctrine\ORM\Exception\InvalidArgumentException

Fetch first column of first result row .


public function fetchAll(array $parameters = [], $hydrationMode = DoctrineQuery::HYDRATE_OBJECT)
    {
        $this->appendParameters($parameters);

        return $this->getQuery()->getResult($hydrationMode);
    }

public function fetchAll ( array $ parameters = [ ] , $ hydrationMode = DoctrineQuery :: HYDRATE_OBJECT ) { $ this -> appendParameters ( $ parameters ) ; return $ this -> getQuery ( ) -> getResult ( $ hydrationMode ) ; }

Fetch all entities.

@param array $parameters
@param int   $hydrationMode

@return array


public function param($value, $type = null, $columnName = 'p')
    {
        $parameterName = $this->findUnusedParameterName($columnName);

        if ($type) {
            $this->appendParameters(
                [
                    $parameterName => [
                        $value,
                        $type
                    ]
                ]
            );
        } else {
            $this->appendParameters([$parameterName => $value]);
        }

        return sprintf(':%s', $parameterName);
    }

public function param ( $ value , $ type = null , $ columnName = 'p' ) { $ parameterName = $ this -> findUnusedParameterName ( $ columnName ) ; if ( $ type ) { $ this -> appendParameters ( [ $ parameterName => [ $ value , $ type ] ] ) ; } else { $ this -> appendParameters ( [ $ parameterName => $ value ] ) ; } return sprintf ( ':%s' , $ parameterName ) ; }

Auto append parameter and replace them with the parameter name.

@param mixed  $value
@param string $type
@param string $columnName

@return string The parameter name.

Auto append parameter and replace them with the parameter name .


protected function findUnusedParameterName($columnName = 'p')
    {
        $parameters = $this->getParameters()->map(
            function($parameter) {
                /** @var Parameter $parameter */
                return $parameter->getName();
            }
        );
        $index      = 0;

        do {
            $parameterName = $columnName . $index;
            $index++;
        } while ($parameters->contains($parameterName));

        return $parameterName;
    }

protected
function
findUnusedParameterName
(
$
columnName
=
'p'
)
{
$
parameters
=
$
this
->
getParameters
(
)
->
map
(
function
(
$
parameter
)
{
/** @var Parameter $parameter */
return
$
parameter
->
getName
(
)
;
}
)
;
$
index
=
0
;
do
{
$
parameterName
=
$
columnName
.
$
index
;
$
index
++
;
}
while
(
$
parameters
->
contains
(
$
parameterName
)
)
;
return
$
parameterName
;
}

Find unused parameter name.

@param string $columnName

@return string


protected function parseCallMethods($method, array $lists, array $arguments, $prefix = true)
    {
        $condition  = null;
        $fieldName  = null;
        $methodName = null;

        foreach ($lists as $name => $requireArgs) {
            if (strpos($method, 'and') === 0) {
                $method    = lcfirst(substr($method, 3));
                $condition = 'and';
            } elseif (strpos($method, 'or') === 0) {
                $method    = lcfirst(substr($method, 2));
                $condition = 'or';
            }

            if (strlen($method) < strlen($name)) {
                continue;
            }

            $position = false;

            if ($prefix && strpos($method, $name) === 0) {
                $position = 0;
            } elseif (!$prefix) {
                $position = strpos($method, $name, strlen($name));
            }

            if ($position !== false) {
                /** @noinspection IsEmptyFunctionUsageInspection */
                if ($requireArgs && empty($arguments)) {
                    throw ORMException::findByRequiresParameter(sprintf('%s::%s', static::class, $method));
                }

                if ($prefix) {
                    $fieldName  = substr($method, strlen($name));
                    $methodName = $name;
                } elseif (!$prefix) {
                    $fieldName  = substr($method, 0, $position);
                    $methodName = $name;
                }
                break;
            }
        }

        if ($fieldName && $methodName) {
            $fieldName     = lcfirst(Inflector::classify($fieldName));
            $className     = $this->getEntityClassName();
            $classMetadata = $this->getEntityManager()->getClassMetadata($className);

            if (!$classMetadata->hasField($fieldName) && !$classMetadata->hasAssociation($fieldName)) {
                throw ORMException::invalidFindByCall($className, $fieldName, $method);
            }
        }

        return [
            'condition'  => $condition,
            'fieldName'  => $fieldName,
            'methodName' => $methodName
        ];
    }

A parseCallMethods function.

@param string $method
@param array  $lists
@param array  $arguments
@param bool   $prefix

@return array
@throws \Doctrine\ORM\ORMException


private function callFunctionalityFields($fieldName, $methodName, array $arguments = [], $condition = null)
    {
        switch ($methodName) {
            case 'where':
            case 'filterBy':
                if ($condition === 'or') {
                    $this->orWhere(sprintf('%s = %s', $this->alias($fieldName), $arguments[0]));
                } else {
                    $this->andWhere(sprintf('%s = %s', $this->alias($fieldName), $arguments[0]));
                }
                break;
            case 'orderBy':
            case 'orderAscBy':
            case 'orderDescBy':
                if ($methodName === 'orderAscBy') {
                    $arguments = ['ASC'];
                } elseif ($methodName === 'orderDescBy') {
                    $arguments = ['DESC'];
                }

                if (count($arguments) === 1) {
                    $this->orderBy($fieldName, $arguments[0]);
                } else {
                    $this->orderBy($fieldName);
                }
                break;
            case 'addOrderBy':
            case 'addOrderAscBy':
            case 'addOrderDescBy':
                if ($methodName === 'addOrderAscBy') {
                    $arguments = ['ASC'];
                } elseif ($methodName === 'addOrderDescBy') {
                    $arguments = ['DESC'];
                }

                if (count($arguments) === 1) {
                    $this->addOrderBy($fieldName, $arguments[0]);
                } else {
                    $this->addOrderBy($fieldName);
                }
                break;
            case 'groupBy':
                $this->groupBy($this->alias($fieldName));
                break;
            case 'addGroupBy':
                $this->addGroupBy($this->alias($fieldName));
                break;
            default:
                // Do Nothing
                break;
        }

        return $this;
    }

private
function
callFunctionalityFields
(
$
fieldName
,
$
methodName
,
array
$
arguments
=
[
]
,
$
condition
=
)
{
switch
(
$
methodName
)
{
case
'where'
:
case
'filterBy'
:
if
(
$
condition
===
'or'
)
{
$
this
->
orWhere
(
sprintf
(
'%s = %s'
,
$
this
->
alias
(
$
fieldName
)
,
$
arguments
[
0
]
)
)
;
}
else
{
$
this
->
andWhere
(
sprintf
(
'%s = %s'
,
$
this
->
alias
(
$
fieldName
)
,
$
arguments
[
0
]
)
)
;
}
break
;
case
'orderBy'
:
case
'orderAscBy'
:
case
'orderDescBy'
:
if
(
$
methodName
===
'orderAscBy'
)
{
$
arguments
=
[
'ASC'
]
;
}
elseif
(
$
methodName
===
'orderDescBy'
)
{
$
arguments
=
[
'DESC'
]
;
}
if
(
count
(
$
arguments
)
===
1
)
{
$
this
->
orderBy
(
$
fieldName
,
$
arguments
[
0
]
)
;
}
else
{
$
this
->
orderBy
(
$
fieldName
)
;
}
break
;
case
'addOrderBy'
:
case
'addOrderAscBy'
:
case
'addOrderDescBy'
:
if
(
$
methodName
===
'addOrderAscBy'
)
{
$
arguments
=
[
'ASC'
]
;
}
elseif
(
$
methodName
===
'addOrderDescBy'
)
{
$
arguments
=
[
'DESC'
]
;
}
if
(
count
(
$
arguments
)
===
1
)
{
$
this
->
addOrderBy
(
$
fieldName
,
$
arguments
[
0
]
)
;
}
else
{
$
this
->
addOrderBy
(
$
fieldName
)
;
}
break
;
case
'groupBy'
:
$
this
->
groupBy
(
$
this
->
alias
(
$
fieldName
)
)
;
break
;
case
'addGroupBy'
:
$
this
->
addGroupBy
(
$
this
->
alias
(
$
fieldName
)
)
;
break
;
default
:
// Do Nothing
break
;
}
return
$
this
;
}

A callFunctionalityFields function.

@param string $fieldName
@param string $methodName
@param array  $arguments
@param string $condition

@return $this This QueryBuilder instance.
@throws \ReflectionException


public function isAssoc(): bool
    {
        if (empty($this->array)) {
            return false;
        }

        return (bool) count(array_filter(array_keys($this->array), 'is_string'));
    }

public function isAssoc ( ) : bool { if ( empty ( $ this -> array ) ) { return false ; } return ( bool ) count ( array_filter ( array_keys ( $ this -> array ) , 'is_string' ) ) ; }

Checks a value whether to be an array, if its empty and when not an empty array if it's an associative one.

@return bool

Checks a value whether to be an array if its empty and when not an empty array if it s an associative one .


public function describe(Subject $subject): DescriptionInterface
    {
        $description = $this->createDescription();

        foreach ($this->resolvers as $resolver) {
            $subject = $resolver->resolve($subject);
        }

        foreach ($this->enhancers as $enhancer) {
            if (false === $enhancer->supports($subject)) {
                continue;
            }

            $enhancer->enhanceFromClass($description, $subject->getClass());

            if ($subject->hasObject()) {
                $enhancer->enhanceFromObject($description, $subject);
            }
        }

        return $description;
    }

public function describe ( Subject $ subject ) : DescriptionInterface { $ description = $ this -> createDescription ( ) ; foreach ( $ this -> resolvers as $ resolver ) { $ subject = $ resolver -> resolve ( $ subject ) ; } foreach ( $ this -> enhancers as $ enhancer ) { if ( false === $ enhancer -> supports ( $ subject ) ) { continue ; } $ enhancer -> enhanceFromClass ( $ description , $ subject -> getClass ( ) ) ; if ( $ subject -> hasObject ( ) ) { $ enhancer -> enhanceFromObject ( $ description , $ subject ) ; } } return $ description ; }

Return a description of the given subject.

Return a description of the given subject .


public function timestamp($domain, $where, $comment = null)
    {
        $now = microtime(true);
        $this->timestamp[] = array(
          'domain'  => $domain,
          'where'   => $where,
          'comment' => $comment,
          'when'    => $now,
          'memory'  => memory_get_usage(true),
          'duration'=> 0,
        );

        if ($this->pos > 0) {
            $this->timestamp[$this->pos - 1]['memory-peak'] = memory_get_peak_usage(true);
            $this->timestamp[$this->pos - 1]['duration']    = $now - $this->timestamp[$this->pos - 1]['when'];
        }

        $this->pos++;
    }

public function timestamp ( $ domain , $ where , $ comment = null ) { $ now = microtime ( true ) ; $ this -> timestamp [ ] = array ( 'domain' => $ domain , 'where' => $ where , 'comment' => $ comment , 'when' => $ now , 'memory' => memory_get_usage ( true ) , 'duration' => 0 , ) ; if ( $ this -> pos > 0 ) { $ this -> timestamp [ $ this -> pos - 1 ] [ 'memory-peak' ] = memory_get_peak_usage ( true ) ; $ this -> timestamp [ $ this -> pos - 1 ] [ 'duration' ] = $ now - $ this -> timestamp [ $ this -> pos - 1 ] [ 'when' ] ; } $ this -> pos ++ ; }

Timestamp, log a event with a time.

@param string $domain is the module or class.
@param string $where a more specific place in the domain.
@param string $comment on the timestamp.


public function timestampAsTable()
    {

        // Set up the table
        $first = $this->timestamp[0]['when'];
        $last = $this->timestamp[count($this->timestamp) - 1]['when'];
        $html = "

Timestamps

Domain	Where	When (sec)	Duration (sec)	Percent	Memory (MB)	Memory peak (MB)	Comment
";
        $right = ' style="text-align: right;"';
        $total = array('domain' => array(), 'where' => array());

        $totalDuration = $last - $first;

        // Create the main table
        foreach ($this->timestamp as $val) {
            $when     = $val['when'] - $first;
            $duration = round($val['duration'], $this->precision);
            $percent  = round(($when) / $totalDuration * 100);
            $memory   = round($val['memory'] / 1024 / 1024, 2);
            $peak     = isset($val['memory-peak']) ? round($val['memory-peak'] / 1024 / 1024, 2): 0;
            $when     = round($when, $this->precision);
            $html .= "
{$val['domain']}	{$val['where']}	{$when}	{$duration}	{$percent}	{$memory}	{$peak}	{$val['comment']}
";
            @$total['domain'][$val['domain']] += $val['duration'];
            @$total['where'][$val['where']] += $val['duration'];
        }

        $html .= "

Duration per domain

Domain	Duration	Percent
";

        // Create the table grouped by domain
        arsort($total['domain']);

        foreach ($total['domain'] as $key => $val) {
            if ($totalDuration != 0) {
                $percent = round($val / $totalDuration * 100, 1);
            } else {
                $percent = 100;
            }

            $roundedDuration = round($val, $this->precision);
            $html .= "
{$key}	{$roundedDuration}	{$percent}
";
        }

        $html .= "

Duration per area

Area	Duration	Percent
";

        // Create the table grouped by area
        arsort($total['where']);

        foreach ($total['where'] as $key => $val) {
            if ($totalDuration != 0) {
                $percent = round($val / $totalDuration * 100, 1);
            } else {
                $percent = 100;
            }

            $roundedDuration = round($val, $this->precision);
            $html .= "
{$key}	{$roundedDuration}	{$percent}
";
        }

        $html .= "
";

        return $html;
    }

Print all timestamp to a table.

@return string with a html-table to display all timestamps.


public function pageLoadTime()
    {
        $first = $this->timestamp[0]['when'];
        $last = $this->timestamp[count($this->timestamp) - 1]['when'];
        $loadtime = round($last - $first, 3);
        return $loadtime;
    }

public function pageLoadTime ( ) { $ first = $ this -> timestamp [ 0 ] [ 'when' ] ; $ last = $ this -> timestamp [ count ( $ this -> timestamp ) - 1 ] [ 'when' ] ; $ loadtime = round ( $ last - $ first , 3 ) ; return $ loadtime ; }

Returns load time of the page

@return The page load time.


public function mostTimeConsumingDomain()
    {
        $total = array();

        // Gather total duration data of each domain
        foreach ($this->timestamp as $val) {
            $duration = round($val['duration'], $this->precision);
            @$total[$val['domain']] += $duration;
        }

        // Get the key of the most time consuming element
        $mostConsumingTime = 0;
        $mostConsumingDomain = "";
        foreach ($total as $key => $val) {
            if ($val >= $mostConsumingTime) {
                $mostConsumingDomain = $key;
                $mostConsumingTime = $val;
            }
        }

        return $mostConsumingDomain;
    }

Get the most time consuming domain.

@return The most time consuming domain.


protected function renderHeader() {
        if (!isset($this->header)) {
            return '';
        }
        if (isset($this->headerOptions)) {
            Html::addCssClass($this->headerOptions, ['widget' => 'card-header']);
            $tag = ArrayHelper::remove($this->headerOptions, 'tag', 'div');
            $header = Html::tag($tag, $this->header, $this->headerOptions);
        } else {
            $header = $this->header;
        }
        return $header;
    }

protected function renderHeader ( ) { if ( ! isset ( $ this -> header ) ) { return '' ; } if ( isset ( $ this -> headerOptions ) ) { Html :: addCssClass ( $ this -> headerOptions , [ 'widget' => 'card-header' ] ) ; $ tag = ArrayHelper :: remove ( $ this -> headerOptions , 'tag' , 'div' ) ; $ header = Html :: tag ( $ tag , $ this -> header , $ this -> headerOptions ) ; } else { $ header = $ this -> header ; } return $ header ; }


protected function renderHeaderImage() {
        if (!isset($this->headerImage)) {
            return '';
        }
        Html::addCssClass($this->headerImageOptions, ['widget' => 'card-img-top']);
        return $this->htmlHlp->img($this->headerImage, $this->headerImageOptions);
    }

protected function renderHeaderImage ( ) { if ( ! isset ( $ this -> headerImage ) ) { return '' ; } Html :: addCssClass ( $ this -> headerImageOptions , [ 'widget' => 'card-img-top' ] ) ; return $ this -> htmlHlp -> img ( $ this -> headerImage , $ this -> headerImageOptions ) ; }


protected function renderBody($body = null, $includeOb = false) {
        $body = isset($body) ? $body : $this->body;
        $bodyContent = '';
        $bodyTag = 'div';
        if (is_array($body)) {
            $bodyRows = [];
            foreach ($body as $bodyRow) {
                $bodyRowContent = $this->renderBody($bodyRow);
                if (empty($bodyRowContent)) {
                    continue;
                }
                $bodyRows[] = $bodyRowContent;
            }
            $bodyContent = implode("\n", $bodyRows);
        } else {
            if (isset($this->bodyOptions)) {
                if (isset($this->overlayImage)) {
                    Html::addCssClass($this->bodyOptions, ['widget' => 'card-img-overlay']);
                } else {
                    Html::addCssClass($this->bodyOptions, ['widget' => 'card-body']);
                }
                $bodyTag = ArrayHelper::remove($this->bodyOptions, 'tag', 'div');
                $bodyOptions = $this->bodyOptions;
            }
            if (isset($body)) {
                $bodyContent .= $body;
            }
        }
        if ($includeOb) {
            $bodyContent .= ob_get_clean();
        }
        return isset($bodyOptions) ? $this->htmlHlp->tag($bodyTag, $bodyContent, $bodyOptions) : $bodyContent;
    }

protected function renderBody ( $ body = null , $ includeOb = false ) { $ body = isset ( $ body ) ? $ body : $ this -> body ; $ bodyContent = '' ; $ bodyTag = 'div' ; if ( is_array ( $ body ) ) { $ bodyRows = [ ] ; foreach ( $ body as $ bodyRow ) { $ bodyRowContent = $ this -> renderBody ( $ bodyRow ) ; if ( empty ( $ bodyRowContent ) ) { continue ; } $ bodyRows [ ] = $ bodyRowContent ; } $ bodyContent = implode ( "\n" , $ bodyRows ) ; } else { if ( isset ( $ this -> bodyOptions ) ) { if ( isset ( $ this -> overlayImage ) ) { Html :: addCssClass ( $ this -> bodyOptions , [ 'widget' => 'card-img-overlay' ] ) ; } else { Html :: addCssClass ( $ this -> bodyOptions , [ 'widget' => 'card-body' ] ) ; } $ bodyTag = ArrayHelper :: remove ( $ this -> bodyOptions , 'tag' , 'div' ) ; $ bodyOptions = $ this -> bodyOptions ; } if ( isset ( $ body ) ) { $ bodyContent .= $ body ; } } if ( $ includeOb ) { $ bodyContent .= ob_get_clean ( ) ; } return isset ( $ bodyOptions ) ? $ this -> htmlHlp -> tag ( $ bodyTag , $ bodyContent , $ bodyOptions ) : $ bodyContent ; }

Render card body
@param string $body
@param bool   $includeOb
@return string


protected function renderFooter() {
        if (!isset($this->footer)) {
            return '';
        }
        if (isset($this->footerOptions)) {
            Html::addCssClass($this->footerOptions, ['widget' => 'card-footer']);
            $tag = ArrayHelper::remove($this->footerOptions, 'tag', 'div');
            $footer = $this->htmlHlp->tag($tag, $this->footer, $this->footerOptions);
        } else {
            $footer = $this->footer;
        }
        return $footer;
    }

protected function renderFooter ( ) { if ( ! isset ( $ this -> footer ) ) { return '' ; } if ( isset ( $ this -> footerOptions ) ) { Html :: addCssClass ( $ this -> footerOptions , [ 'widget' => 'card-footer' ] ) ; $ tag = ArrayHelper :: remove ( $ this -> footerOptions , 'tag' , 'div' ) ; $ footer = $ this -> htmlHlp -> tag ( $ tag , $ this -> footer , $ this -> footerOptions ) ; } else { $ footer = $ this -> footer ; } return $ footer ; }


public function group()
    {
        $namespace = \Reaction::$app->router->getRelativeControllerNamespace(static::class);
        $namespace = substr($namespace, 0, -10);
        $namespaceArray = explode('\\', $namespace);
        array_walk($namespaceArray, function(&$value) {
            $value = Inflector::camel2id($value, '-');
        });
        return implode('/', $namespaceArray);
    }

public function group ( ) { $ namespace = \ Reaction :: $ app -> router -> getRelativeControllerNamespace ( static :: class ) ; $ namespace = substr ( $ namespace , 0 , - 10 ) ; $ namespaceArray = explode ( '\\' , $ namespace ) ; array_walk ( $ namespaceArray , function ( & $ value ) { $ value = Inflector :: camel2id ( $ value , '-' ) ; } ) ; return implode ( '/' , $ namespaceArray ) ; }

Get route group name, if empty no grouping
@return string

Get route group name if empty no grouping


public function getOptionValues($actionID = null)
    {
        // $actionId might be used in subclasses to provide properties specific to action id
        $properties = [];
        foreach ($this->options($actionID) as $property) {
            $properties[$property] = $this->$property;
        }

        return $properties;
    }

Returns properties corresponding to the options for the action id
Child classes may override this method to specify possible properties.

@param string $actionID the action id of the current request
@return array properties corresponding to the options for the action

Returns properties corresponding to the options for the action id Child classes may override this method to specify possible properties .


public function getActionArgsHelp($actionId)
    {
        $methodName = static::getActionMethod($actionId);
        $method = ReflectionHelper::getMethodReflection($this, $methodName);
        $tags = ReflectionHelper::getMethodDocTags($method, $this);
        $params = isset($tags['param']) ? (array)$tags['param'] : [];

        $args = [];

        /** @var \ReflectionParameter $reflection */
        foreach ($method->getParameters() as $i => $reflection) {
            if ($reflection->getClass() !== null) {
                continue;
            }
            $name = $reflection->getName();
            $tag = isset($params[$i]) ? $params[$i] : '';
            if (preg_match('/^(\S+)\s+(\$\w+\s+)?(.*)/s', $tag, $matches)) {
                $type = $matches[1];
                $comment = $matches[3];
            } else {
                $type = null;
                $comment = $tag;
            }
            if ($reflection->isDefaultValueAvailable()) {
                $args[$name] = [
                    'required' => false,
                    'type' => $type,
                    'default' => $reflection->getDefaultValue(),
                    'comment' => $comment,
                ];
            } else {
                $args[$name] = [
                    'required' => true,
                    'type' => $type,
                    'default' => null,
                    'comment' => $comment,
                ];
            }
        }

        return $args;
    }

Returns the help information for the anonymous arguments for the action.

The returned value should be an array. The keys are the argument names, and the values are
the corresponding help information. Each value must be an array of the following structure:

- required: boolean, whether this argument is required.
- type: string, the PHP type of this argument.
- default: string, the default value of this argument
- comment: string, the comment of this argument

The default implementation will return the help information extracted from the doc-comment of
the parameters corresponding to the action method.

@param string $actionId
@return array the help information of the action arguments

Returns the help information for the anonymous arguments for the action .


public function getActionOptionsHelp($actionId)
    {
        $optionNames = $this->options($actionId);
        if (empty($optionNames)) {
            return [];
        }

        $class = ReflectionHelper::getClassReflection($this);
        $options = [];
        foreach ($class->getProperties() as $property) {
            $name = $property->getName();
            if (!in_array($name, $optionNames, true)) {
                continue;
            }
            $defaultValue = $property->getValue($this);
            $tags = ReflectionHelper::getPropertyDocTags($property);

            // Display camelCase options in kebab-case
            $name = Inflector::camel2id($name, '-', true);

            if (isset($tags['var']) || isset($tags['property'])) {
                $doc = isset($tags['var']) ? $tags['var'] : $tags['property'];
                if (is_array($doc)) {
                    $doc = reset($doc);
                }
                if (preg_match('/^(\S+)(.*)/s', $doc, $matches)) {
                    $type = $matches[1];
                    $comment = $matches[2];
                } else {
                    $type = null;
                    $comment = $doc;
                }
                $options[$name] = [
                    'type' => $type,
                    'default' => $defaultValue,
                    'comment' => $comment,
                ];
            } else {
                $options[$name] = [
                    'type' => null,
                    'default' => $defaultValue,
                    'comment' => '',
                ];
            }
        }

        return $options;
    }

Returns the help information for the options for the action.

The returned value should be an array. The keys are the option names, and the values are
the corresponding help information. Each value must be an array of the following structure:

- type: string, the PHP type of this argument.
- default: string, the default value of this argument
- comment: string, the comment of this argument

The default implementation will return the help information extracted from the doc-comment of
the properties corresponding to the action options.

@param string $actionId
@return array the help information of the action options

Returns the help information for the options for the action .


public function getHeaders()
    {
        if ($this->_headers === null) {
            $this->_headers = new HeaderCollection();
            $headers = $this->reactRequest->getHeaders();
            foreach ($headers as $name => $value) {
                $this->_headers->add($name, $value);
            }
            $this->filterHeaders($this->_headers);
        }

        return $this->_headers;
    }

public function getHeaders ( ) { if ( $ this -> _headers === null ) { $ this -> _headers = new HeaderCollection ( ) ; $ headers = $ this -> reactRequest -> getHeaders ( ) ; foreach ( $ headers as $ name => $ value ) { $ this -> _headers -> add ( $ name , $ value ) ; } $ this -> filterHeaders ( $ this -> _headers ) ; } return $ this -> _headers ; }

Returns the header collection.
The header collection contains incoming HTTP headers.
@return HeaderCollection the header collection

Returns the header collection . The header collection contains incoming HTTP headers .


public function getIsFlash()
    {
        /** @var string $userAgent */
        $userAgent = $this->getHeaders()->get('User-Agent', '');
        return stripos($userAgent, 'Shockwave') !== false
            || stripos($userAgent, 'Flash') !== false;
    }

public
function
getIsFlash
(
)
{
/** @var string $userAgent */
$
userAgent
=
$
this
->
getHeaders
(
)
->
get
(
'User-Agent'
,
''
)
;
return
stripos
(
$
userAgent
,
'Shockwave'
)
!==
false
||
stripos
(
$
userAgent
,
'Flash'
)
!==
false
;
}

Returns whether this is an Adobe Flash or Flex request.
@return bool whether this is an Adobe Flash or Adobe Flex request.

Returns whether this is an Adobe Flash or Flex request .


public function getRawBody()
    {
        if ($this->_rawBody === null) {
            $this->_rawBody = $this->reactRequest->getBody();
        }

        return $this->_rawBody;
    }

public function getRawBody ( ) { if ( $ this -> _rawBody === null ) { $ this -> _rawBody = $ this -> reactRequest -> getBody ( ) ; } return $ this -> _rawBody ; }

Returns the raw HTTP request body.
@return string the request body


public function getBodyParams()
    {
        if ($this->_bodyParams === null) {
            $reactMethod = strtoupper($this->reactRequest->getMethod());
            $reactBody = $this->reactRequest->getParsedBody();
            if ($reactMethod === 'POST' && isset($reactBody[$this->methodParam])) {
                $this->_bodyParams = $reactBody;
                unset($this->_bodyParams[$this->methodParam]);
                return $this->_bodyParams;
            }

            $rawContentType = $this->getContentType();
            if (($pos = strpos($rawContentType, ';')) !== false) {
                // e.g. text/html; charset=UTF-8
                $contentType = substr($rawContentType, 0, $pos);
            } else {
                $contentType = $rawContentType;
            }

            if (isset($this->parsers[$contentType])) {
                $parser = Reaction::create($this->parsers[$contentType]);
                if (!($parser instanceof RequestParserInterface)) {
                    throw new InvalidConfigException("The '$contentType' request parser is invalid. It must implement the Reaction\\Web\\RequestParserInterface.");
                }
                $this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
            } elseif (isset($this->parsers['*'])) {
                $parser = Reaction::create($this->parsers['*']);
                if (!($parser instanceof RequestParserInterface)) {
                    throw new InvalidConfigException('The fallback request parser is invalid. It must implement the Reaction\\Web\\RequestParserInterface.');
                }
                $this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType);
            } elseif ($this->getMethod() === 'POST') {
                // PHP has already parsed the body so we have all params in $_POST
                $this->_bodyParams = $reactBody;
            } else {
                $this->_bodyParams = [];
                mb_parse_str($this->getRawBody(), $this->_bodyParams);
            }
        }

        return $this->_bodyParams;
    }

Returns the request parameters given in the request body.

Request parameters are determined using the parsers configured in [[parsers]] property.
If no parsers are configured for the current [[contentType]] it uses the PHP function `mb_parse_str()`
to parse the [[rawBody|request body]].
@return array the request parameters given in the request body.
@throws \Reaction\Exceptions\InvalidConfigException if a registered parser does not implement the [[RequestParserInterface]].
@see _getMethod()
@see getBodyParam()
@see setBodyParams()

Returns the request parameters given in the request body .


public function getHostInfo()
    {
        if ($this->_hostInfo === null) {
            $secure = $this->getIsSecureConnection();
            $http = $secure ? 'https' : 'http';
            $serverName = $this->getServerParam('SERVER_NAME');

            if ($this->getHeaders()->has('X-Forwarded-Host')) {
                $this->_hostInfo = $http . '://' . $this->getHeaders()->get('X-Forwarded-Host');
            } elseif ($this->getHeaders()->has('Host')) {
                $this->_hostInfo = $http . '://' . $this->getHeaders()->get('Host');
            } elseif (isset($serverName)) {
                $this->_hostInfo = $http . '://' . $serverName;
                $port = $secure ? $this->getSecurePort() : $this->getPort();
                if (($port !== 80 && !$secure) || ($port !== 443 && $secure)) {
                    $this->_hostInfo .= ':' . $port;
                }
            }
        }

        return $this->_hostInfo;
    }

public function getHostInfo ( ) { if ( $ this -> _hostInfo === null ) { $ secure = $ this -> getIsSecureConnection ( ) ; $ http = $ secure ? 'https' : 'http' ; $ serverName = $ this -> getServerParam ( 'SERVER_NAME' ) ; if ( $ this -> getHeaders ( ) -> has ( 'X-Forwarded-Host' ) ) { $ this -> _hostInfo = $ http . '://' . $ this -> getHeaders ( ) -> get ( 'X-Forwarded-Host' ) ; } elseif ( $ this -> getHeaders ( ) -> has ( 'Host' ) ) { $ this -> _hostInfo = $ http . '://' . $ this -> getHeaders ( ) -> get ( 'Host' ) ; } elseif ( isset ( $ serverName ) ) { $ this -> _hostInfo = $ http . '://' . $ serverName ; $ port = $ secure ? $ this -> getSecurePort ( ) : $ this -> getPort ( ) ; if ( ( $ port !== 80 && ! $ secure ) || ( $ port !== 443 && $ secure ) ) { $ this -> _hostInfo .= ':' . $ port ; } } } return $ this -> _hostInfo ; }

Returns the schema and host part of the current request URL.

The returned URL does not have an ending slash.

By default this value is based on the user request information. This method will
return the value of `$_SERVER['HTTP_HOST']` if it is available or `$_SERVER['SERVER_NAME']` if not.
You may want to check out the [PHP documentation](http://php.net/manual/en/reserved.variables.server.php)
for more information on these variables.

You may explicitly specify it by setting the [[setHostInfo()|hostInfo]] property.

> Warning: Dependent on the server configuration this information may not be
> reliable and [may be faked by the user sending the HTTP request](https://www.acunetix.com/vulnerabilities/web/host-header-attack).
> If the webserver is configured to serve the same site independent of the value of
> the `Host` header, this value is not reliable. In such situations you should either
> fix your webserver configuration or explicitly set the value by setting the [[setHostInfo()|hostInfo]] property.
> If you don't have access to the server configuration, you can setup [[\yii\filters\HostControl]] filter at
> application level in order to protect against such kind of attack.

@property string|null schema and hostname part (with port number if needed) of the request URL
(e.g. `http://www.example.com`), null if can't be obtained from `$_SERVER` and wasn't set.
See [[getHostInfo()]] for security related notes on this property.
@return string|null schema and hostname part (with port number if needed) of the request URL
(e.g. `http://www.example.com`), null if can't be obtained from `$_SERVER` and wasn't set.
@see setHostInfo()

Returns the schema and host part of the current request URL .


public function getScriptUrl()
    {
        $server = $this->getServerParams();
        if ($this->_scriptUrl === null) {
            $scriptFile = $this->getScriptFile();
            $scriptName = basename($scriptFile);
            if (isset($server['SCRIPT_NAME']) && basename($server['SCRIPT_NAME']) === $scriptName) {
                $this->_scriptUrl = $server['SCRIPT_NAME'];
            } elseif (isset($server['PHP_SELF']) && basename($server['PHP_SELF']) === $scriptName) {
                $this->_scriptUrl = $server['PHP_SELF'];
            } elseif (isset($server['ORIG_SCRIPT_NAME']) && basename($server['ORIG_SCRIPT_NAME']) === $scriptName) {
                $this->_scriptUrl = $server['ORIG_SCRIPT_NAME'];
            } elseif (isset($server['PHP_SELF']) && ($pos = strpos($server['PHP_SELF'], '/' . $scriptName)) !== false) {
                $this->_scriptUrl = substr($server['SCRIPT_NAME'], 0, $pos) . '/' . $scriptName;
            } elseif (!empty($server['DOCUMENT_ROOT']) && strpos($scriptFile, $server['DOCUMENT_ROOT']) === 0) {
                $this->_scriptUrl = str_replace([$server['DOCUMENT_ROOT'], '\\'], ['', '/'], $scriptFile);
            } else {
                throw new InvalidConfigException('Unable to determine the entry script URL.');
            }
        }

        return $this->_scriptUrl;
    }

Returns the relative URL of the entry script.
The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
@return string the relative URL of the entry script.
@throws InvalidConfigException if unable to determine the entry script URL

Returns the relative URL of the entry script . The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework .


public function getServerParams() {
        if (!isset($this->_serverParams)) {
            $this->_serverParams = Reaction\Helpers\ArrayHelper::merge($this->getDefaultServerParams(), $this->reactRequest->getServerParams());
        }
        return $this->_serverParams;
    }

public function getServerParams ( ) { if ( ! isset ( $ this -> _serverParams ) ) { $ this -> _serverParams = Reaction \ Helpers \ ArrayHelper :: merge ( $ this -> getDefaultServerParams ( ) , $ this -> reactRequest -> getServerParams ( ) ) ; } return $ this -> _serverParams ; }