protected function getLinksFromDataArray(array $linksArray)
    {
        $links = array();
        foreach ($linksArray as $linkArray) {
            $link = new Link();

            if (isset($linkArray['rel']) && is_array($linkArray['rel'])) {
                $link->setRel($linkArray['rel']);
            }

            if (isset($linkArray['href']) && is_string($linkArray['href'])) {
                $link->setHref($linkArray['href']);
            }

            $links[] = $link;
        }

        return $links;
    }

protected function getLinksFromDataArray ( array $ linksArray ) { $ links = array ( ) ; foreach ( $ linksArray as $ linkArray ) { $ link = new Link ( ) ; if ( isset ( $ linkArray [ 'rel' ] ) && is_array ( $ linkArray [ 'rel' ] ) ) { $ link -> setRel ( $ linkArray [ 'rel' ] ) ; } if ( isset ( $ linkArray [ 'href' ] ) && is_string ( $ linkArray [ 'href' ] ) ) { $ link -> setHref ( $ linkArray [ 'href' ] ) ; } $ links [ ] = $ link ; } return $ links ; }

Helper method to convert a link data array to an array of link objects

@param array $linksArray
@return Link[]


public function send(RequestInterface $request)
    {
        $deferred = new Deferred();
        try {
            $response = $this->call($request);
            $deferred->resolve($response);
        } catch (\Exception $caught) {
            $deferred->reject($caught);
        }

        return $deferred->promise();
    }

public function send ( RequestInterface $ request ) { $ deferred = new Deferred ( ) ; try { $ response = $ this -> call ( $ request ) ; $ deferred -> resolve ( $ response ) ; } catch ( \ Exception $ caught ) { $ deferred -> reject ( $ caught ) ; } return $ deferred -> promise ( ) ; }

Send out an HTTP requests returning a promise

@param RequestInterface $request

@return PromiseInterface


private function call(RequestInterface $request)
    {
        $this->prepare($request);
        $result = curl_exec($this->handler);

        if (curl_errno($this->handler) !== 0) {
            throw new RuntimeException(
                "Error connecting to server: ".curl_error($this->handler)
            );
        }

        $response = $this->createResponse($result);

        $this->checkClientError($response, $request);

        $this->checkServerError($response, $request);

        return $response;
    }

private
function
call
(
RequestInterface
$
request
)
{
$
this
->
prepare
(
$
request
)
;
$
result
=
curl_exec
(
$
this
->
handler
)
;
if
(
curl_errno
(
$
this
->
handler
)
!==
0
)
{
throw
new
RuntimeException
(
"Error connecting to server: "
.
curl_error
(
$
this
->
handler
)
)
;
}
$
response
=
$
this
->
createResponse
(
$
result
)
;
$
this
->
checkClientError
(
$
response
,
$
request
)
;
$
this
->
checkServerError
(
$
response
,
$
request
)
;
return
$
response
;
}

Call the HTTP server returning the response

@param RequestInterface $request

@return Response

@throws RuntimeException If any error occur while preparing and connecting to the server
@throws ClientErrorException for responses with status codes between 400 and 499
@throws ServerErrorException for responses with status codes grater or equal to 500


private function prepare(RequestInterface $request)
    {
        $this->reset($this->handler);
        $this->setUrl($request);
        $this->options[CURLOPT_CUSTOMREQUEST] = $request->getMethod();
        $this->setHeaders($request);
        $this->options[CURLOPT_POSTFIELDS] = (string) $request->getBody();

        if ($this->auth instanceof HttpClientAuthentication) {
            $this->options[CURLOPT_USERPWD] = "{$this->auth->username()}:{$this->auth->password()}";
            $this->options[CURLOPT_HTTPAUTH] = $this->auth->type();
        }

        curl_setopt_array($this->handler, $this->options);
    }

Prepares the cURL handler options

@param RequestInterface $request


private function setUrl(RequestInterface $request)
    {
        $target = $request->getRequestTarget();
        $parts = parse_url($target);

        $uri = $this->url instanceof Uri
            ? $this->url
            : $request->getUri();

        $uri = $uri->withPath($parts['path']);
        $uri = array_key_exists('query', $parts)
            ? $uri->withQuery($parts['query'])
            : $uri;

        $this->options[CURLOPT_URL] = (string) $uri;
    }

private function setUrl ( RequestInterface $ request ) { $ target = $ request -> getRequestTarget ( ) ; $ parts = parse_url ( $ target ) ; $ uri = $ this -> url instanceof Uri ? $ this -> url : $ request -> getUri ( ) ; $ uri = $ uri -> withPath ( $ parts [ 'path' ] ) ; $ uri = array_key_exists ( 'query' , $ parts ) ? $ uri -> withQuery ( $ parts [ 'query' ] ) : $ uri ; $ this -> options [ CURLOPT_URL ] = ( string ) $ uri ; }

Sets the URL for cURL to use

@param RequestInterface $request


private function setHeaders(RequestInterface $request)
    {
        $headers = [];
        foreach ($request->getHeaders() as $header => $values) {
            $headers[] = "{$header}: ".implode('; ', $values);
        }
        $this->options[CURLOPT_HTTPHEADER] = $headers;
    }

private
function
setHeaders
(
RequestInterface
$
request
)
{
$
headers
=
[
]
;
foreach
(
$
request
->
getHeaders
(
)
as
$
header
=>
$
values
)
{
$
headers
[
]
=
"{$header}: "
.
implode
(
'; '
,
$
values
)
;
}
$
this
->
options
[
CURLOPT_HTTPHEADER
]
=
$
headers
;
}

Sets the headers from the request

@param RequestInterface $request


private function createResponse($result)
    {
        $status = curl_getinfo($this->handler, CURLINFO_HTTP_CODE);
        list($header, $body) = $this->splitHeaderFromBody($result);
        return new Response($status, trim($body), $this->parseHeaders($header));
    }

private function createResponse ( $ result ) { $ status = curl_getinfo ( $ this -> handler , CURLINFO_HTTP_CODE ) ; list ( $ header , $ body ) = $ this -> splitHeaderFromBody ( $ result ) ; return new Response ( $ status , trim ( $ body ) , $ this -> parseHeaders ( $ header ) ) ; }

Creates a response from cURL execution result

@param string $result

@return Response


private function splitHeaderFromBody($result)
    {
        $header_size = curl_getinfo($this->handler, CURLINFO_HEADER_SIZE);

        $header = substr($result, 0, $header_size);
        $body = substr($result, $header_size);

        return [trim($header), trim($body)];
    }

private function splitHeaderFromBody ( $ result ) { $ header_size = curl_getinfo ( $ this -> handler , CURLINFO_HEADER_SIZE ) ; $ header = substr ( $ result , 0 , $ header_size ) ; $ body = substr ( $ result , $ header_size ) ; return [ trim ( $ header ) , trim ( $ body ) ] ; }

Splits the cURL execution result into header and body

@param $result

@return array


private function parseHeaders($header)
    {
        $lines = explode("\n", $header);
        $headers = [];
        foreach ($lines as $line) {
            if (strpos($line, ':') === false) {
                continue;
            }

            $middle=explode(":", $line);
            $headers[trim($middle[0])] = trim($middle[1]);
        }
        return $headers;
    }

private function parseHeaders ( $ header ) { $ lines = explode ( "\n" , $ header ) ; $ headers = [ ] ; foreach ( $ lines as $ line ) { if ( strpos ( $ line , ':' ) === false ) { continue ; } $ middle = explode ( ":" , $ line ) ; $ headers [ trim ( $ middle [ 0 ] ) ] = trim ( $ middle [ 1 ] ) ; } return $ headers ; }

Parses the HTTP message headers from header part

@param string $header

@return array


public function countTotalLogType($logtype)
    {
        $count = 0;

        if (isset($this->log_sections['Logs']) && is_array($this->log_sections['Logs'])) {
            foreach ($this->log_sections['Logs'] as $item) {
                if (isset($item['logtype']) && $item['logtype'] == $logtype) {
                    $count++;
                }
            }// endforeach;
            unset($item);
        }

        return $count;
    }

public
function
countTotalLogType
(
$
logtype
)
{
$
count
=
0
;
if
(
isset
(
$
this
->
log_sections
[
'Logs'
]
)
&&
is_array
(
$
this
->
log_sections
[
'Logs'
]
)
)
{
foreach
(
$
this
->
log_sections
[
'Logs'
]
as
$
item
)
{
if
(
isset
(
$
item
[
'logtype'
]
)
&&
$
item
[
'logtype'
]
==
$
logtype
)
{
$
count
++
;
}
}
// endforeach;
unset
(
$
item
)
;
}
return
$
count
;
}

Count total log type in the "Logs" section.

@param string $logtype Accept debug, info, notice, warning, error, critical, alert, emergency. referrer: http://www.php-fig.org/psr/psr-3/
@return integer Return counted total log type in the "Logs" section.

Count total log type in the Logs section .


public function display($dbh = '', $display_db_function = '')
    {
        $this->gatherAll();

        global $rundizProfilerBeautifulIndent;
        $rundizProfilerBeautifulIndent = $this->beautifulIndent;

        // return display views.
        ob_start();
        require __DIR__.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR.'display.php';
        $this->reset();
        $output = ob_get_contents();
        ob_end_clean();

        return $output;
    }

public
function
display
(
$
dbh
=
''
,
$
display_db_function
=
''
)
{
$
this
->
gatherAll
(
)
;
global
$
rundizProfilerBeautifulIndent
;
$
rundizProfilerBeautifulIndent
=
$
this
->
beautifulIndent
;
// return display views.
ob_start
(
)
;
require
__DIR__
.
DIRECTORY_SEPARATOR
.
'views'
.
DIRECTORY_SEPARATOR
.
'display.php'
;
$
this
->
reset
(
)
;
$
output
=
ob_get_contents
(
)
;
ob_end_clean
(
)
;
return
$
output
;
}

display the profiler data results.

@return string return the profiler result in html.


private function gatherFiles()
    {
        if (!array_key_exists('Files', $this->log_sections)) {
            return ;
        }

        $files = get_included_files();
        $section_data_array = [];
        $total_size = 0;
        $largest_size = 0;

        if (is_array($files)) {
            foreach ($files as $file) {
                $size = filesize($file);
                $section_data_array[] = [
                    'data' => $file,
                    'size' => $size,
                ];
                $total_size = bcadd($total_size, $size);

                if ($size > $largest_size) {
                    $largest_size = $size;
                }
            }// endforeach;
            unset($file, $size);
        }

        $section_data_array['total_size'] = $total_size;
        $section_data_array['largest_size'] = $largest_size;
        unset($largest_size, $total_size);

        $this->log_sections['Files'] = $section_data_array;
        unset($files, $section_data_array);
    }

private
function
gatherFiles
(
)
{
if
(
!
array_key_exists
(
'Files'
,
$
this
->
log_sections
)
)
{
return
;
}
$
files
=
get_included_files
(
)
;
$
section_data_array
=
[
]
;
$
total_size
=
0
;
$
largest_size
=
0
;
if
(
is_array
(
$
files
)
)
{
foreach
(
$
files
as
$
file
)
{
$
size
=
filesize
(
$
file
)
;
$
section_data_array
[
]
=
[
'data'
=>
$
file
,
'size'
=>
$
size
,
]
;
$
total_size
=
bcadd
(
$
total_size
,
$
size
)
;
if
(
$
size
>
$
largest_size
)
{
$
largest_size
=
$
size
;
}
}
// endforeach;
unset
(
$
file
,
$
size
)
;
}
$
section_data_array
[
'total_size'
]
=
$
total_size
;
$
section_data_array
[
'largest_size'
]
=
$
largest_size
;
unset
(
$
largest_size
,
$
total_size
)
;
$
this
->
log_sections
[
'Files'
]
=
$
section_data_array
;
unset
(
$
files
,
$
section_data_array
)
;
}


private function gatherInputGet()
    {
        if (!array_key_exists('Get', $this->log_sections)) {
            return ;
        }

        $section_data_array = [];

        if (isset($_GET) && is_array($_GET)) {
            foreach ($_GET as $name => $value) {
                $section_data_array[] = [
                    'data' => $name,
                    'inputvalue' => $value,
                ];
            }// endforeach;
            unset($name, $value);
        }

        $this->log_sections['Get'] = $section_data_array;
        unset($section_data_array);
    }

