public function getAction()
    {
        if( is_string($this->action) &&
            $this->namespace ){
            return trim($this->namespace, '\\') . '\\' . $this->action;
        }

        return $this->action;
    }

public function getAction ( ) { if ( is_string ( $ this -> action ) && $ this -> namespace ) { return trim ( $ this -> namespace , '\\' ) . '\\' . $ this -> action ; } return $ this -> action ; }

Get route action.

@return string|callable


public function getPathParams(string $path): array
    {
        $pathParams = [];

        // Build out the regex
        $pattern = implode("\/", $this->getPatternParts());

        if( preg_match("/^{$pattern}$/", $path, $parts) ){

            // Grab all but the first match, because that will always be the full string.
            foreach( array_slice($parts, 1, count($parts) - 1) as $i => $param ) {
                $pathParams[$this->namedPathParameters[$i]] = $param;
            }

        }

        return $pathParams;
    }

Extract the path parameters for the given URI.

Makes a key => value pair of path part names and their value.

Eg.

The route "books/{id}" with an actual URI of "books/1234"
will return:

[
"id" => "1234",
]

These named path params are used during Dependency Injection resolution
in the Kernel to pass off to the matched method parameter.

@param string $path
@return array<string, string>

Extract the path parameters for the given URI .


public function matchScheme($scheme): bool
    {
        if( empty($this->schemes) ){
            return true;
        }

        return array_search(strtolower($scheme), array_map('strtolower', $this->schemes)) !== false;
    }

public function matchScheme ( $ scheme ) : bool { if ( empty ( $ this -> schemes ) ) { return true ; } return array_search ( strtolower ( $ scheme ) , array_map ( 'strtolower' , $ this -> schemes ) ) !== false ; }

Does the given scheme match this route's scheme?

@param string $scheme
@return bool

Does the given scheme match this route s scheme?


public function matchHostname(string $hostnames): bool
    {
        if( empty($this->hostnames) ){
            return true;
        }

        return array_search(strtolower($hostnames), array_map('strtolower', $this->hostnames)) !== false;
    }

public function matchHostname ( string $ hostnames ) : bool { if ( empty ( $ this -> hostnames ) ) { return true ; } return array_search ( strtolower ( $ hostnames ) , array_map ( 'strtolower' , $ this -> hostnames ) ) !== false ; }

Does the given hostname match the route's hostname?

@param string $hostnames
@return bool

Does the given hostname match the route s hostname?


public function matchUri(string $uri): bool
    {
        $pattern = implode("\/", $this->patternParts);
        return preg_match("/^{$pattern}$/i", $this->stripLeadingAndTrailingSlash($uri)) != false;
    }

public function matchUri ( string $ uri ) : bool { $ pattern = implode ( "\/" , $ this -> patternParts ) ; return preg_match ( "/^{$pattern}$/i" , $ this -> stripLeadingAndTrailingSlash ( $ uri ) ) != false ; }

Does the given URI match the route's URI?

@param string $uri
@return bool

Does the given URI match the route s URI?


public function fetchTree($rootSearchRule, $depth, $globalSearchRule = "") {
        $this->depth = $depth;
        $this->globalSearchRule = $globalSearchRule;

        // query on given search rule
        $searchRule = "(" . $rootSearchRule . ")";
        if ($globalSearchRule != "")
            $searchRule .= " AND (" . $globalSearchRule . ")";
        $recordList = $this->directFetch($searchRule);
        if (!$recordList) {
            $this->rootNodes = array();
            return;
        }
        foreach ($recordList as $rec) {
            $this->rootNodes[] = new NodeRecord($rec);
        }
        if ($this->depth <= 1)
            return $this->rootNodes;
        if (is_array($this->rootNodes)) {
            foreach ($this->rootNodes as $node) {
                $this->_getChildrenNodes($node, 1);
            }
        }
        return $this->rootNodes;
    }

public
function
fetchTree
(
$
rootSearchRule
,
$
depth
,
$
globalSearchRule
=
""
)
{
$
this
->
depth
=
$
depth
;
$
this
->
globalSearchRule
=
$
globalSearchRule
;
// query on given search rule
$
searchRule
=
"("
.
$
rootSearchRule
.
")"
;
if
(
$
globalSearchRule
!=
""
)
$
searchRule
.=
" AND ("
.
$
globalSearchRule
.
")"
;
$
recordList
=
$
this
->
directFetch
(
$
searchRule
)
;
if
(
!
$
recordList
)
{
$
this
->
rootNodes
=
array
(
)
;
return
;
}
foreach
(
$
recordList
as
$
rec
)
{
$
this
->
rootNodes
[
]
=
new
NodeRecord
(
$
rec
)
;
}
if
(
$
this
->
depth
<=
1
)
return
$
this
->
rootNodes
;
if
(
is_array
(
$
this
->
rootNodes
)
)
{
foreach
(
$
this
->
rootNodes
as
$
node
)
{
$
this
->
_getChildrenNodes
(
$
node
,
1
)
;
}
}
return
$
this
->
rootNodes
;
}

Fetch records in tree structure

@return <type>


public function fetchNodePath($nodeSearchRule, &$pathArray) {
        $recordList = $this->directFetch($nodeSearchRule);
        if (count($recordList) >= 1) {

            if ($recordList[0]['PId'] != '0') {
                $searchRule = "[Id]='" . $recordList[0]['PId'] . "'";
                $this->fetchNodePath($searchRule, $pathArray);
            }
            $nodes = new \NodeRecord($recordList[0]);
            array_push($pathArray, $nodes);
            return $pathArray;
        }
    }

public function fetchNodePath ( $ nodeSearchRule , & $ pathArray ) { $ recordList = $ this -> directFetch ( $ nodeSearchRule ) ; if ( count ( $ recordList ) >= 1 ) { if ( $ recordList [ 0 ] [ 'PId' ] != '0' ) { $ searchRule = "[Id]='" . $ recordList [ 0 ] [ 'PId' ] . "'" ; $ this -> fetchNodePath ( $ searchRule , $ pathArray ) ; } $ nodes = new \ NodeRecord ( $ recordList [ 0 ] ) ; array_push ( $ pathArray , $ nodes ) ; return $ pathArray ; } }

Fetch node path

@param string $nodeSearchRule
@param array $pathArray
@return <type>


private function _getChildrenNodes(&$node, $depth) {
        $pid = $node->recordId;

        $searchRule = "[PId]='$pid'";
        if ($this->globalSearchRule != "")
            $searchRule .= " AND " . $this->globalSearchRule;
        $recordList = $this->directFetch($searchRule);

        foreach ($recordList as $rec) {
            $node->childNodes[] = new NodeRecord($rec);
        }

        // reach leave node
        if ($node->childNodes == null) {
            return;
        }

        $depth++;
        // reach given depth
        if ($depth >= $this->depth) {
            return;
        } else {
            foreach ($node->childNodes as $node_c) {
                $this->_getChildrenNodes($node_c, $depth);
            }
        }
    }

private
function
_getChildrenNodes
(
&
$
node
,
$
depth
)
{
$
pid
=
$
node
->
recordId
;
$
searchRule
=
"[PId]='$pid'"
;
if
(
$
this
->
globalSearchRule
!=
""
)
$
searchRule
.=
" AND "
.
$
this
->
globalSearchRule
;
$
recordList
=
$
this
->
directFetch
(
$
searchRule
)
;
foreach
(
$
recordList
as
$
rec
)
{
$
node
->
childNodes
[
]
=
new
NodeRecord
(
$
rec
)
;
}
// reach leave node
if
(
$
node
->
childNodes
==
)
{
return
;
}
$
depth
++
;
// reach given depth
if
(
$
depth
>=
$
this
->
depth
)
{
return
;
}
else
{
foreach
(
$
node
->
childNodes
as
$
node_c
)
{
$
this
->
_getChildrenNodes
(
$
node_c
,
$
depth
)
;
}
}
}

List all children records of a given record

@return void


public function getSettings($groups = null, $flag = null)
    {
        $settings = array();

        foreach ($this->results as $result) {
            if (IResult::SUCCESS === $result->getStatus()) {
                $settings = array_merge($settings, $result->getSettings($groups, $flag));
            }
        }

        return $settings;
    }

public function getSettings ( $ groups = null , $ flag = null ) { $ settings = array ( ) ; foreach ( $ this -> results as $ result ) { if ( IResult :: SUCCESS === $ result -> getStatus ( ) ) { $ settings = array_merge ( $ settings , $ result -> getSettings ( $ groups , $ flag ) ) ; } } return $ settings ; }

Returns an array of ISetting instances that match the given criterias
from the successful results of this report.

@param mixed $groups string or array of group names settings should match, the default null matches always
@param integer $flag type of settings to get

@return array of ISetting instances

Returns an array of ISetting instances that match the given criterias from the successful results of this report .


protected function getLink()
    {
        if ($this->link == null)
            return null;
        $formobj = $this->getFormObj();
        return Expression::evaluateExpression($this->link, $formobj);
    }

protected function getLink ( ) { if ( $ this -> link == null ) return null ; $ formobj = $ this -> getFormObj ( ) ; return Expression :: evaluateExpression ( $ this -> link , $ formobj ) ; }


protected function getText()
    {
        if ($this->text == null)
            return null;
        $formObj = $this->getFormObj();
        return Expression::evaluateExpression($this->text, $formObj);
    }

protected function getText ( ) { if ( $ this -> text == null ) return null ; $ formObj = $ this -> getFormObj ( ) ; return Expression :: evaluateExpression ( $ this -> text , $ formObj ) ; }


protected function getNewRecord()
    {
        if ($this->getDataObj()) {
            $recArr = $this->getDataObj()->newRecord();
        }
        if (!$recArr)
            return null;
        // load default values if new record value is empty
        $defaultRecArr = array();
        foreach ($this->dataPanel as $element) {
            if ($element->fieldName) {
                $defaultRecArr[$element->fieldName] = $element->getDefaultValue();
            }
        }
        foreach ($recArr as $field => $val) {
            if ($val == "" && $defaultRecArr[$field] != "") {
                $recArr[$field] = $defaultRecArr[$field];
            }
        }
        return $recArr;
    }


public function setSecret($secret, $format = self::FORMAT_RAW)
    {
        if ($format == static::FORMAT_HEX) {
            $secret = hex2bin($secret);
        } elseif ($format == static::FORMAT_BASE32) {
            $secret = $this->base32decode($secret);
        }

        $this->secret = $secret;
    }

public function setSecret ( $ secret , $ format = self :: FORMAT_RAW ) { if ( $ format == static :: FORMAT_HEX ) { $ secret = hex2bin ( $ secret ) ; } elseif ( $ format == static :: FORMAT_BASE32 ) { $ secret = $ this -> base32decode ( $ secret ) ; } $ this -> secret = $ secret ; }

Sets a secret token.

@param string $secret The secret token in format specified in the second parameter
@param [type] $format (optional) The format of the secret token - defaults to raw format


private static function getBinary(float $number): int
	{
		$num = 2;
		if ($number < $num) {
			return 0;
		}
		$result = $num;
		while (true) {
			$num *= 2;
			if ($number < $num) {
				return $result;
			}
			$result = $num;
		}
		return 0;
	}

private static function getBinary ( float $ number ) : int { $ num = 2 ; if ( $ number < $ num ) { return 0 ; } $ result = $ num ; while ( true ) { $ num *= 2 ; if ( $ number < $ num ) { return $ result ; } $ result = $ num ; } return 0 ; }

Vrati cislo v binarni velikosti
@param float|int $number
@return int


public static function getNumber(float $number, int $decimal = 2): string
	{
		if (floor($number) == $number) {
			$decimal = 0;
		}

		switch (self::$locale) {
			default:
			case 'cs':
			case 'sk':
			case 'de':
			case 'pl':
				return number_format($number, $decimal, ',', ' ');
			case 'en':
				return number_format($number, $decimal);
		}
	}

public
static
function
getNumber
(
float
$
number
,
int
$
decimal
=
2
)
:
string
{
if
(
floor
(
$
number
)
==
$
number
)
{
$
decimal
=
0
;
}
switch
(
self
::
$
locale
)
{
default
:
case
'cs'
:
case
'sk'
:
case
'de'
:
case
'pl'
:
return
number_format
(
$
number
,
$
decimal
,
','
,
' '
)
;
case
'en'
:
return
number_format
(
$
number
,
$
decimal
)
;
}
}

