public function responseMiddleware(Request $request, Response $response, array $middleware = null)
    {
        // Set the middleware to any middleware passed or the base middleware
        $middleware = $middleware ?? self::$middleware;

        // Get the application
        $app = $this->getApplication();

        // Iterate through the middleware
        foreach ($middleware as $item) {
            // If the middleware is a group
            if ($this->isMiddlewareGroup($item)) {
                // Recurse into that middleware group
                $this->responseMiddleware(
                    $request,
                    $response,
                    $this->getMiddlewareGroup($item)
                );

                continue;
            }

            /* @var \Valkyrja\Http\Middleware\Middleware $item */
            $response = $item::after($request, $response);

            // Set the returned response in the container
            $app->container()->singleton(Response::class, $response);
        }

        return $response;
    }

Dispatch after request processed middleware.

@param Request  $request    The request
@param Response $response   The response
@param array    $middleware [optional] The middleware to dispatch

@return mixed

Dispatch after request processed middleware .


public function terminableMiddleware(Request $request, Response $response, array $middleware = null): void
    {
        // Set the middleware to any middleware passed or the base middleware
        $middleware = $middleware ?? self::$middleware;

        // Iterate through the middleware
        foreach ($middleware as $item) {
            // If the middleware is a group
            if ($this->isMiddlewareGroup($item)) {
                // Recurse into that middleware group
                $this->terminableMiddleware(
                    $request,
                    $response,
                    $this->getMiddlewareGroup($item)
                );

                continue;
            }

            /* @var \Valkyrja\Http\Middleware\Middleware $item */
            $item::terminate($request, $response);
        }
    }

Dispatch terminable middleware.

@param Request  $request    The request
@param Response $response   The response
@param array    $middleware [optional] The middleware to dispatch

@return void


public function index() {
        $rep = $this->getResponse('html', true);

        $webservices = jWSDL::getSoapControllers();

        if(sizeof($webservices) != 0){
            $service = $this->param('service');

            if (empty($service)) {
                $module = $webservices[0]['module'];
                $controller = $webservices[0]['class'];
            }else{
                if(!strpos($service, '~')===FALSE){
                    list($module, $controller) =  explode('~',$service);
                }
                if (empty($module) || empty($controller)) {
                    throw new JException("jsoap~errors.service.param.invalid");
                }
            }

            //Used for documentation of data structures classes
            $className = $this->param('className');

            $wsdl = new jWSDL($module, $controller);
            $doc = $wsdl->doc($className);
            $doc['menu'] = $webservices;
            $rep->body->assign("doc", $doc);
            $rep->title = "Documentation - ".$controller;
        }else{
            $rep->title = "Documentation -  Web services";
        }
        $rep->bodyTpl = 'jsoap~soap_doc';
        return $rep;
    }

Display the web service documentation for the requested service


public function wsdl() {

        $rep = $this->getResponse('xml');
        $rep->sendXMLHeader = FALSE;

        $service = $this->param('service');

        if (empty($service)) {
            throw new jException("jsoap~errors.service.param.required");
        }

        if(!strpos($service, '~')===FALSE){
            list($module, $controller) =  explode('~',$service);
        }
        if (empty($module) || empty($controller)) {
            throw new jException("jsoap~errors.service.param.invalid");
        }

        $wsdl = new jWSDL($module, $controller);
        $rep->content = $wsdl->getWSDLFile();

        return $rep;
    }

public function wsdl ( ) { $ rep = $ this -> getResponse ( 'xml' ) ; $ rep -> sendXMLHeader = FALSE ; $ service = $ this -> param ( 'service' ) ; if ( empty ( $ service ) ) { throw new jException ( "jsoap~errors.service.param.required" ) ; } if ( ! strpos ( $ service , '~' ) === FALSE ) { list ( $ module , $ controller ) = explode ( '~' , $ service ) ; } if ( empty ( $ module ) || empty ( $ controller ) ) { throw new jException ( "jsoap~errors.service.param.invalid" ) ; } $ wsdl = new jWSDL ( $ module , $ controller ) ; $ rep -> content = $ wsdl -> getWSDLFile ( ) ; return $ rep ; }

Return the WSDL file for a soap web service


static function initOptions() {
        global $min_allowDebugFlag;
        global $min_errorLogger;
        global $min_enableBuilder;
        global $min_cachePath;
        global $min_documentRoot;
        global $min_cacheFileLocking;
        global $min_symlinks;
        global $min_serveOptions;
        global $min_uploaderHoursBehind;
        global $min_customConfigPaths;

        if (!isset($min_allowDebugFlag))
            $min_allowDebugFlag = false;

        if (!isset($min_errorLogger)) {
            $min_errorLogger = false;
        }

        $min_enableBuilder = false;

        $min_cachePath = \jApp::tempPath('minify/');
        if (!file_exists($min_cachePath)) {
            mkdir($min_cachePath, 0775);
        }

        if (!isset($min_documentRoot)) {
            $min_documentRoot = self::getDocumentRoot();
        }

        if (!isset($min_cacheFileLocking)) {
            $min_cacheFileLocking = true;
        }

        if (!isset($min_serveOptions['bubbleCssImports'])) {
            $min_serveOptions['bubbleCssImports'] = false;
        }

        if (!isset($min_serveOptions['maxAge'])) {
            $min_serveOptions['maxAge'] = 1800;
        }

        $min_serveOptions['minApp']['groupsOnly'] = false;

        if (!isset($min_serveOptions['minApp']['maxFiles'])) {
            $min_serveOptions['minApp']['maxFiles'] = 10;
        }

        if (!isset($min_symlinks)) {
            $min_symlinks = array();
        }

        if (!isset($min_uploaderHoursBehind)) {
            $min_uploaderHoursBehind = 0;
        }

        if (!isset($min_customConfigPaths)) {
            $min_customConfigPaths = array(
                'groups' => \jApp::configPath('minifyGroupsConfig.php')
            );
        }

        ini_set('zlib.output_compression', '0');
    }

static function initOptions ( ) { global $ min_allowDebugFlag ; global $ min_errorLogger ; global $ min_enableBuilder ; global $ min_cachePath ; global $ min_documentRoot ; global $ min_cacheFileLocking ; global $ min_symlinks ; global $ min_serveOptions ; global $ min_uploaderHoursBehind ; global $ min_customConfigPaths ; if ( ! isset ( $ min_allowDebugFlag ) ) $ min_allowDebugFlag = false ; if ( ! isset ( $ min_errorLogger ) ) { $ min_errorLogger = false ; } $ min_enableBuilder = false ; $ min_cachePath = \ jApp :: tempPath ( 'minify/' ) ; if ( ! file_exists ( $ min_cachePath ) ) { mkdir ( $ min_cachePath , 0775 ) ; } if ( ! isset ( $ min_documentRoot ) ) { $ min_documentRoot = self :: getDocumentRoot ( ) ; } if ( ! isset ( $ min_cacheFileLocking ) ) { $ min_cacheFileLocking = true ; } if ( ! isset ( $ min_serveOptions [ 'bubbleCssImports' ] ) ) { $ min_serveOptions [ 'bubbleCssImports' ] = false ; } if ( ! isset ( $ min_serveOptions [ 'maxAge' ] ) ) { $ min_serveOptions [ 'maxAge' ] = 1800 ; } $ min_serveOptions [ 'minApp' ] [ 'groupsOnly' ] = false ; if ( ! isset ( $ min_serveOptions [ 'minApp' ] [ 'maxFiles' ] ) ) { $ min_serveOptions [ 'minApp' ] [ 'maxFiles' ] = 10 ; } if ( ! isset ( $ min_symlinks ) ) { $ min_symlinks = array ( ) ; } if ( ! isset ( $ min_uploaderHoursBehind ) ) { $ min_uploaderHoursBehind = 0 ; } if ( ! isset ( $ min_customConfigPaths ) ) { $ min_customConfigPaths = array ( 'groups' => \ jApp :: configPath ( 'minifyGroupsConfig.php' ) ) ; } ini_set ( 'zlib.output_compression' , '0' ) ; }


public function toTimestamp(string $date, string $time = ''): int
    {
        if (empty($time)) {
            $time = '00:00:01';
        }

        // create unix_timestamp
        return strtotime($date . ' ' . $time);
    }

public
function
toTimestamp
(
string
$
date
,
string
$
time
=
''
)
:
int
{
if
(
empty
(
$
time
)
)
{
$
time
=
'00:00:01'
;
}
// create unix_timestamp
return
strtotime
(
$
date
.
' '
.
$
time
)
;
}

Converts a date and time string into timestamp

@param string $date
@param string $time

@return number


public function fromTimestamp(int $timestamp, string $dateformat = 'Y-m-d', string $timeformat = 'H:i'): array
    {
        return [
            'stamp' => $timestamp,
            'date' => date($dateformat, $timestamp),
            'time' => date($timeformat, $timestamp),
            'week' => date('W', $timestamp),
            'day' => date('d', $timestamp),
            'month' => date('m', $timestamp),
            'hour' => date('H', $timestamp),
            'minute' => date('i', $timestamp)
        ];
    }

public function fromTimestamp ( int $ timestamp , string $ dateformat = 'Y-m-d' , string $ timeformat = 'H:i' ) : array { return [ 'stamp' => $ timestamp , 'date' => date ( $ dateformat , $ timestamp ) , 'time' => date ( $ timeformat , $ timestamp ) , 'week' => date ( 'W' , $ timestamp ) , 'day' => date ( 'd' , $ timestamp ) , 'month' => date ( 'm' , $ timestamp ) , 'hour' => date ( 'H' , $ timestamp ) , 'minute' => date ( 'i' , $ timestamp ) ] ; }

Converts a timestamp into many date infos

@param int $timestamp
The timestamp to convert
@param string $dateformat
The dateformat (Default: 'Y-m-d')
@param string $timeformat
The timeformat (Default: 'H:i')

@return array


public function dateConversion(string $date, string $format = 'Y-m-d'): string
    {
        return date($format, strtotime($date));
    }

public function dateConversion ( string $ date , string $ format = 'Y-m-d' ) : string { return date ( $ format , strtotime ( $ date ) ) ; }

Converts a date into another format

@param string $date
@param string $format

@return string


public function timeLeft(int $timestamp, bool $Left = true): string
    {
        $diff = $bLeft == true ? time() - $timestamp : $timestamp;

        $showdiff = [
            "y" => 0,
            "m" => 0,
            "w" => 0,
            "d" => 0,
            "h" => 0,
            "min" => 0
        ];

        while ($diff >= 31536000) {
            // 1 year = 31536000 seconds
            $diff -= 31536000;
            $showdiff['y'] ++;
        }
        while ($diff >= 2419200) {
            // 1 day = 2592000 seconds
            $diff -= 2419200;
            $showdiff['m'] ++;
        }
        while ($diff >= 648000) {
            // 1 week = 604800 seconds
            $diff -= 648000;
            $showdiff['w'] ++;
        }

        while ($diff >= 86400) {
            // 1 day = 86400 seconds
            $diff -= 86400;
            $showdiff['d'] ++;
        }

        while ($diff >= 3600) {
            // 1 hour = 3600 seconds
            $diff -= 3600;
            $showdiff['h'] ++;
        }

        while ($diff >= 60) {
            // 1 minute = 60 seconds
            $diff -= 60;
            $showdiff['min'] ++;
        }

        return $showdiff;
    }