private
function
gatherInputGet
(
)
{
if
(
!
array_key_exists
(
'Get'
,
$
this
->
log_sections
)
)
{
return
;
}
$
section_data_array
=
[
]
;
if
(
isset
(
$
_GET
)
&&
is_array
(
$
_GET
)
)
{
foreach
(
$
_GET
as
$
name
=>
$
value
)
{
$
section_data_array
[
]
=
[
'data'
=>
$
name
,
'inputvalue'
=>
$
value
,
]
;
}
// endforeach;
unset
(
$
name
,
$
value
)
;
}
$
this
->
log_sections
[
'Get'
]
=
$
section_data_array
;
unset
(
$
section_data_array
)
;
}


private function gatherInputPost()
    {
        if (!array_key_exists('Post', $this->log_sections)) {
            return ;
        }

        $section_data_array = [];

        if (isset($_POST) && is_array($_POST)) {
            foreach ($_POST as $name => $value) {
                $section_data_array[] = [
                    'data' => $name,
                    'inputvalue' => $value,
                ];
            }// endforeach;
            unset($name, $value);
        }

        $this->log_sections['Post'] = $section_data_array;
        unset($section_data_array);
    }

private
function
gatherInputPost
(
)
{
if
(
!
array_key_exists
(
'Post'
,
$
this
->
log_sections
)
)
{
return
;
}
$
section_data_array
=
[
]
;
if
(
isset
(
$
_POST
)
&&
is_array
(
$
_POST
)
)
{
foreach
(
$
_POST
as
$
name
=>
$
value
)
{
$
section_data_array
[
]
=
[
'data'
=>
$
name
,
'inputvalue'
=>
$
value
,
]
;
}
// endforeach;
unset
(
$
name
,
$
value
)
;
}
$
this
->
log_sections
[
'Post'
]
=
$
section_data_array
;
unset
(
$
section_data_array
)
;
}


private function gatherInputSession()
    {
        if (!array_key_exists('Session', $this->log_sections)) {
            return ;
        }

        $section_data_array = [];

        if (isset($_SESSION) && is_array($_SESSION)) {
            foreach ($_SESSION as $name => $value) {
                $section_data_array[] = [
                    'data' => $name,
                    'inputvalue' => $value,
                ];
            }// endforeach;
            unset($name, $value);
        }

        $this->log_sections['Session'] = $section_data_array;
        unset($section_data_array);
    }

private
function
gatherInputSession
(
)
{
if
(
!
array_key_exists
(
'Session'
,
$
this
->
log_sections
)
)
{
return
;
}
$
section_data_array
=
[
]
;
if
(
isset
(
$
_SESSION
)
&&
is_array
(
$
_SESSION
)
)
{
foreach
(
$
_SESSION
as
$
name
=>
$
value
)
{
$
section_data_array
[
]
=
[
'data'
=>
$
name
,
'inputvalue'
=>
$
value
,
]
;
}
// endforeach;
unset
(
$
name
,
$
value
)
;
}
$
this
->
log_sections
[
'Session'
]
=
$
section_data_array
;
unset
(
$
section_data_array
)
;
}


public function getMicrotime($at_start = false)
    {
        if ($at_start === true && is_array($_SERVER) && array_key_exists('REQUEST_TIME_FLOAT', $_SERVER)) {
            return floatval($_SERVER['REQUEST_TIME_FLOAT']);
        }

        return floatval(microtime(true));
    }

public function getMicrotime ( $ at_start = false ) { if ( $ at_start === true && is_array ( $ _SERVER ) && array_key_exists ( 'REQUEST_TIME_FLOAT' , $ _SERVER ) ) { return floatval ( $ _SERVER [ 'REQUEST_TIME_FLOAT' ] ) ; } return floatval ( microtime ( true ) ) ; }

get microtime.

@param boolean $at_start set to true if this microtime is get at the very beginning of the app. this can allow newer php version to use $_SERVER['REQUEST_TIME_FLOAT'];
@return float microtime in float.


public function summaryMatchKey($section, $matchKey, $sectionKey)
    {
        if (!is_string($section)) {
            $section = null;
        }

        if (!is_string($matchKey)) {
            $matchKey = null;
        }

        if (!is_numeric($sectionKey)) {
            $sectionKey = 0;
        }

        $output = '';

        if (isset($this->log_sections[$section]) && is_array($this->log_sections[$section]) && $matchKey !== null) {
            $matchKeyTime = [];
            $matchKeyMemory = [];

            foreach ($this->log_sections[$section] as $key => $item) {
                if (isset($item['matchKey']) && $item['matchKey'] == $matchKey && $key <= $sectionKey) {
                    if (count($matchKeyMemory) >= 2 || count($matchKeyTime) >= 2) {
                        break;
                    }

                    if (isset($item['time'])) {
                        $matchKeyTime[] = $item['time'];
                    }

                    if (isset($item['memory'])) {
                        $matchKeyMemory[] = $item['memory'];
                    }
                }
            }// endforeach;
            unset($item, $key);

            if (count($matchKeyTime) >= 2) {
                $output = $this->getReadableTime((max($matchKeyTime)-min($matchKeyTime))*1000);
            } elseif (count($matchKeyMemory) >= 2) {
                $output = $this->getReadableFileSize(max($matchKeyMemory)-min($matchKeyMemory));
            }

            unset($matchKeyMemory, $matchKeyTime);
        }

        return $output;
    }

public
function
summaryMatchKey
(
$
section
,
$
matchKey
,
$
sectionKey
)
{
if
(
!
is_string
(
$
section
)
)
{
$
section
=
;
}
if
(
!
is_string
(
$
matchKey
)
)
{
$
matchKey
=
;
}
if
(
!
is_numeric
(
$
sectionKey
)
)
{
$
sectionKey
=
0
;
}
$
output
=
''
;
if
(
isset
(
$
this
->
log_sections
[
$
section
]
)
&&
is_array
(
$
this
->
log_sections
[
$
section
]
)
&&
$
matchKey
!==
)
{
$
matchKeyTime
=
[
]
;
$
matchKeyMemory
=
[
]
;
foreach
(
$
this
->
log_sections
[
$
section
]
as
$
key
=>
$
item
)
{
if
(
isset
(
$
item
[
'matchKey'
]
)
&&
$
item
[
'matchKey'
]
==
$
matchKey
&&
$
key
<=
$
sectionKey
)
{
if
(
count
(
$
matchKeyMemory
)
>=
2
||
count
(
$
matchKeyTime
)
>=
2
)
{
break
;
}
if
(
isset
(
$
item
[
'time'
]
)
)
{
$
matchKeyTime
[
]
=
$
item
[
'time'
]
;
}
if
(
isset
(
$
item
[
'memory'
]
)
)
{
$
matchKeyMemory
[
]
=
$
item
[
'memory'
]
;
}
}
}
// endforeach;
unset
(
$
item
,
$
key
)
;
if
(
count
(
$
matchKeyTime
)
>=
2
)
{
$
output
=
$
this
->
getReadableTime
(
(
max
(
$
matchKeyTime
)
min
(
$
matchKeyTime
)
)
*
1000
)
;
}
elseif
(
count
(
$
matchKeyMemory
)
>=
2
)
{
$
output
=
$
this
->
getReadableFileSize
(
max
(
$
matchKeyMemory
)
min
(
$
matchKeyMemory
)
)
;
}
unset
(
$
matchKeyMemory
,
$
matchKeyTime
)
;
}
return
$
output
;
}

Summary start and end of match key in a section.

@param string $section The section name.
@param string $matchKey The match key in that section.
@param integer $sectionKey The array index key of the section for check while displaying in the loop.
@return string Return the readable result if found 2 match key and can summary. Return empty string if not found.

Summary start and end of match key in a section .


public static function createFiles()
    {
        $fixer = new static();
        $files = $fixer->saneFilesArray($_FILES);
        $fixed = [];
        foreach ($files as $key => $data) {
            $fixed[$key] = $fixer->createUploadedFile($data);
        }
        return $fixed;
    }

public static function createFiles ( ) { $ fixer = new static ( ) ; $ files = $ fixer -> saneFilesArray ( $ _FILES ) ; $ fixed = [ ] ; foreach ( $ files as $ key => $ data ) { $ fixed [ $ key ] = $ fixer -> createUploadedFile ( $ data ) ; } return $ fixed ; }

Creates the uploaded file objects within a normalized files tree

@return array|UploadedFile[]


private function createUploadedFile($data)
    {
        if (array_key_exists('tmp_name', $data)) {
            return UploadedFile::create($data);
        }

        $result = [];
        foreach ($data as $key => $datum) {
            $result[$key] = $this->createUploadedFile($datum);
        }
        return $result;
    }

private function createUploadedFile ( $ data ) { if ( array_key_exists ( 'tmp_name' , $ data ) ) { return UploadedFile :: create ( $ data ) ; } $ result = [ ] ; foreach ( $ data as $ key => $ datum ) { $ result [ $ key ] = $ this -> createUploadedFile ( $ datum ) ; } return $ result ; }

Helper function to recursively create UploadedFile objects

@param array $data

@return array|UploadedFile


private function filesFlip(&$result, $keys, $value)
    {
        if (is_array($value)) {
            foreach ($value as $k => $v) {
                $newKeys = $keys;
                array_push($newKeys, $k);
                $this->filesFlip($result, $newKeys, $v);
            }
            return;
        }

        $res = $value;
        // Move the innermost key to the outer spot
        $first = array_shift($keys);
        array_push($keys, $first);
        foreach (array_reverse($keys) as $kk) {
            // You might think we'd say $res[$kk] = $res, but $res starts
            // out not as an array
            $res = array($kk => $res);
        }

        $result = $this->arrayMergeRecursive($result, $res);
    }

Move the innermost key to the outer spot

@param array  $result
@param array  $keys
@param mixed  $value


private function arrayMergeRecursive($array1, $array2)
    {
        if (!is_array($array1) or !is_array($array2)) {
            return $array2;
        }

        foreach ($array2 as $sKey2 => $sValue2) {
            $array1[$sKey2] = $this->arrayMergeRecursive(@$array1[$sKey2], $sValue2);
        }
        return $array1;
    }

private function arrayMergeRecursive ( $ array1 , $ array2 ) { if ( ! is_array ( $ array1 ) or ! is_array ( $ array2 ) ) { return $ array2 ; } foreach ( $ array2 as $ sKey2 => $ sValue2 ) { $ array1 [ $ sKey2 ] = $ this -> arrayMergeRecursive ( @ $ array1 [ $ sKey2 ] , $ sValue2 ) ; } return $ array1 ; }

Recursively merge provided arrays

@param array|string $array1
@param array|string $array2

@return array


public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $request = $request->withAttribute('sessionDriver', $this->sessionDriver);
        return $handler->handle($request);
    }

public function process ( ServerRequestInterface $ request , RequestHandlerInterface $ handler ) : ResponseInterface { $ request = $ request -> withAttribute ( 'sessionDriver' , $ this -> sessionDriver ) ; return $ handler -> handle ( $ request ) ; }

Process an incoming server request and return a response, optionally delegating
response creation to a handler.

@param ServerRequestInterface $request
@param RequestHandlerInterface $handler

@return ResponseInterface

Process an incoming server request and return a response optionally delegating response creation to a handler .


public function add()
	{
		// Are we creating this object from the menu add wizard?
		// Toss the menu_id URL variable into the session instead
		if (Input::get('menu_id')) {
			return Redirect::to($this->uri('add'))->with('menu_id', Input::get('menu_id'));
		}
		// And grab the menu_id from the session or the old input, depending on whether we're new here
		if (Session::has('menu_id')) {
			$this->data['menu_id'] = Session::get('menu_id');
		} else if (Input::old('menu_id')) {
			$this->data['menu_id'] = Input::old('menu_id');
		}

		$this->data['action'] = 'add';
		return View::make($this->view('add-or-edit'), $this->data);
	}

Show the form for adding.

Both add() and edit() use the same view:  add-or-edit

There are two ways of adding a new item.  One is from its index,
and the other is from the menu index's 'Add Link' wizard.

@return \Illuminate\Http\RedirectResponse|\Illuminate\View\View