Vrati zformatovane cislo
@param float $number
@param int $decimal
@return string


public function addTableColumn($join, $column, $alias=null)
    {
        $tcol = $this->getTableColumn($join, $column);
        if ($alias) $tcol .= " AS ".$alias;
        if (!$this->_tableColumns)
            $this->_tableColumns = $tcol;
        else
            $this->_tableColumns .= ", ".$tcol;
    }

public
function
addTableColumn
(
$
join
,
$
column
,
$
alias
=
)
{
$
tcol
=
$
this
->
getTableColumn
(
$
join
,
$
column
)
;
if
(
$
alias
)
$
tcol
.=
" AS "
.
$
alias
;
if
(
!
$
this
->
_tableColumns
)
$
this
->
_tableColumns
=
$
tcol
;
else
$
this
->
_tableColumns
.=
", "
.
$
tcol
;
}

Add a join table and cloumn in the sql statement

@param string $join table join name
@param string $column column name
@return void


public function addSqlExpression($sqlExpr, $alias=null)
    {
        if ($alias)
            $sqlExpr .= ' AS '.$alias;
        if (!$this->_tableColumns)
            $this->_tableColumns = $sqlExpr;
        else
            $this->_tableColumns .= ", ".$sqlExpr;
    }

public
function
addSqlExpression
(
$
sqlExpr
,
$
alias
=
)
{
if
(
$
alias
)
$
sqlExpr
.=
' AS '
.
$
alias
;
if
(
!
$
this
->
_tableColumns
)
$
this
->
_tableColumns
=
$
sqlExpr
;
else
$
this
->
_tableColumns
.=
", "
.
$
sqlExpr
;
}

Add SQL expression in the sql statement
sqlExpr has format of "...join1.column1, ... join2.column2...". Replace join with alias

@param string $sqlExpr sql expression
@param string $alias sql alias
@return void

Add SQL expression in the sql statement sqlExpr has format of ... join1 . column1 ... join2 . column2 ... . Replace join with alias


public function resetSQL()
    {
        $this->_sqlWhere = null;
        $this->_orderBy = null;
        $this->_otherSQL = null;
    }

public function resetSQL ( ) { $ this -> _sqlWhere = null ; $ this -> _orderBy = null ; $ this -> _otherSQL = null ; }


public function addOrderBy($orderBy)
    {
        if ($orderBy == null)
            return;
        if ($this->_orderBy == null)
        {
            $this->_orderBy = $orderBy;
        }
        elseif (strpos($this->_orderBy, $orderBy) === false)
        {
            $this->_orderBy .= " AND " . $orderBy;
        }
    }

public
function
addOrderBy
(
$
orderBy
)
{
if
(
$
orderBy
==
)
return
;
if
(
$
this
->
_orderBy
==
)
{
$
this
->
_orderBy
=
$
orderBy
;
}
elseif
(
strpos
(
$
this
->
_orderBy
,
$
orderBy
)
===
false
)
{
$
this
->
_orderBy
.=
" AND "
.
$
orderBy
;
}
}

Add order by clause

@param string $orderBy SQL ORDER BY clause
@return void


public function addOtherSQL($otherSQL)
    {
        if ($otherSQL == null)
            return;
        if ($this->_otherSQL == null)
        {
            $this->_otherSQL = $otherSQL;
        }
        elseif (strpos($this->_otherSQL, $otherSQL) === false)
        {
            $this->_otherSQL .= " AND " . $otherSQL;
        }
    }

public
function
addOtherSQL
(
$
otherSQL
)
{
if
(
$
otherSQL
==
)
return
;
if
(
$
this
->
_otherSQL
==
)
{
$
this
->
_otherSQL
=
$
otherSQL
;
}
elseif
(
strpos
(
$
this
->
_otherSQL
,
$
otherSQL
)
===
false
)
{
$
this
->
_otherSQL
.=
" AND "
.
$
otherSQL
;
}
}

Add other SQL clause

@param string $otherSQL additional SQL statment
@return void


public function addAssociation($assoc)
    {
        $where = "";
        if ($assoc["Relationship"] == "1-M" || $assoc["Relationship"] == "M-1" || $assoc["Relationship"] == "1-1")
        {
            // assc table should same as maintable
            if ($assoc["Table"] != $this->_mainTable) return;
            // add table to join table
            $mytable_col = $this->getTableColumn(null, $assoc["Column"]);
            // construct table.column = 'field value'
            $where = $mytable_col." = '".$assoc["FieldRefVal"]."'";

            $mytable_col2 = $this->getTableColumn(null, $assoc["Column2"]);
            if($assoc["Column2"]){
            	$where .= " AND ".$mytable_col2." = '".$assoc["FieldRefVal2"]."'";
            }
            $mytable_cond_col = $this->getTableColumn(null, $assoc["CondColumn"]);
            if($assoc["CondColumn"]){
            	$where .= " AND $mytable_cond_col ='".$assoc["CondValue"]."' ";
            }
        	if($assoc["Condition"]){
            	$where .= " AND ".$assoc["Condition"]." ";
            }
        }
        elseif ($assoc["Relationship"] == "M-M" || $assoc["Relationship"] == "Self-Self")
        {
            // ... INNER JOIN xtable TX ON TX.column2 = T0.column
            // WHERE ... Tx.column1 = 'PrtTableColumnValue'
            $mytable_col = $this->getTableColumn(null, $assoc["Column"]);   // this table's alias.column
            $xtable = $assoc["XTable"];    // xtable's name
            $column1 = $assoc["XColumn1"]; // xtable column1
            $column2 = $assoc["XColumn2"]; // xtable column2
            $xalias = "TX";
            if (isset($this->_tableAliasList[$xtable]))
                $xalias = $this->_tableAliasList[$xtable];

            // add a table join for the xtable if such join of the table is not there before (note: may report error if has same join).
            //if (strpos($this->tableJoins, "JOIN $xtable") === false)
            if (!isset($this->_tableAliasList[$xtable]))
            {
                $this->_tableJoins .= " INNER JOIN `$xtable` $xalias ON $xalias.$column2 = $mytable_col ";
                $this->_tableAliasList[$xtable] = $xalias;
            }

            // add a new where condition
            if($assoc["Relationship"] == "Self-Self")
            {
            	$columnId = $this->getTableColumn("", $assoc["ParentRecordIdColumn"]);
            	$where = "($xalias.$column1 = '".$assoc["FieldRefVal"]."' OR $xalias.$column2 = '".$assoc["FieldRefVal"]."' ) AND $columnId != '".$assoc["FieldRefVal"]."'";
            	$this->_tableJoins .=  " OR $xalias.$column1 = $mytable_col ";
            }else{
            	$where = "$xalias.$column1 = '".$assoc["FieldRefVal"]."'";
            }
        }

        if (strlen($where) > 1)
            $this->addSqlWhere($where);
    }

Add association in the SQL

@param array $assoc additional SQL statment
@return void


public function getSqlStatement()
    {
        $ret = "SELECT " . $this->_tableColumns;
        $ret .= " FROM " . $this->_tableJoins;

        if ($this->_sqlWhere != null)
        {
            $ret .= " WHERE " . $this->_sqlWhere;
        }
        /*
        if ($this->orderBy != null)
        {
            $ret .= " ORDER BY " . $this->orderBy;
	}
        */
        if ($this->_otherSQL != null)
        {
            $ret .= " " . $this->_otherSQL;
        }
        if ($this->_orderBy != null)
        {
            $ret .= " ORDER BY " . $this->_orderBy;
        }
        return $ret;
    }

Get the SQL statement

@return string SQL statement


public function get($key)
    {
        if (isset($this->varValue[$key])) {
            return new DataRecord($this->varValue[$key], $this->bizDataObj);
        } else {
            return NULL;
        }
    }

public function get ( $ key ) { if ( isset ( $ this -> varValue [ $ key ] ) ) { return new DataRecord ( $ this -> varValue [ $ key ] , $ this -> bizDataObj ) ; } else { return NULL ; } }

Get item value of array

@param mixed $key
@return mixed


public function cliAction()
    {
        $exitCode = $this->cliApplication->run(new RequestInput($this->getRequest()));

        if (is_numeric($exitCode)) {
            $model = new ConsoleModel();
            $model->setErrorLevel($exitCode);

            return $model;
        }
    }

public function cliAction ( ) { $ exitCode = $ this -> cliApplication -> run ( new RequestInput ( $ this -> getRequest ( ) ) ) ; if ( is_numeric ( $ exitCode ) ) { $ model = new ConsoleModel ( ) ; $ model -> setErrorLevel ( $ exitCode ) ; return $ model ; } }

Index action - runs the console application


private static function getDefaultTemplateLocations()
    {
        return array(
            Openbizx::$app->getModulePath() . "/$packagePath/template/$templateFile",
            dirname(Openbizx::$app->getModulePath() . "/$packagePath") . "/template/$templateFile",
            Openbizx::$app->getModulePath() . "/$moduleName/template/$templateFile",
            //Openbizx::$app->getModulePath()."/common/template/$templateFile",
            $templateRoot . "/$templateFile"
        );
    }

Get list of default template location
@return array


public function render()
    {
    	$value = $this->text ? $this->getText() : $this->value;
        $fromList   = array();
        $this->getFromList($fromList);
        $valueArr = explode(',', $this->value);
        $style = $this->getStyle();
        $func = $this->getFunction();
        $id = $this->objectName;
        $selectedStr = '';

        $selectedStr = $value;

        foreach ($fromList as $option)
        {
            $test = array_search($option['val'], $valueArr);
            if (!($test === false))
            {
                $selectedStr = $option['txt'] ;
                break;
            }
        }

        if($selectedStr=="0" || $selectedStr==null){
        	$selectedStr = $this->blankOption;
        }

        if ($this->getLink())
        {
            $link = $this->getLink();
            $sHTML = "" . $selectedStr . "";
        }
        else
            $sHTML = "" . $selectedStr . "";

        if($this->backgroundColor)
        {
            	$bgcolor = $this->getBackgroundColor();
       			if($bgcolor){
            		$sHTML = "
$sHTML
";
            	}
        }
        return $sHTML;
    }

"<a id=\"$id\" href=\"$link\" $func $style>"

Render, draw the element to show description

@return string HTML text

Render draw the element to show description


protected function getFontGoogle($api_key = '')
    {
        // Check API KEY
        if (!empty($api_key)) {
            $fonts = $this->getFontViaAPI($api_key);

            // Check fonts
            if (is_array($fonts) && !empty($fonts)) {
                return $fonts;
            }
        }

        /**
         * Return best fonts from Chad Mazzola
         * @see http://hellohappy.org/beautiful-web-type/
         */
        return [
            'sans_serif'    => [
                'name'  => 'sansserif',
                'title' => 'sansserif',
                'sizes' => '',
            ],
            'abril_fatface' => [
                'name'  => 'Abril+Fatface',
                'title' => 'Abril Fatface',
                'sizes' => '',
            ],
            'cardo'         => [
                'name'  => 'Cardo',
                'title' => 'Cardo',
                'sizes' => '400,400italic',
            ],
            'gravitas_one'  => [
                'name'  => 'Gravitas+One',
                'title' => 'Gravitas One',
                'sizes' => '',
            ],
            'lato'          => [
                'name'  => 'Lato',
                'title' => 'Lato',
                'sizes' => '100,900',
            ],
            'merriweather'  => [
                'name'  => 'Merriweather',
                'title' => 'Merriweather',
                'sizes' => '400,900',
            ],
            'open_sans'     => [
                'name'  => 'Open+Sans',
                'title' => 'Open Sans',
                'sizes' => '300,400,600,700,800',
            ],
            'oswald'        => [
                'name'  => 'Oswald',
                'title' => 'Oswald',
                'sizes' => '300,400,700',
            ],
            'playfair_display'  => [
                'name'  => 'Playfair+Display',
                'title' => 'Playfair Display',
                'sizes' => '400,900,700italic',
            ],
            'pt_sans'       => [
                'name'  => 'PT+Sans',
                'title' => 'PT Sans',
                'sizes' => '400,700',
            ],
            'vollkorn'      => [
                'name'  => 'Vollkorn',
                'title' => 'Vollkorn',
                'sizes' => '400,400italic',
            ],
        ];
    }