public
function
timeLeft
(
int
$
timestamp
,
bool
$
Left
=
true
)
:
string
{
$
diff
=
$
bLeft
==
true
time
(
)
$
timestamp
:
$
timestamp
;
$
showdiff
=
[
"y"
=>
0
,
"m"
=>
0
,
"w"
=>
0
,
"d"
=>
0
,
"h"
=>
0
,
"min"
=>
0
]
;
while
(
$
diff
>=
31536000
)
{
// 1 year = 31536000 seconds
$
diff
-=
31536000
;
$
showdiff
[
'y'
]
++
;
}
while
(
$
diff
>=
2419200
)
{
// 1 day = 2592000 seconds
$
diff
-=
2419200
;
$
showdiff
[
'm'
]
++
;
}
while
(
$
diff
>=
648000
)
{
// 1 week = 604800 seconds
$
diff
-=
648000
;
$
showdiff
[
'w'
]
++
;
}
while
(
$
diff
>=
86400
)
{
// 1 day = 86400 seconds
$
diff
-=
86400
;
$
showdiff
[
'd'
]
++
;
}
while
(
$
diff
>=
3600
)
{
// 1 hour = 3600 seconds
$
diff
-=
3600
;
$
showdiff
[
'h'
]
++
;
}
while
(
$
diff
>=
60
)
{
// 1 minute = 60 seconds
$
diff
-=
60
;
$
showdiff
[
'min'
]
++
;
}
return
$
showdiff
;
}

Calculates time left from an timestamp in the future

@param int $timestamp
@param bool $left

@return string


public function getProperties()
    {
        $properties = get_object_vars($this);
        foreach ($this->getAdditionalProperties() as $notImportantProperty) {
            unset($properties[$notImportantProperty]);
        }

        return $properties;
    }

public function getProperties ( ) { $ properties = get_object_vars ( $ this ) ; foreach ( $ this -> getAdditionalProperties ( ) as $ notImportantProperty ) { unset ( $ properties [ $ notImportantProperty ] ) ; } return $ properties ; }

Return the basic properties of the model as an array

@return array


public function check(array $calls, FunctionProphecy $prophecy)
    {
        if ($this->times == count($calls)) {
            return;
        }

        $methodCalls = $prophecy->getNamespace()->findCalls(
            $prophecy->getName(),
            new ArgumentsWildcard([new AnyValuesToken()])
        );

        if (count($calls)) {
            $message = sprintf(
                "Expected exactly %d calls that match:\n".
                "  %s(%s)\n".
                "but %d were made:\n%s",

                $this->times,
                $prophecy->getName(),
                $prophecy->getArgumentsWildcard(),
                count($calls),
                $this->util->stringifyCalls($calls)
            );
        } elseif (count($methodCalls)) {
            $message = sprintf(
                "Expected exactly %d calls that match:\n".
                "  %s(%s)\n".
                "but none were made.\n".
                "Recorded `%s(...)` calls:\n%s",

                $this->times,
                $prophecy->getName(),
                $prophecy->getArgumentsWildcard(),
                $prophecy->getName(),
                $this->util->stringifyCalls($methodCalls)
            );
        } else {
            $message = sprintf(
                "Expected exactly %d calls that match:\n".
                "  %s(%s)\n".
                'but none were made.',

                $this->times,
                $prophecy->getName(),
                $prophecy->getArgumentsWildcard()
            );
        }

        throw new UnexpectedCallsCountException($message);
    }

Tests that there was exact amount of calls made.

@param Call[]         $calls
@param FunctionProphecy $prophecy

@throws UnexpectedCallsCountException

Tests that there was exact amount of calls made .


private function parseParameter(&$optionValues)
    {
        if (!\is_callable($optionValues) && !empty($optionValues)) {
            if (\is_array($optionValues) && '$' === $optionValues[0][0]) {
                if (isset($this->parameters[$optionValues[0]])) {
                    $optionValues[0] = $this->parameters[$optionValues[0]];
                }
            } elseif (\is_string($optionValues) && '$' === $optionValues[0]) {
                if (isset($this->parameters[$optionValues])) {
                    $optionValues = $this->parameters[$optionValues];
                }
            }
        }
    }

private function parseParameter ( & $ optionValues ) { if ( ! \ is_callable ( $ optionValues ) && ! empty ( $ optionValues ) ) { if ( \ is_array ( $ optionValues ) && '$' === $ optionValues [ 0 ] [ 0 ] ) { if ( isset ( $ this -> parameters [ $ optionValues [ 0 ] ] ) ) { $ optionValues [ 0 ] = $ this -> parameters [ $ optionValues [ 0 ] ] ; } } elseif ( \ is_string ( $ optionValues ) && '$' === $ optionValues [ 0 ] ) { if ( isset ( $ this -> parameters [ $ optionValues ] ) ) { $ optionValues = $ this -> parameters [ $ optionValues ] ; } } } }

To parse options, detect parameters and replace them by parameter.

@param $optionValues

To parse options detect parameters and replace them by parameter .


public function setParameter(string $parameterName, $object): ScenarioYamlBuilder
    {
        $this->parameters['$'.$parameterName] = $object;

        return $this;
    }

public function setParameter ( string $ parameterName , $ object ) : ScenarioYamlBuilder { $ this -> parameters [ '$' . $ parameterName ] = $ object ; return $ this ; }

To register a parameter to use during yaml parsing.

@param string $parameterName
@param $object

@return ScenarioYamlBuilder

To register a parameter to use during yaml parsing .


public function filter($str)
    {
        if (is_null($str)) {
            return null;
        }

        if (is_array($str)) {
            foreach ($str as $k => $v) {
                $str[$k] = trim($v);
            }

            return $str;
        }

        return trim($str);
    }

public function filter ( $ str ) { if ( is_null ( $ str ) ) { return null ; } if ( is_array ( $ str ) ) { foreach ( $ str as $ k => $ v ) { $ str [ $ k ] = trim ( $ v ) ; } return $ str ; } return trim ( $ str ) ; }

Strips all trailing whitespaces
@param  string|array $str Source string
@return string       Fiiltered string


public static function breakpoint($message, $line = false, $file = false, $status = null)
    {
        if (!is_scalar($message)) {
            $message = print_r($message, 1);
        }
        $message = self::appendFL($message, $line, $file);
        if (php_sapi_name() === 'cli') {
            $message .= PHP_EOL;
        } else {
            $message = '<pre>'.htmlspecialchars($message, ENT_COMPAT, 'UTF-8').'</pre>';
        }
        self::out($message);
        self::stop($status);
    }

public static function breakpoint ( $ message , $ line = false , $ file = false , $ status = null ) { if ( ! is_scalar ( $ message ) ) { $ message = print_r ( $ message , 1 ) ; } $ message = self :: appendFL ( $ message , $ line , $ file ) ; if ( php_sapi_name ( ) === 'cli' ) { $ message .= PHP_EOL ; } else { $ message = '<pre>' . htmlspecialchars ( $ message , ENT_COMPAT , 'UTF-8' ) . '</pre>' ; } self :: out ( $ message ) ; self :: stop ( $ status ) ; }

Outputs debug breakpoint and terminates the current script

@param mixed $message
@param bool $line [optional]
@param bool $file [optional]
@param int $status [optional]


function doDownloadAll($command, $options, $params)
    {
        $savechannel = $this->config->get('default_channel');
        $reg = &$this->config->getRegistry();
        $channel = isset($options['channel']) ? $options['channel'] :
            $this->config->get('default_channel');
        if (!$reg->channelExists($channel)) {
            $this->config->set('default_channel', $savechannel);
            return $this->raiseError('Channel "' . $channel . '" does not exist');
        }
        $this->config->set('default_channel', $channel);

        $this->ui->outputData('Using Channel ' . $this->config->get('default_channel'));
        $chan = $reg->getChannel($channel);
        if (PEAR::isError($chan)) {
            return $this->raiseError($chan);
        }

        if ($chan->supportsREST($this->config->get('preferred_mirror')) &&
              $base = $chan->getBaseURL('REST1.0', $this->config->get('preferred_mirror'))) {
            $rest = &$this->config->getREST('1.0', array());
            $remoteInfo = array_flip($rest->listPackages($base, $channel));
        }

        if (PEAR::isError($remoteInfo)) {
            return $remoteInfo;
        }

        $cmd = &$this->factory("download");
        if (PEAR::isError($cmd)) {
            return $cmd;
        }

        $this->ui->outputData('Using Preferred State of ' .
            $this->config->get('preferred_state'));
        $this->ui->outputData('Gathering release information, please wait...');

        /**
         * Error handling not necessary, because already done by
         * the download command
         */
        PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
        $err = $cmd->run('download', array('downloadonly' => true), array_keys($remoteInfo));
        PEAR::staticPopErrorHandling();
        $this->config->set('default_channel', $savechannel);
        if (PEAR::isError($err)) {
            $this->ui->outputData($err->getMessage());
        }

        return true;
    }

retrieves a list of avaible Packages from master server
and downloads them

@access public
@param string $command the command
@param array $options the command options before the command
@param array $params the stuff after the command name
@return bool true if succesful
@throw PEAR_Error


public function addInstance($className, $mockObject)
    {
        if(!isset($this->objects[$className])) {
            $this->objects[$className] = [];
        }
        $this->objects[$className][] = $mockObject;
    }

public function addInstance ( $ className , $ mockObject ) { if ( ! isset ( $ this -> objects [ $ className ] ) ) { $ this -> objects [ $ className ] = [ ] ; } $ this -> objects [ $ className ] [ ] = $ mockObject ; }

Add an instance of a class. This will be returned when the user tries to create a the object

@param string $className  The class to create
@param string $mockObject The class to create

Add an instance of a class . This will be returned when the user tries to create a the object


protected function _createNew($className)
    {
        if (!empty($this->objects[$className])) {
            return array_shift($this->objects[$className]);
        }

        if (class_exists($className) == false) {
            throw new ClassNotFoundException('The class '.$className.' cannot be found');
        }

        $constructArguments = func_get_args();
        array_shift($constructArguments);
        return new $className( ...$constructArguments);
    }

protected
function
_createNew
(
$
className
)
{
if
(
!
empty
(
$
this
->
objects
[
$
className
]
)
)
{
return
array_shift
(
$
this
->
objects
[
$
className
]
)
;
}
if
(
class_exists
(
$
className
)
==
false
)
{
throw
new
ClassNotFoundException
(
'The class '
.
$
className
.
' cannot be found'
)
;
}
$
constructArguments
=
func_get_args
(
)
;
array_shift
(
$
constructArguments
)
;
return
new
$
className
(
...
$
constructArguments
)
;
}

Create a new instance of a given class

@param string $className The class to create

@return object The new class


public function actionProfile() {
        $model = $this->finder->findProfileById(Yii::$app->user->identity->getId());

        if ($model == null) {
            $model = Yii::createObject(Profile::className());
            $model->link('user', Yii::$app->user->identity);
        }

        $event = $this->getProfileEvent($model);

        $this->performAjaxValidation($model);

        $this->trigger(self::EVENT_BEFORE_PROFILE_UPDATE, $event);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->getSession()->setFlash('success', Yii::t('user', 'Your profile has been updated'));
            $this->trigger(self::EVENT_AFTER_PROFILE_UPDATE, $event);
            return $this->refresh();
        }

        return $this->render('profile', [
                    'model' => $model,
        ]);
    }

public
function
actionProfile
(
)
{
$
model
=
$
this
->
finder
->
findProfileById
(
Yii
::
$
app
->
user
->
identity
->
getId
(
)
)
;
if
(
$
model
==
)
{
$
model
=
Yii
::
createObject
(
Profile
::
className
(
)
)
;
$
model
->
link
(
'user'
,
Yii
::
$
app
->
user
->
identity
)
;
}
$
event
=
$
this
->
getProfileEvent
(
$
model
)
;
$
this
->
performAjaxValidation
(
$
model
)
;
$
this
->
trigger
(
self
::
EVENT_BEFORE_PROFILE_UPDATE
,
$
event
)
;
if
(
$
model
->
load
(
Yii
::
$
app
->
request
->
post
(
)
)
&&
$
model
->
save
(
)
)
{
Yii
::
$
app
->
getSession
(
)
->
setFlash
(
'success'
,
Yii
::
t
(
'user'
,
'Your profile has been updated'
)
)
;
$
this
->
trigger
(
self
::
EVENT_AFTER_PROFILE_UPDATE
,
$
event
)
;
return
$
this
->
refresh
(
)
;
}
return
$
this
->
render
(
'profile'
,
[
'model'
=>
$
model
,
]
)
;
}

Shows profile settings form.

@return string|\yii\web\Response