public function edit($id)
	{
		$Model = App::make($this->Model);

		$this->data[$this->singular] = $Model::withTrashed()->findOrFail($id);
		$this->data['action']        = 'edit';

		return View::make($this->view('add-or-edit'), $this->data);
	}

public function edit ( $ id ) { $ Model = App :: make ( $ this -> Model ) ; $ this -> data [ $ this -> singular ] = $ Model :: withTrashed ( ) -> findOrFail ( $ id ) ; $ this -> data [ 'action' ] = 'edit' ; return View :: make ( $ this -> view ( 'add-or-edit' ) , $ this -> data ) ; }

Show the model form for editing.

Both add() and edit() use the same view:  add-or-edit

@param int $id - The ID of the model we're editing.
@return \Illuminate\View\View


public function attempt_edit($id)
	{
		$Model  = App::make($this->Model);
		$object = $Model::withTrashed()->findOrFail($id);

		$errors = $object->validate();
		if (count($errors)) {
			return Redirect::to($this->uri('edit/' . $id))->withInput()->withErrors($errors);
		}

		$object->save();

		return $this->edit_redirect($object);
	}

public function attempt_edit ( $ id ) { $ Model = App :: make ( $ this -> Model ) ; $ object = $ Model :: withTrashed ( ) -> findOrFail ( $ id ) ; $ errors = $ object -> validate ( ) ; if ( count ( $ errors ) ) { return Redirect :: to ( $ this -> uri ( 'edit/' . $ id ) ) -> withInput ( ) -> withErrors ( $ errors ) ; } $ object -> save ( ) ; return $ this -> edit_redirect ( $ object ) ; }

Edit a model.

When attempting to edit a model, we simply call validate() on it
and then save it.  All models that extend AngelModel have a saving()
model event that calls the assign() method and fills the model's columns/properties
from the posted inputs.

@param int $id - The ID of the model we're editing.
@return $this->edit_redirect() - Where to go after a successful edit?


public function edit_redirect($object)
	{
		return Redirect::to($this->uri('edit/' . $object->id))->with('success', '

' . $this->Model . ' successfully updated.

uri('', true) . '">Return to index

		');
	}

Where to go after a successful edit?

Often times, we want to just change where we redirect to after editing the model.
That is why this function exists.

@param AngelModel $object - The model we just edited.
@return \Illuminate\Http\RedirectResponse


public function order()
	{
		$Model   = App::make($this->Model);
		$orders  = Input::get('orders');
		$objects = $Model::whereIn('id', array_keys($orders))->get();

		foreach ($objects as $object) {
			$object->order = $orders[$object->id];
			$object->save();
		}

		return 1;
	}

public function order ( ) { $ Model = App :: make ( $ this -> Model ) ; $ orders = Input :: get ( 'orders' ) ; $ objects = $ Model :: whereIn ( 'id' , array_keys ( $ orders ) ) -> get ( ) ; foreach ( $ objects as $ object ) { $ object -> order = $ orders [ $ object -> id ] ; $ object -> save ( ) ; } return 1 ; }


public function delete($id, $ajax = false)
	{
		$Model = App::make($this->Model);

		$object = $Model::findOrFail($id);
		$object->delete();

		if ($ajax) return 1;

		return $this->delete_redirect();
	}

public function delete ( $ id , $ ajax = false ) { $ Model = App :: make ( $ this -> Model ) ; $ object = $ Model :: findOrFail ( $ id ) ; $ object -> delete ( ) ; if ( $ ajax ) return 1 ; return $ this -> delete_redirect ( ) ; }

Delete a model by ID.

@param int $id - The ID of the model we're deleting.
@param bool $ajax - Is this an AJAX deletion?
@return $this->delete_redirect() - Where to go after a deletion?


public function getUploadedFiles()
    {
        if (null === $this->uploadedFiles) {
            $this->uploadedFiles = UploadedFilesFactory::createFiles();
        }
        return $this->uploadedFiles;
    }

public function getUploadedFiles ( ) { if ( null === $ this -> uploadedFiles ) { $ this -> uploadedFiles = UploadedFilesFactory :: createFiles ( ) ; } return $ this -> uploadedFiles ; }

Retrieve normalized file upload data.

@return UploadedFile[]


public function withUploadedFiles(array $uploadedFiles)
    {
        if (! $this->checkUploadedFiles($uploadedFiles)) {
            throw new InvalidArgumentException(
                "The uploaded files array given has at least one leaf that is not ".
                "an UploadedFile object."
            );
        }

        $request = clone $this;
        $request->uploadedFiles = $uploadedFiles;
        return $request;
    }

Create a new instance with the specified uploaded files.

@param array $uploadedFiles An array tree of UploadedFileInterface instances.
@return Request

@throws InvalidArgumentException if an invalid structure is provided.

Create a new instance with the specified uploaded files .


private function checkUploadedFiles(array $files)
    {
        $valid = true;

        foreach ($files as $file) {
            if (is_array($file)) {
                $valid = $this->checkUploadedFiles($files);
                break;
            }

            if (! $file instanceof UploadedFile) {
                $valid = false;
                break;
            }
        }

        return $valid;
    }

private function checkUploadedFiles ( array $ files ) { $ valid = true ; foreach ( $ files as $ file ) { if ( is_array ( $ file ) ) { $ valid = $ this -> checkUploadedFiles ( $ files ) ; break ; } if ( ! $ file instanceof UploadedFile ) { $ valid = false ; break ; } } return $ valid ; }

Check if provided files array is valid

@param array $files

@return bool


private function loadHeaders()
    {
        foreach ($_SERVER as $key => $value) {
            $subset = substr($key, 0, 5);
            if ($subset <> 'HTTP_' && $subset <> 'CONTE') {
                continue;
            }
            $header = str_replace(
                ' ',
                '-',
                ucwords(
                    str_replace(['http_', '_'], ['', ' '], strtolower($key))
                )
            );
            $this->headers[$this->headerKey($header)] = [$value];
        }
    }

private
function
loadHeaders
(
)
{
foreach
(
$
_SERVER
as
$
key
=>
$
value
)
{
$
subset
=
substr
(
$
key
,
0
,
5
)
;
if
(
$
subset
<>
'HTTP_'
&&
$
subset
<>
'CONTE'
)
{
continue
;
}
$
header
=
str_replace
(
' '
,
'-'
,
ucwords
(
str_replace
(
[
'http_'
,
'_'
]
,
[
''
,
' '
]
,
strtolower
(
$
key
)
)
)
)
;
$
this
->
headers
[
$
this
->
headerKey
(
$
header
)
]
=
[
$
value
]
;
}
}


public function withAttribute($name, $value)
    {
        $request = clone $this;
        $request->attributes[$name] = $value;
        return $request;
    }

public function withAttribute ( $ name , $ value ) { $ request = clone $ this ; $ request -> attributes [ $ name ] = $ value ; return $ request ; }

Return an instance with the specified derived request attribute.

This method allows setting a single derived request attribute as
described in getAttributes().

@see getAttributes()
@param string $name The attribute name.
@param mixed $value The value of the attribute.

@return Request

Return an instance with the specified derived request attribute .


public function withoutAttribute($name)
    {
        $request = clone $this;
        if (array_key_exists($name, $request->attributes)) {
            unset($request->attributes[$name]);
        }
        return $request;
    }

public function withoutAttribute ( $ name ) { $ request = clone $ this ; if ( array_key_exists ( $ name , $ request -> attributes ) ) { unset ( $ request -> attributes [ $ name ] ) ; } return $ request ; }

Return an instance that removes the specified derived request attribute.

This method allows removing a single derived request attribute as
described in getAttributes().

@see getAttributes()
@param string $name The attribute name.

@return Request

Return an instance that removes the specified derived request attribute .


static function checkMTime($mtime, $sendHeaders=null) {
        header("Last-Modified: " . gmdate("D, d M Y H:i:s", $mtime) . " GMT");

        $headers = function_exists("getallheaders")
            ? getallheaders()
            : (function_exists("apache_request_headers")
                ? apache_request_headers()
                : false);

        if (is_array($headers) && isset($headers['If-Modified-Since'])) {
            $client_mtime = explode(';', $headers['If-Modified-Since']);
            $client_mtime = @strtotime($client_mtime[0]);
            if ($client_mtime >= $mtime) {
                header('HTTP/1.1 304 Not Modified');
                if (is_array($sendHeaders) && count($sendHeaders))
                    foreach ($sendHeaders as $header)
                        header($header);
                elseif ($sendHeaders !== null)
                    header($sendHeaders);
                die;
            }
        }
    }

static
function
checkMTime
(
$
mtime
,
$
sendHeaders
=
)
{
header
(
"Last-Modified: "
.
gmdate
(
"D, d M Y H:i:s"
,
$
mtime
)
.
" GMT"
)
;
$
headers
=
function_exists
(
"getallheaders"
)
getallheaders
(
)
:
(
function_exists
(
"apache_request_headers"
)
apache_request_headers
(
)
:
false
)
;
if
(
is_array
(
$
headers
)
&&
isset
(
$
headers
[
'If-Modified-Since'
]
)
)
{
$
client_mtime
=
explode
(
';'
,
$
headers
[
'If-Modified-Since'
]
)
;
$
client_mtime
=
@
strtotime
(
$
client_mtime
[
0
]
)
;
if
(
$
client_mtime
>=
$
mtime
)
{
header
(
'HTTP/1.1 304 Not Modified'
)
;
if
(
is_array
(
$
sendHeaders
)
&&
count
(
$
sendHeaders
)
)
foreach
(
$
sendHeaders
as
$
header
)
header
(
$
header
)
;
elseif
(
$
sendHeaders
!==
)
header
(
$
sendHeaders
)
;
die
;
}
}
}

Check if given modification time is newer than client-side one. If not,
the method will tell the client to get the content from its own cache.
Afterwards the script process will be terminated. This feature requires
the PHP to be configured as Apache module.
@param integer $mtime
@param mixed $sendHeaders

Check if given modification time is newer than client - side one . If not the method will tell the client to get the content from its own cache . Afterwards the script process will be terminated . This feature requires the PHP to be configured as Apache module .


public function getHeader($name)
    {
        $key = $this->headerKey($name);
        if (array_key_exists($key, $this->headers)) {
            return $this->headers[$key];
        }

        return [];
    }

public function getHeader ( $ name ) { $ key = $ this -> headerKey ( $ name ) ; if ( array_key_exists ( $ key , $ this -> headers ) ) { return $ this -> headers [ $ key ] ; } return [ ] ; }

Retrieves a message header value by the given case-insensitive name.

This method returns an array of all the header values of the given
case-insensitive header name.

If the header does not appear in the message, this method MUST return an
empty array.

@param string $name Case-insensitive header field name.
@return string[] An array of string values as provided for the given
header. If the header does not appear in the message, this method MUST
return an empty array.

Retrieves a message header value by the given case - insensitive name .


private function setStatus($status, $reasonPhrase = '')
    {
        HttpCodes::check($status);
        $this->status = intval($status, 10);
        if ($reasonPhrase === '') {
            $this->reasonPhrase = HttpCodes::reasonPhraseFor($this->status);
        }
    }

private function setStatus ( $ status , $ reasonPhrase = '' ) { HttpCodes :: check ( $ status ) ; $ this -> status = intval ( $ status , 10 ) ; if ( $ reasonPhrase === '' ) { $ this -> reasonPhrase = HttpCodes :: reasonPhraseFor ( $ this -> status ) ; } }

Sets the response status code

@param int    $status
@param string $reasonPhrase


public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        $response = self::execute($this->callable, [$request, $handler]);
        if (!$response instanceof ResponseInterface) {
            throw new UnexpectedValueException(
                sprintf('The middleware must return an instance of %s', ResponseInterface::class)
            );
        }
        return $response;
    }

Process an incoming server request and return a response, optionally delegating
response creation to an handler.

@param ServerRequestInterface $request
@param RequestHandlerInterface $handler

@return ResponseInterface

Process an incoming server request and return a response optionally delegating response creation to an handler .


static function mysql_version()
	{
		$version = DB::select('SELECT VERSION() AS `version`');
		$version = explode('-', $version[0]->version);
		$version = $version[0];
		return $version;
	}

static
function
mysql_version
(
)
{
$
version
=
DB
::
select
(
'SELECT VERSION() AS `version`'
)
;
$
version
=
explode
(
'-'
,
$
version
[
0
]
->
version
)
;
$
version
=
$
version
[
0
]
;
return
$
version
;
}