Return all available Google fonts.

@param   string  $api_key
@return  array   $fonts


public function matchesGroup($groups = null)
    {
        if (null !== $groups) {
            $group_names = self::getGroupNames($groups);
            return in_array($this->group, $group_names);
        }

        return true;
    }

public function matchesGroup ( $ groups = null ) { if ( null !== $ groups ) { $ group_names = self :: getGroupNames ( $ groups ) ; return in_array ( $ this -> group , $ group_names ) ; } return true ; }

Determines whether this setting's group matches the given groups.

@param mixed $groups string or array with group names, default null matches always

@return boolean true when this setting's group matches the given groups

Determines whether this setting s group matches the given groups .


public function validateInput()
    {
        $this->errorFields = array();
        foreach ($this->bizRecord->inputFields as $fld) {

            /* @var $bizField BizField */
            $bizField = $this->bizRecord->get($fld);
            if ($bizField->encrypted == "Y") {
                if ($bizField->checkRequired() == true &&
                        ($bizField->value === null || $bizField->value === "")) {
                    $this->errorMessage = $this->getMessage("DATA_FIELD_REQUIRED", array($fld));
                    $this->errorFields[$bizField->objectName] = $this->errorMessage;
                }
                continue;
            }
            if ($bizField->checkRequired() == true &&
                    ($bizField->value === null || $bizField->value === "")) {
                $this->errorMessage = $this->getMessage("DATA_FIELD_REQUIRED", array($fld));
                $this->errorFields[$bizField->objectName] = $this->errorMessage;
            } elseif ($bizField->value !== null && $bizField->checkValueType() == false) {
                $this->errorMessage = $this->getMessage("DATA_FIELD_INCORRECT_TYPE", array($fld, $bizField->type));
                $this->errorFields[$bizField->objectName] = $this->errorMessage;
            } elseif ($bizField->value !== null && $bizField->Validate() == false) {

                /* @var $validateService validateService */
                $validateService = Openbizx::getService(VALIDATE_SERVICE);
                $this->errorMessage = $validateService->getErrorMessage($bizField->validator, $bizField->objectName);
                if ($this->errorMessage == false) { //Couldn't get a clear error message so let's try this
                    $this->errorMessage = $this->getMessage("DATA_FIELD_INVALID_INPUT", array($fld, $value, $bizField->validator));                //
                }
                $this->errorFields[$bizField->objectName] = $this->errorMessage;
            }
        }
        if (count($this->errorFields) > 0) {
            //print_r($this->errorFields);
            throw new Openbizx\Validation\Exception($this->errorFields);
            //return false;
        }

        // validate uniqueness
        if ($this->validateUniqueness() == false) {
            return false;
        }

        return true;
    }

Validate user input data and trigger error message and adjust BizField if invalid.

@return boolean
@todo: throw Openbizx\Data\Exception

Validate user input data and trigger error message and adjust BizField if invalid .


protected function validateUniqueness()
    {
        if (!$this->uniqueness)
            return true;
        $groupList = explode(";", $this->uniqueness);
        foreach ($groupList as $group) {
            $searchRule = "";
            $needCheck = true;
            $fields = explode(",", $group);
            foreach ($fields as $fld) {
                $bizField = $this->bizRecord->get($fld);
                if ($bizField->value === null || $bizField->value === "" || $bizField->value == $bizField->oldValue) {
                    $needCheck = false;
                    break;
                }
                if ($searchRule == "") {
                    $searchRule = "[" . $bizField->objectName . "]='" . addslashes($bizField->value) . "'";
                } else {
                    $searchRule .= " AND [" . $bizField->objectName . "]='" . addslashes($bizField->value) . "'";
                }
            }
            if ($needCheck) {
                $recordList = $this->directFetch($searchRule, 1);
                if ($recordList->count() > 0) {
                    $this->errorMessage = $this->getMessage("DATA_NOT_UNIQUE", array($group));
                    foreach ($fields as $fld) {
                        $this->errorFields[$fld] = $this->errorMessage;
                    }
                }
            }
        }
        if (count($this->errorFields) > 0) {
            throw new Openbizx\Validation\Exception($this->errorFields);
            return false;
        }
        return true;
    }

protected
function
validateUniqueness
(
)
{
if
(
!
$
this
->
uniqueness
)
return
true
;
$
groupList
=
explode
(
";"
,
$
this
->
uniqueness
)
;
foreach
(
$
groupList
as
$
group
)
{
$
searchRule
=
""
;
$
needCheck
=
true
;
$
fields
=
explode
(
","
,
$
group
)
;
foreach
(
$
fields
as
$
fld
)
{
$
bizField
=
$
this
->
bizRecord
->
get
(
$
fld
)
;
if
(
$
bizField
->
value
===
||
$
bizField
->
value
===
""
||
$
bizField
->
value
==
$
bizField
->
oldValue
)
{
$
needCheck
=
false
;
break
;
}
if
(
$
searchRule
==
""
)
{
$
searchRule
=
"["
.
$
bizField
->
objectName
.
"]='"
.
addslashes
(
$
bizField
->
value
)
.
"'"
;
}
else
{
$
searchRule
.=
" AND ["
.
$
bizField
->
objectName
.
"]='"
.
addslashes
(
$
bizField
->
value
)
.
"'"
;
}
}
if
(
$
needCheck
)
{
$
recordList
=
$
this
->
directFetch
(
$
searchRule
,
1
)
;
if
(
$
recordList
->
count
(
)
>
0
)
{
$
this
->
errorMessage
=
$
this
->
getMessage
(
"DATA_NOT_UNIQUE"
,
array
(
$
group
)
)
;
foreach
(
$
fields
as
$
fld
)
{
$
this
->
errorFields
[
$
fld
]
=
$
this
->
errorMessage
;
}
}
}
}
if
(
count
(
$
this
->
errorFields
)
>
0
)
{
throw
new
Openbizx
\
Validation
\
Exception
(
$
this
->
errorFields
)
;
return
false
;
}
return
true
;
}

Validate uniqueness
Uniqueness = "fld1,fld2;fld3,fld4;..."

@return boolean


public function canUpdateRecord($record = null)
    {

        if ($this->dataPermControl == 'Y') {
            $svcObj = Openbizx::getService(OPENBIZ_DATAPERM_SERVICE);
            if (!$record) {
                $record = $this->getActiveRecord();
            }
            $result = $svcObj->checkDataPerm($record, 2, $this);
            if ($result == false) {
                return false;
            }
        }

        $result = $this->canUpdateRecordCondition();
        return $result;
    }

public function canUpdateRecord ( $ record = null ) { if ( $ this -> dataPermControl == 'Y' ) { $ svcObj = Openbizx :: getService ( OPENBIZ_DATAPERM_SERVICE ) ; if ( ! $ record ) { $ record = $ this -> getActiveRecord ( ) ; } $ result = $ svcObj -> checkDataPerm ( $ record , 2 , $ this ) ; if ( $ result == false ) { return false ; } } $ result = $ this -> canUpdateRecordCondition ( ) ; return $ result ; }

Check if the current record can be updated

@return boolean


public function canDeleteRecord($record = null)
    {
        if ($this->dataPermControl == 'Y') {
            $svcObj = Openbizx::getService(OPENBIZ_DATAPERM_SERVICE);
            if (!$record) {
                $record = $this->getActiveRecord();
            }
            $result = $svcObj->checkDataPerm($record, 3, $this);
            if ($result == false) {
                return false;
            }
        }

        $result = $this->canDeleteRecordCondition();
        return $result;
    }

public function canDeleteRecord ( $ record = null ) { if ( $ this -> dataPermControl == 'Y' ) { $ svcObj = Openbizx :: getService ( OPENBIZ_DATAPERM_SERVICE ) ; if ( ! $ record ) { $ record = $ this -> getActiveRecord ( ) ; } $ result = $ svcObj -> checkDataPerm ( $ record , 3 , $ this ) ; if ( $ result == false ) { return false ; } } $ result = $ this -> canDeleteRecordCondition ( ) ; return $ result ; }

Check if the current record can be deleted

@return boolean


public function updateRecord($recArr, $oldRecord = null)
    {
        $this->events()->trigger(__FUNCTION__ . '.pre', $this, array('record' => $recArr, 'old_record' => $oldRecord));
        if (!$this->canUpdateRecord($oldRecord)) {
            $this->errorMessage = MessageHelper::getMessage("DATA_NO_PERMISSION_UPDATE", $this->objectName);
            throw new Openbizx\Data\Exception($this->errorMessage);
            return false;
        }

        if (!$oldRecord)
            $oldRecord = $this->getActiveRecord();

        if (!$recArr["Id"])
            $recArr["Id"] = $this->getFieldValue("Id");

        // save the old values
        $this->bizRecord->saveOldRecord($oldRecord);
        // set the new values
        $this->bizRecord->setInputRecord($recArr);

        if (!$this->validateInput())
            return false;

        $sql = $this->getSQLHelper()->buildUpdateSQL($this);

        if ($sql) {
            $db = $this->getDBConnection("WRITE");
            if ($this->useTransaction)
                $db->beginTransaction();

            try {
                $this->cascadeUpdate(); // cascade update

                Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", "Update Sql = $sql");
                $db->query($sql);

                if ($this->useTransaction)
                    $db->commit();
            } catch (Exception $e) {
                if ($this->useTransaction)
                    $db->rollBack();

                if ($e instanceof Openbizx\Data\Exception)
                    throw $e;
                else {
                    Openbizx::$app->getLog()->log(LOG_ERR, "DATAOBJ", "Query error : " . $e->getMessage());
                    $this->errorMessage = $this->getMessage("DATA_ERROR_QUERY") . ": " . $sql . ". " . $e->getMessage();
                    throw new Openbizx\Data\Exception($this->errorMessage);
                }
                return false;
            }

            $this->cleanCache(); //clean cached data
            $this->_postUpdateLobFields($recArr);
            $this->currentRecord = null;
            $this->_postUpdateRecord($recArr);
        }
        $this->events()->trigger(__FUNCTION__ . '.post', $this, array('record' => $recArr, 'old_record' => $oldRecord));
        return true;
    }

public
function
updateRecord
(
$
recArr
,
$
oldRecord
=
)
{
$
this
->
events
(
)
->
trigger
(
__FUNCTION__
.
'.pre'
,
$
this
,
array
(
'record'
=>
$
recArr
,
'old_record'
=>
$
oldRecord
)
)
;
if
(
!
$
this
->
canUpdateRecord
(
$
oldRecord
)
)
{
$
this
->
errorMessage
=
MessageHelper
::
getMessage
(
"DATA_NO_PERMISSION_UPDATE"
,
$
this
->
objectName
)
;
throw
new
Openbizx
\
Data
\
Exception
(
$
this
->
errorMessage
)
;
return
false
;
}
if
(
!
$
oldRecord
)
$
oldRecord
=
$
this
->
getActiveRecord
(
)
;
if
(
!
$
recArr
[
"Id"
]
)
$
recArr
[
"Id"
]
=
$
this
->
getFieldValue
(
"Id"
)
;
// save the old values
$
this
->
bizRecord
->
saveOldRecord
(
$
oldRecord
)
;
// set the new values
$
this
->
bizRecord
->
setInputRecord
(
$
recArr
)
;
if
(
!
$
this
->
validateInput
(
)
)
return
false
;
$
sql
=
$
this
->
getSQLHelper
(
)
->
buildUpdateSQL
(
$
this
)
;
if
(
$
sql
)
{
$
db
=
$
this
->
getDBConnection
(
"WRITE"
)
;
if
(
$
this
->
useTransaction
)
$
db
->
beginTransaction
(
)
;
try
{
$
this
->
cascadeUpdate
(
)
;
// cascade update
Openbizx
::
$
app
->
getLog
(
)
->
log
(
LOG_DEBUG
,
"DATAOBJ"
,
"Update Sql = $sql"
)
;
$
db
->
query
(
$
sql
)
;
if
(
$
this
->
useTransaction
)
$
db
->
commit
(
)
;
}
catch
(
Exception
$
e
)
{
if
(
$
this
->
useTransaction
)
$
db
->
rollBack
(
)
;
if
(
$
e
instanceof
Openbizx
\
Data
\
Exception
)
throw
$
e
;
else
{
Openbizx
::
$
app
->
getLog
(
)
->
log
(
LOG_ERR
,
"DATAOBJ"
,
"Query error : "
.
$
e
->
getMessage
(
)
)
;
$
this
->
errorMessage
=
$
this
->
getMessage
(
"DATA_ERROR_QUERY"
)
.
": "
.
$
sql
.
". "
.
$
e
->
getMessage
(
)
;
throw
new
Openbizx
\
Data
\
Exception
(
$
this
->
errorMessage
)
;
}
return
false
;
}
$
this
->
cleanCache
(
)
;
//clean cached data
$
this
->
_postUpdateLobFields
(
$
recArr
)
;
$
this
->
currentRecord
=
;
$
this
->
_postUpdateRecord
(
$
recArr
)
;
}
$
this
->
events
(
)
->
trigger
(
__FUNCTION__
.
'.post'
,
$
this
,
array
(
'record'
=>
$
recArr
,
'old_record'
=>
$
oldRecord
)
)
;
return
true
;
}