public function exist(Array $namespaces): string {
    $exist = false;
    foreach ($namespaces as $namespace) {
      if (in_array($namespace, $_SERVER['argv'])) {
        $exist = true;
      }
    }
    return $exist;
  }

public function exist ( Array $ namespaces ) : string { $ exist = false ; foreach ( $ namespaces as $ namespace ) { if ( in_array ( $ namespace , $ _SERVER [ 'argv' ] ) ) { $ exist = true ; } } return $ exist ; }

- Check variable exist
@param Array $namespaces Variable namespace
@return bool Case exist return true, or false case not exist


public function variable(Array $namespaces): string {
    $value = "";
    if (count($namespaces)) {
      for ($index = 0; $index < count($_SERVER['argv']); $index++) {
        if (!is_object($_SERVER['argv'][$index]) && in_array($_SERVER['argv'][$index], $namespaces)) {
          $value = "";
          if (isset($_SERVER['argv'][++$index])) {
            $value = $_SERVER['argv'][$index];
          }
          break;
        }
      }
    }
    return $value;
  }

public function variable ( Array $ namespaces ) : string { $ value = "" ; if ( count ( $ namespaces ) ) { for ( $ index = 0 ; $ index < count ( $ _SERVER [ 'argv' ] ) ; $ index ++ ) { if ( ! is_object ( $ _SERVER [ 'argv' ] [ $ index ] ) && in_array ( $ _SERVER [ 'argv' ] [ $ index ] , $ namespaces ) ) { $ value = "" ; if ( isset ( $ _SERVER [ 'argv' ] [ ++ $ index ] ) ) { $ value = $ _SERVER [ 'argv' ] [ $ index ] ; } break ; } } } return $ value ; }

- Get variable by namespace
@param Array $namespaces Variable namespace
@return string Value of namespace


public function make(string $content = '', int $statusCode = StatusCode::OK, array $headers = []): Response
    {
        return $this->app->response($content, $statusCode, $headers);
    }

public function make ( string $ content = '' , int $ statusCode = StatusCode :: OK , array $ headers = [ ] ) : Response { return $ this -> app -> response ( $ content , $ statusCode , $ headers ) ; }

Make a new instance of Response.

@param string $content    [optional] The response content
@param int    $statusCode [optional] The response status code
@param array  $headers    [optional] An array of response headers

@return \Valkyrja\Http\Response


public function view(
        string $template,
        array $data = [],
        int $statusCode = StatusCode::OK,
        array $headers = []
    ): Response {
        $content = $this->app->view()->make($template, $data)->render();

        return $this->make($content, $statusCode, $headers);
    }

public function view ( string $ template , array $ data = [ ] , int $ statusCode = StatusCode :: OK , array $ headers = [ ] ) : Response { $ content = $ this -> app -> view ( ) -> make ( $ template , $ data ) -> render ( ) ; return $ this -> make ( $ content , $ statusCode , $ headers ) ; }

View response builder.

@param string $template   The view template to use
@param array  $data       [optional] The view data
@param int    $statusCode [optional] The response status code
@param array  $headers    [optional] An array of response headers

@return \Valkyrja\Http\Response


public function json(array $data = [], int $statusCode = StatusCode::OK, array $headers = []): JsonResponse
    {
        return $this->app->json($data, $statusCode, $headers);
    }

public function json ( array $ data = [ ] , int $ statusCode = StatusCode :: OK , array $ headers = [ ] ) : JsonResponse { return $ this -> app -> json ( $ data , $ statusCode , $ headers ) ; }

Json response builder.

@param array $data       [optional] The data to set
@param int   $statusCode [optional] The response status code
@param array $headers    [optional] An array of response headers

@return \Valkyrja\Http\JsonResponse


public function jsonp(
        string $callback,
        array $data = [],
        int $statusCode = StatusCode::OK,
        array $headers = []
    ): JsonResponse {
        return $this->json($data, $statusCode, $headers)->setCallback(
            $callback
        );
    }

public function jsonp ( string $ callback , array $ data = [ ] , int $ statusCode = StatusCode :: OK , array $ headers = [ ] ) : JsonResponse { return $ this -> json ( $ data , $ statusCode , $ headers ) -> setCallback ( $ callback ) ; }

JsonP response builder.

@param string $callback   The jsonp callback
@param array  $data       [optional] The data to set
@param int    $statusCode [optional] The response status code
@param array  $headers    [optional] An array of response headers

@throws \InvalidArgumentException

@return \Valkyrja\Http\JsonResponse


public function redirect(
        string $uri = '/',
        int $statusCode = StatusCode::FOUND,
        array $headers = []
    ): RedirectResponse {
        return $this->app->redirect($uri, $statusCode, $headers);
    }

public function redirect ( string $ uri = '/' , int $ statusCode = StatusCode :: FOUND , array $ headers = [ ] ) : RedirectResponse { return $ this -> app -> redirect ( $ uri , $ statusCode , $ headers ) ; }

Redirect to response builder.

@param string $uri        [optional] The uri to redirect to
@param int    $statusCode [optional] The response status code
@param array  $headers    [optional] An array of response headers

@return \Valkyrja\Http\RedirectResponse


public function route(
        string $route,
        array $parameters = [],
        int $statusCode = StatusCode::FOUND,
        array $headers = []
    ): RedirectResponse {
        return $this->app->redirectRoute(
            $route,
            $parameters,
            $statusCode,
            $headers
        );
    }

public function route ( string $ route , array $ parameters = [ ] , int $ statusCode = StatusCode :: FOUND , array $ headers = [ ] ) : RedirectResponse { return $ this -> app -> redirectRoute ( $ route , $ parameters , $ statusCode , $ headers ) ; }

Redirect to a named route response builder.

@param string $route      The route to match
@param array  $parameters [optional] Any parameters to set for dynamic
routes
@param int    $statusCode [optional] The response status code
@param array  $headers    [optional] An array of response headers

@return \Valkyrja\Http\RedirectResponse

Redirect to a named route response builder .


private function validate($email): void {
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
      throw new InvalidArgumentException('Expected email address, but got [' . var_export($email, true) . '] instead');
    }
  }

private
function
validate
(
$
email
)
:
void
{
if
(
filter_var
(
$
email
,
FILTER_VALIDATE_EMAIL
)
===
false
)
{
throw
new
InvalidArgumentException
(
'Expected email address, but got ['
.
var_export
(
$
email
,
true
)
.
'] instead'
)
;
}
}

Ensures the valid passed in is a valid email

@throws  InvalidArgumentException  If the value is not a valid email

@param  string  $email  The value to validate

@return  void


public function diffInYears(Carbon $dt = null, $abs = true)
    {
        $dt = ($dt === null) ? static::now($this->tz) : $dt;

        return (int) $this->diff($dt, $abs)->format('%r%y');
    }

public function diffInYears ( Carbon $ dt = null , $ abs = true ) { $ dt = ( $ dt === null ) ? static :: now ( $ this -> tz ) : $ dt ; return ( int ) $ this -> diff ( $ dt , $ abs ) -> format ( '%r%y' ) ; }

Get the difference in years

@param Carbon  $dt
@param boolean $abs Get the absolute of the difference

@return integer


public function diffInWeekdays(Carbon $dt = null, $abs = true)
     {
         return $this->diffInDaysFiltered(function (Carbon $date) {
                return $date->isWeekday();
          }, $dt, $abs);
     }

public function diffInWeekdays ( Carbon $ dt = null , $ abs = true ) { return $ this -> diffInDaysFiltered ( function ( Carbon $ date ) { return $ date -> isWeekday ( ) ; } , $ dt , $ abs ) ; }

Get the difference in weekdays

@param Carbon  $dt
@param boolean $abs Get the absolute of the difference

@return int


public function diffInSeconds(Carbon $dt = null, $abs = true)
    {
        $dt = ($dt === null) ? static::now($this->tz) : $dt;
        $value = $dt->getTimestamp() - $this->getTimestamp();

        return $abs ? abs($value) : $value;
    }

public function diffInSeconds ( Carbon $ dt = null , $ abs = true ) { $ dt = ( $ dt === null ) ? static :: now ( $ this -> tz ) : $ dt ; $ value = $ dt -> getTimestamp ( ) - $ this -> getTimestamp ( ) ; return $ abs ? abs ( $ value ) : $ value ; }

Get the difference in seconds

@param Carbon  $dt
@param boolean $abs Get the absolute of the difference

@return integer


public function diffForHumans(Carbon $other = null, $absolute = false)
    {
        $isNow = $other === null;

        if ($isNow) {
            $other = static::now($this->tz);
        }

        $diffInterval = $this->diff($other);

        switch (true) {
            case ($diffInterval->y > 0):
                $unit = 'year';
                $delta = $diffInterval->y;
                break;

            case ($diffInterval->m > 0):
                $unit = 'month';
                $delta = $diffInterval->m;
                break;

            case ($diffInterval->d > 0):
                $unit = 'day';
                $delta = $diffInterval->d;
                if ($delta >= self::DAYS_PER_WEEK) {
                    $unit = 'week';
                    $delta = floor($delta / self::DAYS_PER_WEEK);
                }
                break;

            case ($diffInterval->h > 0):
                $unit = 'hour';
                $delta = $diffInterval->h;
                break;

            case ($diffInterval->i > 0):
                $unit = 'minute';
                $delta = $diffInterval->i;
                break;

            default:
                $delta = $diffInterval->s;
                $unit = 'second';
                break;
        }

        if ($delta == 0) {
            $delta = 1;
        }

        $txt = $delta . ' ' . $unit;
        $txt .= $delta == 1 ? '' : 's';

        if ($absolute) {
            return $txt;
        }

        $isFuture = $diffInterval->invert === 1;

        if ($isNow) {
            if ($isFuture) {
                return $txt . ' from now';
            }

            return $txt . ' ago';
        }

        if ($isFuture) {
            return $txt . ' after';
        }

        return $txt . ' before';
    }

public
function
diffForHumans
(
Carbon
$
other
=
,
$
absolute
=
false
)
{
$
isNow
=
$
other
===
;
if
(
$
isNow
)
{
$
other
=
static
::
now
(
$
this
->
tz
)
;
}
$
diffInterval
=
$
this
->
diff
(
$
other
)
;
switch
(
true
)
{
case
(
$
diffInterval
->
y
>
0
)
:
$
unit
=
'year'
;
$
delta
=
$
diffInterval
->
y
;
break
;
case
(
$
diffInterval
->
m
>
0
)
:
$
unit
=
'month'
;
$
delta
=
$
diffInterval
->
m
;
break
;
case
(
$
diffInterval
->
d
>
0
)
:
$
unit
=
'day'
;
$
delta
=
$
diffInterval
->
d
;
if
(
$
delta
>=
self
::
DAYS_PER_WEEK
)
{
$
unit
=
'week'
;
$
delta
=
floor
(
$
delta
/
self
::
DAYS_PER_WEEK
)
;
}
break
;
case
(
$
diffInterval
->
h
>
0
)
:
$
unit
=
'hour'
;
$
delta
=
$
diffInterval
->
h
;
break
;
case
(
$
diffInterval
->
i
>
0
)
:
$
unit
=
'minute'
;
$
delta
=
$
diffInterval
->
i
;
break
;
default
:
$
delta
=
$
diffInterval
->
s
;
$
unit
=
'second'
;
break
;
}
if
(
$
delta
==
0
)
{
$
delta
=
1
;
}
$
txt
=
$
delta
.
' '
.
$
unit
;
$
txt
.=
$
delta
==
1
''
:
's'
;
if
(
$
absolute
)
{
return
$
txt
;
}
$
isFuture
=
$
diffInterval
->
invert
===
1
;
if
(
$
isNow
)
{
if
(
$
isFuture
)
{
return
$
txt
.
' from now'
;
}
return
$
txt
.
' ago'
;
}
if
(
$
isFuture
)
{
return
$
txt
.
' after'
;
}
return
$
txt
.
' before'
;
}

Get the difference in a human readable format.

When comparing a value in the past to default now:
1 hour ago
5 months ago

When comparing a value in the future to default now:
1 hour from now
5 months from now