Get the MySQL version of the server.

@return string - i.e.: '5.5.12'


public function authenticate(array $credentials)
	{
		list($username, $password) = $credentials;

		$user = $this->repository->getActiveUser($username);

		if (!$user) {
			throw new Security\AuthenticationException('The username is incorrect.', self::IDENTITY_NOT_FOUND);

		} elseif (!Passwords::verify($password, $user->password)) {
			throw new Security\AuthenticationException('The password is incorrect.', self::INVALID_CREDENTIAL);

		} elseif (Passwords::needsRehash($user->password)) {
			$this->repository->update($user->id, ['password' => Passwords::hash($password)]);
		}

		$data = $user->toArray();
		unset($data['password']);

		return new Security\Identity($user->id, $user->role, $data);
	}

public
function
authenticate
(
array
$
credentials
)
{
list
(
$
username
,
$
password
)
=
$
credentials
;
$
user
=
$
this
->
repository
->
getActiveUser
(
$
username
)
;
if
(
!
$
user
)
{
throw
new
Security
\
AuthenticationException
(
'The username is incorrect.'
,
self
::
IDENTITY_NOT_FOUND
)
;
}
elseif
(
!
Passwords
::
verify
(
$
password
,
$
user
->
password
)
)
{
throw
new
Security
\
AuthenticationException
(
'The password is incorrect.'
,
self
::
INVALID_CREDENTIAL
)
;
}
elseif
(
Passwords
::
needsRehash
(
$
user
->
password
)
)
{
$
this
->
repository
->
update
(
$
user
->
id
,
[
'password'
=>
Passwords
::
hash
(
$
password
)
]
)
;
}
$
data
=
$
user
->
toArray
(
)
;
unset
(
$
data
[
'password'
]
)
;
return
new
Security
\
Identity
(
$
user
->
id
,
$
user
->
role
,
$
data
)
;
}

Performs an authentication

@param array $credentials

@return Security\Identity|Security\IIdentity
@throws \Nette\Security\AuthenticationException


public function findAll()
	{
		if ($this->user && $this->user->isInRole('root')) {
			return $this->repository->findAllActive();

		} else {
			return $this->repository->findAllActive()
									->where('role !=', 'root');
		}

	}

public
function
findAll
(
)
{
if
(
$
this
->
user
&&
$
this
->
user
->
isInRole
(
'root'
)
)
{
return
$
this
->
repository
->
findAllActive
(
)
;
}
else
{
return
$
this
->
repository
->
findAllActive
(
)
->
where
(
'role !='
,
'root'
)
;
}
}


public function findAllDeactivated()
	{
		if ($this->user && $this->user->isInRole('root')) {
			return $this->repository->findAll()
									->where('active', '0');

		} else {
			return $this->repository->findAll()
									->where('active', '0')
									->where('role !=', 'root');
		}
	}

public
function
findAllDeactivated
(
)
{
if
(
$
this
->
user
&&
$
this
->
user
->
isInRole
(
'root'
)
)
{
return
$
this
->
repository
->
findAll
(
)
->
where
(
'active'
,
'0'
)
;
}
else
{
return
$
this
->
repository
->
findAll
(
)
->
where
(
'active'
,
'0'
)
->
where
(
'role !='
,
'root'
)
;
}
}

Return all deactivated users

@return array|Nette\Database\Table\IRow[]


public function add($data = [])
	{
		if (isset($data['email']) && isset($data['password'])) {
			if ((isset($data['username']) && $data['username'] === '')
				or !$this->useUsernames
			){
				$data['username'] = $data['email'];
			}

			if (!Validators::isEmail($data['email'])){
				throw new \InvalidArgumentException('Bad email address format');
			}
			if (!Validators::is($data['password'], 'string:6..')){
				throw new \InvalidArgumentException('Too short password');
			}

			$create = [
				'email' => $data['email'],
				'username' => self::clearUsername($data['username']),
				'password' => Passwords::hash($data['password']),
			];

		} else {
			throw new \InvalidArgumentException('We need email and password');
		}

		if (isset($data['role'])) {
			$create['role'] = $data['role'];
		} else {
			$create['role'] = 'user';
		}

		if (isset($data['name'])) {
			$create['name'] = $data['name'];
		}

		if ($this->isImage() && isset($data['avatar_namespace']) && isset($data['avatar_filename'])) {
			$create['avatar_namespace'] = $data['avatar_namespace'];
			$create['avatar_filename'] = $data['avatar_filename'];
		}

		$person = $this->repository->insert($create);

		return $person;
	}

public
function
add
(
$
data
=
[
]
)
{
if
(
isset
(
$
data
[
'email'
]
)
&&
isset
(
$
data
[
'password'
]
)
)
{
if
(
(
isset
(
$
data
[
'username'
]
)
&&
$
data
[
'username'
]
===
''
)
or
!
$
this
->
useUsernames
)
{
$
data
[
'username'
]
=
$
data
[
'email'
]
;
}
if
(
!
Validators
::
isEmail
(
$
data
[
'email'
]
)
)
{
throw
new
\
InvalidArgumentException
(
'Bad email address format'
)
;
}
if
(
!
Validators
::
is
(
$
data
[
'password'
]
,
'string:6..'
)
)
{
throw
new
\
InvalidArgumentException
(
'Too short password'
)
;
}
$
create
=
[
'email'
=>
$
data
[
'email'
]
,
'username'
=>
self
::
clearUsername
(
$
data
[
'username'
]
)
,
'password'
=>
Passwords
::
hash
(
$
data
[
'password'
]
)
,
]
;
}
else
{
throw
new
\
InvalidArgumentException
(
'We need email and password'
)
;
}
if
(
isset
(
$
data
[
'role'
]
)
)
{
$
create
[
'role'
]
=
$
data
[
'role'
]
;
}
else
{
$
create
[
'role'
]
=
'user'
;
}
if
(
isset
(
$
data
[
'name'
]
)
)
{
$
create
[
'name'
]
=
$
data
[
'name'
]
;
}
if
(
$
this
->
isImage
(
)
&&
isset
(
$
data
[
'avatar_namespace'
]
)
&&
isset
(
$
data
[
'avatar_filename'
]
)
)
{
$
create
[
'avatar_namespace'
]
=
$
data
[
'avatar_namespace'
]
;
$
create
[
'avatar_filename'
]
=
$
data
[
'avatar_filename'
]
;
}
$
person
=
$
this
->
repository
->
insert
(
$
create
)
;
return
$
person
;
}

Inserts new user

@param array|\Nette\ArrayHash $data

@return \Nette\Database\Table\ActiveRow
@throws \Aprila\DuplicateEntryException


public function getOption($value)
	{
		if(!in_array($value, $this->allowedValues, true))
		{
			throw new InvalidOptionValueException('Invalid $metricOption argument "' . $value . '", allowed values: '
			                                      . implode(', ', $this->allowedValues));
		}

		return '-metric ' . $value . ' ';
	}

public
function
getOption
(
$
value
)
{
if
(
!
in_array
(
$
value
,
$
this
->
allowedValues
,
true
)
)
{
throw
new
InvalidOptionValueException
(
'Invalid $metricOption argument "'
.
$
value
.
'", allowed values: '
.
implode
(
', '
,
$
this
->
allowedValues
)
)
;
}
return
'-metric '
.
$
value
.
' '
;
}

Returns a prepared metric options string.

@param string $value

@return string
@throws InvalidOptionValueException

Returns a prepared metric options string .


private static function set_current_lang_from_post_id($postId)
    {
        if (WpCxense::instance()->settings->languagesIsEnabled()) {
            WpCxense::instance()->settings->setCurrentLocale(LanguageProvider::getPostLanguage($postId));
        }
    }

private static function set_current_lang_from_post_id ( $ postId ) { if ( WpCxense :: instance ( ) -> settings -> languagesIsEnabled ( ) ) { WpCxense :: instance ( ) -> settings -> setCurrentLocale ( LanguageProvider :: getPostLanguage ( $ postId ) ) ; } }

Sets the locale on the settings page based upon to the locale of the post

@param $postId


public function isEncryptedContainer($encrypted, $key)
    {
        try
        {
            $data = JWT::decode($encrypted, $key);
        }
        catch(Exception $e)
        {
            return false;
        }

        return $this->isJson($data->container);
    }

public function isEncryptedContainer ( $ encrypted , $ key ) { try { $ data = JWT :: decode ( $ encrypted , $ key ) ; } catch ( Exception $ e ) { return false ; } return $ this -> isJson ( $ data -> container ) ; }

Check if string is encrypted Container

@param string $encrypted
@param string $key
@return bool


public function isEncryptedString($encrypted, $key)
    {
        try
        {
            $data = JWT::decode($encrypted, $key);
        }
        catch(Exception $e)
        {
            return false;
        }

        return is_string($data->string);
    }

public function isEncryptedString ( $ encrypted , $ key ) { try { $ data = JWT :: decode ( $ encrypted , $ key ) ; } catch ( Exception $ e ) { return false ; } return is_string ( $ data -> string ) ; }

Check if string is encrypted String

@param string $encrypted
@param string $key
@return bool


public function dump()
    {
        return
            $this->startFile().
            $this->addNamespace().
            $this->startClass().
            $this->addProperties().
            $this->addMethods().
            $this->endClass()
        ;
    }

public function dump ( ) { return $ this -> startFile ( ) . $ this -> addNamespace ( ) . $ this -> startClass ( ) . $ this -> addProperties ( ) . $ this -> addMethods ( ) . $ this -> endClass ( ) ; }

Dump the definition.

@return string The PHP code of the definition.

@api


static public function exportArray(array $array, $indent)
    {
        $code = array();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $value = self::exportArray($value, $indent + 4);
            } else {
                $value = null === $value ? 'null' : var_export($value, true);
            }

            $code[] = sprintf('%s%s => %s,', str_repeat(' ', $indent), var_export($key, true), $value);
        }

        return sprintf("array(\n%s\n%s)", implode("\n", $code), str_repeat(' ', $indent - 4));
    }

static
public
function
exportArray
(
array
$
array
,
$
indent
)
{
$
code
=
array
(
)
;
foreach
(
$
array
as
$
key
=>
$
value
)
{
if
(
is_array
(
$
value
)
)
{
$
value
=
self
::
exportArray
(
$
value
,
$
indent
+
4
)
;
}
else
{
$
value
=
===
$
value
'null'
:
var_export
(
$
value
,
true
)
;
}
$
code
[
]
=
sprintf
(
'%s%s => %s,'
,
str_repeat
(
' '
,
$
indent
)
,
var_export
(
$
key
,
true
)
,
$
value
)
;
}
return
sprintf
(
"array(\n%s\n%s)"
,
implode
(
"\n"
,
$
code
)
,
str_repeat
(
' '
,
$
indent
4
)
)
;
}

Export an array.

Based on Symfony\Component\DependencyInjection\Dumper\PhpDumper::exportParameters
http://github.com/symfony/symfony

@param array $array  The array.
@param int   $indent The indent.

@return string The array exported.


public function preGlobalProcess(\ArrayObject $configClasses, Container $container)
    {
        $this->configClasses = $configClasses;
        $this->definitions = $container;

        $this->doPreGlobalProcess();

        $this->configClasses = null;
        $this->definitions = null;
    }

public function preGlobalProcess ( \ ArrayObject $ configClasses , Container $ container ) { $ this -> configClasses = $ configClasses ; $ this -> definitions = $ container ; $ this -> doPreGlobalProcess ( ) ; $ this -> configClasses = null ; $ this -> definitions = null ; }

Pre global process of the extension.

@param \ArrayObject                $configClasses The config classes.
@param Mandango\Mondator\Container $container     The global container.

@api


public function postGlobalProcess(\ArrayObject $configClasses, Container $container)
    {
        $this->configClasses = $configClasses;
        $this->definitions = $container;

        $this->doPostGlobalProcess();

        $this->configClasses = null;
        $this->definitions = null;
    }

public function postGlobalProcess ( \ ArrayObject $ configClasses , Container $ container ) { $ this -> configClasses = $ configClasses ; $ this -> definitions = $ container ; $ this -> doPostGlobalProcess ( ) ; $ this -> configClasses = null ; $ this -> definitions = null ; }

Post global process of the extension.