Update record using given input record array

@param array $recArr - associated array whose keys are field names of this BizDataObj
@param array $oldRecord - associated array who is the old record field name / value pairs
@return boolean - if return false, the caller can call GetErrorMessage to get the error.


public function newRecord()
    {
        $recArr = $this->bizRecord->getEmptyRecordArr();

        // if association is 1-M, set the field (pointing to the column) value as the FieldRefVal
        if ($this->association["Relationship"] == "1-M") {
            foreach ($this->bizRecord as $field) {
                if ($field->column == $this->association["Column"] && !$field->join) {
                    $recArr[$field->objectName] = $this->association["FieldRefVal"];
                    break;
                }
            }
        }

        return $recArr;
    }

Create an empty new record

@return array - empty record array with default values


protected function generateId($isBeforeInsert = true, $tableName = null, $idCloumnName = null)
    {
        // Identity type id is generated after insert is done.
        // If this method is called before insert, return null.
        if ($isBeforeInsert && $this->idGeneration == 'Identity')
            return null;

        if (!$isBeforeInsert && $this->idGeneration != 'Identity') {
            $this->errorMessage = MessageHelper::getMessage("DATA_UNABLE_GET_ID", $this->objectName);
            return false;
        }

        /* @var $genIdService genIdService */
        $genIdService = Openbizx::getService(GENID_SERVICE);
        if ($this->m_db) {
            $db = $this->m_db;
        } else {
            $db = $this->getDBConnection("READ");
        }
        $dbInfo = Openbizx::$app->getConfiguration()->getDatabaseInfo($this->databaseAliasName);
        $dbType = $dbInfo["Driver"];
        $table = $tableName ? $tableName : $this->mainTableName;
        $column = $idCloumnName ? $idCloumnName : $this->getField("Id")->column;

        try {
            $newId = $genIdService->getNewID($this->idGeneration, $db, $dbType, $table, $column);
        } catch (Exception $e) {
            $this->errorMessage = $e->getMessage();
            return false;
        }
        return $newId;
    }

Generate Id according to the IdGeneration attribute

@param boolean $isBeforeInsert
@param string $tableName
@param string $idCloumnName
@return long|string|boolean


public function insertRecord($recArr)
    {
        $this->events()->trigger(__FUNCTION__ . '.pre', $this, array('record', $recArr));
        if ($this->_isNeedGenerateId($recArr))
            $recArr["Id"] = $this->generateId();    // for certain cases, id is generated before insert

        $this->bizRecord->setInputRecord($recArr);

        if (!$this->validateInput())
            return false;

        $db = $this->getDBConnection("WRITE");

        try {
            $sql = $this->getSQLHelper()->buildInsertSQL($this, $joinValues);
            if ($sql) {
                Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", "Insert Sql = $sql");
                $db->query($sql, $bindValues);
            }
            //$mainId = $db->lastInsertId();
            if ($this->_isNeedGenerateId($recArr)) {
                $this->m_db = $db; //compatiable for CLI mode and also speed up of it running
                $mainId = $this->generateId(false);
                $recArr["Id"] = $mainId;
            }
            Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", "New record Id is " . $recArr["Id"]);
        } catch (Exception $e) {
            Openbizx::$app->getLog()->log(LOG_ERR, "DATAOBJ", "Query Error : " . $e->getMessage());
            $this->errorMessage = $this->getMessage("DATA_ERROR_QUERY") . ": " . $sql . ". " . $e->getMessage();
            throw new Openbizx\Data\Exception($this->errorMessage);
            return null;
        }

        $this->bizRecord->setInputRecord($recArr);

        if ($this->_postUpdateLobFields($recArr) === false) {
            $this->errorMessage = $db->ErrorMsg();
            return false;
        }

        $this->cleanCache();

        $this->recordId = $recArr["Id"];
        $this->currentRecord = null;

        $this->_postInsertRecord($recArr);
        $this->events()->trigger(__FUNCTION__ . '.post', $this, array('record', $recArr));
        return $recArr["Id"];
    }

Insert record using given input record array

@param array $recArr - associated array whose keys are field names of this BizDataObj
@return boolean - if return false, the caller can call getErrorMessage to get the error.


public function deleteRecord($recArr)
    {
        $this->events()->trigger(__FUNCTION__ . '.pre', $this, array('record', $recArr));
        if (!$this->canDeleteRecord()) {
            $this->errorMessage = MessageHelper::getMessage("DATA_NO_PERMISSION_DELETE", $this->objectName);
            throw new Openbizx\Data\Exception($this->errorMessage);
            return false;
        }

        if ($recArr) {
            $delrec = $recArr;
        } else {
            $delrec = $this->getActiveRecord();
        }

        $this->bizRecord->setInputRecord($delrec);

        $sql = $this->getSQLHelper()->buildDeleteSQL($this);
        if ($sql) {
            $db = $this->getDBConnection("WRITE");
            $db->beginTransaction();
            try {
                $this->cascadeDelete(); // cascade delete
                Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", "Delete Sql = $sql");
                $db->query($sql);
                $db->commit();
                $this->bizRecord->saveOldRecord($delrec); // save old record only if delete success
            } catch (Exception $e) {
                $db->rollBack();
                if ($e instanceof Openbizx\Data\Exception)
                    throw $e;
                else {
                    Openbizx::$app->getLog()->log(LOG_ERR, "DATAOBJ", "Query error : " . $e->getMessage());
                    $this->errorMessage = $this->getMessage("DATA_ERROR_QUERY") . ": " . $sql . ". " . $e->getMessage();
                    throw new Openbizx\Data\Exception($this->errorMessage);
                }
                return false;
            }
        }

        //clean cached data
        $this->cleanCache();

        $this->_postDeleteRecord($this->bizRecord->getKeyValue());
        $this->events()->trigger(__FUNCTION__ . '.pre', $this, array('record', $recArr));
        return true;
    }

Delete current record or delete the given input record

@param array $recArr - associated array whose keys are field names of this BizDataObj
@return boolean - if return false, the caller can call GetErrorMessage to get the error.


public function getOnAuditFields()
    {
        $fieldList = array();
        foreach ($this->bizRecord as $field) {
            if ($field->onAudit)
                $fieldList[] = $field;
        }
        return $fieldList;
    }

public function getOnAuditFields ( ) { $ fieldList = array ( ) ; foreach ( $ this -> bizRecord as $ field ) { if ( $ field -> onAudit ) $ fieldList [ ] = $ field ; } return $ fieldList ; }

Get auditable fields

@return array list of {@link BizField} objects who are auditable


private function _runDOTrigger($triggerType)
    {
        // locate the trigger metadata file BOName_Trigger.xml
        $triggerServiceName = $this->objectName . "_Trigger";
        $xmlFile = ObjectFactoryHelper::getXmlFileWithPath($triggerServiceName);
        if (!$xmlFile) {
            return;
        }

        $triggerService = Openbizx::getObject($triggerServiceName);
        if ($triggerService == null) {
            return;
        }
        // invoke trigger service ExecuteTrigger($triggerType, $currentRecord)

        $triggerService->execute($this, $triggerType);
    }

Run DataObject trigger

@param string $triggerType type of the trigger


public function getJoinFields($joinDataObj)
    {
        // get the maintable of the joindataobj
        $joinTable = $joinDataObj->mainTableName;
        $returnRecord = array();

        // find the proper join according to the maintable
        foreach ($this->tableJoins as $tableJoin) {
            if ($tableJoin->table == $joinTable) {
                // populate the column-fieldvalue to columnRef-fieldvalue
                // get the field mapping to the column, then get the field value
                $joinFieldName = $joinDataObj->bizRecord->getFieldByColumn($tableJoin->column); // joined-main table

                if (!$joinFieldName) {
                    continue;
                }

                $refFieldName = $this->bizRecord->getFieldByColumn($tableJoin->columnRef); // join table
                $returnRecord[$refFieldName] = $joinFieldName;

                // populate joinRecord's field to current record
                foreach ($this->bizRecord as $field) {
                    if ($field->join == $tableJoin->objectName) {
                        // use join column to match joinRecord field's column
                        $jFieldName = $joinDataObj->bizRecord->getFieldByColumn($field->column); // joined-main table
                        $returnRecord[$field->objectName] = $jFieldName;
                    }
                }
                break;
            }
        }
        return $returnRecord;
    }

Get all fields that belong to the same join of the input field

@param BizDataObj $joinDataObj the join data object
@return array joined fields array


public function joinRecord($joinDataObj, $joinName = "")
    {
        // get the maintable of the joindataobj
        $joinTable = $joinDataObj->mainTableName;
        $joinRecord = null;
        $returnRecord = array();

        // find the proper join according to join name and the maintable
        foreach ($this->tableJoins as $tableJoin) {
            if (($joinName == $tableJoin->objectName || $joinName == "") && $tableJoin->table == $joinTable) {
                // populate the column-fieldvalue to columnRef-fieldvalue
                // get the field mapping to the column, then get the field value
                $joinFieldName = $joinDataObj->bizRecord->getFieldByColumn($tableJoin->column); // joined-main table
                if (!$joinFieldName)
                    continue;
                if (!$joinRecord)
                    $joinRecord = $joinDataObj->getActiveRecord();
                $refFieldName = $this->bizRecord->getFieldByColumn($tableJoin->columnRef); // join table
                $returnRecord[$refFieldName] = $joinRecord[$joinFieldName];
                // populate joinRecord's field to current record
                foreach ($this->bizRecord as $fld) {
                    if ($fld->join == $tableJoin->objectName) {
                        // use join column to match joinRecord field's column
                        $jfldname = $joinDataObj->bizRecord->getFieldByColumn($fld->column); // joined-main table
                        $returnRecord[$fld->objectName] = $joinRecord[$jfldname];
                    }
                }
                break;
            }
        }
        // return a modified record with joined record data
        return $returnRecord;
    }

Pick the joined object's current record to the current record

@param BizDataObj $joinDataObj
@param string $joinName name of join (optional)
@return array return a modified record with joined record data

Pick the joined object s current record to the current record


private function _isNeedGenerateId($recArr)
    {
        if ($this->idGeneration != 'None' && (!$recArr["Id"] || $recArr["Id"] == "")) {
            return true;
        }
        if ($this->idGeneration == 'Identity') {
            return true;
        }
    }

private function _isNeedGenerateId ( $ recArr ) { if ( $ this -> idGeneration != 'None' && ( ! $ recArr [ "Id" ] || $ recArr [ "Id" ] == "" ) ) { return true ; } if ( $ this -> idGeneration == 'Identity' ) { return true ; } }

Is need to generate Id?

@param array $recArr array of record
@return boolean


public function run()
    {
        $successful = true;

        $this->initReport();

        $checks = array();
        foreach ($this->config->getCheckDefinitions() as $check_definition) {
            $checks[] = $this->getCheckInstance($check_definition);
        }

        $progress = $this->command->getHelperSet()->get('progress');
        $progress->setFormat(' %current%/%max% [%bar%] %percent%% Elapsed: %elapsed% ');

        $progress->start($this->command->getOutput(), count($checks));

        // run all checks defined in the configuration
        foreach ($checks as $check) {
            // process the check
            $succeeded = (bool) $check->run();

            // collect the result
            $result = $check->getResult();

            if (!$result instanceof IResult) {
                throw new \LogicException(
                    'The result of check "' . $check->getName() . '" (group "' . $check->getGroup() . '", class "' .
                    get_class($check) . '") must implement IResult.'
                );
            }

            // mark the check's result as success or failure
            if (!$succeeded) {
                $result->setStatus(IResult::FAIL);
            } else {
                $result->setStatus(IResult::SUCCESS);
            }

            // add the check's result to the report
            $this->report->addResult($result);

            $successful &= $succeeded;

            $progress->advance();
        }

        $progress->finish();

        return $successful;
    }