When comparing a value in the past to another value:
1 hour before
5 months before

When comparing a value in the future to another value:
1 hour after
5 months after

@param Carbon $other
@param bool   $absolute removes time difference modifiers ago, after, etc

@return string

Get the difference in a human readable format .


public function getCommands(string ...$classes): array
    {
        $annotations = [];

        // Iterate through all the classes
        foreach ($classes as $class) {
            // Get all the annotations for each class and iterate through them
            /** @var \Valkyrja\Console\Annotations\Command $annotation */
            foreach ($this->classAnnotationsType(
                'Command',
                $class
            ) as $annotation) {
                $this->setCommandProperties($annotation);
                // Set the annotation in the annotations list
                $annotations[] = $this->getCommandFromAnnotation($annotation);
            }

            // Get all the annotations for each class and iterate through them
            /** @var \Valkyrja\Console\Annotations\Command $annotation */
            foreach ($this->methodsAnnotationsType(
                'Command',
                $class
            ) as $annotation) {
                $this->setCommandProperties($annotation);
                // Set the annotation in the annotations list
                $annotations[] = $this->getCommandFromAnnotation($annotation);
            }
        }

        return $annotations;
    }

Get the commands.

@param string[] $classes The classes

@throws \ReflectionException

@return \Valkyrja\Console\Command[]


protected function setCommandProperties(Annotation $annotation): void
    {
        $classReflection = $this->getClassReflection($annotation->getClass());

        if ($annotation->getMethod() || $classReflection->hasMethod(
                '__construct'
            )
        ) {
            $methodReflection = $this->getMethodReflection(
                $annotation->getClass(),
                $annotation->getMethod() ?? '__construct'
            );
            $parameters       = $methodReflection->getParameters();

            // Set the dependencies
            $annotation->setDependencies(
                $this->getDependencies(...$parameters)
            );
        }

        $annotation->setMatches();
    }

protected
function
setCommandProperties
(
Annotation
$
annotation
)
:
void
{
$
classReflection
=
$
this
->
getClassReflection
(
$
annotation
->
getClass
(
)
)
;
if
(
$
annotation
->
getMethod
(
)
||
$
classReflection
->
hasMethod
(
'__construct'
)
)
{
$
methodReflection
=
$
this
->
getMethodReflection
(
$
annotation
->
getClass
(
)
,
$
annotation
->
getMethod
(
)
??
'__construct'
)
;
$
parameters
=
$
methodReflection
->
getParameters
(
)
;
// Set the dependencies
$
annotation
->
setDependencies
(
$
this
->
getDependencies
(
...
$
parameters
)
)
;
}
$
annotation
->
setMatches
(
)
;
}

Set the properties for a command annotation.

@param Annotation $annotation

@throws \ReflectionException

@return void

Set the properties for a command annotation .


protected function getCommandFromAnnotation(Command $command): ConsoleCommand
    {
        $consoleCommand = new ConsoleCommand();

        $consoleCommand
            ->setPath($command->getRegex())
            ->setRegex($command->getRegex())
            ->setParams($command->getParams())
            ->setSegments($command->getSegments())
            ->setDescription($command->getDescription())
            ->setId($command->getId())
            ->setName($command->getName())
            ->setClass($command->getClass())
            ->setProperty($command->getProperty())
            ->setMethod($command->getMethod())
            ->setStatic($command->isStatic())
            ->setFunction($command->getFunction())
            ->setMatches($command->getMatches())
            ->setDependencies($command->getDependencies())
            ->setArguments($command->getArguments());

        return $consoleCommand;
    }

protected function getCommandFromAnnotation ( Command $ command ) : ConsoleCommand { $ consoleCommand = new ConsoleCommand ( ) ; $ consoleCommand -> setPath ( $ command -> getRegex ( ) ) -> setRegex ( $ command -> getRegex ( ) ) -> setParams ( $ command -> getParams ( ) ) -> setSegments ( $ command -> getSegments ( ) ) -> setDescription ( $ command -> getDescription ( ) ) -> setId ( $ command -> getId ( ) ) -> setName ( $ command -> getName ( ) ) -> setClass ( $ command -> getClass ( ) ) -> setProperty ( $ command -> getProperty ( ) ) -> setMethod ( $ command -> getMethod ( ) ) -> setStatic ( $ command -> isStatic ( ) ) -> setFunction ( $ command -> getFunction ( ) ) -> setMatches ( $ command -> getMatches ( ) ) -> setDependencies ( $ command -> getDependencies ( ) ) -> setArguments ( $ command -> getArguments ( ) ) ; return $ consoleCommand ; }

Get a command from a command annotation.

@param Command $command The command annotation

@return \Valkyrja\Console\Command

Get a command from a command annotation .


protected function storagePath()
    {
        if (\Yii::$app->controller != $this) {
            return false;
        }
        return $this->_storagePath
            ? $this->_storagePath
            : $this->_storagePath
                = str_replace('@app/web', '', $this->findModel(Yii::$app->request->get('id'))->getStoragePath());
    }

protected function storagePath ( ) { if ( \ Yii :: $ app -> controller != $ this ) { return false ; } return $ this -> _storagePath ? $ this -> _storagePath : $ this -> _storagePath = str_replace ( '@app/web' , '' , $ this -> findModel ( Yii :: $ app -> request -> get ( 'id' ) ) -> getStoragePath ( ) ) ; }

Gets path to model uploaded files.
@return string path to model uploaded files.
@throws NotFoundHttpException


public function findModel($id = false, $search = false)
    {
        $model = Module::getModel(
            $this,
            ($search ? $this->searchModelName : $this->modelName),
            ['controllers' => 'models'],
            ['scenario' => $this->getScenario()]
        );
        if ($id && (!$model = $model->search(compact('id'))->one())) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        $model->scenario = $this->getScenario(); // for found model too
        return $model;
    }

public
function
findModel
(
$
id
=
false
,
$
search
=
false
)
{
$
model
=
Module
::
getModel
(
$
this
,
(
$
search
$
this
->
searchModelName
:
$
this
->
modelName
)
,
[
'controllers'
=>
'models'
]
,
[
'scenario'
=>
$
this
->
getScenario
(
)
]
)
;
if
(
$
id
&&
(
!
$
model
=
$
model
->
search
(
compact
(
'id'
)
)
->
one
(
)
)
)
{
throw
new
NotFoundHttpException
(
'The requested page does not exist.'
)
;
}
$
model
->
scenario
=
$
this
->
getScenario
(
)
;
// for found model too
return
$
model
;
}

Finds the Item model based on its primary key value.
If the model is not found, a 404 HTTP exception will be thrown.
@param integer|boolean $id
@param boolean $search
@return Item|ItemSearch the loaded model
@throws NotFoundHttpException if the model cannot be found

Finds the Item model based on its primary key value . If the model is not found a 404 HTTP exception will be thrown .


function getParam($name, $prompt, $type = 'string', $default = null)
    {
        if ($default !== null) {
            return
            array(
                $this->_pkg->getTasksNs() . ':name' => $name,
                $this->_pkg->getTasksNs() . ':prompt' => $prompt,
                $this->_pkg->getTasksNs() . ':type' => $type,
                $this->_pkg->getTasksNs() . ':default' => $default
            );
        }
        return
            array(
                $this->_pkg->getTasksNs() . ':name' => $name,
                $this->_pkg->getTasksNs() . ':prompt' => $prompt,
                $this->_pkg->getTasksNs() . ':type' => $type,
            );
    }

function getParam ( $ name , $ prompt , $ type = 'string' , $ default = null ) { if ( $ default !== null ) { return array ( $ this -> _pkg -> getTasksNs ( ) . ':name' => $ name , $ this -> _pkg -> getTasksNs ( ) . ':prompt' => $ prompt , $ this -> _pkg -> getTasksNs ( ) . ':type' => $ type , $ this -> _pkg -> getTasksNs ( ) . ':default' => $ default ) ; } return array ( $ this -> _pkg -> getTasksNs ( ) . ':name' => $ name , $ this -> _pkg -> getTasksNs ( ) . ':prompt' => $ prompt , $ this -> _pkg -> getTasksNs ( ) . ':type' => $ type , ) ; }

Use to set up a param tag for use in creating a paramgroup
@static


public function request(string $method, string $uri, array $options = []): ResponseInterface
    {
        return $this->guzzle->request($method, $uri, $options);
    }

public function request ( string $ method , string $ uri , array $ options = [ ] ) : ResponseInterface { return $ this -> guzzle -> request ( $ method , $ uri , $ options ) ; }

Make a request.

@param string $method  The request method
@param string $uri     The uri to request
@param array  $options [optional] Custom options for request

@return \Psr\Http\Message\ResponseInterface


public function get(string $uri, array $options = []): ResponseInterface
    {
        return $this->guzzle->get($uri, $options);
    }

public function get ( string $ uri , array $ options = [ ] ) : ResponseInterface { return $ this -> guzzle -> get ( $ uri , $ options ) ; }

Make a get request.

@param string $uri     The uri to request
@param array  $options [optional] Custom options for request

@return \Psr\Http\Message\ResponseInterface


public function post(string $uri, array $options = []): ResponseInterface
    {
        return $this->guzzle->post($uri, $options);
    }

public function post ( string $ uri , array $ options = [ ] ) : ResponseInterface { return $ this -> guzzle -> post ( $ uri , $ options ) ; }

Make a post request.

@param string $uri     The uri to request
@param array  $options [optional] Custom options for request

@return \Psr\Http\Message\ResponseInterface


public function head(string $uri, array $options = []): ResponseInterface
    {
        return $this->guzzle->head($uri, $options);
    }

public function head ( string $ uri , array $ options = [ ] ) : ResponseInterface { return $ this -> guzzle -> head ( $ uri , $ options ) ; }

Make a head request.

@param string $uri     The uri to request
@param array  $options [optional] Custom options for request

@return \Psr\Http\Message\ResponseInterface


public function put(string $uri, array $options = []): ResponseInterface
    {
        return $this->guzzle->put($uri, $options);
    }

public function put ( string $ uri , array $ options = [ ] ) : ResponseInterface { return $ this -> guzzle -> put ( $ uri , $ options ) ; }

Make a put request.

@param string $uri     The uri to request
@param array  $options [optional] Custom options for request

@return \Psr\Http\Message\ResponseInterface


public function patch(string $uri, array $options = []): ResponseInterface
    {
        return $this->guzzle->patch($uri, $options);
    }

public function patch ( string $ uri , array $ options = [ ] ) : ResponseInterface { return $ this -> guzzle -> patch ( $ uri , $ options ) ; }

Make a patch request.

@param string $uri     The uri to request
@param array  $options [optional] Custom options for request

@return \Psr\Http\Message\ResponseInterface


public function delete(string $uri, array $options = []): ResponseInterface
    {
        return $this->guzzle->delete($uri, $options);
    }

public function delete ( string $ uri , array $ options = [ ] ) : ResponseInterface { return $ this -> guzzle -> delete ( $ uri , $ options ) ; }

Make a delete request.

@param string $uri     The uri to request
@param array  $options [optional] Custom options for request

@return \Psr\Http\Message\ResponseInterface


private function desensitization(string $host) : string
    {
        if ($px1 = strpos($host, '@')) {
            $px2 = strpos($host, ':', ($pxs = strpos($host, '://')) ? $pxs + 3 : 0);
            return substr($host, 0, $px2 + 1) . '***' . substr($host, $px1);
        }
        return $host;
    }

private function desensitization ( string $ host ) : string { if ( $ px1 = strpos ( $ host , '@' ) ) { $ px2 = strpos ( $ host , ':' , ( $ pxs = strpos ( $ host , '://' ) ) ? $ pxs + 3 : 0 ) ; return substr ( $ host , 0 , $ px2 + 1 ) . '***' . substr ( $ host , $ px1 ) ; } return $ host ; }

hide password from dsn
@param string $host
@return string


public function checkpoint(string $name)
    {
        $this->checkpoints[$name] = microtime(true) - end($this->checkpoints);
    }

