idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
48,400
protected function getStatus ( $ response , $ isRedirect ) { if ( $ isRedirect ) { return new Status ( 'pending' ) ; } if ( isset ( $ response [ 'PAYMENTINFO_0_PAYMENTSTATUS' ] ) && $ response [ 'PAYMENTINFO_0_PAYMENTSTATUS' ] == 'Pending' ) { return new Status ( 'pending' ) ; } return new Status ( 'paid' ) ; }
Map PayPal response to status object .
48,401
protected function addAddress ( array $ params , array $ options ) { if ( $ address = Arr :: get ( $ options , 'address' ) ? : Arr :: get ( $ options , 'billing_address' ) ) { $ params [ 'address' ] [ 'street1' ] = Arr :: get ( $ address , 'address1' ) ; if ( $ address2 = Arr :: get ( $ address , 'address2' ) ) { $ params [ 'address' ] [ 'street2' ] = $ address2 ; } if ( $ address3 = Arr :: get ( $ address , 'address3' ) ) { $ params [ 'address' ] [ 'street3' ] = $ address3 ; } if ( $ externalNumber = Arr :: get ( $ address , 'external_number' ) ) { $ params [ 'address' ] [ 'external_number' ] = $ externalNumber ; } $ params [ 'address' ] [ 'city' ] = Arr :: get ( $ address , 'city' ) ; $ params [ 'address' ] [ 'country' ] = Arr :: get ( $ address , 'country' ) ; $ params [ 'address' ] [ 'state' ] = Arr :: get ( $ address , 'state' ) ; $ params [ 'address' ] [ 'postal_code' ] = Arr :: get ( $ address , 'zip' ) ; return $ params ; } }
Add address to request .
48,402
protected function addDiscountLines ( array $ params , array $ options ) { if ( isset ( $ options [ 'discount' ] ) ) { $ type = Arr :: get ( $ options , 'discount_type' ) ; if ( ! in_array ( $ type , [ 'loyalty' , 'campaign' , 'coupon' , 'sign' ] ) ) { $ type = 'loyalty' ; } $ code = Arr :: get ( $ options , 'discount_code' , '---' ) ; if ( strlen ( $ code ) < 3 ) { $ code .= str_repeat ( '-' , 3 - strlen ( $ code ) ) ; } $ params [ 'discount_lines' ] [ ] = [ 'type' => $ type , 'code' => $ code , 'amount' => $ options [ 'discount' ] , ] ; } return $ params ; }
Add order discount lines param .
48,403
protected function addBillingAddress ( array $ params , array $ options ) { if ( $ address = Arr :: get ( $ options , 'billing_address' ) && $ taxId = Arr :: get ( $ address , 'tax_id' ) && $ companyName = Arr :: get ( $ address , 'company_name' ) ) { $ addressFiltered = Arr :: filters ( [ 'street1' => Arr :: get ( $ address , 'address1' ) , 'street2' => Arr :: get ( $ address , 'address2' ) , 'street3' => Arr :: get ( $ address , 'address3' ) , 'external_number' => Arr :: get ( $ address , 'external_number' ) , 'city' => Arr :: get ( $ address , 'city' ) , 'country' => Arr :: get ( $ address , 'country' ) , 'state' => Arr :: get ( $ address , 'state' ) , 'postal_code' => Arr :: get ( $ address , 'zip' ) , ] ) ; if ( ! empty ( $ addressFiltered ) ) { $ params [ 'fiscal_entity' ] [ 'address' ] = $ addressFiltered ; } $ params [ 'fiscal_entity' ] [ 'phone' ] = Arr :: get ( $ address , 'phone' , Arr :: get ( $ options , 'phone' , 'none' ) ) ; $ params [ 'fiscal_entity' ] [ 'email' ] = Arr :: get ( $ address , 'email' , Arr :: get ( $ options , 'email' , 'none' ) ) ; $ params [ 'fiscal_entity' ] [ 'tax_id' ] = $ taxId ; $ params [ 'fiscal_entity' ] [ 'company_name' ] = $ companyName ; } return $ params ; }
Add Billing address to request .
48,404
protected function getStatus ( $ response ) { if ( isset ( $ response [ 'refunded' ] ) && $ response [ 'refunded' ] == true ) { return new Status ( 'refunded' ) ; } if ( ! isset ( $ response [ 'status' ] ) && ! isset ( $ response [ 'type' ] ) ) { return ; } $ status = isset ( $ response [ 'status' ] ) ? $ response [ 'status' ] : $ response [ 'type' ] ; switch ( $ status ) { case 'pending' : case 'charge.pending' : return new Status ( 'pending' ) ; case 'success' : case 'charge.success' : return new Status ( 'paid' ) ; case 'declined' : case 'charge.declined' : return new Status ( 'failed' ) ; case 'deleted' : case 'charge.deleted' : return new Status ( 'canceled' ) ; case 'expired' : case 'charge.expired' : return new Status ( 'voided' ) ; break ; } }
Map ComproPago response to status object .
48,405
public function addExtension ( ExtensionInterface $ extension ) { if ( ! in_array ( $ extension , $ this -> extensions ) ) { $ this -> extensions [ ] = $ extension ; $ options = Phug :: getExtensionsOptions ( [ $ extension ] ) ; foreach ( [ $ this , $ this -> getCompiler ( ) ] as $ instance ) { $ instance -> setOptionsRecursive ( $ options ) ; } $ this -> initCompiler ( ) ; } }
Plug an Phug extension to Pug .
48,406
public function setKeyword ( $ keyword , $ action ) { if ( ! is_callable ( $ action ) ) { throw new InvalidArgumentException ( "Please add a callable action for your keyword $keyword" , 30 ) ; } if ( ! $ this -> hasValidCustomKeywordsOption ( ) ) { $ this -> setOption ( 'keywords' , [ ] ) ; } if ( $ action instanceof ExtensionContainerInterface ) { $ this -> addExtension ( $ action -> getExtension ( ) ) ; } $ this -> setOption ( [ 'keywords' , $ keyword ] , $ action ) ; }
Set custom keyword .
48,407
public function addKeyword ( $ keyword , $ action ) { if ( $ this -> hasKeyword ( $ keyword ) ) { throw new InvalidArgumentException ( "The keyword $keyword is already set." , 31 ) ; } $ this -> setKeyword ( $ keyword , $ action ) ; }
Add custom keyword .
48,408
public function replaceKeyword ( $ keyword , $ action ) { if ( ! $ this -> hasKeyword ( $ keyword ) ) { throw new InvalidArgumentException ( "The keyword $keyword is not set." , 32 ) ; } $ this -> setKeyword ( $ keyword , $ action ) ; }
Replace custom keyword .
48,409
public function requirements ( $ name = null ) { $ requirements = [ 'cacheFolderExists' => ! $ this -> getDefaultOption ( 'cache_dir' ) || is_dir ( $ this -> getOption ( 'cache_dir' ) ) , 'cacheFolderIsWritable' => ! $ this -> getDefaultOption ( 'cache_dir' ) || is_writable ( $ this -> getOption ( 'cache_dir' ) ) , ] ; if ( $ name ) { if ( ! isset ( $ requirements [ $ name ] ) ) { throw new InvalidArgumentException ( $ name . ' is not in the requirements list (' . implode ( ', ' , array_keys ( $ requirements ) ) . ')' , 19 ) ; } return $ requirements [ $ name ] ; } return $ requirements ; }
Returns list of requirements in an array identified by keys . For each of them the value can be true if the requirement is fulfilled false else .
48,410
public function getNodeEngine ( ) { if ( ! $ this -> nodeEngine ) { $ this -> nodeEngine = new NodejsPhpFallback ( $ this -> hasOption ( 'node_path' ) ? $ this -> getDefaultOption ( 'node_path' ) : 'node' ) ; } return $ this -> nodeEngine ; }
Return the NodejsPhpFallback instance used to execute pug - cli via node .
48,411
public static function pugJsCacheCheck ( $ renderFile , $ filename , self $ pug ) { return file_exists ( $ renderFile ) && ( filemtime ( $ renderFile ) >= filemtime ( $ filename ) || ! $ pug -> getDefaultOption ( 'upToDateCheck' ) ) ; }
Returns true if the rendered file is up to date against the source .
48,412
public function renderWithPhp ( $ input , array $ vars , $ filename = null ) { return parent :: render ( $ input , $ vars , $ filename ) ; }
Render using the PHP engine .
48,413
public function renderString ( $ input , array $ vars = [ ] , $ filename = null ) { $ fallback = function ( ) use ( $ input , $ vars , $ filename ) { return $ this -> renderWithPhp ( $ input , $ vars , $ filename ) ; } ; if ( $ this -> getDefaultOption ( 'pugjs' ) ) { return $ this -> renderWithJs ( $ input , $ filename , $ vars , $ fallback ) ; } return call_user_func ( $ fallback ) ; }
Render HTML code from a Pug input string .
48,414
public function displayString ( $ input , array $ vars = [ ] , $ filename = null ) { if ( $ this -> getDefaultOption ( 'pugjs' ) ) { echo $ this -> renderString ( $ input , $ vars , $ filename ) ; return ; } parent :: display ( $ input , $ vars , $ filename ) ; }
Display HTML code from a Pug input string .
48,415
protected function log ( RequestInterface $ request , $ delay ) { if ( isset ( $ this -> logger ) ) { $ level = $ this -> getLogLevel ( $ request ) ; $ message = $ this -> getLogMessage ( $ request , $ delay ) ; $ context = compact ( 'request' , 'delay' ) ; $ this -> logger -> log ( $ level , $ message , $ context ) ; } }
Logs a request which is being delayed by a specified amount of time .
48,416
protected function getLogMessage ( RequestInterface $ request , $ delay ) { return vsprintf ( "[%s] %s %s will be delayed by {$delay}us" , [ gmdate ( 'd/M/Y:H:i:s O' ) , $ request -> getMethod ( ) , $ request -> getUri ( ) , ] ) ; }
Formats a request and delay time as a log message .
48,417
protected function getLogLevel ( RequestInterface $ request ) { if ( ! $ this -> logLevel ) { return $ this -> getDefaultLogLevel ( ) ; } if ( is_callable ( $ this -> logLevel ) ) { return call_user_func ( $ this -> logLevel , $ request ) ; } return ( string ) $ this -> logLevel ; }
Returns a log level for a given response .
48,418
protected function setAllowance ( RequestInterface $ request ) { return function ( ResponseInterface $ response ) use ( $ request ) { $ this -> provider -> setRequestAllowance ( $ request , $ response ) ; return $ response ; } ; }
Returns a callable handler which allows the provider to set the request allowance for the next request using the current response .
48,419
public function getRoute ( RequestInterface $ request ) { $ route = $ request -> getUri ( ) -> __toString ( ) ; if ( $ request -> getMethod ( ) === 'DELETE' && strpos ( $ request -> getUri ( ) , 'messages' ) !== false ) { $ route = 'DELETE-' . $ request -> getUri ( ) ; } return $ route ; }
Returns the route for the current URL .
48,420
function add ( $ Title , $ Description , $ ParentID = null ) { if ( $ ParentID === null ) $ ParentID = $ this -> rootId ( ) ; return ( int ) $ this -> { $ this -> type ( ) } -> insertChildData ( array ( "Title" => $ Title , "Description" => $ Description ) , "ID=?" , $ ParentID ) ; }
Adds a new role or permission Returns new entry s ID
48,421
function addPath ( $ Path , array $ Descriptions = null ) { if ( $ Path [ 0 ] !== "/" ) throw new \ Exception ( "The path supplied is not valid." ) ; $ Path = substr ( $ Path , 1 ) ; $ Parts = explode ( "/" , $ Path ) ; $ Parent = 1 ; $ index = 0 ; $ CurrentPath = "" ; $ NodesCreated = 0 ; foreach ( $ Parts as $ p ) { if ( isset ( $ Descriptions [ $ index ] ) ) $ Description = $ Descriptions [ $ index ] ; else $ Description = "" ; $ CurrentPath .= "/{$p}" ; $ t = $ this -> pathId ( $ CurrentPath ) ; if ( ! $ t ) { $ IID = $ this -> add ( $ p , $ Description , $ Parent ) ; $ Parent = $ IID ; $ NodesCreated ++ ; } else { $ Parent = $ t ; } $ index += 1 ; } return ( int ) $ NodesCreated ; }
Adds a path and all its components . Will not replace or create siblings if a component exists .
48,422
public function returnId ( $ entity = null ) { if ( substr ( $ entity , 0 , 1 ) == "/" ) { $ entityID = $ this -> pathId ( $ entity ) ; } else { $ entityID = $ this -> titleId ( $ entity ) ; } return $ entityID ; }
Returns ID of entity
48,423
public function pathId ( $ Path ) { $ Path = "root" . $ Path ; if ( $ Path [ strlen ( $ Path ) - 1 ] == "/" ) $ Path = substr ( $ Path , 0 , strlen ( $ Path ) - 1 ) ; $ Parts = explode ( "/" , $ Path ) ; $ Adapter = get_class ( Jf :: $ Db ) ; if ( $ Adapter == "mysqli" or ( $ Adapter == "PDO" and Jf :: $ Db -> getAttribute ( PDO :: ATTR_DRIVER_NAME ) == "mysql" ) ) { $ GroupConcat = "GROUP_CONCAT(parent.Title ORDER BY parent.Lft SEPARATOR '/')" ; } elseif ( $ Adapter == "PDO" and Jf :: $ Db -> getAttribute ( PDO :: ATTR_DRIVER_NAME ) == "sqlite" ) { $ GroupConcat = "GROUP_CONCAT(parent.Title,'/')" ; } else { throw new \ Exception ( "Unknown Group_Concat on this type of database: {$Adapter}" ) ; } $ res = Jf :: sql ( "SELECT node.ID,{$GroupConcat} AS Path FROM {$this->tablePrefix()}{$this->type()} AS node, {$this->tablePrefix()}{$this->type()} AS parent WHERE node.Lft BETWEEN parent.Lft AND parent.Rght AND node.Title=? GROUP BY node.ID HAVING Path = ? " , $ Parts [ count ( $ Parts ) - 1 ] , $ Path ) ; if ( $ res ) return $ res [ 0 ] [ 'ID' ] ; else return null ; $ QueryBase = ( "SELECT n0.ID \nFROM {$this->tablePrefix()}{$this->type()} AS n0" ) ; $ QueryCondition = "\nWHERE n0.Title=?" ; for ( $ i = 1 ; $ i < count ( $ Parts ) ; ++ $ i ) { $ j = $ i - 1 ; $ QueryBase .= "\nJOIN {$this->tablePrefix()}{$this->type()} AS n{$i} ON (n{$j}.Lft BETWEEN n{$i}.Lft+1 AND n{$i}.Rght)" ; $ QueryCondition .= "\nAND n{$i}.Title=?" ; $ QueryBase .= "\nLEFT JOIN {$this->tablePrefix()}{$this->type()} AS nn{$i} ON (nn{$i}.Lft BETWEEN n{$i}.Lft+1 AND n{$j}.Lft-1)" ; $ QueryCondition .= "\nAND nn{$i}.Lft IS NULL" ; } $ Query = $ QueryBase . $ QueryCondition ; $ PartsRev = array_reverse ( $ Parts ) ; array_unshift ( $ PartsRev , $ Query ) ; print_ ( $ PartsRev ) ; $ res = call_user_func_array ( "Jf::sql" , $ PartsRev ) ; if ( $ res ) return $ res [ 0 ] [ 'ID' ] ; else return null ; }
Returns ID of a path
48,424
function getPath ( $ ID ) { $ res = $ this -> { $ this -> type ( ) } -> pathConditional ( "ID=?" , $ ID ) ; $ out = null ; if ( is_array ( $ res ) ) foreach ( $ res as $ r ) if ( $ r [ 'ID' ] == 1 ) $ out = '/' ; else $ out .= "/" . $ r [ 'Title' ] ; if ( strlen ( $ out ) > 1 ) return substr ( $ out , 1 ) ; else return $ out ; }
Returns path of a node
48,425
function descendants ( $ ID ) { $ res = $ this -> { $ this -> type ( ) } -> descendantsConditional ( false , "ID=?" , $ ID ) ; $ out = array ( ) ; if ( is_array ( $ res ) ) foreach ( $ res as $ v ) $ out [ $ v [ 'Title' ] ] = $ v ; return $ out ; }
Returns descendants of a node with their depths in integer
48,426
function reset ( $ Ensure = false ) { if ( $ Ensure !== true ) { throw new \ Exception ( "You must pass true to this function, otherwise it won't work." ) ; return ; } $ res = Jf :: sql ( "DELETE FROM {$this->tablePrefix()}{$this->type()}" ) ; $ Adapter = get_class ( Jf :: $ Db ) ; if ( $ this -> isMySql ( ) ) Jf :: sql ( "ALTER TABLE {$this->tablePrefix()}{$this->type()} AUTO_INCREMENT=1 " ) ; elseif ( $ this -> isSQLite ( ) ) Jf :: sql ( "delete from sqlite_sequence where name=? " , $ this -> tablePrefix ( ) . "{$this->type()}" ) ; else throw new \ Exception ( "Rbac can not reset table on this type of database: {$Adapter}" ) ; $ iid = Jf :: sql ( "INSERT INTO {$this->tablePrefix()}{$this->type()} (Title,Description,Lft,Rght) VALUES (?,?,?,?)" , "root" , "root" , 0 , 1 ) ; return ( int ) $ res ; }
Reset the table back to its initial state Keep in mind that this will not touch relations
48,427
function resetAssignments ( $ Ensure = false ) { if ( $ Ensure !== true ) { throw new \ Exception ( "You must pass true to this function, otherwise it won't work." ) ; return ; } $ res = Jf :: sql ( "DELETE FROM {$this->tablePrefix()}rolepermissions" ) ; $ Adapter = get_class ( Jf :: $ Db ) ; if ( $ this -> isMySql ( ) ) Jf :: sql ( "ALTER TABLE {$this->tablePrefix()}rolepermissions AUTO_INCREMENT =1 " ) ; elseif ( $ this -> isSQLite ( ) ) Jf :: sql ( "delete from sqlite_sequence where name=? " , $ this -> tablePrefix ( ) . "_rolepermissions" ) ; else throw new \ Exception ( "Rbac can not reset table on this type of database: {$Adapter}" ) ; $ this -> assign ( $ this -> rootId ( ) , $ this -> rootId ( ) ) ; return $ res ; }
Remove all role - permission relations mostly used for testing
48,428
function check ( $ Permission , $ UserID = null ) { if ( $ UserID === null ) throw new \ RbacUserNotProvidedException ( "\$UserID is a required argument." ) ; if ( is_numeric ( $ Permission ) ) { $ PermissionID = $ Permission ; } else { if ( substr ( $ Permission , 0 , 1 ) == "/" ) $ PermissionID = $ this -> Permissions -> pathId ( $ Permission ) ; else $ PermissionID = $ this -> Permissions -> titleId ( $ Permission ) ; } if ( $ PermissionID === null ) throw new RbacPermissionNotFoundException ( "The permission '{$Permission}' not found." ) ; if ( $ this -> isSQLite ( ) ) { $ LastPart = "AS Temp ON ( TR.ID = Temp.RoleID) WHERE TUrel.UserID=? AND Temp.ID=?" ; } else { $ LastPart = "ON ( TR.ID = TRel.RoleID) WHERE TUrel.UserID=? AND TPdirect.ID=?" ; } $ Res = Jf :: sql ( "SELECT COUNT(*) AS Result FROM {$this->tablePrefix()}userroles AS TUrel JOIN {$this->tablePrefix()}roles AS TRdirect ON (TRdirect.ID=TUrel.RoleID) JOIN {$this->tablePrefix()}roles AS TR ON ( TR.Lft BETWEEN TRdirect.Lft AND TRdirect.Rght) JOIN ( {$this->tablePrefix()}permissions AS TPdirect JOIN {$this->tablePrefix()}permissions AS TP ON ( TPdirect.Lft BETWEEN TP.Lft AND TP.Rght) JOIN {$this->tablePrefix()}rolepermissions AS TRel ON (TP.ID=TRel.PermissionID) ) $LastPart" , $ UserID , $ PermissionID ) ; return $ Res [ 0 ] [ 'Result' ] >= 1 ; }
Checks whether a user has a permission or not .
48,429
function enforce ( $ Permission , $ UserID = null ) { if ( $ UserID === null ) throw new \ RbacUserNotProvidedException ( "\$UserID is a required argument." ) ; if ( ! $ this -> check ( $ Permission , $ UserID ) ) { header ( 'HTTP/1.1 403 Forbidden' ) ; die ( "<strong>Forbidden</strong>: You do not have permission to access this resource." ) ; } return true ; }
Enforce a permission on a user
48,430
function reset ( $ Ensure = false ) { if ( $ Ensure !== true ) { throw new \ Exception ( "You must pass true to this function, otherwise it won't work." ) ; return ; } $ res = true ; $ res = $ res and $ this -> Roles -> resetAssignments ( true ) ; $ res = $ res and $ this -> Roles -> reset ( true ) ; $ res = $ res and $ this -> Permissions -> reset ( true ) ; $ res = $ res and $ this -> Users -> resetAssignments ( true ) ; return $ res ; }
Remove all roles permissions and assignments mostly used for testing
48,431
function remove ( $ ID , $ Recursive = false ) { $ this -> unassignRoles ( $ ID ) ; if ( ! $ Recursive ) return $ this -> permissions -> deleteConditional ( "ID=?" , $ ID ) ; else return $ this -> permissions -> deleteSubtreeConditional ( "ID=?" , $ ID ) ; }
Remove permissions from system
48,432
function roles ( $ Permission , $ OnlyIDs = true ) { if ( ! is_numeric ( $ Permission ) ) $ Permission = $ this -> returnId ( $ Permission ) ; if ( $ OnlyIDs ) { $ Res = Jf :: sql ( "SELECT RoleID AS `ID` FROM {$this->tablePrefix()}rolepermissions WHERE PermissionID=? ORDER BY RoleID" , $ Permission ) ; if ( is_array ( $ Res ) ) { $ out = array ( ) ; foreach ( $ Res as $ R ) $ out [ ] = $ R [ 'ID' ] ; return $ out ; } else return null ; } else { return Jf :: sql ( "SELECT `TP`.ID, `TP`.Title, `TP`.Description FROM {$this->tablePrefix()}roles AS `TP` LEFT JOIN {$this->tablePrefix()}rolepermissions AS `TR` ON (`TR`.RoleID=`TP`.ID) WHERE PermissionID=? ORDER BY TP.ID" , $ Permission ) ; } }
Returns all roles assigned to a permission
48,433
function remove ( $ ID , $ Recursive = false ) { $ this -> unassignPermissions ( $ ID ) ; $ this -> unassignUsers ( $ ID ) ; if ( ! $ Recursive ) return $ this -> roles -> deleteConditional ( "ID=?" , $ ID ) ; else return $ this -> roles -> deleteSubtreeConditional ( "ID=?" , $ ID ) ; }
Remove roles from system
48,434
function hasPermission ( $ Role , $ Permission ) { $ Res = Jf :: sql ( " SELECT COUNT(*) AS Result FROM {$this->tablePrefix()}rolepermissions AS TRel JOIN {$this->tablePrefix()}permissions AS TP ON ( TP.ID= TRel.PermissionID) JOIN {$this->tablePrefix()}roles AS TR ON ( TR.ID = TRel.RoleID) WHERE TR.Lft BETWEEN (SELECT Lft FROM {$this->tablePrefix()}roles WHERE ID=?) AND (SELECT Rght FROM {$this->tablePrefix()}roles WHERE ID=?) /* the above section means any row that is a descendants of our role (if descendant roles have some permission, then our role has it two) */ AND TP.ID IN ( SELECT parent.ID FROM {$this->tablePrefix()}permissions AS node, {$this->tablePrefix()}permissions AS parent WHERE node.Lft BETWEEN parent.Lft AND parent.Rght AND ( node.ID=? ) ORDER BY parent.Lft ); /* the above section returns all the parents of (the path to) our permission, so if one of our role or its descendants has an assignment to any of them, we're good. */ " , $ Role , $ Role , $ Permission ) ; return $ Res [ 0 ] [ 'Result' ] >= 1 ; }
Checks to see if a role has a permission or not
48,435
function permissions ( $ Role , $ OnlyIDs = true ) { if ( ! is_numeric ( $ Role ) ) $ Role = $ this -> returnId ( $ Role ) ; if ( $ OnlyIDs ) { $ Res = Jf :: sql ( "SELECT PermissionID AS `ID` FROM {$this->tablePrefix()}rolepermissions WHERE RoleID=? ORDER BY PermissionID" , $ Role ) ; if ( is_array ( $ Res ) ) { $ out = array ( ) ; foreach ( $ Res as $ R ) $ out [ ] = $ R [ 'ID' ] ; return $ out ; } else return null ; } else { return Jf :: sql ( "SELECT `TP`.ID, `TP`.Title, `TP`.Description FROM {$this->tablePrefix()}permissions AS `TP` LEFT JOIN {$this->tablePrefix()}rolepermissions AS `TR` ON (`TR`.PermissionID=`TP`.ID) WHERE RoleID=? ORDER BY TP.ID" , $ Role ) ; } }
Returns all permissions assigned to a role
48,436
function assign ( $ Role , $ UserID = null ) { if ( $ UserID === null ) throw new \ RbacUserNotProvidedException ( "\$UserID is a required argument." ) ; if ( is_numeric ( $ Role ) ) { $ RoleID = $ Role ; } else { if ( substr ( $ Role , 0 , 1 ) == "/" ) $ RoleID = Jf :: $ Rbac -> Roles -> pathId ( $ Role ) ; else $ RoleID = Jf :: $ Rbac -> Roles -> titleId ( $ Role ) ; } $ res = Jf :: sql ( "INSERT INTO {$this->tablePrefix()}userroles (UserID,RoleID,AssignmentDate) VALUES (?,?,?) " , $ UserID , $ RoleID , Jf :: time ( ) ) ; return $ res >= 1 ; }
Assigns a role to a user
48,437
function unassign ( $ Role , $ UserID = null ) { if ( $ UserID === null ) throw new \ RbacUserNotProvidedException ( "\$UserID is a required argument." ) ; if ( is_numeric ( $ Role ) ) { $ RoleID = $ Role ; } else { if ( substr ( $ Role , 0 , 1 ) == "/" ) $ RoleID = Jf :: $ Rbac -> Roles -> pathId ( $ Role ) ; else $ RoleID = Jf :: $ Rbac -> Roles -> titleId ( $ Role ) ; } return Jf :: sql ( "DELETE FROM {$this->tablePrefix()}userroles WHERE UserID=? AND RoleID=?" , $ UserID , $ RoleID ) >= 1 ; }
Unassigns a role from a user
48,438
function roleCount ( $ UserID = null ) { if ( $ UserID === null ) throw new \ RbacUserNotProvidedException ( "\$UserID is a required argument." ) ; $ Res = Jf :: sql ( "SELECT COUNT(*) AS Result FROM {$this->tablePrefix()}userroles WHERE UserID=?" , $ UserID ) ; return ( int ) $ Res [ 0 ] [ 'Result' ] ; }
Return count of roles assigned to a user
48,439
function getID ( $ ConditionString , $ Rest = null ) { $ args = func_get_args ( ) ; array_shift ( $ args ) ; $ Query = "SELECT {$this->id()} AS ID FROM {$this->table()} WHERE $ConditionString LIMIT 1" ; array_unshift ( $ args , $ Query ) ; $ Res = call_user_func_array ( ( "Jf::sql" ) , $ args ) ; if ( $ Res ) return $ Res [ 0 ] [ "ID" ] ; else return null ; }
Returns the ID of a node based on a SQL conditional string It accepts other params in the PreparedStatements format
48,440
function insertSiblingData ( $ FieldValueArray = array ( ) , $ ConditionString = null , $ Rest = null ) { $ this -> lock ( ) ; $ Arguments = func_get_args ( ) ; array_shift ( $ Arguments ) ; array_shift ( $ Arguments ) ; if ( $ ConditionString ) $ ConditionString = "WHERE $ConditionString" ; $ Query = "SELECT {$this->right()} AS `Right`" . " FROM {$this->table()} $ConditionString" ; array_unshift ( $ Arguments , $ Query ) ; $ Sibl = call_user_func_array ( "Jf::sql" , $ Arguments ) ; $ Sibl = $ Sibl [ 0 ] ; if ( $ Sibl == null ) { $ Sibl [ "Left" ] = $ Sibl [ "Right" ] = 0 ; } Jf :: sql ( "UPDATE {$this->table()} SET {$this->right()} = {$this->right()} + 2 WHERE {$this->right()} > ?" , $ Sibl [ "Right" ] ) ; Jf :: sql ( "UPDATE {$this->table()} SET {$this->left()} = {$this->left()} + 2 WHERE {$this->left()} > ?" , $ Sibl [ "Right" ] ) ; $ FieldsString = $ ValuesString = "" ; $ Values = array ( ) ; if ( $ FieldValueArray ) foreach ( $ FieldValueArray as $ k => $ v ) { $ FieldsString .= "," ; $ FieldsString .= "`" . $ k . "`" ; $ ValuesString .= ",?" ; $ Values [ ] = $ v ; } $ Query = "INSERT INTO {$this->table()} ({$this->left()},{$this->right()} $FieldsString) " . "VALUES(?,? $ValuesString)" ; array_unshift ( $ Values , $ Sibl [ "Right" ] + 2 ) ; array_unshift ( $ Values , $ Sibl [ "Right" ] + 1 ) ; array_unshift ( $ Values , $ Query ) ; $ Res = call_user_func_array ( "Jf::sql" , $ Values ) ; $ this -> unlock ( ) ; return $ Res ; }
Adds a sibling after a node
48,441
function editData ( $ FieldValueArray = array ( ) , $ ConditionString = null , $ Rest = null ) { $ Arguments = func_get_args ( ) ; array_shift ( $ Arguments ) ; array_shift ( $ Arguments ) ; if ( $ ConditionString ) $ ConditionString = "WHERE $ConditionString" ; $ FieldsString = "" ; $ Values = array ( ) ; if ( $ FieldValueArray ) foreach ( $ FieldValueArray as $ k => $ v ) { if ( $ FieldsString != "" ) $ FieldsString .= "," ; $ FieldsString .= "`" . $ k . "`=?" ; $ Values [ ] = $ v ; } $ Query = "UPDATE {$this->table()} SET $FieldsString $ConditionString" ; array_unshift ( $ Values , $ Query ) ; $ Arguments = array_merge ( $ Values , $ Arguments ) ; return call_user_func_array ( "Jf::sql" , $ Arguments ) ; }
Edits a node
48,442
public function resourceLinkMeta ( string $ type , string $ id ) : array { foreach ( $ this -> resourceMap as $ resourceLink ) { if ( isset ( $ resourceLink [ "meta" ] ) && $ resourceLink [ "type" ] === $ type && $ resourceLink [ "id" ] === $ id ) { return $ resourceLink [ "meta" ] ; } } return [ ] ; }
Get meta information that may be defined next to the resource identifier link . This occurs when a relationship contains additional data besides the relation s identifiers .
48,443
private function getCacheItemMatcher ( array $ expectedData ) { return Argument :: that ( function ( array $ actualData ) use ( $ expectedData ) { foreach ( $ expectedData as $ key => $ value ) { if ( ! isset ( $ actualData [ $ key ] ) ) { return false ; } if ( $ key === 'expiresAt' || $ key === 'createdAt' ) { continue ; } if ( $ actualData [ $ key ] !== $ value ) { return false ; } } return true ; } ) ; }
Private function to match cache item data .
48,444
public static function clientCache ( CacheItemPoolInterface $ pool , StreamFactory $ streamFactory , array $ config = [ ] ) { if ( isset ( $ config [ 'respect_response_cache_directives' ] ) ) { $ config [ 'respect_response_cache_directives' ] [ ] = 'no-cache' ; $ config [ 'respect_response_cache_directives' ] [ ] = 'max-age' ; $ config [ 'respect_response_cache_directives' ] = array_unique ( $ config [ 'respect_response_cache_directives' ] ) ; } else { $ config [ 'respect_response_cache_directives' ] = [ 'no-cache' , 'max-age' ] ; } return new self ( $ pool , $ streamFactory , $ config ) ; }
This method will setup the cachePlugin in client cache mode . When using the client cache mode the plugin will cache responses with private cache directive .
48,445
public static function serverCache ( CacheItemPoolInterface $ pool , StreamFactory $ streamFactory , array $ config = [ ] ) { return new self ( $ pool , $ streamFactory , $ config ) ; }
This method will setup the cachePlugin in server cache mode . This is the default caching behavior it refuses to cache responses with the private or no - cache directives .
48,446
private function getMaxAge ( ResponseInterface $ response ) { if ( ! in_array ( 'max-age' , $ this -> config [ 'respect_response_cache_directives' ] , true ) ) { return $ this -> config [ 'default_ttl' ] ; } $ maxAge = $ this -> getCacheControlDirective ( $ response , 'max-age' ) ; if ( ! is_bool ( $ maxAge ) ) { $ ageHeaders = $ response -> getHeader ( 'Age' ) ; foreach ( $ ageHeaders as $ age ) { return $ maxAge - ( ( int ) $ age ) ; } return ( int ) $ maxAge ; } $ headers = $ response -> getHeader ( 'Expires' ) ; foreach ( $ headers as $ header ) { return ( new \ DateTime ( $ header ) ) -> getTimestamp ( ) - ( new \ DateTime ( ) ) -> getTimestamp ( ) ; } return $ this -> config [ 'default_ttl' ] ; }
Get a ttl in seconds . It could return null if we do not respect cache headers and got no defaultTtl .
48,447
private function configureOptions ( OptionsResolver $ resolver ) { $ resolver -> setDefaults ( [ 'cache_lifetime' => 86400 * 30 , 'default_ttl' => 0 , 'respect_cache_headers' => null , 'hash_algo' => 'sha1' , 'methods' => [ 'GET' , 'HEAD' ] , 'respect_response_cache_directives' => [ 'no-cache' , 'private' , 'max-age' , 'no-store' ] , 'cache_key_generator' => null , 'cache_listeners' => [ ] , ] ) ; $ resolver -> setAllowedTypes ( 'cache_lifetime' , [ 'int' , 'null' ] ) ; $ resolver -> setAllowedTypes ( 'default_ttl' , [ 'int' , 'null' ] ) ; $ resolver -> setAllowedTypes ( 'respect_cache_headers' , [ 'bool' , 'null' ] ) ; $ resolver -> setAllowedTypes ( 'methods' , 'array' ) ; $ resolver -> setAllowedTypes ( 'cache_key_generator' , [ 'null' , 'Http\Client\Common\Plugin\Cache\Generator\CacheKeyGenerator' ] ) ; $ resolver -> setAllowedValues ( 'hash_algo' , hash_algos ( ) ) ; $ resolver -> setAllowedValues ( 'methods' , function ( $ value ) { $ matches = preg_grep ( '/[^A-Z0-9!#$%&\'*+\-.^_`|~]/' , $ value ) ; return empty ( $ matches ) ; } ) ; $ resolver -> setAllowedTypes ( 'cache_listeners' , [ 'array' ] ) ; $ resolver -> setNormalizer ( 'respect_cache_headers' , function ( Options $ options , $ value ) { if ( null !== $ value ) { @ trigger_error ( 'The option "respect_cache_headers" is deprecated since version 1.3 and will be removed in 2.0. Use "respect_response_cache_directives" instead.' , E_USER_DEPRECATED ) ; } return null === $ value ? true : $ value ; } ) ; $ resolver -> setNormalizer ( 'respect_response_cache_directives' , function ( Options $ options , $ value ) { if ( false === $ options [ 'respect_cache_headers' ] ) { return [ ] ; } return $ value ; } ) ; }
Configure an options resolver .
48,448
private function getModifiedSinceHeaderValue ( CacheItemInterface $ cacheItem ) { $ data = $ cacheItem -> get ( ) ; if ( ! isset ( $ data [ 'createdAt' ] ) ) { return ; } $ modified = new \ DateTime ( '@' . $ data [ 'createdAt' ] ) ; $ modified -> setTimezone ( new \ DateTimeZone ( 'GMT' ) ) ; return sprintf ( '%s GMT' , $ modified -> format ( 'l, d-M-y H:i:s' ) ) ; }
Get the value of the If - Modified - Since header .
48,449
private function handleCacheListeners ( RequestInterface $ request , ResponseInterface $ response , $ cacheHit , $ cacheItem ) { foreach ( $ this -> config [ 'cache_listeners' ] as $ cacheListener ) { $ response = $ cacheListener -> onCacheResponse ( $ request , $ response , $ cacheHit , $ cacheItem ) ; } return $ response ; }
Call the cache listeners if they are set .
48,450
public function onCacheResponse ( RequestInterface $ request , ResponseInterface $ response , $ fromCache , $ cacheItem ) { return $ response -> withHeader ( $ this -> headerName , $ fromCache ? 'HIT' : 'MISS' ) ; }
Called before the cache plugin returns the response with information on whether that response came from cache .
48,451
public static function newSpreadsheet ( $ phpSpreadsheet = NULL ) { if ( is_object ( $ phpSpreadsheet ) ) { self :: $ _objSpreadsheet = & $ phpSpreadsheet ; } elseif ( is_string ( $ phpSpreadsheet ) ) { self :: $ _objSpreadsheet = \ PhpOffice \ PhpSpreadsheet \ IOFactory :: load ( $ phpSpreadsheet ) ; } else { self :: $ _objSpreadsheet = new \ PhpOffice \ PhpSpreadsheet \ Spreadsheet ( ) ; } return self :: resetSheet ( ) ; }
New or load an PhpSpreadsheet object
48,452
public static function setSheet ( $ sheet = 0 , $ title = NULL , $ normalizeTitle = false ) { self :: resetSheet ( ) ; if ( is_object ( $ sheet ) ) { self :: $ _objSheet = & $ sheet ; } elseif ( is_numeric ( $ sheet ) && $ sheet >= 0 && self :: $ _objSpreadsheet ) { $ sheetCount = self :: $ _objSpreadsheet -> getSheetCount ( ) ; if ( $ sheet >= $ sheetCount ) { for ( $ i = $ sheetCount ; $ i <= $ sheet ; $ i ++ ) { self :: $ _objSpreadsheet -> createSheet ( $ i ) ; } } self :: $ _objSheet = self :: $ _objSpreadsheet -> setActiveSheetIndex ( $ sheet ) ; } elseif ( is_null ( $ sheet ) && self :: $ _objSpreadsheet ) { self :: setSheet ( self :: getSheetCount ( ) ) ; } else { throw new Exception ( "Invalid or empty PhpSpreadsheet Object for setting sheet" , 400 ) ; } if ( $ title ) { if ( $ normalizeTitle ) { $ title = str_replace ( self :: $ _invalidCharacters , '' , $ title ) ; $ title = mb_substr ( $ title , 0 , 31 ) ; } self :: $ _objSheet -> setTitle ( $ title ) ; } return new static ( ) ; }
Set an active PhpSpreadsheet Sheet
48,453
public static function getSheet ( $ identity = null , $ autoCreate = false ) { if ( ! $ identity ) { return self :: $ _objSheet ; } if ( is_numeric ( $ identity ) ) { $ objSheet = self :: $ _objSpreadsheet -> getSheet ( $ identity ) ; if ( ! $ objSheet && $ autoCreate ) { $ objSheet = self :: setSheet ( $ identity ) -> getSheet ( ) ; } } elseif ( is_string ( $ identity ) ) { $ objSheet = self :: $ _objSpreadsheet -> getSheetByName ( $ identity ) ; if ( ! $ objSheet && $ autoCreate ) { $ objSheet = self :: setSheet ( null , $ identity , true ) -> getSheet ( ) ; } } return $ objSheet ; }
Get PhpSpreadsheet Sheet object from cache
48,454
public static function addRows ( $ data , $ rowAttributes = null ) { foreach ( $ data as $ key => $ row ) { self :: addRow ( $ row , $ rowAttributes ) ; } return new static ( ) ; }
Add rows to the actived sheet of PhpSpreadsheet
48,455
public static function save ( $ filename = 'excel' , $ format = 'Xlsx' ) { $ objPhpSpreadsheet = self :: validExcelObj ( ) ; $ objWriter = \ PhpOffice \ PhpSpreadsheet \ IOFactory :: createWriter ( $ objPhpSpreadsheet , $ format ) ; $ inTypeList = isset ( self :: $ _writerTypeInfo [ $ format ] ) ? true : false ; $ extension = ( $ inTypeList ) ? self :: $ _writerTypeInfo [ $ format ] [ 'extension' ] : '' ; $ filepath = ( stripos ( $ filename , $ extension ) === ( strlen ( $ filename ) - strlen ( $ extension ) ) ) ? $ filename : "{$filename}{$extension}" ; $ objWriter -> save ( $ filepath ) ; return $ filepath ; }
Save as file
48,456
public static function getRow ( $ toString = true , $ options = [ ] , callable $ callback = null ) { $ worksheet = self :: validSheetObj ( ) ; $ defaultOptions = [ 'columnOffset' => 0 , 'columns' => NULL , 'timestamp' => true , 'timestampFormat' => 'Y-m-d H:i:s' , ] ; $ options = array_replace ( $ defaultOptions , $ options ) ; $ startColumn = ( $ options [ 'columnOffset' ] ) ? : 0 ; $ columns = ( $ options [ 'columns' ] ) ? : self :: alpha2num ( $ worksheet -> getHighestColumn ( ) ) ; self :: $ _offsetRow ++ ; if ( self :: $ _offsetRow > $ worksheet -> getHighestRow ( ) ) { return [ ] ; } $ data = [ ] ; for ( $ col = $ startColumn + 1 ; $ col <= $ columns ; ++ $ col ) { $ cell = $ worksheet -> getCellByColumnAndRow ( $ col , self :: $ _offsetRow ) ; $ value = $ cell -> getValue ( ) ; if ( $ options [ 'timestamp' ] && \ PhpOffice \ PhpSpreadsheet \ Shared \ Date :: isDateTime ( $ cell ) ) { $ value = \ PhpOffice \ PhpSpreadsheet \ Shared \ Date :: excelToTimestamp ( $ value ) ; $ value = ( $ options [ 'timestampFormat' ] ) ? date ( $ options [ 'timestampFormat' ] , $ value ) : $ value ; } $ value = ( $ toString ) ? ( string ) $ value : $ value ; if ( $ callback ) { $ callback ( $ value , $ col , self :: $ _offsetRow ) ; } $ data [ ] = $ value ; } return $ data ; }
Get data of a row from the actived sheet of PhpSpreadsheet
48,457
public static function getRows ( $ toString = true , Array $ options = [ ] , callable $ callback = null ) { $ worksheet = self :: validSheetObj ( ) ; $ defaultOptions = [ 'rowOffset' => 0 , 'rows' => NULL , 'columns' => NULL , 'timestamp' => true , 'timestampFormat' => 'Y-m-d H:i:s' , ] ; $ options = array_replace ( $ defaultOptions , $ options ) ; $ highestRow = $ worksheet -> getHighestRow ( ) ; $ rowOffset = ( $ options [ 'rowOffset' ] && $ options [ 'rowOffset' ] <= $ highestRow ) ? $ options [ 'rowOffset' ] : 0 ; $ rows = ( $ options [ 'rows' ] && ( $ rowOffset + $ options [ 'rows' ] ) < $ highestRow ) ? $ options [ 'rows' ] : $ highestRow - $ rowOffset ; $ options [ 'columns' ] = ( $ options [ 'columns' ] ) ? : self :: alpha2num ( $ worksheet -> getHighestColumn ( ) ) ; self :: $ _offsetRow = $ rowOffset ; $ data = [ ] ; $ pointerRow = & $ data ; for ( $ i = 1 ; $ i <= $ rows ; $ i ++ ) { $ pointerRow [ ] = self :: getRow ( $ toString , $ options , $ callback ) ; } return $ data ; }
Get rows from the actived sheet of PhpSpreadsheet
48,458
public static function getCoordinateMap ( $ key = NULL ) { if ( $ key ) { return isset ( self :: $ _keyCoordinateMap [ $ key ] ) ? self :: $ _keyCoordinateMap [ $ key ] : NULL ; } else { return self :: $ _keyCoordinateMap ; } }
Get Coordinate Map by key or all from the actived sheet
48,459
public static function getColumnMap ( $ key = NULL ) { if ( $ key ) { return isset ( self :: $ _keyColumnMap [ $ key ] ) ? self :: $ _keyColumnMap [ $ key ] : NULL ; } else { return self :: $ _keyColumnMap ; } }
Get Column Alpha Map by key or all from the actived sheet
48,460
public static function getRowMap ( $ key = NULL ) { if ( $ key ) { return isset ( self :: $ _keyRowMap [ $ key ] ) ? self :: $ _keyRowMap [ $ key ] : NULL ; } else { return self :: $ _keyRowMap ; } }
Get Row Number Map by key or all from the actived sheet
48,461
public static function getRangeMap ( $ key = NULL ) { if ( $ key ) { return isset ( self :: $ _keyRangeMap [ $ key ] ) ? self :: $ _keyRangeMap [ $ key ] : NULL ; } else { return self :: $ _keyRangeMap ; } }
Get Range Map by key or all from the actived sheet
48,462
public static function getRangeAll ( ) { $ sheetObj = self :: validSheetObj ( ) ; return self :: num2alpha ( self :: $ _offsetCol + 1 ) . '1:' . $ sheetObj -> getHighestColumn ( ) . $ sheetObj -> getHighestRow ( ) ; }
Get Range of all actived cells from the actived sheet
48,463
public static function setWrapText ( $ range = NULL , $ value = true ) { $ sheetObj = self :: validSheetObj ( ) ; $ range = ( $ range ) ? $ range : self :: getRangeAll ( ) ; $ sheetObj -> getStyle ( $ range ) -> getAlignment ( ) -> setWrapText ( $ value ) ; return new static ( ) ; }
Set WrapText for all actived cells or set by giving range to the actived sheet
48,464
public static function setStyle ( $ styleArray , $ range = NULL ) { $ sheetObj = self :: validSheetObj ( ) ; $ range = ( $ range ) ? $ range : self :: getRangeAll ( ) ; $ sheetObj -> getStyle ( $ range ) -> applyFromArray ( $ styleArray ) ; return new static ( ) ; }
Set Style for all actived cells or set by giving range to the actived sheet
48,465
public static function setAutoSize ( $ colAlphaStart = NULL , $ colAlphaEnd = NULL , $ value = true ) { $ sheetObj = self :: validSheetObj ( ) ; $ colStart = ( $ colAlphaStart ) ? self :: alpha2num ( $ colAlphaStart ) : self :: $ _offsetCol + 1 ; $ colEnd = ( $ colAlphaEnd ) ? self :: alpha2num ( $ colAlphaEnd ) : self :: alpha2num ( $ sheetObj -> getHighestColumn ( ) ) ; foreach ( range ( $ colStart , $ colEnd ) as $ key => $ colNum ) { $ sheetObj -> getColumnDimension ( self :: num2alpha ( $ colNum ) ) -> setAutoSize ( $ value ) ; } return new static ( ) ; }
Set AutoSize for all actived cells or set by giving column range to the actived sheet
48,466
public static function num2alpha ( $ n ) { $ n = $ n - 1 ; $ r = '' ; for ( $ i = 1 ; $ n >= 0 && $ i < 10 ; $ i ++ ) { $ r = chr ( 0x41 + ( $ n % pow ( 26 , $ i ) / pow ( 26 , $ i - 1 ) ) ) . $ r ; $ n -= pow ( 26 , $ i ) ; } return $ r ; }
Number to Alpha
48,467
public static function alpha2num ( $ a ) { $ r = 0 ; $ l = strlen ( $ a ) ; for ( $ i = 0 ; $ i < $ l ; $ i ++ ) { $ r += pow ( 26 , $ i ) * ( ord ( $ a [ $ l - $ i - 1 ] ) - 0x40 ) ; } return $ r ; }
Alpha to Number
48,468
private static function validExcelObj ( $ excelObj = NULL ) { if ( is_object ( $ excelObj ) ) { return $ excelObj ; } elseif ( is_object ( self :: $ _objSpreadsheet ) ) { return self :: $ _objSpreadsheet ; } else { throw new Exception ( "Invalid or empty PhpSpreadsheet Object" , 400 ) ; } }
Validate and return the selected PhpSpreadsheet Object
48,469
private static function validSheetObj ( $ sheetObj = NULL ) { if ( is_object ( $ sheetObj ) ) { return $ sheetObj ; } elseif ( is_object ( self :: $ _objSheet ) ) { return self :: $ _objSheet ; } elseif ( is_object ( self :: $ _objSpreadsheet ) ) { return self :: setSheet ( ) -> getSheet ( ) ; } else { throw new Exception ( "Invalid or empty PhpSpreadsheet Sheet Object" , 400 ) ; } }
Validate and return the selected PhpSpreadsheet Sheet Object
48,470
public function setAccessToken ( $ token ) { $ google = Container :: getInstance ( ) -> make ( Client :: class ) ; $ google -> getCache ( ) -> clear ( ) ; $ google -> setAccessToken ( $ token ) ; if ( isset ( $ token [ 'refresh_token' ] ) and $ google -> isAccessTokenExpired ( ) ) { $ google -> fetchAccessTokenWithRefreshToken ( ) ; } return $ this -> setService ( $ google -> make ( 'sheets' ) ) -> setDriveService ( $ google -> make ( 'drive' ) ) ; }
set access_token and set new service
48,471
protected function setStartValues ( ) { $ this -> result -> setStartTime ( microtime ( true ) ) ; $ this -> result -> setStartMemory ( memory_get_usage ( ) ) ; }
Set values before callback is executed .
48,472
protected function executeCallback ( ) { if ( $ this -> muted ) { return $ this -> executeMutedCallback ( ) ; } $ this -> result -> setValue ( call_user_func_array ( $ this -> callback , $ this -> params ) ) ; }
Execute the callback with parameters .
48,473
protected function executeMutedCallback ( ) { try { $ this -> result -> setValue ( call_user_func_array ( $ this -> callback , $ this -> params ) ) ; } catch ( Throwable $ exception ) { $ this -> result -> setException ( $ exception ) ; $ this -> result -> setValue ( null ) ; } }
Execute the callback but swallow exceptions .
48,474
protected function setEndValues ( ) { $ this -> result -> setEndTime ( microtime ( true ) ) ; $ this -> result -> setEndMemory ( memory_get_usage ( ) ) ; }
Set values after the callback has executed .
48,475
public function run ( Experiment $ experiment ) { $ control = $ this -> runControl ( $ experiment ) ; $ trials = $ this -> runTrials ( $ experiment ) ; $ this -> determineMatches ( $ experiment -> getMatcher ( ) , $ control , $ trials ) ; return new Report ( $ experiment -> getName ( ) , $ control , $ trials ) ; }
Run an experiment and retrieve the result .
48,476
protected function runControl ( Experiment $ experiment ) { return ( new Machine ( $ experiment -> getControl ( ) , $ experiment -> getParams ( ) , false , $ experiment -> getControlContext ( ) ) ) -> execute ( ) ; }
Run the control callback and record its execution state .
48,477
protected function runTrials ( Experiment $ experiment ) { $ executions = [ ] ; foreach ( $ experiment -> getTrials ( ) as $ name => $ trial ) { $ executions [ $ name ] = ( new Machine ( $ trial -> getCallback ( ) , $ experiment -> getParams ( ) , true , $ trial -> getContext ( ) ) ) -> execute ( ) ; } return $ executions ; }
Run trial callbacks and record their execution state .
48,478
protected function determineMatches ( Matcher $ matcher , Result $ control , array $ trials = [ ] ) { foreach ( $ trials as $ trial ) { if ( $ matcher -> match ( $ control -> getValue ( ) , $ trial -> getValue ( ) ) ) { $ trial -> setMatch ( true ) ; } } }
Determine whether trial results match the control .
48,479
public function setJournals ( array $ journals = [ ] ) { $ this -> journals = [ ] ; foreach ( $ journals as $ journal ) { $ this -> addJournal ( $ journal ) ; } return $ this ; }
Register a collection of journals .
48,480
public function runExperiment ( Experiment $ experiment ) { if ( $ experiment -> shouldRun ( ) ) { $ report = $ this -> getReport ( $ experiment ) ; return $ report -> getControl ( ) -> getValue ( ) ; } return call_user_func_array ( $ experiment -> getControl ( ) , $ experiment -> getParams ( ) ) ; }
Run an experiment .
48,481
public function getReport ( Experiment $ experiment ) { $ report = ( new Intern ) -> run ( $ experiment ) ; $ this -> reportToJournals ( $ experiment , $ report ) ; return $ report ; }
Run an experiment and return the result .
48,482
protected function reportToJournals ( Experiment $ experiment , Report $ report ) { foreach ( $ this -> journals as $ journal ) { $ journal -> report ( $ experiment , $ report ) ; } }
Report experiment result to registered journals .
48,483
public function report ( Experiment $ experiment , Report $ report ) { $ this -> experiment = $ experiment ; $ this -> report = $ report ; }
Dispatch a report to storage .
48,484
public function control ( callable $ callback , $ context = null ) { $ this -> control = $ callback ; $ this -> controlContext = $ context ; return $ this ; }
Register a control callback .
48,485
public function trial ( $ name , callable $ callback , $ context = null ) { $ this -> trials [ $ name ] = new Trial ( $ name , $ callback , $ context ) ; return $ this ; }
Register a trial callback .
48,486
public function take ( StreamName $ streamName , AggregateRootInterface $ aggregate , DomainMessage $ message ) { $ id = $ aggregate -> getAggregateRootId ( ) ; if ( ! $ this -> strategy -> isFulfilled ( $ streamName , $ aggregate ) ) { return false ; } if ( ! $ this -> snapshotStore -> has ( $ id , $ message -> getVersion ( ) ) ) { $ this -> snapshotStore -> save ( Snapshot :: take ( $ id , $ aggregate , $ message -> getVersion ( ) ) ) ; } return true ; }
Takes a snapshot
48,487
public static function take ( AggregateIdInterface $ aggregateId , AggregateRootInterface $ aggregate , $ version ) { $ dateTime = \ DateTimeImmutable :: createFromFormat ( 'U.u' , sprintf ( '%.6F' , microtime ( true ) ) ) ; return new static ( $ aggregateId , $ aggregate , $ version , $ dateTime ) ; }
Take a snapshot
48,488
protected function apply ( DomainEventInterface $ event ) { $ handler = $ this -> determineEventHandlerMethodFor ( $ event ) ; if ( ! method_exists ( $ this , $ handler ) ) { return ; } $ this -> { $ handler } ( $ event ) ; }
Apply given event
48,489
protected function bulk ( Request $ request , $ action , $ transKey , array $ input = [ ] ) { $ this -> validate ( $ request , [ 'items' => 'required' ] ) ; $ items = $ request -> input ( 'items' ) ; $ request -> replace ( $ input ) ; $ models = collect ( ) ; foreach ( $ items as $ id ) { $ response = $ this -> { $ action } ( $ id , $ request ) ; if ( ! $ response -> isNotFound ( ) ) { if ( $ response -> isClientError ( ) ) { return $ response ; } $ models -> push ( $ response -> getOriginalContent ( ) ) ; } } return $ this -> response ( $ models , $ this -> trans ( $ transKey , $ models -> count ( ) ) ) ; }
Carry out a bulk action .
48,490
protected function updateModel ( $ model , array $ attributes , $ authorize = [ ] ) { if ( is_null ( $ model ) || ! $ model -> exists ) { return $ this -> notFoundResponse ( ) ; } $ this -> parseAuthorization ( $ model , $ authorize ) ; $ model -> update ( $ attributes ) ; return $ this -> response ( $ model , $ this -> trans ( 'updated' ) ) ; }
Update a given model s attributes .
48,491
protected function parseAuthorization ( $ model , $ authorize = [ ] ) { if ( ! empty ( $ authorize ) ) { if ( is_string ( $ authorize ) ) { $ authorize = [ $ authorize , $ model ] ; } list ( $ ability , $ authorizeModel ) = $ authorize ; $ this -> authorize ( $ ability , $ authorizeModel ) ; } }
Parse an authorization parameter and authorize if applicable .
48,492
protected function response ( $ data , $ message = "" , $ code = 200 ) { $ message = empty ( $ message ) ? [ ] : compact ( 'message' ) ; return ( request ( ) -> ajax ( ) || request ( ) -> wantsJson ( ) ) ? new JsonResponse ( $ message + compact ( 'data' ) , $ code ) : new Response ( $ data , $ code ) ; }
Create a generic response .
48,493
protected function notFoundResponse ( ) { $ content = [ 'error' => "Resource not found." ] ; return ( request ( ) -> ajax ( ) || request ( ) -> wantsJson ( ) ) ? new JsonResponse ( $ content , 404 ) : new Response ( $ content , 404 ) ; }
Create a not found response .
48,494
protected function remember ( $ key , callable $ function ) { $ class = new ReflectionClass ( $ this ) ; $ class = $ class -> getShortName ( ) ; $ lifetimes = config ( 'forum.preferences.cache_lifetimes' ) ; $ lifetime = isset ( $ lifetimes [ $ class ] [ $ key ] ) ? $ lifetimes [ $ class ] [ $ key ] : $ lifetimes [ 'default' ] ; return Cache :: remember ( $ class . $ this -> id . $ key , $ lifetime , $ function ) ; }
Cache a value from the given callback based on the current class name the given key and the configured cache lifetime .
48,495
protected function setPublishables ( ) { $ this -> publishes ( [ "{$this->baseDir()}config/api.php" => config_path ( 'forum.api.php' ) , "{$this->baseDir()}config/integration.php" => config_path ( 'forum.integration.php' ) , "{$this->baseDir()}config/preferences.php" => config_path ( 'forum.preferences.php' ) , "{$this->baseDir()}config/routing.php" => config_path ( 'forum.routing.php' ) , "{$this->baseDir()}config/validation.php" => config_path ( 'forum.validation.php' ) ] , 'config' ) ; $ this -> publishes ( [ "{$this->baseDir()}migrations/" => base_path ( 'database/migrations' ) ] , 'migrations' ) ; $ this -> publishes ( [ "{$this->baseDir()}translations/" => base_path ( 'resources/lang/vendor/forum' ) , ] , 'translations' ) ; }
Define files published by this package .
48,496
public function registerPolicies ( GateContract $ gate ) { $ forumPolicy = config ( 'forum.integration.policies.forum' ) ; foreach ( get_class_methods ( new $ forumPolicy ( ) ) as $ method ) { $ gate -> define ( $ method , "{$forumPolicy}@{$method}" ) ; } foreach ( config ( 'forum.integration.policies.model' ) as $ model => $ policy ) { $ gate -> policy ( $ model , $ policy ) ; } }
Register the package policies .
48,497
public function addPhpConfigRequirement ( $ cfgName , $ evaluation , $ approveCfgAbsence = false , $ testMessage = null , $ helpHtml = null , $ helpText = null ) { $ this -> add ( new PhpConfigRequirement ( $ cfgName , $ evaluation , $ approveCfgAbsence , $ testMessage , $ helpHtml , $ helpText , false ) ) ; }
Adds a mandatory requirement in form of a PHP configuration option .
48,498
public function addPhpConfigRecommendation ( $ cfgName , $ evaluation , $ approveCfgAbsence = false , $ testMessage = null , $ helpHtml = null , $ helpText = null ) { $ this -> add ( new PhpConfigRequirement ( $ cfgName , $ evaluation , $ approveCfgAbsence , $ testMessage , $ helpHtml , $ helpText , true ) ) ; }
Adds an optional recommendation in form of a PHP configuration option .
48,499
public function hasPhpConfigIssue ( ) { foreach ( $ this -> requirements as $ req ) { if ( ! $ req -> isFulfilled ( ) && $ req instanceof PhpConfigRequirement ) { return true ; } } return false ; }
Returns whether a PHP configuration option is not correct .