Execute the checks that are defined in the config
and generate a report to consume by others.

Execute the checks that are defined in the config and generate a report to consume by others .


protected function initReport()
    {
        $report_implementor = $this->config->getReportImplementor();
        $report = new $report_implementor();

        if (!$report instanceof IReport) {
            throw new \InvalidArgumentException(
                'The given report class "' . $report_implementor . '" does not implement IReport.'
            );
        }

        $this->report = $report;
        $this->report->setParameters(new Parameters($this->config->get('report', array())));

        return $this->report;
    }

protected
function
initReport
(
)
{
$
report_implementor
=
$
this
->
config
->
getReportImplementor
(
)
;
$
report
=
new
$
report_implementor
(
)
;
if
(
!
$
report
instanceof
IReport
)
{
throw
new
\
InvalidArgumentException
(
'The given report class "'
.
$
report_implementor
.
'" does not implement IReport.'
)
;
}
$
this
->
report
=
$
report
;
$
this
->
report
->
setParameters
(
new
Parameters
(
$
this
->
config
->
get
(
'report'
,
array
(
)
)
)
)
;
return
$
this
->
report
;
}

Initializes the internal report instance being used to collect the results of the checks.

@return IReport report instance

Initializes the internal report instance being used to collect the results of the checks .


private function resolveRoute(Request $request): Route
    {
        if( ($route = $this->router->resolve($request)) === null ){

            // 405 Method Not Allowed
            if( ($methods = $this->router->getMethodsForUri($request)) ){
                throw new MethodNotAllowedHttpException;
            }

            // 404 Not Found
            throw new NotFoundHttpException("Route not found");
        }

        return $route;
    }

private
function
resolveRoute
(
Request
$
request
)
:
Route
{
if
(
(
$
route
=
$
this
->
router
->
resolve
(
$
request
)
)
===
)
{
// 405 Method Not Allowed
if
(
(
$
methods
=
$
this
->
router
->
getMethodsForUri
(
$
request
)
)
)
{
throw
new
MethodNotAllowedHttpException
;
}
// 404 Not Found
throw
new
NotFoundHttpException
(
"Route not found"
)
;
}
return
$
route
;
}

Resolve to a Route instance or throw exception

@param Request $request
@throws NotFoundHttpException
@throws MethodNotAllowedHttpException
@return Route


private function resolveActionParameters(Request $request, callable $target): array
    {
        // Get the target's parameters
        if( is_array($target) ) {
            $functionParameters = (new \ReflectionClass(get_class($target[0])))->getMethod($target[1])->getParameters();
        }

        else{
            $functionParameters = (new \ReflectionFunction($target))->getParameters();
        }

        $params = [];

        /** @var \ReflectionParameter $parameter */
        foreach( $functionParameters as $parameter ){

            /**
             *
             * @NOTE We cast the ReflectionType to string because the ::getName() method does not appear in
             * PHP 7 until 7.1
             *
             */
            // Check container first for an instance of this parameter type
            if( $parameter->getType() &&
                (string) $parameter->getType() === Request::class ){
                $params[$parameter->getPosition()] = $request;
            }

            // Check request attributes for this parameter name
            elseif( $request->attributes->has($parameter->getName()) ){
                $params[$parameter->getPosition()] = $request->attributes->get($parameter->getName());
            }

            else {
                $params[$parameter->getPosition()] = null;
            }
        }

        return $params;
    }

Resolve the action parameters for dependency injection.

@param Request $request
@param callable $target
@return array

Resolve the action parameters for dependency injection .


public function has($name, $groups = null, $flag = null)
    {
        foreach ($this->settings as $setting) {
            if (($setting->getName() === $name) && $setting->matchesGroup($groups) && $setting->matchesFlag($flag)) {
                return true;
            }
        }

        return false;
    }

public function has ( $ name , $ groups = null , $ flag = null ) { foreach ( $ this -> settings as $ setting ) { if ( ( $ setting -> getName ( ) === $ name ) && $ setting -> matchesGroup ( $ groups ) && $ setting -> matchesFlag ( $ flag ) ) { return true ; } } return false ; }

Returns whether a cached value for a setting from the loaded cache exists, that matches the given criterias.

@param string $name key of wanted setting
@param mixed $groups group name of setting, default is null and matches always
@param integer $flag setting type to match, default is null and matches always

@return boolean true if value for that setting is in cache; false otherwise

Returns whether a cached value for a setting from the loaded cache exists that matches the given criterias .


public function get($name, $groups = null, $flag = null)
    {
        $found = null;

        foreach ($this->settings as $setting) {
            if (($setting->getName() === $name) && $setting->matchesGroup($groups) && $setting->matchesFlag($flag)) {
                return $setting;
            }
        }

        return $found;
    }

public function get ( $ name , $ groups = null , $ flag = null ) { $ found = null ; foreach ( $ this -> settings as $ setting ) { if ( ( $ setting -> getName ( ) === $ name ) && $ setting -> matchesGroup ( $ groups ) && $ setting -> matchesFlag ( $ flag ) ) { return $ setting ; } } return $ found ; }

Returns the first setting from the loaded cache that matches the given criterias.

@param string $name key of wanted setting
@param mixed $groups group name of setting, default is null and matches always
@param integer $flag setting type to match, default is null and matches always

@return ISetting|null matching setting

Returns the first setting from the loaded cache that matches the given criterias .


public function getAll($groups = null, $flag = null)
    {
        $settings = array();

        if (null === $groups) {
            foreach ($this->settings as $setting) {
                $settings[] = $setting;
            }
        } elseif (is_string($groups) || is_array($groups)) {
            foreach ($this->settings as $setting) {
                if ($setting->matchesGroup($groups) && $setting->matchesFlag($flag)) {
                    $settings[] = $setting;
                }
            }
        } else {
            throw new \InvalidArgumentException(
                'Only a null value, a single string as group name or an array of group names are supported.'
            );
        }

        return $settings;
    }

Returns an array of settings matching the given criterias.

@param mixed $groups name of a group or array of group names or null for all settings regardless of group
@param type $flag only return settings that match the given flag value

@return array of setting instances matching the specification

@throws \InvalidArgumentException if $groups is neither null nor a string or an array

Returns an array of settings matching the given criterias .


public function load()
    {
        $location = $this->location;

        // no location given from commandline -> use config values or fallback to default location
        if (empty($location)) {
            $location = $this->parameters->get(
                'read_location',
                $this->parameters->get(
                    'location',
                    $this->getDefaultLocation()
                )
            );
        }

        $this->location = $location;

        if (!is_readable($location) || !is_file($location)) {
            return false;
        }

        $content = file_get_contents($location);

        if (false === $content) {
            return false;
        }

        $result = json_decode($content, true);

        if (null === $result) {
            throw new \InvalidArgumentException('Cache could not be decoded from file: ' . $location);
        }

        $items = array();
        foreach ($result as $setting) {
            $items[] = new Setting($setting['name'], $setting['value'], $setting['group'], $setting['flag']);
        }

        $this->settings = $items;

        return true;
    }

Loads the settings from the configured or default location.

@return boolean true, if reading from cache succeeded; false otherwise.

@throws \InvalidArgumentException on invalid or broken cache file

Loads the settings from the configured or default location .


public function setLocation($location)
    {
        if (!is_readable($location)) {
            throw new \InvalidArgumentException('Given cache location "' . $location . '" is not readable.');
        }

        $this->location = $location;

        return $this;
    }

public
function
setLocation
(
$
location
)
{
if
(
!
is_readable
(
$
location
)
)
{
throw
new
\
InvalidArgumentException
(
'Given cache location "'
.
$
location
.
'" is not readable.'
)
;
}
$
this
->
location
=
$
location
;
return
$
this
;
}

Sets the given location as the cache location to use.

@param string $location cache file path

@return ReadOnlyCache this instance for fluent API support

@throws \InvalidArgumentException if location is not readable

Sets the given location as the cache location to use .


protected function prefixCss( $content )
  {
    $replaced = array();
    if( $rules = $this->getRules( $content ) )
    {
      foreach( $rules as $rule )
      {
        $prefixed = array();
        if( strpos( $content, $rule->getRaw() ) !== false && !in_array( $rule->getRaw(), $replaced ) )
        {

          if( array_key_exists( $rule->getProperty(), $this->prefixValue ) )
          {
            if( array_key_exists( $rule->getValue(), $this->prefixValue[ $rule->getProperty() ] ) )
            {
              $prefixed = $this->getPrefixRules( $rule->getProperty(), $this->prefixValue[ $rule->getProperty() ][ $rule->getValue() ], $rule->getBang() );
            }
          }
          elseif( array_key_exists( $rule->getProperty(), $this->prefixProperty ) )
          {
            $prefixed = $this->getPrefixRules( $this->prefixProperty[ $rule->getProperty() ], $rule->getValue(), $rule->getBang() );
          }
          elseif( array_key_exists( $rule->getProperty(), $this->prefixMethod ) )
          {
            $method = $this->prefixMethod[ $rule->getProperty() ];
            $prefixed  = $this->$method( $rule->getValue(), $rule->getBang() );
          }

          if( !empty( $prefixed ) )
          {
            $newRules = array();
            foreach( $prefixed as $pRule )
            {
              /** @var CssRule $pRule */
              $pRule->setTemplate( $rule->getTemplate() );
              $newRules[] = $pRule->getOutput();
            }

            $replaced[] = $rule->getRaw();
            $replacement = str_replace( $rule->getOutput(), implode( "\n", $newRules ), $rule->getRaw() );
            $content = str_replace($rule->getRaw(),$replacement,$content);

          }
        }
      }
    }

    return $content;
  }

protected
function
prefixCss
(
$
content
)
{
$
replaced
=
array
(
)
;
if
(
$
rules
=
$
this
->
getRules
(
$
content
)
)
{
foreach
(
$
rules
as
$
rule
)
{
$
prefixed
=
array
(
)
;
if
(
strpos
(
$
content
,
$
rule
->
getRaw
(
)
)
!==
false
&&
!
in_array
(
$
rule
->
getRaw
(
)
,
$
replaced
)
)
{
if
(
array_key_exists
(
$
rule
->
getProperty
(
)
,
$
this
->
prefixValue
)
)
{
if
(
array_key_exists
(
$
rule
->
getValue
(
)
,
$
this
->
prefixValue
[
$
rule
->
getProperty
(
)
]
)
)
{
$
prefixed
=
$
this
->
getPrefixRules
(
$
rule
->
getProperty
(
)
,
$
this
->
prefixValue
[
$
rule
->
getProperty
(
)
]
[
$
rule
->
getValue
(
)
]
,
$
rule
->
getBang
(
)
)
;
}
}
elseif
(
array_key_exists
(
$
rule
->
getProperty
(
)
,
$
this
->
prefixProperty
)
)
{
$
prefixed
=
$
this
->
getPrefixRules
(
$
this
->
prefixProperty
[
$
rule
->
getProperty
(
)
]
,
$
rule
->
getValue
(
)
,
$
rule
->
getBang
(
)
)
;
}
elseif
(
array_key_exists
(
$
rule
->
getProperty
(
)
,
$
this
->
prefixMethod
)
)
{
$
method
=
$
this
->
prefixMethod
[
$
rule
->
getProperty
(
)
]
;
$
prefixed
=
$
this
->
$
method
(
$
rule
->
getValue
(
)
,
$
rule
->
getBang
(
)
)
;
}
if
(
!
empty
(
$
prefixed
)
)
{
$
newRules
=
array
(
)
;
foreach
(
$
prefixed
as
$
pRule
)
{
/** @var CssRule $pRule */
$
pRule
->
setTemplate
(
$
rule
->
getTemplate
(
)
)
;
$
newRules
[
]
=
$
pRule
->
getOutput
(
)
;
}
$
replaced
[
]
=
$
rule
->
getRaw
(
)
;
$
replacement
=
str_replace
(
$
rule
->
getOutput
(
)
,
implode
(
"\n"
,
$
newRules
)
,
$
rule
->
getRaw
(
)
)
;
$
content
=
str_replace
(
$
rule
->
getRaw
(
)
,
$
replacement
,
$
content
)
;
}
}
}
}
return
$
content
;
}