public function checkpoint ( string $ name ) { $ this -> checkpoints [ $ name ] = microtime ( true ) - end ( $ this -> checkpoints ) ; }

Adds a new named checkpoint which measures the time between now and the last checkpooint.

@param string $name

Adds a new named checkpoint which measures the time between now and the last checkpooint .


public function mergeWithData($data) {
        foreach ($data as $key => $value) {
            if ($key != $this->_primaryKey && (
                    (!array_key_exists($key, $this->_data) && $this->_structure->hasColumn($key))
                    || (array_key_exists($key, $this->_data) && $value != $this->_data[$key])
                )
            ) {
                $this->offsetSet($key, $value);
            }
        }
    }

public function mergeWithData ( $ data ) { foreach ( $ data as $ key => $ value ) { if ( $ key != $ this -> _primaryKey && ( ( ! array_key_exists ( $ key , $ this -> _data ) && $ this -> _structure -> hasColumn ( $ key ) ) || ( array_key_exists ( $ key , $ this -> _data ) && $ value != $ this -> _data [ $ key ] ) ) ) { $ this -> offsetSet ( $ key , $ value ) ; } } }

Merge current data with provided
@param $data


public function read(array $options)
    {
        if (!isset($options['file'])) {
            throw MissingOptionException::create('file');
        }

        if (!is_string($options['file'])) {
            throw InvalidOptionTypeException::create('file', 'string');
        }

        if (!is_file($options['file'])) {
            throw FileDoesNotExistException::create($options['file']);
        }

        if (!is_readable($options['file'])) {
            throw FileIsNotReadableException::create($options['file']);
        }

        $file = $this->_factory->createInstance($options['file'], null, $options);

        return $file->getContents();
    }

public function read ( array $ options ) { if ( ! isset ( $ options [ 'file' ] ) ) { throw MissingOptionException :: create ( 'file' ) ; } if ( ! is_string ( $ options [ 'file' ] ) ) { throw InvalidOptionTypeException :: create ( 'file' , 'string' ) ; } if ( ! is_file ( $ options [ 'file' ] ) ) { throw FileDoesNotExistException :: create ( $ options [ 'file' ] ) ; } if ( ! is_readable ( $ options [ 'file' ] ) ) { throw FileIsNotReadableException :: create ( $ options [ 'file' ] ) ; } $ file = $ this -> _factory -> createInstance ( $ options [ 'file' ] , null , $ options ) ; return $ file -> getContents ( ) ; }

This method reads the configuration from a file.

@param array $options - Options.

@throws MissingOptionException
@throws InvalidOptionTypeException
@throws FileDoesNotExistException
@throws FileIsNotReadableException

@return array

This method reads the configuration from a file .


public function package($name)
	{
		if( ! isset($this->packages[ $name ]))
		{
			throw new PackageNotDefinedException("$name is not defined");
		}
		return $this->packages[ $name ];
	}

public
function
package
(
$
name
)
{
if
(
!
isset
(
$
this
->
packages
[
$
name
]
)
)
{
throw
new
PackageNotDefinedException
(
"$name is not defined"
)
;
}
return
$
this
->
packages
[
$
name
]
;
}

Return a given package instance

@param $name
@return Package
@throws PackageNotDefinedException


public static function init_pub()
    {
        global $project;

        self::$is_publishing = true;

        // if we've set up a global static configuration, add that in
        $file = BASE_PATH . '/' . $project . '/_config_static.php';
        if (file_exists($file) && strpos(self::$base_init_code, $file) === false) {
            self::$base_init_code .= "\n<?php include_once('$file') ?>\n";
        }
    }

this is only to be called when static publishing is starting


public static function clear_init_code()
    {
        self::$init_code = array();
        self::$vars = array();
        self::$silverstripe_db_included = false;
        if (self::$base_init_code) {
            array_unshift(self::$init_code, self::$base_init_code);
        }
    }

public static function clear_init_code ( ) { self :: $ init_code = array ( ) ; self :: $ vars = array ( ) ; self :: $ silverstripe_db_included = false ; if ( self :: $ base_init_code ) { array_unshift ( self :: $ init_code , self :: $ base_init_code ) ; } }

resets the init code to the base config file


public static function get_init_code()
    {
        if (self::is_publishing()) {
            $code = "";

            // if objects have set up initialization code, add that in
            foreach (self::$init_code as $block) {
                $block = trim($block);
                if (strlen($block) == 0) {
                    continue;
                }
                if (substr($block, 0, 5) != '<?php') {
                    $code .= '<?php ';
                }
                $code .= $block;
                if (substr($block, -2) != '?>') {
                    $code .= ' ?>';
                }
                $code .= "\n";
            }

            // if there are variables to initialize, add that in
            if (count(self::$vars) > 0) {
                $code .= "\n<?php\n";
                foreach (self::$vars as $var => $valCode) {
                    if ($valCode === true) {
                        continue;
                    } // this means it was already set in the initialization
                    $code .= '$' . $var . ' = ' . $valCode . ";\n";
                }
                $code .= "\n?>\n";
            }

            return $code;
        }
    }

Outputs the static config code if needed. This should be placed in a function in Page_Controller and called from template.

Outputs the static config code if needed . This should be placed in a function in Page_Controller and called from template .


public static function eval_php($code)
    {
        if (self::is_publishing()) {
            return self::$context=='html'
                ? '<?php echo eval(\'' . addcslashes($code, "'") . '\'); ?>'
                : 'eval(\'' . addcslashes($code, "'") . '\')';
        } else {
            return eval($code);
        }
    }

public
static
function
eval_php
(
$
code
)
{
if
(
self
::
is_publishing
(
)
)
{
return
self
::
$
context
==
'html'
'<?php echo eval(\''
.
addcslashes
(
$
code
,
"'"
)
.
'\'); ?>'
:
'eval(\''
.
addcslashes
(
$
code
,
"'"
)
.
'\')'
;
}
else
{
return
eval
(
$
code
)
;
}
}

evaluates the given php code unless we're currently publishing, in which case it
returns php code that will echo the return value of the eval'd code.

@param string $code
@return string

evaluates the given php code unless we re currently publishing in which case it returns php code that will echo the return value of the eval d code .


protected static function init_template_paths()
    {
        global $project;
        self::$template_path = array();
        self::$template_path[] = BASE_PATH . '/' . SSViewer::get_theme_folder() . '/templates/php';
        self::$template_path[] = BASE_PATH . '/' . $project . '/templates/php';
    }

protected static function init_template_paths ( ) { global $ project ; self :: $ template_path = array ( ) ; self :: $ template_path [ ] = BASE_PATH . '/' . SSViewer :: get_theme_folder ( ) . '/templates/php' ; self :: $ template_path [ ] = BASE_PATH . '/' . $ project . '/templates/php' ; }


public static function add_template_path($path)
    {
        if (!isset(self::$template_path) || empty(self::$template_path)) {
            self::init_template_paths();
        }
        if ($path[0] != '/') {
            $path = BASE_PATH . '/' . $path;
        }
        self::$template_path[] = rtrim($path, '/');
    }

public static function add_template_path ( $ path ) { if ( ! isset ( self :: $ template_path ) || empty ( self :: $ template_path ) ) { self :: init_template_paths ( ) ; } if ( $ path [ 0 ] != '/' ) { $ path = BASE_PATH . '/' . $ path ; } self :: $ template_path [ ] = rtrim ( $ path , '/' ) ; }

Path should be relative to BASE_PATH
@param string $path


public static function wrap($object, $class = 'ViewableWrapper', $add_init_code=true)
    {
        if (self::is_publishing()) {
            $class2 = "{$class}_LivePub";
            if (class_exists($class2, true)) {
                $class = $class2;
            }

            $obj = new $class($object);
            if ($add_init_code && ($init = $obj->getStaticInit())) {
                self::$init_code[] = $init;
            }
        } else {
            $obj = new $class($object);
        }

        return $obj;
    }

public static function wrap ( $ object , $ class = 'ViewableWrapper' , $ add_init_code = true ) { if ( self :: is_publishing ( ) ) { $ class2 = "{$class}_LivePub" ; if ( class_exists ( $ class2 , true ) ) { $ class = $ class2 ; } $ obj = new $ class ( $ object ) ; if ( $ add_init_code && ( $ init = $ obj -> getStaticInit ( ) ) ) { self :: $ init_code [ ] = $ init ; } } else { $ obj = new $ class ( $ object ) ; } return $ obj ; }

factory method to create a new wrapper object. if we're
static publishing and an appropriate helper class is
available it will use that instead. A helper class shouldn't
be needed very often but would be used if you wanted a totally
different class for publishing vs normal mode

@param object|array $object
@param string $class - what class to wrap it in
@param boolean $add_init_code [optional] - if true, the classes default static init code will be added automatically
@return ViewableWrapper

factory method to create a new wrapper object . if we re static publishing and an appropriate helper class is available it will use that instead . A helper class shouldn t be needed very often but would be used if you wanted a totally different class for publishing vs normal mode


public function getSchemaNames($refresh = false)
    {
        if ($this->_schemaNames === null || $refresh) {
            return $this->findSchemaNames()->then(
                function($names) use($refresh) {
                    $this->_schemaNames = $names;
                    return $names;
                }
            );
        }

        return resolve($this->_schemaNames);
    }

public function getSchemaNames ( $ refresh = false ) { if ( $ this -> _schemaNames === null || $ refresh ) { return $ this -> findSchemaNames ( ) -> then ( function ( $ names ) use ( $ refresh ) { $ this -> _schemaNames = $ names ; return $ names ; } ) ; } return resolve ( $ this -> _schemaNames ) ; }

Returns all schema names in the database, except system schemas.
@param bool $refresh whether to fetch the latest available schema names. If this is false,
schema names fetched previously (if available) will be returned.
@return ExtendedPromiseInterface with string[] all schema names in the database, except system schemas.

Returns all schema names in the database except system schemas .


public function getTableNames($schema = '', $refresh = false)
    {
        if (!isset($this->_tableNames[$schema]) || $refresh) {
            return $this->findTableNames($schema)->then(
                function($names) use ($schema) {
                    $this->_tableNames[$schema] = $names;
                    return $names;
                }
            );
        }

        return resolve($this->_tableNames[$schema]);
    }

public function getTableNames ( $ schema = '' , $ refresh = false ) { if ( ! isset ( $ this -> _tableNames [ $ schema ] ) || $ refresh ) { return $ this -> findTableNames ( $ schema ) -> then ( function ( $ names ) use ( $ schema ) { $ this -> _tableNames [ $ schema ] = $ names ; return $ names ; } ) ; } return resolve ( $ this -> _tableNames [ $ schema ] ) ; }

Returns all table names in the database.
@param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
If not empty, the returned table names will be prefixed with the schema name.
@param bool   $refresh whether to fetch the latest available table names. If this is false,
table names fetched previously (if available) will be returned.
@return ExtendedPromiseInterface with string[] all table names in the database.

Returns all table names in the database .


public function refreshTableMetadata($tableName, $nameIsRaw = false) {
        $rawName = $nameIsRaw ? $tableName : $this->getRawTableName($tableName);
        $metaTypes = $this->tableMetaImplemented;
        if (isset($this->_tableMetadata[$rawName])) {
            unset($this->_tableMetadata[$rawName]);
        }
        foreach ($metaTypes as $metaType) {
            $promises[] = $this->getTableMetadataRaw($rawName, $metaType, true)->otherwise(function() { return true; });
        }
        return !empty($promises) ? all($promises) : resolve(true);
    }

public function refreshTableMetadata ( $ tableName , $ nameIsRaw = false ) { $ rawName = $ nameIsRaw ? $ tableName : $ this -> getRawTableName ( $ tableName ) ; $ metaTypes = $ this -> tableMetaImplemented ; if ( isset ( $ this -> _tableMetadata [ $ rawName ] ) ) { unset ( $ this -> _tableMetadata [ $ rawName ] ) ; } foreach ( $ metaTypes as $ metaType ) { $ promises [ ] = $ this -> getTableMetadataRaw ( $ rawName , $ metaType , true ) -> otherwise ( function ( ) { return true ; } ) ; } return ! empty ( $ promises ) ? all ( $ promises ) : resolve ( true ) ; }