@param \ArrayObject                $configClasses The config classes.
@param Mandango\Mondator\Container $container     The global container.

@api


public static function noTokenForTokenTypes($tokenTypes) : ParseException
    {
        $message = "No token could be found for any of types ";
        $message .= join(", ", $tokenTypes);

        return new ParseException($message, self::NO_TOKEN);
    }

Create parse exceptiion for missing token

@param $tokenTypes
@return ParseException


public function make($from, $type)
    {
        $type = $type ?: static::SIMPLE;

        switch ($type)
        {
            case static::SIMPLE:
                return new Container($from);
            case static::REVERTABLE:
                return new RevertableContainer($from);
            default:
                throw new InvalidArgumentException('Argument 2 is invalid');
        }
    }

public
function
make
(
$
from
,
$
type
)
{
$
type
=
$
type
:
static
::
SIMPLE
;
switch
(
$
type
)
{
case
static
::
SIMPLE
:
return
new
Container
(
$
from
)
;
case
static
::
REVERTABLE
:
return
new
RevertableContainer
(
$
from
)
;
default
:
throw
new
InvalidArgumentException
(
'Argument 2 is invalid'
)
;
}
}

Return constructed instance of Container Type

@param mixed $from
@param int|null   $type
@return \im\Primitive\Container\Container|\im\Primitive\Container\RevertableContainer


public function recover($id, $user = TRUE)
	{
		$recover = array(
			'deleted_at' => NULL,
		);

		if ($user) {
			$recover['deleted_by'] = NULL;
		}

		$this->rawGet($id)->update($recover);

		return $this->get($id);
	}

public function recover ( $ id , $ user = TRUE ) { $ recover = array ( 'deleted_at' => NULL , ) ; if ( $ user ) { $ recover [ 'deleted_by' ] = NULL ; } $ this -> rawGet ( $ id ) -> update ( $ recover ) ; return $ this -> get ( $ id ) ; }

Undo soft delete

@param $id int
@param boolean $user

@return \Nette\Database\Table\IRow


public function newClassExtensionsProcess($class, \ArrayObject $configClasses, \ArrayObject $newClassExtensions)
    {
        $this->class = $class;
        $this->configClasses = $configClasses;
        $this->configClass = $configClasses[$class];
        $this->newClassExtensions = $newClassExtensions;

        $this->doNewClassExtensionsProcess();

        $this->class = null;
        $this->configClasses = null;
        $this->configClass = null;
        $this->newClassExtensions = null;
    }

public function newClassExtensionsProcess ( $ class , \ ArrayObject $ configClasses , \ ArrayObject $ newClassExtensions ) { $ this -> class = $ class ; $ this -> configClasses = $ configClasses ; $ this -> configClass = $ configClasses [ $ class ] ; $ this -> newClassExtensions = $ newClassExtensions ; $ this -> doNewClassExtensionsProcess ( ) ; $ this -> class = null ; $ this -> configClasses = null ; $ this -> configClass = null ; $ this -> newClassExtensions = null ; }

New class extensions process.

@param string       $class              The class.
@param \ArrayObject $configClasses      The config classes.
@param \ArrayObject $newClassExtensions The new class extensions.

@api


public function newConfigClassesProcess($class, \ArrayObject $configClasses, \ArrayObject $newConfigClasses)
    {
        $this->class = $class;
        $this->configClasses = $configClasses;
        $this->configClass = $configClasses[$class];
        $this->newConfigClasses = $newConfigClasses;

        $this->doNewConfigClassesProcess();

        $this->class = null;
        $this->configClasses = null;
        $this->configClass = null;
        $this->newConfigClasses = null;
    }

public function newConfigClassesProcess ( $ class , \ ArrayObject $ configClasses , \ ArrayObject $ newConfigClasses ) { $ this -> class = $ class ; $ this -> configClasses = $ configClasses ; $ this -> configClass = $ configClasses [ $ class ] ; $ this -> newConfigClasses = $ newConfigClasses ; $ this -> doNewConfigClassesProcess ( ) ; $ this -> class = null ; $ this -> configClasses = null ; $ this -> configClass = null ; $ this -> newConfigClasses = null ; }

New config classes process.

@param string       $class            The class.
@param \ArrayObject $configClasses    The config classes.
@param \ArrayObject $newConfigClasses The new config classes.

@api


public function configClassProcess($class, \ArrayObject $configClasses)
    {
        $this->class = $class;
        $this->configClasses = $configClasses;
        $this->configClass = $configClasses[$class];

        $this->doConfigClassProcess();

        $this->class = null;
        $this->configClasses = null;
        $this->configClass = null;
    }

public function configClassProcess ( $ class , \ ArrayObject $ configClasses ) { $ this -> class = $ class ; $ this -> configClasses = $ configClasses ; $ this -> configClass = $ configClasses [ $ class ] ; $ this -> doConfigClassProcess ( ) ; $ this -> class = null ; $ this -> configClasses = null ; $ this -> configClass = null ; }

Process the config class.

@param string       $class         The class.
@param \ArrayObject $configClasses The config classes.

@api


public function classProcess($class, \ArrayObject $configClasses, Container $container)
    {
        $this->class = $class;
        $this->configClasses = $configClasses;
        $this->configClass = $configClasses[$class];
        $this->definitions = $container;

        $this->doClassProcess();

        $this->class = null;
        $this->configClasses = null;
        $this->configClass = null;
        $this->definitions = null;
    }

public function classProcess ( $ class , \ ArrayObject $ configClasses , Container $ container ) { $ this -> class = $ class ; $ this -> configClasses = $ configClasses ; $ this -> configClass = $ configClasses [ $ class ] ; $ this -> definitions = $ container ; $ this -> doClassProcess ( ) ; $ this -> class = null ; $ this -> configClasses = null ; $ this -> configClass = null ; $ this -> definitions = null ; }

Process the class.

@param string                      $class         The class.
@param \ArrayObject                $configClasses The config classes.
@param Mandango\Mondator\Container $container     The container.

@api


public function setDefinitions(array $definitions)
    {
        $this->definitions = array();
        foreach ($definitions as $name => $definition) {
            $this->setDefinition($name, $definition);
        }
    }

public function setDefinitions ( array $ definitions ) { $ this -> definitions = array ( ) ; foreach ( $ definitions as $ name => $ definition ) { $ this -> setDefinition ( $ name , $ definition ) ; } }

Set the definitions.

@param array $definitions An array of definitions.

@api


public function getDefinition($name)
    {
        if (!$this->hasDefinition($name)) {
            throw new \InvalidArgumentException(sprintf('The definition "%s" does not exists.', $name));
        }

        return $this->definitions[$name];
    }

public
function
getDefinition
(
$
name
)
{
if
(
!
$
this
->
hasDefinition
(
$
name
)
)
{
throw
new
\
InvalidArgumentException
(
sprintf
(
'The definition "%s" does not exists.'
,
$
name
)
)
;
}
return
$
this
->
definitions
[
$
name
]
;
}

Returns a definition by name.

@param string $name The definition name.

@return Mandango\Mondator\Definition The definition.

@throws \InvalidArgumentException If the definition does not exists.

@api


public function removeDefinition($name)
    {
        if (!$this->hasDefinition($name)) {
            throw new \InvalidArgumentException(sprintf('The definition "%s" does not exists.', $name));
        }

        unset($this->definitions[$name]);
    }

public
function
removeDefinition
(
$
name
)
{
if
(
!
$
this
->
hasDefinition
(
$
name
)
)
{
throw
new
\
InvalidArgumentException
(
sprintf
(
'The definition "%s" does not exists.'
,
$
name
)
)
;
}
unset
(
$
this
->
definitions
[
$
name
]
)
;
}

Remove a definition

@param string $name The definition name

@throws \InvalidArgumentException If the definition does not exists.

@api


public function setConfigClasses(array $configClasses)
    {
        $this->configClasses = array();
        foreach ($configClasses as $class => $configClass) {
            $this->setConfigClass($class, $configClass);
        }
    }

public function setConfigClasses ( array $ configClasses ) { $ this -> configClasses = array ( ) ; foreach ( $ configClasses as $ class => $ configClass ) { $ this -> setConfigClass ( $ class , $ configClass ) ; } }

Set the config classes.

@param array $configClasses An array of config classes (class as key and config class as value).

@api


public function generateContainers()
    {
        $containers = array();
        $containers['_global'] = new Container();

        // global extensions
        $globalExtensions = $this->getExtensions();

        // configClasses
        $configClasses = new \ArrayObject();
        foreach ($this->getConfigClasses() as $class => $configClass) {
            $configClasses[$class] = new \ArrayObject($configClass);
        }

        // classes extensions
        $classesExtensions = new \ArrayObject();
        $this->generateContainersClassesExtensions($globalExtensions, $classesExtensions, $configClasses);

        // config class process
        foreach ($classesExtensions as $class => $classExtensions) {
            foreach ($classExtensions as $classExtension) {
                $classExtension->configClassProcess($class, $configClasses);
            }
        }

        // pre global process
        foreach ($globalExtensions as $globalExtension) {
            $globalExtension->preGlobalProcess($configClasses, $containers['_global']);
        }

        // class process
        foreach ($classesExtensions as $class => $classExtensions) {
            $containers[$class] = $container = new Container();
            foreach ($classExtensions as $classExtension) {
                $classExtension->classProcess($class, $configClasses, $container);
            }
        }

        // post global process
        foreach ($globalExtensions as $globalExtension) {
            $globalExtension->postGlobalProcess($configClasses, $containers['_global']);
        }

        return $containers;
    }

public
function
generateContainers
(
)
{
$
containers
=
array
(
)
;
$
containers
[
'_global'
]
=
new
Container
(
)
;
// global extensions
$
globalExtensions
=
$
this
->
getExtensions
(
)
;
// configClasses
$
configClasses
=
new
\
ArrayObject
(
)
;
foreach
(
$
this
->
getConfigClasses
(
)
as
$
class
=>
$
configClass
)
{
$
configClasses
[
$
class
]
=
new
\
ArrayObject
(
$
configClass
)
;
}
// classes extensions
$
classesExtensions
=
new
\
ArrayObject
(
)
;
$
this
->
generateContainersClassesExtensions
(
$
globalExtensions
,
$
classesExtensions
,
$
configClasses
)
;
// config class process
foreach
(
$
classesExtensions
as
$
class
=>
$
classExtensions
)
{
foreach
(
$
classExtensions
as
$
classExtension
)
{
$
classExtension
->
configClassProcess
(
$
class
,
$
configClasses
)
;
}
}
// pre global process
foreach
(
$
globalExtensions
as
$
globalExtension
)
{
$
globalExtension
->
preGlobalProcess
(
$
configClasses
,
$
containers
[
'_global'
]
)
;
}
// class process
foreach
(
$
classesExtensions
as
$
class
=>
$
classExtensions
)
{
$
containers
[
$
class
]
=
$
container
=
new
Container
(
)
;
foreach
(
$
classExtensions
as
$
classExtension
)
{
$
classExtension
->
classProcess
(
$
class
,
$
configClasses
,
$
container
)
;
}
}
// post global process
foreach
(
$
globalExtensions
as
$
globalExtension
)
{
$
globalExtension
->
postGlobalProcess
(
$
configClasses
,
$
containers
[
'_global'
]
)
;
}
return
$
containers
;
}

Generate the containers.

@return array The containers.

@api


public function dumpContainers(array $containers)
    {
        // directories
        foreach ($containers as $container) {
            foreach ($container->getDefinitions() as $name => $definition) {
                $output = $definition->getOutput();
                $dir    = $output->getDir();

                if (!file_exists($dir) && false === @mkdir($dir, 0777, true)) {
                    throw new \RuntimeException(sprintf('Unable to create the %s directory (%s).', $name, $dir));
                }

                if (!is_writable($dir)) {
                    throw new \RuntimeException(sprintf('Unable to write in the %s directory (%s).', $name, $dir));
                }
            }
        }

        // output
        foreach ($containers as $container) {
            foreach ($container->getDefinitions() as $name => $definition) {
                $output = $definition->getOutput($name);
                $dir    = $output->getDir();

                $file = $dir.DIRECTORY_SEPARATOR.$definition->getClassName().'.php';

                if (!file_exists($file) || $output->getOverride()) {
                    $dumper  = new Dumper($definition);
                    $content = $dumper->dump();

                    $tmpFile = tempnam(dirname($file), basename($file));
                    if (false === @file_put_contents($tmpFile, $content) || !@rename($tmpFile, $file)) {
                        throw new \RuntimeException(sprintf('Failed to write the file "%s".', $file));
                    }
                    chmod($file, 0644);
                }
            }
        }
    }