Finds individual CSS rules and evaluates them for needed prefixes, then replaces the rules with the prefixed rule
as needed.

@param string $content   The CSS, without prefixes.

@return string           The CSS with prefixes.

Finds individual CSS rules and evaluates them for needed prefixes then replaces the rules with the prefixed rule as needed .


protected function prefixAlignItems( $value, $extra = null )
  {
    $prop[] = '-ms-flex-align';

    switch( $value )
    {
      case 'flex-start':
        $val[] = 'start';
        break;
      case 'flex-end':
        $val[] = 'end';
        break;
      default:
        $val[]  = $value;
        $prop[] = '-ms-grid-row-align';
        $val[]  = 'center';
        break;
    }

    $prop[] = '-webkit-align-items';
    $prop[] = 'align-items';
    $val[]  = $value;
    $val[]  = $value;

    return $this->getPrefixRules( $prop, $val, $extra );
  }

protected function prefixAlignItems ( $ value , $ extra = null ) { $ prop [ ] = '-ms-flex-align' ; switch ( $ value ) { case 'flex-start' : $ val [ ] = 'start' ; break ; case 'flex-end' : $ val [ ] = 'end' ; break ; default : $ val [ ] = $ value ; $ prop [ ] = '-ms-grid-row-align' ; $ val [ ] = 'center' ; break ; } $ prop [ ] = '-webkit-align-items' ; $ prop [ ] = 'align-items' ; $ val [ ] = $ value ; $ val [ ] = $ value ; return $ this -> getPrefixRules ( $ prop , $ val , $ extra ) ; }

Properly prefixes the 'align-items' property.

@param string  $value  The value of the property.
@param null    $extra  !important or null

@return array          The prefixed rules to replace the 'align-items' rule.

Properly prefixes the align - items property .


protected function prefixAlignContent( $value, $extra = null )
  {
    $prop = array(
        '-webkit-align-content',
        '-ms-flex-line-pack',
        'align-content'
    );

    $val[] = $value;
    switch( $value )
    {
      case 'flex-start':
        $val[] = 'start';
        break;
      case 'flex-end':
        $val[] = 'end';
        break;
      case 'space-between':
        $val[] = 'justify';
        break;
      case 'space-around':
        $val[] = 'distribute';
        break;
      default:
        $val[] = $value;
        break;
    }

    $val[] = $value;

    return $this->getPrefixRules( $prop, $val, $extra );
  }

protected function prefixAlignContent ( $ value , $ extra = null ) { $ prop = array ( '-webkit-align-content' , '-ms-flex-line-pack' , 'align-content' ) ; $ val [ ] = $ value ; switch ( $ value ) { case 'flex-start' : $ val [ ] = 'start' ; break ; case 'flex-end' : $ val [ ] = 'end' ; break ; case 'space-between' : $ val [ ] = 'justify' ; break ; case 'space-around' : $ val [ ] = 'distribute' ; break ; default : $ val [ ] = $ value ; break ; } $ val [ ] = $ value ; return $ this -> getPrefixRules ( $ prop , $ val , $ extra ) ; }

Properly prefixes the 'align-content' property.

@param string  $value  The value of the property.
@param null    $extra  !important or null

@return array          The prefixed rules to replace the 'align-content' rule.

Properly prefixes the align - content property .


protected function prefixAlignSelf( $value, $extra = null )
  {
    $prop = array(
        '-webkit-align-self',
        '-ms-flex-item-align',
        'align-self'
    );

    $val[] = $value;
    switch( $value )
    {
      case 'flex-start':
        $val[] = 'start';
        break;
      case 'flex-end':
        $val[] = 'end';
        break;
      default:
        $val[] = $value;
        break;
    }

    $val[] = $value;

    return $this->getPrefixRules( $prop, $val, $extra );
  }

protected function prefixAlignSelf ( $ value , $ extra = null ) { $ prop = array ( '-webkit-align-self' , '-ms-flex-item-align' , 'align-self' ) ; $ val [ ] = $ value ; switch ( $ value ) { case 'flex-start' : $ val [ ] = 'start' ; break ; case 'flex-end' : $ val [ ] = 'end' ; break ; default : $ val [ ] = $ value ; break ; } $ val [ ] = $ value ; return $ this -> getPrefixRules ( $ prop , $ val , $ extra ) ; }

Properly prefixes the 'align-self' property.

@param string  $value  The value of the property.
@param null    $extra  !important or null

@return array          The prefixed rules to replace the 'align-self' rule.

Properly prefixes the align - self property .


protected function prefixFlex( $value, $extra = null )
  {
    $parts = explode( " ", $value );
    if( count( $parts ) == 3 )
    {
      // Make sure there's a % after the basis to avoid IE10/11 Bugs.
      // 0px does not work because a minifier would remove it.
      //
      // https://github.com/philipwalton/flexbugs#4-flex-shorthand-declarations-with-unitless-flex-basis-values-are-ignored
      if( $parts[ 2 ] === 0 || $parts[ 2 ] === '0px' )
      {
        $parts[ 2 ] = '0%';
      }
    }

    $prop = array( '-webkit-flex', '-ms-flex', 'flex' );
    $val  = implode( ' ', $parts );

    return $this->getPrefixRules( $prop, $val, $extra );
  }

Properly prefixes the 'flex' property & value.

@param string  $value  The value of the property.
@param null    $extra  !important or null

@return array          The prefixed rules to replace the 'flex' rule.

Properly prefixes the flex property & value .


protected function prefixJustifyContent( $value, $extra = null )
  {
    $prop = array(
        '-webkit-justify-content',
        '-ms-flex-pack',
        'justify-content'
    );

    $val[] = $value;
    switch( $value )
    {
      case 'flex-start':
        $val[] = 'start';
        break;
      case 'flex-end':
        $val[] = 'end';
        break;
      case 'space-between':
        $val[] = 'justify';
        break;
      case 'space-around':
        $val[] = 'distribute';
        break;
      default:
        $val[] = $value;
    }
    $val[] = $value;

    return $this->getPrefixRules( $prop, $val, $extra );
  }

protected function prefixJustifyContent ( $ value , $ extra = null ) { $ prop = array ( '-webkit-justify-content' , '-ms-flex-pack' , 'justify-content' ) ; $ val [ ] = $ value ; switch ( $ value ) { case 'flex-start' : $ val [ ] = 'start' ; break ; case 'flex-end' : $ val [ ] = 'end' ; break ; case 'space-between' : $ val [ ] = 'justify' ; break ; case 'space-around' : $ val [ ] = 'distribute' ; break ; default : $ val [ ] = $ value ; } $ val [ ] = $ value ; return $ this -> getPrefixRules ( $ prop , $ val , $ extra ) ; }

Properly prefixes the 'justify-content' property.

@param string  $value  The value of the property.
@param null    $extra  !important or null

@return array          The prefixed rules to replace the 'justify-content' rule.

Properly prefixes the justify - content property .


private function getPrefixRules( $prop, $val, $extra = null )
  {
    $extra = ( empty( $extra ) ) ? null : ' ' . $extra;
    if( !is_array( $prop ) && is_array( $val ) )
    {
      $properties = array_fill( 0, count( $val ), $prop );
      $values     = $val;
    }
    elseif( !is_array( $val ) && is_array( $prop ) )
    {
      $values     = array_fill( 0, count( $prop ), $val );
      $properties = $prop;
    }
    else
    {
      $properties = $prop;
      $values     = $val;
    }

    $property = null;
    $value    = null;
    do
    {
      $property = ( !empty( $properties ) ) ? array_shift( $properties ) : $property;
      $value    = ( !empty( $values ) ) ? array_shift( $values ) : $property;

      $rules[] = new CssRule( $property, $value, $extra );
    }
    while( !empty( $properties ) && !empty( $values ) );

    return $rules;
  }

private
function
getPrefixRules
(
$
prop
,
$
val
,
$
extra
=
)
{
$
extra
=
(
empty
(
$
extra
)
)
:
' '
.
$
extra
;
if
(
!
is_array
(
$
prop
)
&&
is_array
(
$
val
)
)
{
$
properties
=
array_fill
(
0
,
count
(
$
val
)
,
$
prop
)
;
$
values
=
$
val
;
}
elseif
(
!
is_array
(
$
val
)
&&
is_array
(
$
prop
)
)
{
$
values
=
array_fill
(
0
,
count
(
$
prop
)
,
$
val
)
;
$
properties
=
$
prop
;
}
else
{
$
properties
=
$
prop
;
$
values
=
$
val
;
}
$
property
=
;
$
value
=
;
do
{
$
property
=
(
!
empty
(
$
properties
)
)
array_shift
(
$
properties
)
:
$
property
;
$
value
=
(
!
empty
(
$
values
)
)
array_shift
(
$
values
)
:
$
property
;
$
rules
[
]
=
new
CssRule
(
$
property
,
$
value
,
$
extra
)
;
}
while
(
!
empty
(
$
properties
)
&&
!
empty
(
$
values
)
)
;
return
$
rules
;
}

Interpets the given parameters into a set of CSS rules to insert in replacement of the rule being evaluated.

The number of properties and values given will be matched up to the other.  For instance, if one property
is given, it will be duplicated to match the count of the number of values given and vice versa.

@param array|string         $prop    The property or properties to use with the rules.
@param array|string|float   $val     The value or values to use with the rules.
@param string               $extra   Any extra additions to the rules, such as !important

@return array                        The CSS rules to insert

Interpets the given parameters into a set of CSS rules to insert in replacement of the rule being evaluated .


public function Comment($media_id, $comment)
    {
        $this->AddParam('text', $comment);
        return $this->Post($this->buildUrl($media_id . '/comments'));
    }

public function Comment ( $ media_id , $ comment ) { $ this -> AddParam ( 'text' , $ comment ) ; return $ this -> Post ( $ this -> buildUrl ( $ media_id . '/comments' ) ) ; }

Adds a comment to a particular media
@access public
@param int $media_id A media ID
@param string $comment The text of the comment
@param string $token An access token
@return Response


protected function Delete($url = null, $params = array())
    {
        if (empty($url))
            trigger_error('A URL is required in ' . __METHOD__, E_USER_ERROR);

		if (!empty($params))
			$this->AddParams($params);

        return $this->request->Delete($url, array_merge($this->default_params, $this->parameters))->response;
    }

protected
function
Delete
(
$
url
=
,
$
params
=
array
(
)
)
{
if
(
empty
(
$
url
)
)
trigger_error
(
'A URL is required in '
.
__METHOD__
,
E_USER_ERROR
)
;
if
(
!
empty
(
$
params
)
)
$
this
->
AddParams
(
$
params
)
;
return
$
this
->
request
->
Delete
(
$
url
,
array_merge
(
$
this
->
default_params
,
$
this
->
parameters
)
)
->
response
;
}

A convenience method for making DELETE requests via the request object
@access protected
@param string $url A url in which to make a DELETE request
@param Array $params An associative array of key/value pairs to pass to the API
@return Response


function getFilteredMedia(array $filters, $allowPlaceholder = true)
    {
        $col = [];
        foreach($this['media'] as $medium) {
            if (!isset($hasImage) && $medium['type'] == 'image') {
                $hasImage = true;
            }
            if (in_array($medium['type'], $filters)) {
                $col[] = $medium;
            }
        }

        // Add a placeholder if the image type was requested, and no images were found.
        if (in_array('image', $filters)
            && !isset($hasImage)
            && $allowPlaceholder
            && $this->getPlaceholder()) {
            $col[] = $this->getPlaceholder();
        }

        return $col;
    }

Filter media by types

@param array $filters    image|video|document|audio|other(binary attachments)