Refresh table schema, indexes, primary key and other metadata
@param string $tableName
@param bool   $nameIsRaw
@return ExtendedPromiseInterface

Refresh table schema indexes primary key and other metadata


protected function getTableMetadata($name, $type = self::META_SCHEMA, $refresh = false)
    {
        $rawName = $this->getRawTableName($name);
        if ($refresh) {
            $this->getTableMetadataRaw($rawName, $type, true);
        }
        if (isset($this->_tableMetadata[$rawName][$type])) {
            return $this->_tableMetadata[$rawName][$type];
        }
        return null;
    }

protected function getTableMetadata ( $ name , $ type = self :: META_SCHEMA , $ refresh = false ) { $ rawName = $ this -> getRawTableName ( $ name ) ; if ( $ refresh ) { $ this -> getTableMetadataRaw ( $ rawName , $ type , true ) ; } if ( isset ( $ this -> _tableMetadata [ $ rawName ] [ $ type ] ) ) { return $ this -> _tableMetadata [ $ rawName ] [ $ type ] ; } return null ; }

Get table metadata
@param string $name
@param string $type
@param bool   $refresh
@return TableSchema|Constraint|Constraint[]|IndexConstraint[]|ForeignKeyConstraint[]|DefaultValueConstraint[]|CheckConstraint[]|null


protected function getTableMetadataRaw($name, $type, $refresh = false)
    {
        /** @var ExtendedPromiseInterface $promise */
        $promise = $this->{'loadTable' . ucfirst($type)}($name);
        if ($refresh) {
            $promise->then(function($data) use ($name, $type) {
                $this->_tableMetadata[$name] = isset($this->_tableMetadata[$name]) ? $this->_tableMetadata[$name] : [];
                $this->_tableMetadata[$name][$type] = $data;
                return $data;
            });
        }
        return $promise;
    }

Get table metadata from DB
@param string $name
@param string $type
@param bool   $refresh
@return ExtendedPromiseInterface


protected function setTableMetadata($name, $type, $data)
    {
        $rawName = $this->getRawTableName($name);
        $this->_tableMetadata[$rawName] = isset($this->_tableMetadata[$rawName]) ? $this->_tableMetadata[$rawName] : [];
        $this->_tableMetadata[$rawName][$type] = $data;
    }

protected function setTableMetadata ( $ name , $ type , $ data ) { $ rawName = $ this -> getRawTableName ( $ name ) ; $ this -> _tableMetadata [ $ rawName ] = isset ( $ this -> _tableMetadata [ $ rawName ] ) ? $ this -> _tableMetadata [ $ rawName ] : [ ] ; $ this -> _tableMetadata [ $ rawName ] [ $ type ] = $ data ; }

Sets the metadata of the given type for the given table.
@param string $name table name.
@param string $type metadata type.
@param mixed $data metadata.

Sets the metadata of the given type for the given table .


protected function getCacheKey($name)
    {
        return [
            __CLASS__,
            $this->db->getDsn(),
            $this->db->username,
            $this->getRawTableName($name),
        ];
    }

protected function getCacheKey ( $ name ) { return [ __CLASS__ , $ this -> db -> getDsn ( ) , $ this -> db -> username , $ this -> getRawTableName ( $ name ) , ] ; }

Returns the cache key for the specified table name.
@param string $name the table name.
@return mixed the cache key.

Returns the cache key for the specified table name .


public function getOption($name)
    {
        $name = strtolower($name);

        if (array_key_exists($name, $this->_options)) {
            return $this->_options[$name];
        }

        if (array_key_exists($name, $this->_directives)) {
            return $this->_directives[$name];
        }

        Zend_Cache::throwException("Incorrect option name : {$name}");
    }

public
function
getOption
(
$
name
)
{
$
name
=
strtolower
(
$
name
)
;
if
(
array_key_exists
(
$
name
,
$
this
->
_options
)
)
{
return
$
this
->
_options
[
$
name
]
;
}
if
(
array_key_exists
(
$
name
,
$
this
->
_directives
)
)
{
return
$
this
->
_directives
[
$
name
]
;
}
Zend_Cache
::
throwException
(
"Incorrect option name : {$name}"
)
;
}

Returns an option

@param string $name Optional, the options name to return
@throws Zend_Cache_Exceptions
@return mixed


public function getTmpDir()
    {
        $tmpdir = array();
        foreach (array($_ENV, $_SERVER) as $tab) {
            foreach (array('TMPDIR', 'TEMP', 'TMP', 'windir', 'SystemRoot') as $key) {
                if (isset($tab[$key]) && is_string($tab[$key])) {
                    if (($key == 'windir') or ($key == 'SystemRoot')) {
                        $dir = realpath($tab[$key] . '\\temp');
                    } else {
                        $dir = realpath($tab[$key]);
                    }
                    if ($this->_isGoodTmpDir($dir)) {
                        return $dir;
                    }
                }
            }
        }
        $upload = ini_get('upload_tmp_dir');
        if ($upload) {
            $dir = realpath($upload);
            if ($this->_isGoodTmpDir($dir)) {
                return $dir;
            }
        }
        if (function_exists('sys_get_temp_dir')) {
            $dir = sys_get_temp_dir();
            if ($this->_isGoodTmpDir($dir)) {
                return $dir;
            }
        }
        // Attemp to detect by creating a temporary file
        $tempFile = tempnam(md5(uniqid(rand(), TRUE)), '');
        if ($tempFile) {
            $dir = realpath(dirname($tempFile));
            unlink($tempFile);
            if ($this->_isGoodTmpDir($dir)) {
                return $dir;
            }
        }
        if ($this->_isGoodTmpDir('/tmp')) {
            return '/tmp';
        }
        if ($this->_isGoodTmpDir('\\temp')) {
            return '\\temp';
        }
        Zend_Cache::throwException('Could not determine temp directory, please specify a cache_dir manually');
    }

Determine system TMP directory and detect if we have read access

inspired from Zend_File_Transfer_Adapter_Abstract

@return string
@throws Zend_Cache_Exception if unable to determine directory


public function init() {
        parent::init();
        $this->authManager = Yii::$app->getAuthManager();
        if (!$this->authManager instanceof DbManager) {
            throw new InvalidConfigException('You should configure "authManager" component to use database before executing this migration.');
        }
    }

Initialize migrations.
Calls parent init method, then loads current authManager instance.

@return DbManager
@throws yii\base\InvalidConfigException

Initialize migrations . Calls parent init method then loads current authManager instance .


function createRole($name, $description) {
        if ($user = $this->authManager->getRole($name)) {
            echo "{$name} role already exists\n";
        } else {
            $user = $this->authManager->createRole($name);
            $user->description = $description;
            $this->authManager->add($user);
            echo "{$name} role created\n";
        }
        return $user;
    }

function
createRole
(
$
name
,
$
description
)
{
if
(
$
user
=
$
this
->
authManager
->
getRole
(
$
name
)
)
{
echo
"{$name} role already exists\n"
;
}
else
{
$
user
=
$
this
->
authManager
->
createRole
(
$
name
)
;
$
user
->
description
=
$
description
;
$
this
->
authManager
->
add
(
$
user
)
;
echo
"{$name} role created\n"
;
}
return
$
user
;
}

Create role.
If role already exists doesn nothing.

@param string $name Role name
@param string $description Role description
@return \yii\rbac\Permission the new Permission object

Create role . If role already exists doesn nothing .


function assignChildRole($parent, $child) {
        if (!$this->authManager->hasChild($parent, $child)) {
            $this->authManager->addChild($parent, $child);
            echo "New child '{$child->name}' added to '{$parent->name}'\n";
        } else {
            echo "Role '{$child->name}' was already added to '{$parent->name}'\n";
        }
    }

Assigns child role to parent

@param string $parent Parent role name
@param string $child Child role name


public function register(FunctionProphecy $prophecy)
    {
        $name = $prophecy->getFQName();

        if ($this->has($name)) {
            throw new \Exception();
        }

        if (! function_exists($name)) {
            Generator::generate($prophecy);
        }

        $this->mocks[$name] = $prophecy->getNamespace();

        return $this;
    }

public function register ( FunctionProphecy $ prophecy ) { $ name = $ prophecy -> getFQName ( ) ; if ( $ this -> has ( $ name ) ) { throw new \ Exception ( ) ; } if ( ! function_exists ( $ name ) ) { Generator :: generate ( $ prophecy ) ; } $ this -> mocks [ $ name ] = $ prophecy -> getNamespace ( ) ; return $ this ; }

Register a new function prophecy into the registry

@param FunctionProphecy $prophecy

@return $this

@throws \Exception


public function call($name, $uqfn, array $args)
    {
        if (! $this->has($name)) {
            throw new \Exception();
        }

        return $this->mocks[$name]->call($uqfn, $args);
    }

public function call ( $ name , $ uqfn , array $ args ) { if ( ! $ this -> has ( $ name ) ) { throw new \ Exception ( ) ; } return $ this -> mocks [ $ name ] -> call ( $ uqfn , $ args ) ; }

Call the registered function mock

@param string $name The fully-qualified function name
@param string $uqfn The unqualified function name
@param array $args

@return mixed
@throws \Exception

@internal


public function get($key)
    {
        $key = strtolower($key);

        if (!array_key_exists($key, $this->parameters)) {
            throw new ParameterNotFoundException($key);
        }

        return $this->parameters[$key];
    }

public function get ( $ key ) { $ key = strtolower ( $ key ) ; if ( ! array_key_exists ( $ key , $ this -> parameters ) ) { throw new ParameterNotFoundException ( $ key ) ; } return $ this -> parameters [ $ key ] ; }

Get parameter value

@param string $key The parameter key

@return mixed

@throws ParameterNotFoundException


public function resolveString($value, array $resolving = array())
    {
        $parts = explode('%', $value);
        $keyOnly = (bool) preg_match('/^%([^%\s]+)%$/', $value);
        $return = $parts[0];

        for ($i = 1, $last = count($parts) - 1; $i <= $last; ++$i) {
            $part = $parts[$i];
            $key = strtolower($part);

            if (0 === $i % 2) {
                $return .= $part;
            } elseif ($last === $i) {
                $return .= '%' . $part;
            } elseif (empty($part) || preg_match('/ /', $part)) {
                $return .= '%' . $part . '%';
            } elseif (isset($resolving[$key])) {
                throw new ParameterCircularReferenceException($key, array_keys($resolving));
            } else {
                $resolved = $this->get($key);

                if (true === $keyOnly) {
                    return $this->resolved ? $resolved : $this->resolveValue($resolved, array_merge($resolving, array($key => true)));
                } elseif (!is_string($resolved) && !is_numeric($resolved)) {
                    throw new RuntimeException('Resolved value is not a string or numbers');
                }

                $resolved = (string) $resolved;
                $return .= $this->resolved ? $resolved : $this->resolveValue($resolved, array_merge($resolving, array($key => true)));
            }
        }

        return $return;
    }

Resolves parameters inside a string

@param string $value     The string to resolve
@param array  $resolving An array of keys that are being resolved (used internally to detect circular references)

@return string The resolved string

@throws ParameterCircularReferenceException
@throws RuntimeException


protected function queryToMeta($query)
    {
        $query = str_replace(' ', '+', $query);

        if (preg_match('~^(?:hashtag:|#)(\w+)$~i', $query, $matches)) {

            $type = 'hashtag';
            $url  = 'https://twitter.com/hashtag/' . $matches[1] . '?f=tweets';

        } elseif (preg_match('~^(?:user:|@)(\w+)$~i', $query, $matches)) {

            $type = 'user';
            $url  = 'https://twitter.com/' . $matches[1];

        } elseif (preg_match('~^(?:search:)(.+)$~i', $query, $matches)) {

            $type = 'search';
            $url  = 'https://twitter.com/search?f=tweets&q=' . $matches[1];

        } else {

            $type = 'search';
            $url  = 'https://twitter.com/search?f=tweets&q=' . $query;
        }

        return [ 'query' => $query, 'type' => $type, 'url' => $url ];
    }