Dump containers.

@param array $containers An array of containers.

@api


function it_should_return_inner_value()
    {
        $this->value()->shouldBeBool();
        $this->value()->shouldBeEqualTo($this->init);

        $this->get()->shouldBeBool();
        $this->get()->shouldBeEqualTo($this->init);
    }

function it_should_return_inner_value ( ) { $ this -> value ( ) -> shouldBeBool ( ) ; $ this -> value ( ) -> shouldBeEqualTo ( $ this -> init ) ; $ this -> get ( ) -> shouldBeBool ( ) ; $ this -> get ( ) -> shouldBeEqualTo ( $ this -> init ) ; }


public function setAddress($address)
    {
        $this->address = \is_string($address) ? \explode(',', $address) : $address;

        return $this;
    }

public function setAddress ( $ address ) { $ this -> address = \ is_string ( $ address ) ? \ explode ( ',' , $ address ) : $ address ; return $ this ; }

Set RPC server address.

@param array|string $address One or array of RPC server address for request

@return $this


public function notice($method, array $params = [], array $headers = [])
    {
        $request = new JsonRequest($method, $params);
        $request->headers()->add($headers);

        try {
            $this->execute($request);
        } catch (\Exception $e) {
            // Nothing
        }
    }

public
function
notice
(
$
method
,
array
$
params
=
[
]
,
array
$
headers
=
[
]
)
{
$
request
=
new
JsonRequest
(
$
method
,
$
params
)
;
$
request
->
headers
(
)
->
add
(
$
headers
)
;
try
{
$
this
->
execute
(
$
request
)
;
}
catch
(
\
Exception
$
e
)
{
// Nothing
}
}

Execute one RPC method without response.

@param string $method
@param array  $params
@param array  $headers

Execute one RPC method without response .


public function call($method, array $params = [], array $headers = [])
    {
        $request = new JsonRequest($method, $params, \uniqid(\gethostname().'.', true));
        $request->headers()->add($headers);

        try {
            return $this->execute($request);
        } catch (\Exception $e) {
            return $this->createResponseFromException($e, $request);
        }
    }

public function call ( $ method , array $ params = [ ] , array $ headers = [ ] ) { $ request = new JsonRequest ( $ method , $ params , \ uniqid ( \ gethostname ( ) . '.' , true ) ) ; $ request -> headers ( ) -> add ( $ headers ) ; try { return $ this -> execute ( $ request ) ; } catch ( \ Exception $ e ) { return $ this -> createResponseFromException ( $ e , $ request ) ; } }

Execute one RPC method.

@param string $method
@param array  $params
@param array  $headers

@return null|JsonResponse


protected function createResponseFromException(\Exception $e, JsonRequest $request)
    {
        $response = new JsonResponse();
        $response->setId($request->getId());

        $response->setErrorMessage($e->getMessage());
        $response->setErrorCode($e->getCode());

        return $response;
    }

protected function createResponseFromException ( \ Exception $ e , JsonRequest $ request ) { $ response = new JsonResponse ( ) ; $ response -> setId ( $ request -> getId ( ) ) ; $ response -> setErrorMessage ( $ e -> getMessage ( ) ) ; $ response -> setErrorCode ( $ e -> getCode ( ) ) ; return $ response ; }

Create response from exception and request.

@param \Exception  $e
@param JsonRequest $request

@return JsonResponse

Create response from exception and request .


protected function parserHttp($http)
    {
        $response = [];

        $json = \json_decode($http, true);

        if (JSON_ERROR_NONE !== \json_last_error() || empty($http)) {
            throw new Exceptions\InvalidResponseException('Invalid response from RPC server, must be valid json.');
        }

        /**
         * Create new JsonResponse.
         *
         * @param mixed $json
         *
         * @return JsonResponse
         */
        $createJsonResponse = function ($json) {
            $id = null;
            $result = null;
            $error = [
                'code' => null,
                'message' => null,
                'data' => null,
            ];

            if (
                \is_array($json)
                & \array_key_exists('id', $json)
                & (
                    \array_key_exists('result', $json)
                    || \array_key_exists('error', $json)
                )
            ) {
                $id = $json['id'];
                $result = \array_key_exists('result', $json) ? $json['result'] : null;

                if (\array_key_exists('error', $json)) {
                    $error['code'] = \array_key_exists('code', $json['error']) ? $json['error']['code'] : null;
                    $error['message'] = \array_key_exists('message', $json['error']) ? $json['error']['message'] : null;
                    $error['data'] = \array_key_exists('data', $json['error']) ? $json['error']['data'] : null;
                }

                $response = new JsonResponse();

                $response->setId($id);
                $response->setResult($result);
                $response->setErrorCode($error['code']);
                $response->setErrorMessage($error['message']);
                $response->setErrorData($error['data']);

                return $response;
            }
            throw new Exceptions\InvalidResponseException('Invalid response format from RPC server.');
        };

        if (\array_keys($json) === \range(0, \count($json) - 1)) {
            foreach ($json as $part) {
                $response[] = $createJsonResponse($part);
            }
        } else {
            $response = $createJsonResponse($json);
        }

        return $response;
    }

Parser http response.

@param string $http

@throws Exceptions\InvalidResponseException

@return JsonResponse|JsonResponse[]


public function requestForActionPermission($dontWait = null)
    {
        $sendSuccess = null;

        if (!$this->requestSocket) {
            $this->requestSocket = $this->context->getSocket(\ZMQ::SOCKET_REQ);
            $this->requestSocket->connect($this->getSocketsParams()->getRequestPulsarRsSocketAddress());
        }

        $requestDto = new PreparingRequestDto();

        if ($dontWait) {

            try {

                $this->requestSocket->send(serialize($requestDto));
                $sendSuccess = true;

            } catch (\Exception $e) {

                $this->logger->debug("Possibly work PerformerImitator.");

            }

            $this->becomeTheSubscriberReplyDto = unserialize($this->requestSocket->recv(\ZMQ::MODE_DONTWAIT));

        } else {

            $this->requestSocket->send(serialize($requestDto));

            $this->logger->debug("Performer send preparing request. Wait receive");
            //->recv() block execution until data will received
            $this->becomeTheSubscriberReplyDto = unserialize($this->requestSocket->recv());
            if (!$this->becomeTheSubscriberReplyDto->isAllowToStartSubscription()) {
                throw new PublisherPulsarException(PublisherPulsarExceptionsConstants::SUBSCRIPTION_IS_NOT_ALLOWED);
            }

            $this->logger->debug("Performer got allowing becomeTheSubscriberReply.");

        }

        return $sendSuccess;
    }

Make a request and wait response in blocking mode. After response
start subscription.
@return null

Make a request and wait response in blocking mode . After response start subscription .


public function waitAllowingSubscriptionMessage()
    {
        if (!$this->subscriberSocket) {
            $this->subscriberSocket = $this->context->getSocket(\ZMQ::SOCKET_SUB);
            $this->subscriberSocket->connect($this->getSocketsParams()->getPublisherPulsarSocketAddress());
        }

        $this->subscriberSocket->setSockOpt(\ZMQ::SOCKOPT_SUBSCRIBE, "");
        $this->logger->debug("Performer become subscriber.");

        //use in Pulsar to divide termination of current subscribers and potential subscribers, if early termination occurred
        $this->performerEarlyTerminated->setStandOnSubscription(true);

        $this->pushReadyToGetSubscriptionMsg();

        //->recv() block execution until data will received; all subscribers will continue execution synchronously
        $this->logger->debug("Performer wait subscription msg.");
        $this->publisherToSubscribersDto = unserialize($this->subscriberSocket->recv());
        $this->logger->debug("Performer got subscription msg.");

        if (!$this->publisherToSubscribersDto->isAllowAction()) {
            throw new PublisherPulsarException(PublisherPulsarExceptionsConstants::ACTION_IS_NOT_ALLOWED);
        }

        return null;
    }

Wait subscription message before doing action
@return null


public function pushActionResultInfo(ActionResultingPushDto $resultingPushDto)
    {
        $this->subscriberSocket->setSockOpt(\ZMQ::SOCKOPT_UNSUBSCRIBE, "");

        $this->performerEarlyTerminated->setStandOnSubscription(false);

        $this->logger->debug("Performer was unsubscribed.");

        $this->initOrCheckPushConnection();

        $this->pushSocket->send(serialize($resultingPushDto));

        $this->logger->debug("Performer send actionResulting msg.");

        return null;
    }

public
function
pushActionResultInfo
(
ActionResultingPushDto
$
resultingPushDto
)
{
$
this
->
subscriberSocket
->
setSockOpt
(
\
ZMQ
::
SOCKOPT_UNSUBSCRIBE
,
""
)
;
$
this
->
performerEarlyTerminated
->
setStandOnSubscription
(
false
)
;
$
this
->
logger
->
debug
(
"Performer was unsubscribed."
)
;
$
this
->
initOrCheckPushConnection
(
)
;
$
this
->
pushSocket
->
send
(
serialize
(
$
resultingPushDto
)
)
;
$
this
->
logger
->
debug
(
"Performer send actionResulting msg."
)
;
return
;
}

After action done worker-subscriber stop subscription and by push socket send action's info
@param ActionResultingPushDto $resultingPushDto
@return null

After action done worker - subscriber stop subscription and by push socket send action s info


public function formatLayoutTemplateFiles()
	{
		$list = parent::formatLayoutTemplateFiles();

		$layout = $this->layout ? $this->layout : 'layout';

		$dir = $this->administrationTemplatesDir;

		$list[] = "$dir/@$layout.latte";

		return $list;
	}

public function formatLayoutTemplateFiles ( ) { $ list = parent :: formatLayoutTemplateFiles ( ) ; $ layout = $ this -> layout ? $ this -> layout : 'layout' ; $ dir = $ this -> administrationTemplatesDir ; $ list [ ] = "$dir/@$layout.latte" ; return $ list ; }

Formats layout template file names.
@return array


public function toFile($file, $jsonOptions = 0)
    {
        if (is_dir(pathinfo($file, PATHINFO_DIRNAME)))
        {
            return (bool) file_put_contents($file, $this->toJson($this->getIntegerable($jsonOptions)));
        }

        return false;
    }

public function toFile ( $ file , $ jsonOptions = 0 ) { if ( is_dir ( pathinfo ( $ file , PATHINFO_DIRNAME ) ) ) { return ( bool ) file_put_contents ( $ file , $ this -> toJson ( $ this -> getIntegerable ( $ jsonOptions ) ) ) ; } return false ; }

Write json representation of type value to file
You can specify second argument to call json_encode with params

@param $file
@param int|IntegerContract $jsonOptions
@return bool


public static function dashed($value)
    {
        if (isset(static::$dashedCache[$value]))
        {
            return static::$dashedCache[$value];
        }

        return static::$dashedCache[$value] = StaticStringy::dasherize($value);
    }

public static function dashed ( $ value ) { if ( isset ( static :: $ dashedCache [ $ value ] ) ) { return static :: $ dashedCache [ $ value ] ; } return static :: $ dashedCache [ $ value ] = StaticStringy :: dasherize ( $ value ) ; }

Convert value to dashed case

@param $value

@return string


protected function getSlice($start, $stop, $step)
    {
        $length = $this->length();
        $step = (isset($step)) ? $step : 1;

        if ($step === 0)
        {
            throw new InvalidArgumentException('Slice step cannot be 0');
        }

        if (isset($start))
        {
            $start = $this->adjustBoundary($length, $start, $step);
        }
        else
        {
            $start = ($step > 0) ? 0 : $length - 1;
        }

        if (isset($stop))
        {
            $stop = $this->adjustBoundary($length, $stop, $step);
        }
        else
        {
            $stop = ($step > 0) ? $length : -1;
        }

        // Return an empty string if the set of indices would be empty
        if (($step > 0 && $start >= $stop) || ($step < 0 && $start <= $stop))
        {
            return new static('');
        }

        // Return the substring if step is 1
        if ($step === 1)
        {
            return $this->cut($start, $stop - $start);
        }

        // Otherwise iterate over the slice indices
        $str = '';
        foreach ($this->getIndices($start, $stop, $step) as $index)
        {
            $str .= (isset($this[$index])) ? $this[$index] : '';
        }

        return new static($str);
    }