function getPreferredImage($aspect = null, $orientation = null)
    {
        // If theres no images, check for placeholders
        if (!$this->getFilteredMedia(['image'], false)) {
            if ($ph = $this->getPlaceholder()) {
                if ($aspect) {
                    return $ph['meta']['src'][$aspect];
                }
                return $ph;
            }
            return null;
        }

        if ($this->hasPreferredImage()) {
            $medium = $this->getMedium($this['meta']['media']['preferred_image']);
        }
        elseif ($orientation) {
            $medium = $this->getPreferredImageByOrientation($orientation);
        }
        else {
            $medium = $this['media'][0];
        }

        if ($aspect) {
            return $medium['meta']['src'][$aspect];
        }
        return $medium;
    }

If there is a preferred image this one will be returned. If not, the first one of the
collection will be returned.

If an $orientation is passed, @getPreferredImageByOrientation will be called as a fallback, this will allow
alot less boilerplate code in sitations where you might want the user' favourite image as the highest priority,
but the best fitting alternative to a certain orientation, if not.

F.e.: A large header image:

getPreferredImage('1080p', 'landscape')          Get the user-preferred image, and return the url to the source
of the '1080' format. Or give me the image that best fits the
'landscape' aspect. And if there is no image found at all, give me
a placeholder if possible.

NB: Falls back to placeholders

@param null $aspect                              Return the src string instead of the medium array
@param string|null $orientation                  portrait|landscape|null

@return null|string|array

If there is a preferred image this one will be returned . If not the first one of the collection will be returned .


function getPlaceholder($index = null)
    {
        if (!isset($this['meta']['media']['placeholder'])) {
            return null;
        }
        if (!$this->placeholder_pick) {
            $this->placeholder_pick = rand(0, count($this['meta']['media']['placeholder']) - 1);
        }
        return $this['meta']['media']['placeholder'][$index ?: $this->placeholder_pick];
    }

function getPlaceholder ( $ index = null ) { if ( ! isset ( $ this [ 'meta' ] [ 'media' ] [ 'placeholder' ] ) ) { return null ; } if ( ! $ this -> placeholder_pick ) { $ this -> placeholder_pick = rand ( 0 , count ( $ this [ 'meta' ] [ 'media' ] [ 'placeholder' ] ) - 1 ) ; } return $ this [ 'meta' ] [ 'media' ] [ 'placeholder' ] [ $ index ? : $ this -> placeholder_pick ] ; }

Multiple placeholders can be set for a specific content-type, keep in mind that one will be
set for this session. Server-side relating a specific random placeholder as a preferred one is a WIP.

Multiple placeholders can be set for a specific content - type keep in mind that one will be set for this session . Server - side relating a specific random placeholder as a preferred one is a WIP .


public static function fromString( $string )
  {
    if( preg_match( '#(\s+)?([^:]+):([^!;]+)([^;]+)?#', trim( $string, "\n\r" ), $matches ) )
    {
      $rule = new self();
      $rule
          ->setRaw($string)
          ->setProperty( ( !empty( $matches[ 2 ] ) ) ? trim( $matches[ 2 ] ) : null )
          ->setValue( ( !empty( $matches[ 3 ] ) ) ? trim( $matches[ 3 ] ) : null )
          ->setBang( ( !empty( $matches[ 4 ] ) ) ? trim( $matches[ 4 ] ) : null )
          ->setIndent( ( isset( $matches[ 1 ] ) ) ? strlen( $matches[ 1 ] ) : 0 )
      ;

      // Replace Property in Template
      $pattern  = "#(" . preg_quote( $rule->getProperty(), "#" ) . "([\s:]+))#";

      $template = preg_replace( $pattern, "%s$2", $matches[ 0 ] . ';' );

      // Replace Value in Template
      $pattern = "#(:([\s]+))" . preg_quote( $rule->getValue(), "#" ) . "#";
      $template = preg_replace(  $pattern, "$1%s", $template );

      // Replace Bang in Template
      $pattern  = "#([^!]+)" . preg_quote($rule->getBang(), "#") . ";#";
      $template = preg_replace( $pattern, "$1%s;", $template );

      return $rule->setTemplate( $template );
    }

    return null;
  }

public
static
function
fromString
(
$
string
)
{
if
(
preg_match
(
'#(\s+)?([^:]+):([^!;]+)([^;]+)?#'
,
trim
(
$
string
,
"\n\r"
)
,
$
matches
)
)
{
$
rule
=
new
self
(
)
;
$
rule
->
setRaw
(
$
string
)
->
setProperty
(
(
!
empty
(
$
matches
[
2
]
)
)
trim
(
$
matches
[
2
]
)
:
)
->
setValue
(
(
!
empty
(
$
matches
[
3
]
)
)
trim
(
$
matches
[
3
]
)
:
)
->
setBang
(
(
!
empty
(
$
matches
[
4
]
)
)
trim
(
$
matches
[
4
]
)
:
)
->
setIndent
(
(
isset
(
$
matches
[
1
]
)
)
strlen
(
$
matches
[
1
]
)
:
0
)
;
// Replace Property in Template
$
pattern
=
"#("
.
preg_quote
(
$
rule
->
getProperty
(
)
,
"#"
)
.
"([\s:]+))#"
;
$
template
=
preg_replace
(
$
pattern
,
"%s$2"
,
$
matches
[
0
]
.
';'
)
;
// Replace Value in Template
$
pattern
=
"#(:([\s]+))"
.
preg_quote
(
$
rule
->
getValue
(
)
,
"#"
)
.
"#"
;
$
template
=
preg_replace
(
$
pattern
,
"$1%s"
,
$
template
)
;
// Replace Bang in Template
$
pattern
=
"#([^!]+)"
.
preg_quote
(
$
rule
->
getBang
(
)
,
"#"
)
.
";#"
;
$
template
=
preg_replace
(
$
pattern
,
"$1%s;"
,
$
template
)
;
return
$
rule
->
setTemplate
(
$
template
)
;
}
return
;
}

Create a CssRule object from an existing CSS string.

@param string $string

@return null|CssRule

Create a CssRule object from an existing CSS string .


public function getOutput()
  {
    return sprintf( $this->getTemplate(), $this->getProperty(), $this->getValue(), $this->getBang() );
  }

public function getOutput ( ) { return sprintf ( $ this -> getTemplate ( ) , $ this -> getProperty ( ) , $ this -> getValue ( ) , $ this -> getBang ( ) ) ; }

The properly formatted CSS rule.
@return string


public static function getEloquentReflectionMethod($object, string $method)
    {
        if ($object instanceof Builder) {

            if (method_exists(Model::class, $method)) {
                return new ReflectionMethod(Model::class, $method);
            } elseif (method_exists(Query::class, $method)) {
                return new ReflectionMethod(Query::class, $method);
            }

        } elseif ($object instanceof Model) {

            if (method_exists(Builder::class, $method)) {
                return new ReflectionMethod(Builder::class, $method);
            } elseif (method_exists(Query::class, $method)) {
                return new ReflectionMethod(Query::class, $method);
            }

        }

        // scoping is one of the ways custom methods are magically called.
        if (substr($method, 0, 5) !== "scope") {
            return static::getEloquentReflectionMethod($object, "scope" . ucfirst($method));
        }

        return false;
    }

Checks Eloquent-specific method resolution methods.

@throws \ReflectionException

@param $object
@param $method
@return bool|\ReflectionMethod

Checks Eloquent - specific method resolution methods .


public function indexAction(Request $request)
    {
        $registry = $this->get('ekyna_sitemap.provider_registry');
        $sitemaps = [];

        $lastUpdateDate = null;
        foreach($registry->getSitemaps() as $sitemap) {
            $providers = $registry->getProvidersBySitemap($sitemap);
            $sitemapLastUpdateDate = null;
            /** @var \Ekyna\Bundle\SitemapBundle\Provider\ProviderInterface $provider */
            foreach ($providers as $provider) {
                if (null === $sitemapLastUpdateDate || $sitemapLastUpdateDate < $provider->getLastUpdateDate()) {
                    $sitemapLastUpdateDate = $provider->getLastUpdateDate();
                }
            }
            $sitemaps[$sitemap] = $sitemapLastUpdateDate;
            if (null === $lastUpdateDate || $lastUpdateDate < $sitemapLastUpdateDate) {
                $lastUpdateDate = $sitemapLastUpdateDate;
            }
        }

        $response = new Response();
        $response->setLastModified($lastUpdateDate);
        $response->setPublic();
        if ($response->isNotModified($request)) {
            return $response;
        }
        $response->setMaxAge($this->container->getParameter('ekyna_sitemap.index_ttl'));
        $response->headers->add(['Content-Type' => 'application/xml; charset=UTF-8']);

        return $response->setContent($this->renderView('EkynaSitemapBundle:Sitemap:index.xml.twig', [
            'sitemaps' => $sitemaps,
        ]));
    }

Renders the sitemaps index.

@param Request $request
@return Response


public function sitemapAction(Request $request)
    {
        $sitemap = $request->attributes->get('sitemap', null);

        $registry = $this->get('ekyna_sitemap.provider_registry');
        $providers = $registry->getProvidersBySitemap($sitemap);

        if (0 === count($providers)) {
            throw new NotFoundHttpException('Sitemap not found.');
        }

        $lastUpdateDate = null;
        /** @var \Ekyna\Bundle\SitemapBundle\Provider\ProviderInterface $provider */
        foreach($providers as $provider) {
            if (null === $lastUpdateDate || $lastUpdateDate < $provider->getLastUpdateDate()) {
                $lastUpdateDate = $provider->getLastUpdateDate();
            }
        }

        $response = new Response();
        $response->setLastModified($lastUpdateDate);
        $response->setPublic();
        if ($response->isNotModified($request)) {
            return $response;
        }
        $response->setMaxAge($this->container->getParameter('ekyna_sitemap.sitemap_ttl'));
        $response->headers->add(['Content-Type' => 'application/xml; charset=UTF-8']);

        return $response->setContent($this->renderView('EkynaSitemapBundle:Sitemap:sitemap.xml.twig', [
            'providers' => $providers,
        ]));
    }

Renders the sitemap.

@param Request $request
@return Response


function &getTree()
    {
        // load xml and check if it turns a valid object. TODO: it will throw error.
        /* $xml = simplexml_load_file($this->data);
          if (!$xml) {
          echo 'invalid xml file '.$this->data; exit;
          } */
        //$parser = xml_parser_create('ISO-8859-1');
        $parser = xml_parser_create('');
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($parser, $this->data, $vals, $index);
        xml_parser_free($parser);

        $i = -1;
        return $this->getchildren($vals, $i);
    }

Then, coerce that into a simple nested array.

Then coerce that into a simple nested array .


public function isValidRequest($headerOnly = true, $accessToken = null)
    {
        $accessTokenString = ($accessToken !== null)
                                ? $accessToken
                                : $this->determineAccessToken($headerOnly);

        // Set the access token
        $this->accessToken = $this->getAccessTokenStorage()->get($accessTokenString);

        // Ensure the access token exists
        if (!$this->accessToken instanceof AccessTokenEntity) {
            throw new AccessDeniedException();
        }

        // Check the access token hasn't expired
        // Ensure the auth code hasn't expired
        if ($this->accessToken->isExpired() === true) {
            throw new AccessDeniedException();
        }

        return true;
    }

Checks if the access token is valid or not

@param bool                                                $headerOnly Limit Access Token to Authorization header
@param \OAuth2\Server\Entity\AccessTokenEntity|null $accessToken Access Token

@throws \OAuth2\Server\Exception\AccessDeniedException
@throws \OAuth2\Server\Exception\InvalidRequestException

@return bool


public function determineAccessToken($headerOnly = FALSE)
    {
		switch ($headerOnly){
			case FALSE:
				$accessToken = $this->requestHandler->getParam($this->tokenKey);
				if ($accessToken !== null){
					break;
				}
			case TRUE:
				$tokenType = $this->getTokenType();
				if (strrpos(get_class($tokenType),"Bearer") !== FALSE){
					$accessToken = $tokenType->determineAccessTokenInHeader($this->requestHandler,$this->authHeader);
				}else{
					$accessToken = $tokenType->determineAccessTokenInHeader($this->requestHandler);
				}
				break;
		}

        if (empty($accessToken)) {
            throw new InvalidRequestException('access token');
        }

        return $accessToken;
    }