Convert a query to an associative array of metadata.

@see doc/Twitter.md

@param string $query

@return array with the following structure:
(array)
type  (string) hashtag, search or user
url   (string) URL of the target page
query (string)

Convert a query to an associative array of metadata .


public function twitter($query)
    {
        $meta = $this->queryToMeta($query);

        if (! $page = NoAPI::curl($meta['url'])) return false;

        return $this->parse($page, $meta);
    }

public function twitter ( $ query ) { $ meta = $ this -> queryToMeta ( $ query ) ; if ( ! $ page = NoAPI :: curl ( $ meta [ 'url' ] ) ) return false ; return $ this -> parse ( $ page , $ meta ) ; }

Download and parse the twitter page corresponding to a query.

@see doc/Twitter.md
@see Twitter::queryToMeta()

@param string $query

@return array|bool false on error

Download and parse the twitter page corresponding to a query .


public function renderPanes($panes)
    {
        return $this->renderTabContent ? "\n" . $this->htmlHlp->tag('div', implode("\n", $panes), $this->tabContentOptions) : '';
    }

public function renderPanes ( $ panes ) { return $ this -> renderTabContent ? "\n" . $ this -> htmlHlp -> tag ( 'div' , implode ( "\n" , $ panes ) , $ this -> tabContentOptions ) : '' ; }

Renders tab panes.

@param array $panes
@return string the rendering result.


public function register() {
        if (!$this->validate()) {
            return false;
        }

        /** @var User $user */
        $user = Yii::createObject(User::className());
        $user->setScenario('register');
        $this->loadAttributes($user);

        if (!$user->register()) {
            return false;
        }

        Yii::$app->session->setFlash(
                'info', Yii::t('user', 'Your account has been created and a message with further instructions has been sent to your email')
        );

        return true;
    }

Registers a new user account. If registration was successful it will set flash message.

@return bool

Registers a new user account . If registration was successful it will set flash message .


public function setVector($vector = null)
    {
        $cipher = $this->_openCipher();
        $size   = mcrypt_enc_get_iv_size($cipher);
        if (empty($vector)) {
            $this->_srand();
            if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && version_compare(PHP_VERSION, '5.3.0', '<')) {
                $method = MCRYPT_RAND;
            } else {
                if (file_exists('/dev/urandom') || (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')) {
                    $method = MCRYPT_DEV_URANDOM;
                } elseif (file_exists('/dev/random')) {
                    $method = MCRYPT_DEV_RANDOM;
                } else {
                    $method = MCRYPT_RAND;
                }
            }
            $vector = mcrypt_create_iv($size, $method);
        } else if (strlen($vector) != $size) {

            throw new Zend_Filter_Exception('The given vector has a wrong size for the set algorithm');
        }

        $this->_encryption['vector'] = $vector;
        $this->_closeCipher($cipher);

        return $this;
    }

Sets the initialization vector

@param string $vector (Optional) Vector to set
@return Zend_Filter_Encrypt_Mcrypt


protected function _openCipher()
    {
        $cipher = mcrypt_module_open(
            $this->_encryption['algorithm'],
            $this->_encryption['algorithm_directory'],
            $this->_encryption['mode'],
            $this->_encryption['mode_directory']);

        if ($cipher === false) {

            throw new Zend_Filter_Exception('Mcrypt can not be opened with your settings');
        }

        return $cipher;
    }

Open a cipher

@throws Zend_Filter_Exception When the cipher can not be opened
@return resource Returns the opened cipher


protected function _initCipher($cipher)
    {
        $key = $this->_encryption['key'];

        $keysizes = mcrypt_enc_get_supported_key_sizes($cipher);
        if (empty($keysizes) || ($this->_encryption['salt'] == true)) {
            $this->_srand();
            $keysize = mcrypt_enc_get_key_size($cipher);
            $key     = substr(md5($key), 0, $keysize);
        } else if (!in_array(strlen($key), $keysizes)) {

            throw new Zend_Filter_Exception('The given key has a wrong size for the set algorithm');
        }

        $result = mcrypt_generic_init($cipher, $key, $this->_encryption['vector']);
        if ($result < 0) {

            throw new Zend_Filter_Exception('Mcrypt could not be initialize with the given setting');
        }

        return $this;
    }

Initialises the cipher with the set key

@param  resource $cipher
@throws
@return resource


public static function connect(array $clientCredentials, array $endPoints, $userDataUrl)
    {
        $instance = new static;

        if (! $instance->protocol = self::getAuthProtocol($clientCredentials)) {
            throw new \InvalidArgumentException('Credential keys are invalid.');
        }

        $instance->credentials = $clientCredentials;
        $instance->endPoints   = $endPoints;
        $tokenCredentials      = $instance->fetchTokenCredentials();

        $instance->addToCredentials($tokenCredentials);
        $instance->filterCredentialsByKey('token_credentials');

        return $instance->fetchUserData($userDataUrl);

    }

public
static
function
connect
(
array
$
clientCredentials
,
array
$
endPoints
,
$
userDataUrl
)
{
$
instance
=
new
static
;
if
(
!
$
instance
->
protocol
=
self
::
getAuthProtocol
(
$
clientCredentials
)
)
{
throw
new
\
InvalidArgumentException
(
'Credential keys are invalid.'
)
;
}
$
instance
->
credentials
=
$
clientCredentials
;
$
instance
->
endPoints
=
$
endPoints
;
$
tokenCredentials
=
$
instance
->
fetchTokenCredentials
(
)
;
$
instance
->
addToCredentials
(
$
tokenCredentials
)
;
$
instance
->
filterCredentialsByKey
(
'token_credentials'
)
;
return
$
instance
->
fetchUserData
(
$
userDataUrl
)
;
}

Takes credentials and URLs, checks credentials and gets tokens.
Returns an account with their credentials.

@param  array  $clientCredentials
@param  array  $endPoints
@param  string $userDataUrl
@return object

Takes credentials and URLs checks credentials and gets tokens . Returns an account with their credentials .


public static function verifyCredentials(array $tokenCredentials, $userDataUrl)
    {
        $instance = new static;

        if (! $instance->protocol = self::getAuthProtocol($tokenCredentials)) {
            throw new \InvalidArgumentException('Credential keys are invalid.');
        }

        $instance->addToCredentials($tokenCredentials);
        $instance->filterCredentialsByKey('token_credentials');

        return $instance->fetchUserData($userDataUrl);

    }

public
static
function
verifyCredentials
(
array
$
tokenCredentials
,
$
userDataUrl
)
{
$
instance
=
new
static
;
if
(
!
$
instance
->
protocol
=
self
::
getAuthProtocol
(
$
tokenCredentials
)
)
{
throw
new
\
InvalidArgumentException
(
'Credential keys are invalid.'
)
;
}
$
instance
->
addToCredentials
(
$
tokenCredentials
)
;
$
instance
->
filterCredentialsByKey
(
'token_credentials'
)
;
return
$
instance
->
fetchUserData
(
$
userDataUrl
)
;
}

Checks the token credentials and returns an object with its account data.

@param  array  $tokenCredentials
@param  string $userDataUrl
@return object

Checks the token credentials and returns an object with its account data .


protected function fetchUserData($userDataUrl)
    {
        $plugins = [
            'auth' => $this->newAuthExtension(),
        ];

        $request  = $this->newRequest();
        $userData = $request::init($userDataUrl)
            ->addPlugins($plugins)
            ->GET()
            ->getBody();

        $this->addDataTokens($userData, $this->credentials);

        return $userData;

    }

protected function fetchUserData ( $ userDataUrl ) { $ plugins = [ 'auth' => $ this -> newAuthExtension ( ) , ] ; $ request = $ this -> newRequest ( ) ; $ userData = $ request :: init ( $ userDataUrl ) -> addPlugins ( $ plugins ) -> GET ( ) -> getBody ( ) ; $ this -> addDataTokens ( $ userData , $ this -> credentials ) ; return $ userData ; }

Makes the http request to the "checkUrl", and gets an object with account data.
Additionally it adds token credentials data to the object by if needed.

@param  string $userDataUrl
@return object

Makes the http request to the checkUrl and gets an object with account data . Additionally it adds token credentials data to the object by if needed .


public function newAuthExtension(RequestPluginAdapter $authExtension = null)
    {
        if (empty($authExtension)) {
            $authExtension = new GuzzleAuth($this->credentials);
        }

        return $authExtension;

    }

public function newAuthExtension ( RequestPluginAdapter $ authExtension = null ) { if ( empty ( $ authExtension ) ) { $ authExtension = new GuzzleAuth ( $ this -> credentials ) ; } return $ authExtension ; }

Object builder to create auth plugin extension for request client.
In this case, it creates GuzzleAuth object by default.

@param  \RestGalleries\Http\RequestPluginAdapter $authExtension
@return \RestGalleries\Http\RequestPluginAdapter

Object builder to create auth plugin extension for request client . In this case it creates GuzzleAuth object by default .


protected function addDataTokens(&$object, $tokenCredentials)
    {
        $tokens = &$object->tokens;

        $callback = function ($value, $key) use (&$tokens) {
            $tokens = array_add($tokens, $key, $value);
        };

        array_walk($tokenCredentials, $callback);

    }

protected function addDataTokens ( & $ object , $ tokenCredentials ) { $ tokens = & $ object -> tokens ; $ callback = function ( $ value , $ key ) use ( & $ tokens ) { $ tokens = array_add ( $ tokens , $ key , $ value ) ; } ; array_walk ( $ tokenCredentials , $ callback ) ; }

Add token credentials to the object.

@param  object $object
@param  array  $tokens
@return void


public static function getAuthProtocol(array $credentials)
    {
        $instance       = new static;
        $credentialKeys = array_keys($credentials);

        if ($instance->isOauth1($credentialKeys)) {
            return 'oauth1';
        }

        if ($instance->isOauth2($credentialKeys)) {
            return 'oauth2';
        }

        return false;

    }

public static function getAuthProtocol ( array $ credentials ) { $ instance = new static ; $ credentialKeys = array_keys ( $ credentials ) ; if ( $ instance -> isOauth1 ( $ credentialKeys ) ) { return 'oauth1' ; } if ( $ instance -> isOauth2 ( $ credentialKeys ) ) { return 'oauth2' ; } return false ; }

Checks the credentials and returns the name of the auth system used, if credentials are not founds, returns false.

@param  array $credentials
@return string|boolean

Checks the credentials and returns the name of the auth system used if credentials are not founds returns false .


protected function isOauth1($credentialsKeys)
    {
        $keys = $this->getOauth1Keys();
        foreach ($keys as $value) {
            if (subarray($value, $credentialsKeys)) {
                return true;
            }
        }

        return false;

    }

protected function isOauth1 ( $ credentialsKeys ) { $ keys = $ this -> getOauth1Keys ( ) ; foreach ( $ keys as $ value ) { if ( subarray ( $ value , $ credentialsKeys ) ) { return true ; } } return false ; }

Checks if the credentials are using OAuth1.0.

@param  array $credentials
@return boolean

Checks if the credentials are using OAuth1 . 0 .


protected function isOauth2($credentialsKeys)
    {
        $keys = $this->getOauth2Keys();
        foreach ($keys as $value) {
            if (subarray($value, $credentialsKeys)) {
                return true;
            }
        }

        return false;

    }

protected function isOauth2 ( $ credentialsKeys ) { $ keys = $ this -> getOauth2Keys ( ) ; foreach ( $ keys as $ value ) { if ( subarray ( $ value , $ credentialsKeys ) ) { return true ; } } return false ; }

Checks if the credentials are using OAuth2.0.

@param  array $credentials
@return boolean

Checks if the credentials are using OAuth2 . 0 .


public function close(): void
    {
        // If there is no stream
        if (null === $this->stream) {
            // Don't do anything
            return;
        }

        // Detach the stream
        $resource = $this->detach();

        // Close the stream
        fclose($resource);
    }