Returns a new SliceableStringy instance given start, stop and step
arguments for the desired slice. Start, which indicates the starting
index of the slice, defaults to the first character in the string if
step is positive, and the last character if negative. Stop, which
indicates the exclusive boundary of the range, defaults to the length
of the string if step is positive, and before the first character
if negative. Step allows the user to include only every nth character
in the result, with its sign determining the direction in which indices
are sampled. Throws an exception if step is equal to 0.

@param int|null $start Optional start index of the slice
@param int|null $stop  Optional boundary for the slice
@param int|null $step  Optional rate at which to include characters

@return static                   A new instance containing the slice
@throws InvalidArgumentException If step is equal to 0

Returns a new SliceableStringy instance given start stop and step arguments for the desired slice . Start which indicates the starting index of the slice defaults to the first character in the string if step is positive and the last character if negative . Stop which indicates the exclusive boundary of the range defaults to the length of the string if step is positive and before the first character if negative . Step allows the user to include only every nth character in the result with its sign determining the direction in which indices are sampled . Throws an exception if step is equal to 0 .


protected function getIndices($start, $stop, $step)
    {
        $indices = [];

        if ($step > 0)
        {
            for ($i = $start; $i < $stop; $i += $step)
            {
                $indices[] = $i;
            }
        }
        else
        {
            for ($i = $start; $i > $stop; $i += $step)
            {
                $indices[] = $i;
            }
        }

        return $indices;
    }

protected function getIndices ( $ start , $ stop , $ step ) { $ indices = [ ] ; if ( $ step > 0 ) { for ( $ i = $ start ; $ i < $ stop ; $ i += $ step ) { $ indices [ ] = $ i ; } } else { for ( $ i = $ start ; $ i > $ stop ; $ i += $ step ) { $ indices [ ] = $ i ; } } return $ indices ; }

Returns an array of indices to be included in the slice.

@param int $start Start index of the slice
@param int $stop  Boundary for the slice
@param int $step  Rate at which to include characters

@return array An array of indices in the string

Returns an array of indices to be included in the slice .


public function getOption($value)
	{
		if(is_array($value))
		{
			return $this->_getOptionFromArray($value);
		}
		elseif(preg_match($this->shortHandRegex, strtoupper($value)))
		{
			return '-channel ' . $value . ' ';
		}
		else
		{
			$msg = 'Invalid argument $value "' . $value . '", allowed values are ' . implode(', ',
			                                                                             $this->allowedOptions)
			       . ' as array (e.g.: ["Green", "Blue"]) or some of the characters R G B A O C M Y K without whitespaces and unique';

			return $this->_optionValueException($msg);
		}
	}

Returns a prepared option string.

@param array|string $value Option values.

@throws InvalidOptionValueException If the $values argument is invalid.
@return string Prepared option string.


private function _validateValuesArrayArgument(array $values)
	{
		foreach($values as $value)
		{
			if(!in_array($value, $this->allowedOptions))
			{
				$msg = 'Invalid element in $value array: "' . $value . '", allowed values: ' . implode(', ',
				                                                                            $this->allowedOptions);

				$this->_optionValueException($msg);
			}
		}
	}

private
function
_validateValuesArrayArgument
(
array
$
values
)
{
foreach
(
$
values
as
$
value
)
{
if
(
!
in_array
(
$
value
,
$
this
->
allowedOptions
)
)
{
$
msg
=
'Invalid element in $value array: "'
.
$
value
.
'", allowed values: '
.
implode
(
', '
,
$
this
->
allowedOptions
)
;
$
this
->
_optionValueException
(
$
msg
)
;
}
}
}

Validates the values array and throw an exception if it contains invalid elements.

@param array $values Array to be validated.

@throws InvalidOptionValueException When the values array contains invalid elements.

Validates the values array and throw an exception if it contains invalid elements .


protected function _createOption($option, $value)
	{
		if(!class_exists($option))
		{
			throw new InvalidOptionValueException('Option class "' . $option . '" not found.');
		}
		$class = new $option();
		return $this->_validateOptionInterface($class)->_validateOption($class)->getOption($value);
	}

protected
function
_createOption
(
$
option
,
$
value
)
{
if
(
!
class_exists
(
$
option
)
)
{
throw
new
InvalidOptionValueException
(
'Option class "'
.
$
option
.
'" not found.'
)
;
}
$
class
=
new
$
option
(
)
;
return
$
this
->
_validateOptionInterface
(
$
class
)
->
_validateOption
(
$
class
)
->
getOption
(
$
value
)
;
}

Creates an option and return it.

@param string $option Full qualified class name.
@param mixed  $value  Option value.

@return string
@throws InvalidOptionValueException


protected function declareReplyToReplyStackMessaging()
    {
        $this->replyToReplyStack->on(EventsConstants::MESSAGE, function ($requestDto) {

            if ($this->getRequestForStartFromReplyStack === false) {

                $this->getRequestForStartFromReplyStack = true;

                $startReplyToReplyStack = new PulsarToReplyStackReplyDto();
                $startReplyToReplyStack->setSubscribersNumber($this->shouldBeSubscribersNumber);
                $startReplyToReplyStack->setDtoToTransfer(new BecomeTheSubscriberReplyDto());

                $this->replyToReplyStack->send(serialize($startReplyToReplyStack));

            } else {

                if ($this->replyStackReturnResult === false) {

                    $this->replyStackReturnResult = true;

                    /**
                     * @var ReplyStackToPulsarReturnResultRequestDto $requestDto
                     */
                    $requestDto = unserialize($requestDto);

                    if (!($requestDto instanceof ReplyStackToPulsarReturnResultRequestDto)) {
                        throw new PublisherPulsarException("Unexpected result from ReplyStack.");
                    }

                    $this->considerMeAsSubscriber = $requestDto->getConsiderMeAsSubscriber();

                    $this->logger->debug("PULSAR RECEIVE REPLY STACK RESULT INFO.");

                } else {
                    throw new PublisherPulsarException("Get replyStack result (info about subscribers) twice.");
                }
            }
        });

        $this->replyToReplyStack->on(EventsConstants::ERROR, function ($error) {
            $this->logger->debug(LoggingExceptions::getExceptionString($error));
        });

        return null;
    }

Coordinating work with ReplyStack as sub-process
@return null

Coordinating work with ReplyStack as sub - process


public function get($property, $default = null)
    {
        $property = $this->getStringable($property);

        if ($this->has($property))
        {
            return $this->retrieveValue($property);
        }

        return $default;
    }

public function get ( $ property , $ default = null ) { $ property = $ this -> getStringable ( $ property ) ; if ( $ this -> has ( $ property ) ) { return $ this -> retrieveValue ( $ property ) ; } return $ default ; }

Getter for value. Supports dot notation.
Can retrieve value from objects, arrays, Containers, instances of ArrayableContract and ObjectContract.

@param string|StringContract $property
@param mixed $default
@return mixed|null

Getter for value . Supports dot notation . Can retrieve value from objects arrays Containers instances of ArrayableContract and ObjectContract .


public function getMatchers()
    {
        return array(

            'beInRange' => function($key, $match)
            {
                return in_array($key, $match);
            },

            'beArrayAndExactLengthOf' => function($array, $count)
            {
                return is_array($array) && $count === count($array);
            }

        );
    }

public function getMatchers ( ) { return array ( 'beInRange' => function ( $ key , $ match ) { return in_array ( $ key , $ match ) ; } , 'beArrayAndExactLengthOf' => function ( $ array , $ count ) { return is_array ( $ array ) && $ count === count ( $ array ) ; } ) ; }


public function compareImages($expectedImage, $compareImage, $resultImageName, $resultImageDirectory)
	{
		$time = date('Ymd-His');

		$diffResult    = $this->createDiffGifOnDifferences($expectedImage, $compareImage,
		                                                   $resultImageName . 'Diff' . $time, $resultImageDirectory);
		$compareResult = $this->createComparisonImageOnDifferences($expectedImage, $compareImage,
		                                                           $resultImageName . 'Compared' . $time,
		                                                           $resultImageDirectory);
		if($diffResult || $compareResult)
		{
			$gif = $resultImageName . 'Diff' . $time . '.gif';
			$png = $resultImageName . 'Compared' . $time . '.gif';

			return [$gif, $png];
		}

		return [];
	}

public function compareImages ( $ expectedImage , $ compareImage , $ resultImageName , $ resultImageDirectory ) { $ time = date ( 'Ymd-His' ) ; $ diffResult = $ this -> createDiffGifOnDifferences ( $ expectedImage , $ compareImage , $ resultImageName . 'Diff' . $ time , $ resultImageDirectory ) ; $ compareResult = $ this -> createComparisonImageOnDifferences ( $ expectedImage , $ compareImage , $ resultImageName . 'Compared' . $ time , $ resultImageDirectory ) ; if ( $ diffResult || $ compareResult ) { $ gif = $ resultImageName . 'Diff' . $ time . '.gif' ; $ png = $ resultImageName . 'Compared' . $ time . '.gif' ; return [ $ gif , $ png ] ; } return [ ] ; }

Compares two images and create a diff gif images and a compare image.

@param string $expectedImage        Path to expected image.
@param string $compareImage         Path to compare image.
@param string $resultImageName      Name of result gif, if the images not looking equal.
@param string $resultImageDirectory (Optional) Path to result image directory. If not set, the cwd is used.

@return array Empty if both images looking equal, otherwise an array with the created image names (without the
directory)

Compares two images and create a diff gif images and a compare image .


public function createDiffGifOnDifferences($expectedImage,
	                                           $compareImage,
	                                           $resultImageName,
	                                           $resultImageDirectory = '.')
	{
		if(!$this->compare->same($expectedImage, $compareImage))
		{
			$this->convert->createGifCommand([$expectedImage, $compareImage], $resultImageName, $resultImageDirectory);

			return true;
		}

		return false;
	}

public function createDiffGifOnDifferences ( $ expectedImage , $ compareImage , $ resultImageName , $ resultImageDirectory = '.' ) { if ( ! $ this -> compare -> same ( $ expectedImage , $ compareImage ) ) { $ this -> convert -> createGifCommand ( [ $ expectedImage , $ compareImage ] , $ resultImageName , $ resultImageDirectory ) ; return true ; } return false ; }

Compares two images. If they not looking equal, a gif image of both,
the expected and result image will be created.

@param string $expectedImage        Path to expected image.
@param string $compareImage         Path to compare image.
@param string $resultImageName      Name of result gif, if the images not looking equal.
@param string $resultImageDirectory (Optional) Path to result image directory. If not set, the cwd is used.

@return bool True when a difference gif images was created, false otherwise.

Compares two images . If they not looking equal a gif image of both the expected and result image will be created .


public function createComparisonImageOnDifferences($actualImage,
	                                                   $compareImage,
	                                                   $resultImageName,
	                                                   $resultImageDirectory = '.')
	{
		if(!$this->compare->same($compareImage, $actualImage))
		{
			$this->compare->createComparisonImage($compareImage, $actualImage, $resultImageName, $resultImageDirectory);

			return true;
		}

		return false;
	}

public function createComparisonImageOnDifferences ( $ actualImage , $ compareImage , $ resultImageName , $ resultImageDirectory = '.' ) { if ( ! $ this -> compare -> same ( $ compareImage , $ actualImage ) ) { $ this -> compare -> createComparisonImage ( $ compareImage , $ actualImage , $ resultImageName , $ resultImageDirectory ) ; return true ; } return false ; }

Creates a comparison image when the images looking equal.

@param string $actualImage          Path to the actual image.
@param string $compareImage         Path to expected image.
@param string $resultImageName      Name of result image.
@param string $resultImageDirectory Location of result image.

@return bool True when a compare image was created, false otherwise.

Creates a comparison image when the images looking equal .