public
function
determineAccessToken
(
$
headerOnly
=
FALSE
)
{
switch
(
$
headerOnly
)
{
case
FALSE
:
$
accessToken
=
$
this
->
requestHandler
->
getParam
(
$
this
->
tokenKey
)
;
if
(
$
accessToken
!==
)
{
break
;
}
case
TRUE
:
$
tokenType
=
$
this
->
getTokenType
(
)
;
if
(
strrpos
(
get_class
(
$
tokenType
)
,
"Bearer"
)
!==
FALSE
)
{
$
accessToken
=
$
tokenType
->
determineAccessTokenInHeader
(
$
this
->
requestHandler
,
$
this
->
authHeader
)
;
}
else
{
$
accessToken
=
$
tokenType
->
determineAccessTokenInHeader
(
$
this
->
requestHandler
)
;
}
break
;
}
if
(
empty
(
$
accessToken
)
)
{
throw
new
InvalidRequestException
(
'access token'
)
;
}
return
$
accessToken
;
}

Reads in the access token from the headers

@param bool $headerOnly Limit Access Token to Authorization header

@throws \OAuth2\Server\Exception\InvalidRequestException Thrown if there is no access token presented

@return string


public function call(
        string $method,
        array &$arguments = [],
        string $callType = Caller::TYPE_DEFAULT,
        $result = null,
        bool $catchHalt = true
    ) {
        $done = false;
        $this->each(function ($middleware, $key) use (&$done, &$method, &$arguments, $callType, &$result, $catchHalt) {
            if ($done) {
                return;
            }

            $before = $result;
            if ($result === null && $middleware instanceof MiddlewareInterface) {
                $context = $middleware->getContext();
                if (is_object($context)) {
                    $result = $context;
                    $before = clone $context;
                }
            }

            if ($method) {
                if ($middleware instanceof static) {
                    $result = $middleware->call($method, $arguments, $callType, $result, $catchHalt);
                } elseif ($middleware) {
                    $result = (new Caller($middleware, $result))
                        ->as($callType)
                        ->catch($catchHalt)
                        ->call($method, $arguments);
                }
            }

            if ($this->callContextChanged($callType, $before, $result)) {
                $done = true;
            }
        });
        return $result;
    }

public function call ( string $ method , array & $ arguments = [ ] , string $ callType = Caller :: TYPE_DEFAULT , $ result = null , bool $ catchHalt = true ) { $ done = false ; $ this -> each ( function ( $ middleware , $ key ) use ( & $ done , & $ method , & $ arguments , $ callType , & $ result , $ catchHalt ) { if ( $ done ) { return ; } $ before = $ result ; if ( $ result === null && $ middleware instanceof MiddlewareInterface ) { $ context = $ middleware -> getContext ( ) ; if ( is_object ( $ context ) ) { $ result = $ context ; $ before = clone $ context ; } } if ( $ method ) { if ( $ middleware instanceof static ) { $ result = $ middleware -> call ( $ method , $ arguments , $ callType , $ result , $ catchHalt ) ; } elseif ( $ middleware ) { $ result = ( new Caller ( $ middleware , $ result ) ) -> as ( $ callType ) -> catch ( $ catchHalt ) -> call ( $ method , $ arguments ) ; } } if ( $ this -> callContextChanged ( $ callType , $ before , $ result ) ) { $ done = true ; } } ) ; return $ result ; }

Sends the method call to each item.

@param string $method
@param array $arguments
@param string $result
@param bool $catchHalt
@return mixed


protected function callContextChanged(string $type, $before, $after): bool
    {
        $before = is_object($before) ? get_class($before) : "";
        $after = is_object($after) ? get_class($after) : "";

        return $type === Caller::TYPE_CALLER && $before && $after && $before !== $after;
    }

protected function callContextChanged ( string $ type , $ before , $ after ) : bool { $ before = is_object ( $ before ) ? get_class ( $ before ) : "" ; $ after = is_object ( $ after ) ? get_class ( $ after ) : "" ; return $ type === Caller :: TYPE_CALLER && $ before && $ after && $ before !== $ after ; }

Compares the type against the before and after results to determine if a call from the "methods"
type changed the context before the next middleware class could access it.

@param string $type
@param mixed $before
@param mixed $after
@return bool

Compares the type against the before and after results to determine if a call from the methods type changed the context before the next middleware class could access it .


protected function storeCommand(CommandInterface $command)
    {
        $priority = $command->getPriority();

        for ($count = count($this->commands), $i = 0; $i < $count; $i++) {
            if ($this->commands[$i]->getPriority() < $priority) {
                array_splice($this->commands, $i, 0, [
                    $command
                ]);

                return $command;
            }
        }

        return $this->commands[] = $command;
    }

protected function storeCommand ( CommandInterface $ command ) { $ priority = $ command -> getPriority ( ) ; for ( $ count = count ( $ this -> commands ) , $ i = 0 ; $ i < $ count ; $ i ++ ) { if ( $ this -> commands [ $ i ] -> getPriority ( ) < $ priority ) { array_splice ( $ this -> commands , $ i , 0 , [ $ command ] ) ; return $ command ; } } return $ this -> commands [ ] = $ command ; }

Queues a command according to it's priority.

@param CommandInterface $command
@return CommandInterface

Queues a command according to it s priority .


protected function performExecution(callable $callback)
    {
        $this->executionDepth++;

        $count = $this->executionCount;
        $this->executionCount = 0;

        $this->debug('BEGIN execution (depth: {depth})', [
            'depth' => $this->executionDepth
        ]);

        try {
            $result = $callback();
        } finally {
            $this->debug('END execution (depth: {depth}), {count} commands executed', [
                'depth' => $this->executionDepth,
                'count' => $this->executionCount
            ]);

            $this->executionCount = $count;
            $this->executionDepth--;
        }

        $this->syncExecutions();

        return $result;
    }

Triggers the given callback, can be extended in order to wrap interceptors around execution of commands.

Be sure to call the parent method when you override this method!

Keep in mind that nested executions are allowed and need to be dealt with when implementing
features such as transaction handling.

@param callable $callback This callback triggers the actual execution of commands!
@return mixed Result of an execution, not relevant when only pushing commands.

Triggers the given callback can be extended in order to wrap interceptors around execution of commands .


public function get($ph)
    {
        if (isset($this->phs[$ph])) {
            return $this->phs[$ph];
        }

        return null;
    }

public function get ( $ ph ) { if ( isset ( $ this -> phs [ $ ph ] ) ) { return $ this -> phs [ $ ph ] ; } return null ; }

Get global placeholder

@param string $ph
@return mixed|null


public function create($phar_path = 'environaut.phar')
    {
        if (file_exists($phar_path)) {
            unlink($phar_path);
        }

        $phar = new \Phar($phar_path, 0, 'environaut.phar');

        $phar->setSignatureAlgorithm(\Phar::SHA1);

        $phar->startBuffering();

        $root_dir = dirname(dirname(__DIR__));

        // add environaut files
        $finder = new Finder();

        $finder->files()->notName('PharCompiler.php')->in($root_dir . '/src');

        foreach ($finder as $file) {
            $phar->addFile($file->getRealPath(), 'src/' . $file->getRelativePathname());
        }

        // add vendor files using a whitelist with excludes
        $finder = new Finder();
        $finder->files()
            ->name('*.php')
            ->name('security\.sensiolabs\.org\.crt')
            ->path('/symfony\/console\//')
            ->path('/sensiolabs\/security-checker\//')
            ->notName('SecurityCheckerCommand.php')
            ->notPath('/(\/Tests\/|\/Tester\/)/')
            ->in($root_dir . '/vendor');

        foreach ($finder as $file) {
            $phar->addFile($file->getRealPath(), 'vendor/' . $file->getRelativePathname());
        }

        // add composer vendor autoloading
        $vendor_root_dir = $root_dir . '/vendor/';
        $phar->addFile($vendor_root_dir . 'autoload.php', 'vendor/autoload.php');
        $composer_dir = $vendor_root_dir . 'composer/';
        $phar->addFile($composer_dir . 'autoload_namespaces.php', 'vendor/composer/autoload_namespaces.php');
        $phar->addFile($composer_dir . 'autoload_classmap.php', 'vendor/composer/autoload_classmap.php');
        $phar->addFile($composer_dir . 'autoload_psr4.php', 'vendor/composer/autoload_psr4.php');
        $phar->addFile($composer_dir . 'autoload_real.php', 'vendor/composer/autoload_real.php');
        //$phar->addFile($composer_dir . 'include_paths.php', 'vendor/composer/include_paths.php');
        $phar->addFile($composer_dir . 'ClassLoader.php', 'vendor/composer/ClassLoader.php');

        // environaut executable
        $phar->addFile($root_dir . '/bin/environaut', 'bin/environaut');

        // additional markdown files like README.md or LICENSE.md
        $finder = new Finder();
        $finder->files()->name('*.md')->depth('== 0')->in($root_dir);
        foreach ($finder as $file) {
            $phar->addFile($file->getRealPath(), '/' . $file->getRelativePathname());
        }

        // add startup file
        $phar->setStub($this->getStub());

        $phar->stopBuffering();

        chmod($phar_path, 0755);
    }

Creates a PHP archive file with all files necessary to
run Environaut standalone.

@param string $phar_path full path to the php archive file to create

Creates a PHP archive file with all files necessary to run Environaut standalone .


public static function getPattern(string $name): ?string
    {
        if( array_key_exists($name, static::$patterns) ){
            return static::$patterns[$name];
        }

        return null;
    }

public static function getPattern ( string $ name ) : ? string { if ( array_key_exists ( $ name , static :: $ patterns ) ) { return static :: $ patterns [ $ name ] ; } return null ; }

Get a regex pattern by name

@param string $name
@return string|null


protected function mergeGroupConfig(array $groupConfig): array
    {
        $config = $this->config;

        $config['hostname'] = $groupConfig['hostname'] ?? null;
        $config['prefix'] = $groupConfig['prefix'] ?? null;
        $config['namespace'] = $groupConfig['namespace'] ?? null;

        if( array_key_exists('middleware', $groupConfig) ){

            if( array_key_exists('middleware', $config) ){
                $config['middleware'] = array_merge($config['middleware'], $groupConfig['middleware']);
            }

            else {
                $config['middleware'] = $groupConfig['middleware'];
            }
        }

        return $config;
    }

protected function mergeGroupConfig ( array $ groupConfig ) : array { $ config = $ this -> config ; $ config [ 'hostname' ] = $ groupConfig [ 'hostname' ] ?? null ; $ config [ 'prefix' ] = $ groupConfig [ 'prefix' ] ?? null ; $ config [ 'namespace' ] = $ groupConfig [ 'namespace' ] ?? null ; if ( array_key_exists ( 'middleware' , $ groupConfig ) ) { if ( array_key_exists ( 'middleware' , $ config ) ) { $ config [ 'middleware' ] = array_merge ( $ config [ 'middleware' ] , $ groupConfig [ 'middleware' ] ) ; } else { $ config [ 'middleware' ] = $ groupConfig [ 'middleware' ] ; } } return $ config ; }

Merge parent route Group configs in with child group.

@param array<string> $groupConfig
@return array

Merge parent route Group configs in with child group .


public static function removeRecord($dataObj, $recArr, &$isParentObjUpdated)
    {
        if ($dataObj->association["Relationship"] == "M-M") {
            $isParentObjUpdated = false;
            return self::_removeRecordMtoM($dataObj, $recArr);
        } elseif ($dataObj->association["Relationship"] == "Self-Self") {
            $isParentObjUpdated = false;
            return self::_removeRecordSelftoSelf($dataObj, $recArr);
        } elseif ($dataObj->association["Relationship"] == "M-1" || $dataObj->association["Relationship"] == "1-1") {
            $isParentObjUpdated = true;
            return self::_removeRecordMto1($dataObj, $recArr);
        } elseif ($dataObj->association["Relationship"] == "1-M") {
            $isParentObjUpdated = false;
            return self::_removeRecord1toM($dataObj, $recArr);
        } else {
            throw new Openbizx\Data\Exception("You cannot add a record in dataobj who doesn't have M-M or M-1 or Self-Self relationship with its parent object");
            return false;
        }
    }

Remove a record from current record set of current association relationship

@param BizDataObj $dataObj - the instance of BizDataObj
@param array $recArr - the record array to be removed from the data object
@param boolean &$isParentObjUpdated - flag that indicates if the parent form needs to be updated
@return boolean