public
function
close
(
)
:
void
{
// If there is no stream
if
(
===
$
this
->
stream
)
{
// Don't do anything
return
;
}
// Detach the stream
$
resource
=
$
this
->
detach
(
)
;
// Close the stream
fclose
(
$
resource
)
;
}

Closes the stream and any underlying resources.

@return void

Closes the stream and any underlying resources .


public function attach(string $stream, string $mode = null): void
    {
        $this->setStream($stream, $mode);
    }

public function attach ( string $ stream , string $ mode = null ) : void { $ this -> setStream ( $ stream , $ mode ) ; }

Attaches a new stream.

@param string $stream The stream
@param string $mode   [optional] The mode

@throws \Valkyrja\HttpMessage\Exceptions\InvalidStream

@return void


public function getContents(): string
    {
        // If the stream isn't readable
        if (! $this->isReadable()) {
            // Throw a runtime exception
            throw new RuntimeException('Stream is not readable');
        }

        // Get the stream contents
        $result = stream_get_contents($this->stream);

        // If there was a failure in getting the stream contents
        if (false === $result) {
            // Throw a runtime exception
            throw new RuntimeException('Error reading from stream');
        }

        return $result;
    }

Returns the remaining contents in a string.

@throws \RuntimeException
if unable to read or an error occurs while reading.

@return string

Returns the remaining contents in a string .


protected function setStream(string $stream, string $mode = null): void
    {
        // Set the mode
        $mode = $mode ?? 'r';

        // Open a new resource stream
        $resource = fopen($stream, $mode);

        // If the resource isn't a resource or a stream resource type
        if (! \is_resource($resource) || 'stream' !== get_resource_type(
                $resource
            )
        ) {
            // Throw a new invalid stream exception
            throw new InvalidStream(
                'Invalid stream provided; must be a string stream identifier or stream resource'
            );
        }

        // Set the stream
        $this->stream = $resource;
    }

Set the stream.

@param string $stream The stream
@param string $mode   [optional] The mode

@throws \Valkyrja\HttpMessage\Exceptions\InvalidStream

@return void


public function write(array $data, array $options)
    {
        if (!isset($options['file'])) {
            throw new \InvalidArgumentException(
                'Parameter "file" is mandatory.'
            );
        }

        if (!is_string($options['file'])) {
            throw new \InvalidArgumentException(
                'Parameter "file" must be a string.'
            );
        }

        $file = $this->_factory->createInstance($options['file'], null, $options);

        $file->setContents($data)
            ->save($options);
    }

public
function
write
(
array
$
data
,
array
$
options
)
{
if
(
!
isset
(
$
options
[
'file'
]
)
)
{
throw
new
\
InvalidArgumentException
(
'Parameter "file" is mandatory.'
)
;
}
if
(
!
is_string
(
$
options
[
'file'
]
)
)
{
throw
new
\
InvalidArgumentException
(
'Parameter "file" must be a string.'
)
;
}
$
file
=
$
this
->
_factory
->
createInstance
(
$
options
[
'file'
]
,
,
$
options
)
;
$
file
->
setContents
(
$
data
)
->
save
(
$
options
)
;
}

This method writes the configuration to a file.

@param array $data    - Data.
@param array $options - Options.

@throws \InvalidArgumentException

@return array

This method writes the configuration to a file .


protected function getAccountVirtual()
    {
        $accountIdVirtual  = (int) Post::getInstance()->get('editAccountIdVirtual');
        $accountUserMapper = new AccountUserMapper(Database::get('money'));
        $accountMapper     = new AccountMapper(Database::get('money'));

        //~ Update virtual account if necessary
        if ($accountIdVirtual <= 0) {
            return $accountMapper->newDataInstance();
        }

        $accountUser = $accountUserMapper->findByKeys([
            'account_id' => $accountIdVirtual,
            'user_id'    => Session::getInstance()->get('id'),
        ]);

        if ($accountUser->getUserId() !== Session::getInstance()->get('id')) {
            throw new \Exception('Not Allowed!');
        }

        $account = $accountUser->getAccount();

        if (!$account->isVirtual()) {
            return $accountMapper->newDataInstance();
        }

        return $account;
    }

protected
function
getAccountVirtual
(
)
{
$
accountIdVirtual
=
(
int
)
Post
::
getInstance
(
)
->
get
(
'editAccountIdVirtual'
)
;
$
accountUserMapper
=
new
AccountUserMapper
(
Database
::
get
(
'money'
)
)
;
$
accountMapper
=
new
AccountMapper
(
Database
::
get
(
'money'
)
)
;
//~ Update virtual account if necessary
if
(
$
accountIdVirtual
<=
0
)
{
return
$
accountMapper
->
newDataInstance
(
)
;
}
$
accountUser
=
$
accountUserMapper
->
findByKeys
(
[
'account_id'
=>
$
accountIdVirtual
,
'user_id'
=>
Session
::
getInstance
(
)
->
get
(
'id'
)
,
]
)
;
if
(
$
accountUser
->
getUserId
(
)
!==
Session
::
getInstance
(
)
->
get
(
'id'
)
)
{
throw
new
\
Exception
(
'Not Allowed!'
)
;
}
$
account
=
$
accountUser
->
getAccount
(
)
;
if
(
!
$
account
->
isVirtual
(
)
)
{
return
$
accountMapper
->
newDataInstance
(
)
;
}
return
$
account
;
}

Get virtual account. Return empty account instance if no account id virtual is given.

@return  Account
@throws \Exception

Get virtual account . Return empty account instance if no account id virtual is given .


public function getPreviousAccount($previousId)
    {
        $accountMapper = new AccountMapper(Database::get('money'));

        if ($previousId <= 0) {
            return $accountMapper->newDataInstance();
        }

        return $accountMapper->findById($previousId);
    }

public function getPreviousAccount ( $ previousId ) { $ accountMapper = new AccountMapper ( Database :: get ( 'money' ) ) ; if ( $ previousId <= 0 ) { return $ accountMapper -> newDataInstance ( ) ; } return $ accountMapper -> findById ( $ previousId ) ; }

Get previous account.

@param  int $previousId
@return Account


protected function updateAccountVirtual(Account $account, Account $previousAccount, $amount, $previousAmount)
    {
        $accountMapper = new AccountMapper(Database::get('money'));

        //~ Revert previous amount on previous account
        if ($previousAccount->getId() > 0) {
            if ($previousAccount->getId() !== $account->getId()) {
                $previousAccount->addAmount(-$previousAmount);
                $accountMapper->update($previousAccount);
            } else {
                $account->addAmount(-$previousAmount);
            }
        }

        //~ Update amount of current account
        $account->addAmount($amount);
        $accountMapper->update($account);
    }

Update virtual account

@param  Account $account
@param  Account $previousAccount
@param  float   $amount
@param  float   $previousAmount
@return void


public function cache($duration = null)
    {
        $this->queryCacheDuration = $duration === null ? $this->db->queryCacheDuration : $duration;
        return $this;
    }

public function cache ( $ duration = null ) { $ this -> queryCacheDuration = $ duration === null ? $ this -> db -> queryCacheDuration : $ duration ; return $ this ; }

Enables query cache for this command.
@param int $duration the number of seconds that query result of this command can remain valid in the cache.
If this is not set, the value of [[DatabaseInterface::queryCacheDuration]] will be used instead.
Use 0 to indicate that the cached data will never expire.
@return $this the command object itself


public function setConnection($connection = null)
    {
        if ($connection instanceof TransactionInterface) {
            $connection = $connection->getConnection();
        }
        $this->connection = $connection;
        if ($connection instanceof EventEmitterWildcardInterface) {
            //Remove connection instance on close
            $this->connection->once(ConnectionInterface::EVENT_CLOSE, function() use ($connection) {
                if ($this->connection === $connection) {
                    $this->connection = null;
                }
            });
        }
        return $this;
    }

public
function
setConnection
(
$
connection
=
)
{
if
(
$
connection
instanceof
TransactionInterface
)
{
$
connection
=
$
connection
->
getConnection
(
)
;
}
$
this
->
connection
=
$
connection
;
if
(
$
connection
instanceof
EventEmitterWildcardInterface
)
{
//Remove connection instance on close
$
this
->
connection
->
once
(
ConnectionInterface
::
EVENT_CLOSE
,
function
(
)
use
(
$
connection
)
{
if
(
$
this
->
connection
===
$
connection
)
{
$
this
->
connection
=
;
}
}
)
;
}
return
$
this
;
}

Set connection to use with
@param ConnectionInterface|TransactionInterface|null $connection
@return $this this command instance


public function fetchResultsRow($row = [], $fetchMethod = self::FETCH_ALL, $fetchMode = self::FETCH_MODE_ASSOC, $colIndex = 0) {
        if (in_array($fetchMethod, [static::FETCH_ALL, static::FETCH_ROW])) {
            $this->processResultRow($row);
            return $fetchMode === static::FETCH_MODE_OBJECT ? (object)$row : $row;
        } elseif (in_array($fetchMethod, [static::FETCH_COLUMN, static::FETCH_FIELD]) && $colIndex < count($row)) {
            $rowIndexed = array_values($row);
            $this->processResultRow($rowIndexed[$colIndex]);
            return $rowIndexed[$colIndex];
        }
        return null;
    }

public function fetchResultsRow ( $ row = [ ] , $ fetchMethod = self :: FETCH_ALL , $ fetchMode = self :: FETCH_MODE_ASSOC , $ colIndex = 0 ) { if ( in_array ( $ fetchMethod , [ static :: FETCH_ALL , static :: FETCH_ROW ] ) ) { $ this -> processResultRow ( $ row ) ; return $ fetchMode === static :: FETCH_MODE_OBJECT ? ( object ) $ row : $ row ; } elseif ( in_array ( $ fetchMethod , [ static :: FETCH_COLUMN , static :: FETCH_FIELD ] ) && $ colIndex < count ( $ row ) ) { $ rowIndexed = array_values ( $ row ) ; $ this -> processResultRow ( $ rowIndexed [ $ colIndex ] ) ; return $ rowIndexed [ $ colIndex ] ; } return null ; }

Fetch results row
@param array  $row
@param string $fetchMethod
@param string $fetchMode
@param int    $colIndex
@return array|null|object
@internal


public function insertAndReturn($table, $columns) {
        $params = [];
        $sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
        $tableSchema = $this->db->getSchema()->getTableSchema($table);
        $returnColumns = $tableSchema->getColumnNames();
        if (!empty($returnColumns)) {
            $returning = [];
            foreach ((array)$returnColumns as $name) {
                $returning[] = $this->db->quoteColumnName($name);
            }
            $sql .= ' RETURNING ' . implode(', ', $returning);
        }

        return $this->setSql($sql)->bindValues($params);
    }

public
function
insertAndReturn
(
$
table
,
$
columns
)
{
$
params
=
[
]
;
$
sql
=
$
this
->
db
->
getQueryBuilder
(
)
->
insert
(
$
table
,
$
columns
,
$
params
)
;
$
tableSchema
=
$
this
->
db
->
getSchema
(
)
->
getTableSchema
(
$
table
)
;
$
returnColumns
=
$
tableSchema
->
getColumnNames
(
)
;
if
(
!
empty
(
$
returnColumns
)
)
{
$
returning
=
[
]
;
foreach
(
(
array
)
$
returnColumns
as
$
name
)
{
$
returning
[
]
=
$
this
->
db
->
quoteColumnName
(
$
name
)
;
}
$
sql
.=
' RETURNING '
.
implode
(
', '
,
$
returning
)
;
}
return
$
this
->
setSql
(
$
sql
)
->
bindValues
(
$
params
)
;
}

Creates an INSERT command with RETURNING statement.

For example,

```php
$connection->createCommand()->insertAndReturn('user', [
'name' => 'Sam',
'age' => 30,
])->execute();
```

The method will properly escape the column names, and bind the values to be inserted.

Note that the created command is not executed until [[execute()]] is called.

@param string $table the table that new rows will be inserted into.
@param array|\Reaction\Db\Query $columns the column data (name => value) to be inserted into the table or instance
of [[Reaction\Db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
@return $this the command object itself

Creates an INSERT command with RETURNING statement .