public function same($expectedImage, $compareImage)
	{
		$metric = $this->_createOption(Metric::class, 'AE');
		$cmd    = 'compare ' . $metric . $expectedImage . ' ' . $compareImage . $this->redirectDefaultErrorResponse;

		return (int)`$cmd` === 0;
	}

	/**
	 * Creates a comparison image.
	 *
	 * @param string $compareImage    Expected image.
	 * @param string $actualImage     Current image to compare.
	 * @param string $resultImageName Name of the resulting comparison image.
	 * @param string $resultImageDir  (Optional) Path to directory of result images.
	 *
	 * @return mixed
	 * @throws \ImageMagick\Exceptions\InvalidOptionValueException
	 */
	public function createComparisonImage($compareImage,
	                                      $actualImage,
	                                      $resultImageName,
	                                      $resultImageDir = '.')
	{
		$compose = $this->_createOption(Compose::class, 'src');

		$resultDirectory = rtrim($resultImageDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
		$cmd             = 'compare ' . $compareImage . ' ' . $actualImage . ' ' . $compose . $resultDirectory
		                   . $resultImageName . '.png';

		return `$cmd`;
	}

Compares two images.
Returns true if they looking equal and false otherwise.

@param string $expectedImage Path to the expected image.
@param string $compareImage  Path to compare image.

@return bool
@throws \ImageMagick\Exceptions\InvalidOptionValueException

Compares two images . Returns true if they looking equal and false otherwise .


public function post($route, $callback)
    {
        $this->route(new Route($route, $callback), self::METHOD_POST);
    }

public function post ( $ route , $ callback ) { $ this -> route ( new Route ( $ route , $ callback ) , self :: METHOD_POST ) ; }

Add HTTP POST route

@see    Router::route()
@param  string                $route
@param  array|\Closure|string $callback


public function route(Route $route, $http_method = self::METHOD_GET)
    {
        // Is this a valid HTTP method?
        if (!in_array($http_method, array(
            self::METHOD_HEAD,
            self::METHOD_GET,
            self::METHOD_POST,
            self::METHOD_PUT,
            self::METHOD_PATCH,
            self::METHOD_DELETE
        ))) {
            throw new \InvalidArgumentException("The method {$http_method} is invalid");
        }

        // Does this URL already exist in the routing table?
        if (isset($this->routes[$http_method][$route->pattern()])) {
            // Trigger a new error and exception if errors are on
            throw new \LogicException("The URI {$route->url()} already exists in the routing table");
        }

        // Add the route to the routing table
        $this->routes[$http_method][$route->pattern()] = $route;
    }

Adds a new URL routing rule to the routing table, after converting any of
our special tokens into proper regular expressions.

@param  Route  $route
@param  string $http_method
@throws \InvalidArgumentException If an invalid HTTP method is specified
@throws \LogicException           If the route already exists in the routing table

Adds a new URL routing rule to the routing table after converting any of our special tokens into proper regular expressions .


public function match($url, $http_method = self::METHOD_GET)
    {
        // Make sure there is a trailing slash
        $url = rtrim($url, '/') . '/';

        foreach ($this->routes[$http_method] as $route) {
            if (preg_match($route->pattern(), $url)) {
                return $route;
            }
        }
        return null;
    }

public
function
match
(
$
url
,
$
http_method
=
self
::
METHOD_GET
)
{
// Make sure there is a trailing slash
$
url
=
rtrim
(
$
url
,
'/'
)
.
'/'
;
foreach
(
$
this
->
routes
[
$
http_method
]
as
$
route
)
{
if
(
preg_match
(
$
route
->
pattern
(
)
,
$
url
)
)
{
return
$
route
;
}
}
return
;
}

Returns a Route object if matching URL is found

@param  string $url
@param  string $http_method
@return Route|null


public function run()
    {
        // If no routes have been added, then throw an exception
        try {
            if (empty($this->routes)) {
                throw new \RuntimeException('No routes exist in the routing table. Add some');
            }
        }
        catch (\Exception $e) {
            $this->error($e);
            return FALSE;
        }

        // Try and get a matching route for the current URL
        $route = $this->match(
            $this->request->getPathInfo(),
            $this->request->getMethod()
        );

        // Call not found handler if no match was found
        if ($route === null) {
            $this->not_found();
            return FALSE;
        }

        // Set current route
        $this->current_route = $route;

        // Get parameters from request
        $params = $this->parse_parameters($route);
        // Try to execute callback for route, if it fails, catch the exception and generate a HTTP 500 error
        try {
            $this->current_http_status = \Symfony\Component\HttpFoundation\Response::HTTP_OK;

            // Set response content
            $this->response->setContent($route->execute($params));

            // Send response
            $this->response->send();
            return TRUE;
        }
        catch (\Exception $e) {
            $this->error($e);
            return FALSE;
        }
    }

Runs the router matching engine and then calls the matching route's
callback. otherwise execute the not found handler

@return bool
@throws \RuntimeException If no routes exist in the routing table

Runs the router matching engine and then calls the matching route s callback . otherwise execute the not found handler


public function redirect($url)
    {
        // If no URL is given, throw exception
        try {
            if (empty($url)) {
                throw new \InvalidArgumentException('No URL given');
            }
        }
        catch (\Exception $e) {
            $this->error($e);
            return FALSE;
        }

        // Set redirect status codes and location
        $this->current_http_status = \Symfony\Component\HttpFoundation\Response::HTTP_FOUND;
        $this->response->setStatusCode($this->current_http_status);
        $this->response->headers->set('Location', $url);
        return TRUE;
    }

Redirects to another URL

@param  string $url
@return bool


protected function parse_parameters(Route $route)
    {
        // Get all parameter matches from URL for this route
        $request_url = rtrim($this->request->getPathInfo(), '/') . '/';
        preg_match($route->pattern(), "{$request_url}", $matches);

        $params = array();

        // Retrieve any matches
        foreach ($matches as $key => $value) {
            if (is_string($key)) {
                $params[] = $value;
            }
        }

        return $params;
    }

Parses parameters from URI as per the given route's pattern

@param  Route  $route
@return array

Parses parameters from URI as per the given route s pattern


protected function date($file)
    {
        $file_contents = $this->sonic->app['filesystem']->parse($file['path']);
        if (isset($file_contents['meta']['date']) === FALSE) {
            return NULL;
        }
        return new \DateTime($file_contents['meta']['date']);
    }

protected function date ( $ file ) { $ file_contents = $ this -> sonic -> app [ 'filesystem' ] -> parse ( $ file [ 'path' ] ) ; if ( isset ( $ file_contents [ 'meta' ] [ 'date' ] ) === FALSE ) { return NULL ; } return new \ DateTime ( $ file_contents [ 'meta' ] [ 'date' ] ) ; }

Gets a date from a file

@param  string $file
@return \DateTime|NULL


public function handleSaveImage()
	{
		if ($this->mainManager instanceof MagicManager
			&& $this->mainManager->isGallery()
		) {
			$folder = $this->mainManager->getGalleryFolder();
		} else {
			$this->error();
		}
		if ($folder == '') {
			$folder = 'misc';
		}

		$file = $this->httpRequest->getFile('Filedata');

		if ($file && $file->isOk() && $this->detailObject) {

			// Save ...
			$year = date('Y');
			$month = date('m');
			$namespace = "{$folder}/{$year}/{$month}";

			$this->imageStorage->setNamespace($namespace);
			$image = $this->imageStorage->save($file->getContents(), $file->getName());

			$filename = pathinfo($image->getFile(), PATHINFO_BASENAME);
			$size = $image->getSize();

			// Prepare thumbnail
			$this->imgPipe->setNamespace($namespace);
			$this->imgPipe->request($filename, '100x100', 'exact');

			// Save to database
			$this->mainManager->addGalleryImage($filename, $namespace, $size->getWidth(), $size->getHeight(),
				$file->getContentType(), $this->detailObject->id);

			$response = [
				'status' => '1',
				'height' => $size->getHeight(),
				'width' => $size->getWidth(),
				'mime' => $file->getContentType(),
			];

		} else {
			$response = [
				'status' => '0',
				'error' => 'Error while uploading file',
				'code' => 500,
			];
		}

		$this->sendJson($response);
	}

public
function
handleSaveImage
(
)
{
if
(
$
this
->
mainManager
instanceof
MagicManager
&&
$
this
->
mainManager
->
isGallery
(
)
)
{
$
folder
=
$
this
->
mainManager
->
getGalleryFolder
(
)
;
}
else
{
$
this
->
error
(
)
;
}
if
(
$
folder
==
''
)
{
$
folder
=
'misc'
;
}
$
file
=
$
this
->
httpRequest
->
getFile
(
'Filedata'
)
;
if
(
$
file
&&
$
file
->
isOk
(
)
&&
$
this
->
detailObject
)
{
// Save ...
$
year
=
date
(
'Y'
)
;
$
month
=
date
(
'm'
)
;
$
namespace
=
"{$folder}/{$year}/{$month}"
;
$
this
->
imageStorage
->
setNamespace
(
$
namespace
)
;
$
image
=
$
this
->
imageStorage
->
save
(
$
file
->
getContents
(
)
,
$
file
->
getName
(
)
)
;
$
filename
=
pathinfo
(
$
image
->
getFile
(
)
,
PATHINFO_BASENAME
)
;
$
size
=
$
image
->
getSize
(
)
;
// Prepare thumbnail
$
this
->
imgPipe
->
setNamespace
(
$
namespace
)
;
$
this
->
imgPipe
->
request
(
$
filename
,
'100x100'
,
'exact'
)
;
// Save to database
$
this
->
mainManager
->
addGalleryImage
(
$
filename
,
$
namespace
,
$
size
->
getWidth
(
)
,
$
size
->
getHeight
(
)
,
$
file
->
getContentType
(
)
,
$
this
->
detailObject
->
id
)
;
$
response
=
[
'status'
=>
'1'
,
'height'
=>
$
size
->
getHeight
(
)
,
'width'
=>
$
size
->
getWidth
(
)
,
'mime'
=>
$
file
->
getContentType
(
)
,
]
;
}
else
{
$
response
=
[
'status'
=>
'0'
,
'error'
=>
'Error while uploading file'
,
'code'
=>
500
,
]
;
}
$
this
->
sendJson
(
$
response
)
;
}

it's not only handleGallerySaveImage now. We use it for save texy images too

it s not only handleGallerySaveImage now . We use it for save texy images too


public function get($strPath, array $arrOptions = [])
    {
        $request = wp_remote_get($this->build_uri($strPath), array_merge(
            self::DEFAULT_OPTIONS,
            $arrOptions, [
                'headers' => $this->arrHeaders
            ])
        );

        return new HttpResponse($request);
    }

public function get ( $ strPath , array $ arrOptions = [ ] ) { $ request = wp_remote_get ( $ this -> build_uri ( $ strPath ) , array_merge ( self :: DEFAULT_OPTIONS , $ arrOptions , [ 'headers' => $ this -> arrHeaders ] ) ) ; return new HttpResponse ( $ request ) ; }

Get http request

@param string $strPath
@param array $arrOptions
@return HttpResponse


public function post($strPath, array $arrOptions = [])
    {
        $request = wp_remote_post($this->build_uri($strPath), array_merge(
            self::DEFAULT_OPTIONS,
            $arrOptions, [
                'headers' => $this->arrHeaders
            ])
        );

        return new HttpResponse($request);
    }

public function post ( $ strPath , array $ arrOptions = [ ] ) { $ request = wp_remote_post ( $ this -> build_uri ( $ strPath ) , array_merge ( self :: DEFAULT_OPTIONS , $ arrOptions , [ 'headers' => $ this -> arrHeaders ] ) ) ; return new HttpResponse ( $ request ) ; }

Post http request

@param string $strPath
@param array $arrOptions
@return HttpResponse


public function set_auth()
    {
        $date = date("Y-m-d\TH:i:s.000O");
        $this->arrHeaders['X-cXense-Authentication'] = sprintf(
            'username=%s date=%s hmac-sha256-hex=%s',
            WpCxense::instance()->settings->getApiUser(),
            $date,
            hash_hmac("sha256", $date, WpCxense::instance()->settings->getApiKey())
        );

        return $this;
    }


public function config($option)
    {
        return isset($this->app['settings'][$option]) === TRUE
            ? $this->app['settings'][$option]
            : NULL;
    }

public function config ( $ option ) { return isset ( $ this -> app [ 'settings' ] [ $ option ] ) === TRUE ? $ this -> app [ 'settings' ] [ $ option ] : NULL ; }

Returns Sonic configuration option

@return array