idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
55,400
protected function _nOnealiseSelectManyColumns ( $ columns ) { $ return = [ ] ; foreach ( $ columns as $ column ) { if ( Arrays :: is ( $ column ) ) { foreach ( $ column as $ key => $ value ) { if ( ! is_numeric ( $ key ) ) { $ return [ $ key ] = $ value ; } else { $ return [ ] = $ value ; } } } else { $ return [ ] = $ column ; } } return $ return ; }
Take a column specification for the select many methods and convert it into a nOnealised array of columns and aliases .
55,401
protected function _addJoinSource ( $ join_operator , $ table , $ constraint , $ table_alias = null ) { $ join_operator = trim ( "{$join_operator} JOIN" ) ; $ table = $ this -> _quoteIdentifier ( $ table ) ; if ( ! is_null ( $ table_alias ) ) { $ table_alias = $ this -> _quoteIdentifier ( $ table_alias ) ; $ table .= " {$table_alias}" ; } if ( Arrays :: is ( $ constraint ) ) { list ( $ first_column , $ operator , $ second_column ) = $ constraint ; $ first_column = $ this -> _quoteIdentifier ( $ first_column ) ; $ second_column = $ this -> _quoteIdentifier ( $ second_column ) ; $ constraint = "{$first_column} {$operator} {$second_column}" ; } $ this -> _join_sources [ ] = "{$join_operator} {$table} ON {$constraint}" ; return $ this ; }
Internal method to add a JOIN source to the query .
55,402
public function raw_join ( $ table , $ constraint , $ table_alias , $ parameters = [ ] ) { if ( ! is_null ( $ table_alias ) ) { $ table_alias = $ this -> _quoteIdentifier ( $ table_alias ) ; $ table .= " {$table_alias}" ; } $ this -> _values = array_merge ( $ this -> _values , $ parameters ) ; if ( Arrays :: is ( $ constraint ) ) { list ( $ first_column , $ operator , $ second_column ) = $ constraint ; $ first_column = $ this -> _quoteIdentifier ( $ first_column ) ; $ second_column = $ this -> _quoteIdentifier ( $ second_column ) ; $ constraint = "{$first_column} {$operator} {$second_column}" ; } $ this -> _join_sources [ ] = "{$table} ON {$constraint}" ; return $ this ; }
Add a RAW JOIN source to the query
55,403
public function join ( $ table , $ constraint , $ table_alias = null ) { return $ this -> _addJoinSource ( "" , $ table , $ constraint , $ table_alias ) ; }
Add a simple JOIN source to the query
55,404
public function inner_join ( $ table , $ constraint , $ table_alias = null ) { return $ this -> _addJoinSource ( "INNER" , $ table , $ constraint , $ table_alias ) ; }
Add an INNER JOIN souce to the query
55,405
public function left_outer_join ( $ table , $ constraint , $ table_alias = null ) { return $ this -> _addJoinSource ( "LEFT OUTER" , $ table , $ constraint , $ table_alias ) ; }
Add a LEFT OUTER JOIN souce to the query
55,406
public function right_outer_join ( $ table , $ constraint , $ table_alias = null ) { return $ this -> _addJoinSource ( "RIGHT OUTER" , $ table , $ constraint , $ table_alias ) ; }
Add an RIGHT OUTER JOIN souce to the query
55,407
public function full_outer_join ( $ table , $ constraint , $ table_alias = null ) { return $ this -> _addJoinSource ( "FULL OUTER" , $ table , $ constraint , $ table_alias ) ; }
Add an FULL OUTER JOIN souce to the query
55,408
protected function _addCondition ( $ type , $ fragment , $ values = [ ] ) { $ conditions_class_property_name = "_{$type}_conditions" ; if ( ! Arrays :: is ( $ values ) ) { $ values = array ( $ values ) ; } array_push ( $ this -> $ conditions_class_property_name , array ( self :: CONDITION_FRAGMENT => $ fragment , self :: CONDITION_VALUES => $ values , ) ) ; return $ this ; }
Internal method to add a HAVING or WHERE condition to the query
55,409
protected function _addSimpleCondition ( $ type , $ column_name , $ separator , $ value ) { $ multiple = Arrays :: is ( $ column_name ) ? $ column_name : array ( $ column_name => $ value ) ; $ result = $ this ; foreach ( $ multiple as $ key => $ val ) { if ( count ( $ result -> _join_sources ) > 0 && strpos ( $ key , '.' ) === false ) { $ table = $ result -> _table_name ; if ( ! is_null ( $ result -> _table_alias ) ) { $ table = $ result -> _table_alias ; } $ key = "{$table}.{$key}" ; } $ key = $ result -> _quoteIdentifier ( $ key ) ; $ result = $ result -> _addCondition ( $ type , "{$key} {$separator} ?" , $ val ) ; } return $ result ; }
Helper method to compile a simple COLUMN SEPARATOR VALUE style HAVING or WHERE condition into a string and value ready to be passed to the _addCondition method . Avoids duplication of the call to _quoteIdentifier
55,410
protected function _createPlaceholders ( $ fields ) { if ( ! empty ( $ fields ) ) { $ db_fields = [ ] ; foreach ( $ fields as $ key => $ value ) { if ( Arrays :: exists ( $ key , $ this -> _expr_fields ) ) { $ db_fields [ ] = $ value ; } else { $ db_fields [ ] = '?' ; } } return implode ( ', ' , $ db_fields ) ; } }
Return a string containing the given number of question marks separated by commas . Eg ? ? ?
55,411
public function where_id_is ( $ id ) { return ( Arrays :: is ( $ this -> _getIdColumnName ( ) ) ) ? $ this -> where ( $ this -> _getCompoundIdColumnValues ( $ id ) , null ) : $ this -> where ( $ this -> _getIdColumnName ( ) , $ id ) ; }
Special method to query the table by its primary key
55,412
public function where_any_is ( $ values , $ operator = '=' ) { $ data = [ ] ; $ query = array ( "((" ) ; $ first = true ; foreach ( $ values as $ item ) { if ( $ first ) { $ first = false ; } else { $ query [ ] = ") OR (" ; } $ firstsub = true ; foreach ( $ item as $ key => $ item ) { $ op = is_string ( $ operator ) ? $ operator : ( isset ( $ operator [ $ key ] ) ? $ operator [ $ key ] : '=' ) ; if ( $ firstsub ) { $ firstsub = false ; } else { $ query [ ] = "AND" ; } $ query [ ] = $ this -> _quoteIdentifier ( $ key ) ; $ data [ ] = $ item ; $ query [ ] = $ op . " ?" ; } } $ query [ ] = "))" ; return $ this -> where_raw ( join ( $ query , ' ' ) , $ data ) ; }
Allows adding a WHERE clause that matches any of the conditions specified in the array . Each element in the associative array will be a different condition where the key will be the column name .
55,413
protected function _addOrderBy ( $ column_name , $ ordering ) { $ column_name = $ this -> _quoteIdentifier ( $ column_name ) ; $ this -> _order_by [ ] = "{$column_name} {$ordering}" ; return $ this ; }
Add an ORDER BY clause to the query
55,414
public function group_by ( $ column_name ) { $ column_name = $ this -> _quoteIdentifier ( $ column_name ) ; $ this -> _group_by [ ] = $ column_name ; return $ this ; }
Add a column to the list of columns to GROUP BY
55,415
public function having_id_is ( $ id ) { return ( Arrays :: is ( $ this -> _getIdColumnName ( ) ) ) ? $ this -> having ( $ this -> _getCompoundIdColumnValues ( $ value ) ) : $ this -> having ( $ this -> _getIdColumnName ( ) , $ id ) ; }
Special method to query the table by its primary key .
55,416
protected function _buildSelect ( ) { if ( $ this -> _is_raw_query ) { $ this -> _values = $ this -> _raw_parameters ; return $ this -> _raw_query ; } return $ this -> _joinIfNotEmpty ( " " , array ( $ this -> _buildSelectStart ( ) , $ this -> _buildJoin ( ) , $ this -> _buildWhere ( ) , $ this -> _buildGroupBy ( ) , $ this -> _buildHaving ( ) , $ this -> _buildOrderBy ( ) , $ this -> _buildLimit ( ) , $ this -> _buildOffset ( ) , ) ) ; }
Build a SELECT statement based on the clauses that have been passed to this instance by chaining method calls .
55,417
protected function _buildSelectStart ( ) { $ fragment = 'SELECT ' ; $ result_columns = join ( ', ' , $ this -> _resultColumns ) ; if ( ! is_null ( $ this -> _limit ) && self :: $ _config [ $ this -> _connection_name ] [ 'limit_clause_style' ] === One :: LIMIT_STYLE_TOP_N ) { $ fragment .= "TOP {$this->_limit} " ; } if ( $ this -> _distinct ) { $ result_columns = 'DISTINCT ' . $ result_columns ; } $ fragment .= "{$result_columns} FROM " . $ this -> _quoteIdentifier ( $ this -> _table_name ) ; if ( ! is_null ( $ this -> _table_alias ) ) { $ fragment .= " " . $ this -> _quoteIdentifier ( $ this -> _table_alias ) ; } return $ fragment ; }
Build the start of the SELECT statement
55,418
protected function _buildConditions ( $ type ) { $ conditions_class_property_name = "_{$type}_conditions" ; if ( count ( $ this -> $ conditions_class_property_name ) === 0 ) { return '' ; } $ conditions = [ ] ; foreach ( $ this -> $ conditions_class_property_name as $ condition ) { $ conditions [ ] = $ condition [ self :: CONDITION_FRAGMENT ] ; $ this -> _values = array_merge ( $ this -> _values , $ condition [ self :: CONDITION_VALUES ] ) ; } return Inflector :: upper ( $ type ) . " " . join ( " AND " , $ conditions ) ; }
Build a WHERE or HAVING clause
55,419
protected function _joinIfNotEmpty ( $ glue , $ pieces ) { $ filtered_pieces = [ ] ; foreach ( $ pieces as $ piece ) { if ( is_string ( $ piece ) ) { $ piece = trim ( $ piece ) ; } if ( ! empty ( $ piece ) ) { $ filtered_pieces [ ] = $ piece ; } } return join ( $ glue , $ filtered_pieces ) ; }
Wrapper around PHP s join function which only adds the pieces if they are not empty .
55,420
protected static function _createCacheKey ( $ query , $ parameters , $ table_name = null , $ connection_name = self :: DEFAULT_CONNECTION ) { if ( isset ( self :: $ _config [ $ connection_name ] [ 'create_cache_key' ] ) && is_callable ( self :: $ _config [ $ connection_name ] [ 'create_cache_key' ] ) ) { return call_user_func_array ( self :: $ _config [ $ connection_name ] [ 'create_cache_key' ] , array ( $ query , $ parameters , $ table_name , $ connection_name ) ) ; } $ parameter_string = join ( ',' , $ parameters ) ; $ key = $ query . ':' . $ parameter_string ; return sha1 ( $ key ) ; }
Create a cache key for the given query and parameters .
55,421
protected static function _checkQueryCache ( $ cache_key , $ table_name = null , $ connection_name = self :: DEFAULT_CONNECTION ) { if ( isset ( self :: $ _config [ $ connection_name ] [ 'check_query_cache' ] ) && is_callable ( self :: $ _config [ $ connection_name ] [ 'check_query_cache' ] ) ) { return call_user_func_array ( self :: $ _config [ $ connection_name ] [ 'check_query_cache' ] , array ( $ cache_key , $ table_name , $ connection_name ) ) ; } elseif ( isset ( self :: $ _query_cache [ $ connection_name ] [ $ cache_key ] ) ) { return self :: $ _query_cache [ $ connection_name ] [ $ cache_key ] ; } return false ; }
Check the query cache for the given cache key . If a value is cached for the key return the value . Otherwise return false .
55,422
public static function clear_cache ( $ table_name = null , $ connection_name = self :: DEFAULT_CONNECTION ) { self :: $ _query_cache = [ ] ; if ( isset ( self :: $ _config [ $ connection_name ] [ 'clear_cache' ] ) && is_callable ( self :: $ _config [ $ connection_name ] [ 'clear_cache' ] ) ) { return call_user_func_array ( self :: $ _config [ $ connection_name ] [ 'clear_cache' ] , array ( $ table_name , $ connection_name ) ) ; } }
Clear the query cache
55,423
protected static function _cacheQueryResult ( $ cache_key , $ value , $ table_name = null , $ connection_name = self :: DEFAULT_CONNECTION ) { if ( isset ( self :: $ _config [ $ connection_name ] [ 'cache_query_result' ] ) && is_callable ( self :: $ _config [ $ connection_name ] [ 'cache_query_result' ] ) ) { return call_user_func_array ( self :: $ _config [ $ connection_name ] [ 'cache_query_result' ] , array ( $ cache_key , $ value , $ table_name , $ connection_name ) ) ; } elseif ( ! isset ( self :: $ _query_cache [ $ connection_name ] ) ) { self :: $ _query_cache [ $ connection_name ] = [ ] ; } self :: $ _query_cache [ $ connection_name ] [ $ cache_key ] = $ value ; }
Add the given value to the query cache .
55,424
protected function _run ( ) { $ query = $ this -> _buildSelect ( ) ; $ caching_enabled = self :: $ _config [ $ this -> _connection_name ] [ 'caching' ] ; if ( $ caching_enabled ) { $ cache_key = self :: _createCacheKey ( $ query , $ this -> _values , $ this -> _table_name , $ this -> _connection_name ) ; $ cached_result = self :: _checkQueryCache ( $ cache_key , $ this -> _table_name , $ this -> _connection_name ) ; if ( $ cached_result !== false ) { return $ cached_result ; } } self :: _execute ( $ query , $ this -> _values , $ this -> _connection_name ) ; $ statement = self :: get_last_statement ( ) ; $ rows = [ ] ; while ( $ row = $ statement -> fetch ( PDO :: FETCH_ASSOC ) ) { $ rows [ ] = $ row ; } if ( $ caching_enabled ) { self :: _cacheQueryResult ( $ cache_key , $ rows , $ this -> _table_name , $ this -> _connection_name ) ; } $ this -> _values = [ ] ; $ this -> _resultColumns = array ( '*' ) ; $ this -> _using_default_resultColumns = true ; return $ rows ; }
Execute the SELECT query that has been built up by chaining methods on this class . Return an array of rows as associative arrays .
55,425
public function as_array ( ) { if ( func_num_args ( ) === 0 ) { return $ this -> _data ; } $ args = func_get_args ( ) ; return array_intersect_key ( $ this -> _data , array_flip ( $ args ) ) ; }
Return the raw data wrapped by this One instance as an associative array . Column names may optionally be supplied as arguments if so only those keys will be returned .
55,426
protected function _getIdColumnName ( ) { if ( ! is_null ( $ this -> _instance_id_column ) ) { return $ this -> _instance_id_column ; } if ( isset ( self :: $ _config [ $ this -> _connection_name ] [ 'id_column_overrides' ] [ $ this -> _table_name ] ) ) { return self :: $ _config [ $ this -> _connection_name ] [ 'id_column_overrides' ] [ $ this -> _table_name ] ; } return self :: $ _config [ $ this -> _connection_name ] [ 'id_column' ] ; }
Return the name of the column in the database table which contains the primary key ID of the row .
55,427
public function id ( $ disallowNull = false ) { $ id = $ this -> get ( $ this -> _getIdColumnName ( ) ) ; if ( $ disallowNull ) { if ( Arrays :: is ( $ id ) ) { foreach ( $ id as $ id_part ) { if ( $ id_part === null ) { throw new Exception ( 'Primary key ID contains null value(s)' ) ; } } } else if ( $ id === null ) { throw new Exception ( 'Primary key ID missing from row or is null' ) ; } } return $ id ; }
Get the primary key ID of this object .
55,428
protected function _setOneProperty ( $ key , $ value = null , $ expr = false ) { if ( ! Arrays :: is ( $ key ) ) { $ key = array ( $ key => $ value ) ; } foreach ( $ key as $ field => $ value ) { $ this -> _data [ $ field ] = $ value ; $ this -> _dirty_fields [ $ field ] = $ value ; if ( false === $ expr and isset ( $ this -> _expr_fields [ $ field ] ) ) { unset ( $ this -> _expr_fields [ $ field ] ) ; } else if ( true === $ expr ) { $ this -> _expr_fields [ $ field ] = true ; } } return $ this ; }
Set a property on the One object .
55,429
public function save ( ) { $ query = [ ] ; $ values = array_values ( array_diff_key ( $ this -> _dirty_fields , $ this -> _expr_fields ) ) ; if ( ! $ this -> _is_new ) { if ( empty ( $ values ) && empty ( $ this -> _expr_fields ) ) { return true ; } $ query = $ this -> _buildUpdate ( ) ; $ id = $ this -> id ( true ) ; if ( Arrays :: is ( $ id ) ) { $ values = array_merge ( $ values , array_values ( $ id ) ) ; } else { $ values [ ] = $ id ; } } else { $ query = $ this -> _buildInsert ( ) ; } $ success = self :: _execute ( $ query , $ values , $ this -> _connection_name ) ; $ caching_auto_clear_enabled = self :: $ _config [ $ this -> _connection_name ] [ 'caching_auto_clear' ] ; if ( $ caching_auto_clear_enabled ) { self :: clear_cache ( $ this -> _table_name , $ this -> _connection_name ) ; } if ( $ this -> _is_new ) { $ this -> _is_new = false ; if ( $ this -> count_null_id_columns ( ) != 0 ) { $ db = self :: get_db ( $ this -> _connection_name ) ; if ( $ db -> getAttribute ( PDO :: ATTR_DRIVER_NAME ) == 'pgsql' ) { $ row = self :: get_last_statement ( ) -> fetch ( PDO :: FETCH_ASSOC ) ; foreach ( $ row as $ key => $ value ) { $ this -> _data [ $ key ] = $ value ; } } else { $ column = $ this -> _getIdColumnName ( ) ; if ( Arrays :: is ( $ column ) ) { $ column = array_slice ( $ column , 0 , 1 ) ; } $ this -> _data [ $ column ] = $ db -> lastInsertId ( ) ; } } } $ this -> _dirty_fields = $ this -> _expr_fields = [ ] ; return $ success ; }
Save any fields which have been modified on this object to the database .
55,430
public function _addIdColumnConditions ( & $ query ) { $ query [ ] = "WHERE" ; $ keys = Arrays :: is ( $ this -> _getIdColumnName ( ) ) ? $ this -> _getIdColumnName ( ) : array ( $ this -> _getIdColumnName ( ) ) ; $ first = true ; foreach ( $ keys as $ key ) { if ( $ first ) { $ first = false ; } else { $ query [ ] = "AND" ; } $ query [ ] = $ this -> _quoteIdentifier ( $ key ) ; $ query [ ] = "= ?" ; } }
Add a WHERE clause for every column that belongs to the primary key
55,431
protected function _buildUpdate ( ) { $ query = [ ] ; $ query [ ] = "UPDATE {$this->_quoteIdentifier($this->_table_name)} SET" ; $ field_list = [ ] ; foreach ( $ this -> _dirty_fields as $ key => $ value ) { if ( ! Arrays :: exists ( $ key , $ this -> _expr_fields ) ) { $ value = '?' ; } $ field_list [ ] = "{$this->_quoteIdentifier($key)} = $value" ; } $ query [ ] = join ( ", " , $ field_list ) ; $ this -> _addIdColumnConditions ( $ query ) ; return join ( " " , $ query ) ; }
Build an UPDATE query
55,432
protected function _buildInsert ( ) { $ query [ ] = "INSERT INTO" ; $ query [ ] = $ this -> _quoteIdentifier ( $ this -> _table_name ) ; $ field_list = array_map ( array ( $ this , '_quoteIdentifier' ) , array_keys ( $ this -> _dirty_fields ) ) ; $ query [ ] = "(" . join ( ", " , $ field_list ) . ")" ; $ query [ ] = "VALUES" ; $ placeholders = $ this -> _createPlaceholders ( $ this -> _dirty_fields ) ; $ query [ ] = "({$placeholders})" ; if ( self :: get_db ( $ this -> _connection_name ) -> getAttribute ( PDO :: ATTR_DRIVER_NAME ) == 'pgsql' ) { $ query [ ] = 'RETURNING ' . $ this -> _quoteIdentifier ( $ this -> _getIdColumnName ( ) ) ; } return join ( " " , $ query ) ; }
Build an INSERT query
55,433
public function delete ( ) { $ query = array ( "DELETE FROM" , $ this -> _quoteIdentifier ( $ this -> _table_name ) ) ; $ this -> _addIdColumnConditions ( $ query ) ; return self :: _execute ( join ( " " , $ query ) , Arrays :: is ( $ this -> id ( true ) ) ? array_values ( $ this -> id ( true ) ) : array ( $ this -> id ( true ) ) , $ this -> _connection_name ) ; }
Delete this record from the database
55,434
public function delete_many ( ) { $ query = $ this -> _joinIfNotEmpty ( " " , array ( "DELETE FROM" , $ this -> _quoteIdentifier ( $ this -> _table_name ) , $ this -> _buildWhere ( ) , ) ) ; return self :: _execute ( $ query , $ this -> _values , $ this -> _connection_name ) ; }
Delete many records from the database
55,435
public function getRoute ( ) { foreach ( $ this -> routes as $ route ) { if ( false == ( $ cleansed = $ this -> isValidRoute ( $ route ) ) ) { continue ; } $ route = $ cleansed ; if ( ! $ this -> methodMatches ( $ route ) ) { continue ; } if ( false === $ this -> isAllowedByIp ( $ route ) ) { continue ; } if ( false === $ this -> isAllowedByRole ( $ route ) ) { continue ; } if ( false != ( $ match = $ this -> isDirectMatch ( $ route ) ) ) { return $ match ; } if ( false != ( $ match = $ this -> isParameterisedMatch ( $ route ) ) ) { return $ match ; } } $ e = new RouteNotFoundException ( 'Route for path not found.' ) ; $ e -> setAdditionalData ( 'Path: ' , $ this -> path ) ; throw $ e ; }
Retrieve the matching route from the parameters given .
55,436
public function urlFor ( $ routeName , array $ params = array ( ) ) { $ storageKey = md5 ( $ routeName . serialize ( $ params ) ) ; if ( array_key_exists ( $ storageKey , $ this -> resolvedUrls ) ) { return $ this -> resolvedUrls [ $ storageKey ] ; } if ( ! array_key_exists ( $ routeName , $ this -> routes ) ) { $ this -> resolvedUrls [ $ storageKey ] = $ routeName ; return $ routeName ; } $ route = $ this -> isValidRoute ( $ this -> routes [ $ routeName ] ) ; if ( ! $ route ) { $ this -> resolvedUrls [ $ storageKey ] = $ routeName ; return $ routeName ; } $ path = $ route [ 'path' ] ; if ( empty ( $ params ) ) { $ this -> resolvedUrls [ $ storageKey ] = $ path ; return $ path ; } foreach ( $ params as $ key => $ value ) { if ( is_string ( $ value ) || is_int ( $ value ) ) { $ path = str_replace ( '{' . $ key . '}' , $ value , $ path ) ; } } $ this -> resolvedUrls [ $ storageKey ] = $ path ; return $ path ; }
Get a URL for a given route name
55,437
private function isParameterisedMatch ( array $ route ) { if ( ! preg_match ( '/\{[a-z]+\}/i' , $ route [ 'path' ] ) ) { return false ; } $ routePieces = explode ( '/' , $ route [ 'path' ] ) ; $ urlPieces = explode ( '/' , $ this -> path ) ; if ( count ( $ routePieces ) != count ( $ urlPieces ) ) { return false ; } $ params = array ( ) ; foreach ( $ routePieces as $ routeKey => $ routeValue ) { if ( preg_match ( '/\{[a-z]+\}/i' , $ routeValue , $ matches ) ) { $ paramName = trim ( $ routeValue , '{} ' ) ; $ params [ $ paramName ] = urldecode ( $ urlPieces [ $ routeKey ] ) ; } else { if ( $ routeValue != $ urlPieces [ $ routeKey ] ) { return false ; } } } $ route [ 'params' ] = array_merge_recursive ( $ route [ 'params' ] , $ params ) ; return $ route ; }
Validate if a route matches based on parameters
55,438
private function isValidRoute ( array $ route ) { if ( ! array_key_exists ( 'path' , $ route ) ) { return false ; } if ( ! array_key_exists ( 'view.directRender' , $ route ) ) { $ route [ 'view.directRender' ] = false ; } else { if ( ! is_bool ( $ route [ 'view.directRender' ] ) ) { return false ; } } if ( ! array_key_exists ( 'view.layout' , $ route ) ) { $ route [ 'view.layout' ] = false ; } else { if ( ! is_string ( $ route [ 'view.layout' ] ) ) { return false ; } } if ( ! array_key_exists ( 'method' , $ route ) ) { $ route [ 'method' ] = 'GET' ; } if ( ! array_key_exists ( 'allow' , $ route ) ) { $ route [ 'allow' ] = array ( ) ; } if ( ! array_key_exists ( 'from' , $ route [ 'allow' ] ) ) { $ route [ 'allow' ] [ 'from' ] = '' ; } if ( ! array_key_exists ( 'roles' , $ route [ 'allow' ] ) ) { $ route [ 'allow' ] [ 'roles' ] = '' ; } $ route [ 'method' ] = strtoupper ( $ route [ 'method' ] ) ; if ( ! array_key_exists ( 'params' , $ route ) ) { $ route [ 'params' ] = array ( ) ; } return $ route ; }
Validate and return a cleansed version from a given route
55,439
private function methodMatches ( array $ route ) { $ methods = explode ( '|' , $ route [ 'method' ] ) ; if ( in_array ( $ this -> method , $ methods ) ) { return true ; } return false ; }
Validate the HTTP Request Method matches a given route .
55,440
public function asArray ( ) : array { $ data = [ 'name' => $ this -> project -> getName ( ) , 'path' => $ this -> project -> getPath ( ) , ] ; if ( ( $ foregroundColor = $ this -> project -> getForegroundColor ( ) ) ) { $ data [ 'foreground_color' ] = $ foregroundColor ; } if ( ( $ backgroundColor = $ this -> project -> getBackgroundColor ( ) ) ) { $ data [ 'background_color' ] = $ backgroundColor ; } return $ data ; }
Returns an array of the entity data .
55,441
public function push ( ConversionInterface $ conversion , ResponseInterface $ response ) : StoredConversionInterface { $ storedConversion = new StoredConversion ( $ conversion , $ response ) ; return $ this -> storage [ ] = $ storedConversion ; }
Saving sent conversion in storage
55,442
public static function find ( $ model ) { if ( property_exists ( self :: className ( ) , 'instance' ) ) { if ( static :: $ instance instanceof static ) { $ instance = static :: $ instance ; $ instance -> setDao ( Dao :: component ( ) ) -> setConditions ( ) -> setGroupFields ( ) -> setOrders ( ) -> setLimit ( ) -> setSelect ( ) -> setAsArray ( ) ; return $ instance ; } else { $ instance = new static ( $ model ) ; $ instance -> is_single = true ; return ( static :: $ instance = $ instance ) ; } } return null ; }
Create Query Builder
55,443
protected function getUnauthorizedResponse ( $ statusCode , $ error = null ) { $ authenticateHeader = 'Bearer' ; $ authenticateHeader .= $ error === null ? '' : sprintf ( ' error="%s"' , $ error ) ; $ body = [ 'message' => 'Unauthorized' ] ; $ headers = [ 'WWW-Authenticate' => $ authenticateHeader ] ; return new JsonResponse ( $ body , $ statusCode , $ headers ) ; }
Return an Unauthorized request including a WWW - Authenticate header per the OAuth2 specification
55,444
public function exceptionHandler ( $ message ) { $ errorCode = $ message -> getCode ( ) ? : 404 ; if ( $ this -> customErrorViewExist ( $ errorCode ) ) { $ this -> response -> send ( view ( "errors.{$errorCode}" ) ) ; } error_log ( "planet.ERROR " . $ message -> getMessage ( ) . "\nStack trace:\n" . $ message -> getTraceAsString ( ) ) ; if ( php_sapi_name ( ) == 'cli' ) { ( new ConsoleApplication ) -> renderException ( $ message , new ConsoleOutput ) ; } else { $ debugMode = filter_var ( $ this -> app -> config -> getApp ( 'debug' ) , FILTER_VALIDATE_BOOLEAN ) ; $ exceptionHandler = new ExceptionHandler ( $ debugMode ) ; $ exceptionHandler -> sendPhpResponse ( $ message ) ; } }
To handle application exception
55,445
public function shutdownHandler ( ) { $ error = error_get_last ( ) ; if ( ! is_null ( $ error ) ) { $ this -> exceptionHandler ( new FatalErrorException ( $ error [ 'message' ] , $ error [ 'type' ] , 0 , $ error [ 'file' ] , $ error [ 'line' ] , 0 ) ) ; } }
Shutdown handler executed after script execution finishes
55,446
public function buildRoutes ( EntityReflectionInterface $ entity ) { $ collection = $ this -> entityActionCollectionBuilder -> build ( $ entity ) ; $ routes = [ ] ; foreach ( $ collection as $ action ) { $ pattern = '/' . $ entity -> getSlug ( ) . '/' . $ action -> getSlug ( ) ; $ defaults = [ '_controller' => $ this -> queryController , 'orchestra_type' => $ this :: ROUTE_TYPE , 'entity_method' => $ action -> getMethod ( ) , 'method_slug' => $ action -> getSlug ( ) , 'entity_slug' => $ entity -> getSlug ( ) ] ; $ requirements = [ '_method' => $ this -> methodRequirement ] ; if ( true === $ action -> isCommand ( ) ) { $ defaults [ '_controller' ] = $ this -> commandController ; $ defaults [ 'command_class' ] = $ action -> getCommandClass ( ) ; $ requirements [ '_method' ] = 'GET|POST' ; } if ( true === $ action -> emitEvent ( ) ) { $ defaults [ '_controller' ] = $ this -> eventController ; } $ route = new Route ( $ pattern , $ defaults , $ requirements ) ; $ routeName = $ action -> getRouteName ( ) ; $ routes [ $ routeName ] = $ route ; } return $ routes ; }
Builds all routes for given EntityReflection
55,447
public function create ( $ term , Taxonomy $ taxonomy ) { if ( ! ( $ term instanceof WP_Term ) ) { $ term = get_term ( $ term , $ taxonomy -> getName ( ) ) ; } if ( $ term && ! ( $ term instanceof WP_Error ) ) { return new Term ( $ term , $ taxonomy , $ this ) ; } else { throw new Exception ( 'Term not found' ) ; } }
Create a new Term object .
55,448
public function tostring ( ) { if ( empty ( $ this -> value ) ) { return ( empty ( $ this -> function ) ) ? "$this->function(`$this->name`)" : " `$this->name`" ; } $ str = strtoupper ( $ this -> condition ) . " `$this->name`" ; if ( is_array ( $ this -> value ) ) { $ str .= " IN (" . implode ( "','" , $ this -> value ) . "')" ; } else { $ str .= " = '$this->value'" ; } return $ str ; }
returns a string of the field
55,449
public function getDateInterval ( ) { if ( ! $ this -> from && ! $ this -> to ) { return null ; } return $ this -> from -> diff ( $ this -> to ) ; }
Gets the interval between the two dates
55,450
protected function generatePDF ( $ content , $ filename , $ config = [ ] ) { unset ( $ config [ 'contentBefore' ] , $ config [ 'contentAfter' ] ) ; $ config = array_replace_recursive ( [ 'mode' => Pdf :: MODE_UTF8 , 'options' => [ 'autoLangToFont' => true , 'autoScriptToLang' => true , 'autoVietnamese' => true , 'autoArabic' => true , ] , 'methods' => [ 'SetFooter' => [ '{PAGENO}' ] , ] ] , $ config ) ; $ config [ 'filename' ] = $ filename ; $ config [ 'methods' ] [ 'SetAuthor' ] = [ 'CCIZA LTD.' ] ; $ config [ 'methods' ] [ 'SetCreator' ] = [ 'CZA Extension' ] ; $ config [ 'content' ] = $ content ; $ pdf = new Pdf ( $ config ) ; echo $ pdf -> render ( ) ; }
Generates the PDF file
55,451
public function applyRequestHeaders ( RequestInterface $ request ) { if ( $ this -> files || $ this -> forceMultipart ) { $ request -> setHeader ( 'Content-Type' , 'multipart/form-data; boundary=' . $ this -> getBody ( ) -> getBoundary ( ) ) ; } elseif ( $ this -> fields && ! $ request -> hasHeader ( 'Content-Type' ) ) { $ request -> setHeader ( 'Content-Type' , 'application/x-www-form-urlencoded' ) ; } if ( $ size = $ this -> getSize ( ) ) { $ request -> setHeader ( 'Content-Length' , $ size ) ; } }
Applies request headers to a request based on the POST state
55,452
public function validate_unique ( $ value , $ input , $ args ) { $ result = $ this -> app -> db -> table ( array_shift ( $ args ) ) ; foreach ( $ args as $ arg ) { $ result -> where ( $ arg , '=' , $ value ) ; } if ( $ result -> first ( ) ) { return false ; } return true ; }
To validate unique field
55,453
public function validate_verify ( $ value , $ input , $ args ) { $ userModel = config ( 'auth.model' ) ; $ user = $ userModel :: find ( $ this -> session -> get ( 'loginUserId' ) ) ; if ( $ user ) { if ( $ this -> hash -> verify ( $ value , $ user -> password ) ) { return true ; } return false ; } return false ; }
To verify user password
55,454
public static function tokenize ( string $ plainData ) : array { $ tokens = [ ] ; if ( ! empty ( $ plainData ) ) { $ tokens = ( new self ( $ plainData ) ) -> tokenizeInternal ( ) -> tokens ; } return $ tokens ; }
parse and tokenize input string
55,455
public static function fromArray ( array $ data ) { return new static ( $ data [ 'uri' ] , $ data [ 'title' ] , $ data [ 'date' ] , $ data [ 'type' ] , $ data [ 'content' ] , isset ( $ data [ 'template' ] ) ? $ data [ 'template' ] : null , isset ( $ data [ 'description' ] ) ? $ data [ 'description' ] : null , isset ( $ data [ 'seoTitle' ] ) ? $ data [ 'seoTitle' ] : null , isset ( $ data [ 'excerpt' ] ) ? $ data [ 'excerpt' ] : null , isset ( $ data [ 'isIndex' ] ) ? $ data [ 'isIndex' ] : false ) ; }
Constructs the ContentItem from an array of data
55,456
public function initialize ( ) { Configure :: write ( 'Cache.disable' , true ) ; $ this -> _initUiLang ( ) ; parent :: initialize ( ) ; $ this -> InstallerCompleted = ClassRegistry :: init ( 'InstallerCompleted' , true ) ; if ( $ this -> InstallerCompleted === false ) { $ this -> InstallerCompleted = ClassRegistry :: init ( 'CakeInstaller.InstallerCompleted' ) ; } $ this -> progress = $ this -> helper ( 'Progress' ) ; $ this -> state = $ this -> helper ( 'CakeInstaller.State' ) ; $ this -> waiting = $ this -> helper ( 'CakeInstaller.Waiting' ) ; }
Initializes the Shell acts as constructor for subclasses allows configuration of tasks prior to shell execution
55,457
public function helper ( $ name ) { if ( isset ( $ this -> _helpers [ $ name ] ) ) { return $ this -> _helpers [ $ name ] ; } list ( $ plugin , $ helperClassName ) = pluginSplit ( $ name , true ) ; $ helperClassName = Inflector :: camelize ( $ helperClassName ) . "ShellHelper" ; App :: uses ( $ helperClassName , $ plugin . "Console/Helper" ) ; if ( ! class_exists ( $ helperClassName ) ) { throw new RuntimeException ( "Class " . $ helperClassName . " not found" ) ; } $ helper = new $ helperClassName ( $ this -> stdout ) ; $ this -> _helpers [ $ name ] = $ helper ; return $ helper ; }
Load given shell helper class
55,458
protected function _checkSure ( $ message = null , $ default = null ) { if ( empty ( $ message ) ) { $ message = __d ( 'cake_installer' , 'Are you sure?' ) ; } if ( empty ( $ default ) || ! in_array ( $ default , [ 'y' , 'n' ] ) ) { $ default = 'n' ; } $ options = [ 'y' , 'n' ] ; if ( ! empty ( $ this -> param ( 'yes' ) ) || ( $ this -> in ( $ message , $ options , $ default ) === 'y' ) ) { return true ; } else { return false ; } }
Asks the user if he is sure he wants to perform this action .
55,459
protected function _initUiLang ( ) { $ path = $ this -> path ; $ UIlang = $ this -> _readConfigCore ( $ path , '/(?<![\/]{2})Configure::write\(\'Config\.language\', \'([A-z]{3})\'\)[\s]*;/' ) ; if ( empty ( $ UIlang ) ) { $ UIlang = 'eng' ; } if ( ! Configure :: write ( 'Config.language' , $ UIlang ) ) { return false ; } if ( ! setlocale ( LC_ALL , $ UIlang ) ) { return false ; } return true ; }
Set installer UI language from settings file value .
55,460
protected function _configdb ( $ check = false ) { $ this -> out ( __d ( 'cake_installer' , 'Configure database connections' ) ) ; $ this -> hr ( ) ; if ( $ check && ( $ this -> InstallerCheck -> checkConnectDb ( $ this -> path , true ) === true ) ) { $ this -> out ( '<success>' . __d ( 'cake_installer' , 'This action has already been successfully completed. Skipped.' ) . '</success>' ) ; return true ; } $ result = $ this -> DbConfigExtend -> execute ( ) ; if ( $ check && $ result ) { $ result = null ; } return $ result ; }
Configure database connections .
55,461
protected function _securityKey ( $ path = null ) { if ( empty ( $ path ) ) { return false ; } $ oFile = new File ( $ path . 'Config' . DS . 'core.php' ) ; if ( ! $ oFile -> exists ( ) ) { return false ; } $ contents = $ oFile -> read ( ) ; $ key = '' ; for ( $ i = 0 ; $ i < 2 ; $ i ++ ) { $ key .= substr ( Security :: generateAuthKey ( ) , 0 , 32 ) ; } return $ this -> _writeConfigCore ( $ path , 'Configure::write(\'Security.key\', \'%s\')' , $ key , 'A random numeric string (digits only) used to encrypt/decrypt strings.' ) ; }
Create and write random key for Security . key in the settings file .
55,462
protected function _createdb ( $ check = false ) { $ this -> out ( __d ( 'cake_installer' , 'Creating database and initializing data' ) ) ; $ this -> hr ( ) ; $ resultCheck = $ this -> InstallerCheck -> checkDbTableExists ( ) ; if ( $ resultCheck ) { if ( $ check ) { $ this -> out ( '<success>' . __d ( 'cake_installer' , 'This action has already been successfully completed. Skipped.' ) . '</success>' ) ; return true ; } elseif ( $ this -> useActionNotify ) { if ( ! $ this -> _checkSure ( __d ( 'cake_installer' , 'All schemas exists. Re-create?' ) ) ) { return true ; } } } $ this -> out ( __d ( 'cake_installer' , 'Create schema of application' ) ) ; $ this -> hr ( ) ; $ yesArg = '' ; if ( ! empty ( $ this -> param ( 'yes' ) ) ) { $ yesArg = ' --yes' ; } $ defaultSchemaArgs = 'schema create --quiet' . $ yesArg ; $ this -> dispatchShell ( $ defaultSchemaArgs ) ; $ this -> hr ( ) ; $ this -> nl ( 1 ) ; $ schemaList = $ this -> ConfigInstaller -> getListSchemaCreation ( ) ; if ( empty ( $ schemaList ) ) { return true ; } $ this -> out ( __d ( 'cake_installer' , 'Create additional schemes' ) ) ; foreach ( $ schemaList as $ schemaName ) { if ( empty ( $ schemaName ) ) { continue ; } $ this -> hr ( ) ; $ this -> out ( __d ( 'cake_installer' , 'Create additional scheme: \'%s\'' , $ schemaName ) ) ; $ this -> hr ( ) ; $ this -> nl ( 1 ) ; $ additionalSchemaArgs = 'schema create ' . $ schemaName . ' --quiet' . $ yesArg ; $ this -> dispatchShell ( $ additionalSchemaArgs ) ; } $ this -> hr ( ) ; $ this -> out ( '<info>' . __d ( 'cake_installer' , 'Creating additional schemes completed.' ) . '</info>' ) ; return true ; }
Deploying the database .
55,463
protected function _createCrontabFile ( $ path = null ) { $ data = <<<EOD# Edit this file to introduce tasks to be run by cron.## Each task to run has to be defined through a single line# indicating with different fields when the task will be run# and what command to run for the task## To define the time you can provide concrete values for# minute (m), hour (h), day of month (dom), month (mon),# and day of week (dow) or use '*' in these fields (for 'any').## Notice that tasks will be started based on the cron's system# daemon's notion of time and timezones.## Output of the crontab jobs (including errors) is sent through# email to the user the crontab file belongs to (unless redirected).## For example, you can run a backup of all your user accounts# at 5 a.m every week with:# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/## For more information see the manual pages of crontab(5) and cron(8)## m h dom mon dow commandEOD ; $ oFile = new File ( $ path , true ) ; if ( ! $ oFile -> write ( $ data ) ) { return false ; } return $ oFile -> close ( ) ; }
Create dafault crontab file .
55,464
protected function _setbaseurl ( $ check = false ) { $ this -> out ( __d ( 'cake_installer' , 'Setting base URL' ) ) ; $ this -> hr ( ) ; $ path = $ this -> path ; $ currentBaseUrl = $ this -> _readConfigCore ( $ path , '/(?<![\/]{2})Configure::write\(\'App\.fullBaseUrl\', \'(http[s]?\:\/\/[A-z0-9\.\/]+)\'\)[\s]*;/' ) ; if ( ! empty ( $ currentBaseUrl ) ) { if ( $ check ) { $ this -> out ( '<success>' . __d ( 'cake_installer' , 'This action has already been successfully completed. Skipped.' ) . '</success>' ) ; return true ; } elseif ( $ this -> useActionNotify ) { if ( ! $ this -> _checkSure ( __d ( 'cake_installer' , 'Base URL set to \'%s\'. Change?' , $ currentBaseUrl ) ) ) { return true ; } } } $ baseUrl = $ this -> _getBaseUrl ( ) ; $ result = null ; if ( $ baseUrl !== $ currentBaseUrl ) { $ result = $ this -> _writeBaseUrl ( $ path , $ baseUrl ) ; } $ this -> hr ( ) ; if ( $ result === null ) { $ this -> out ( '<info>' . __d ( 'cake_installer' , 'Base URL is not changed.' ) . '</info>' ) ; $ result = true ; } elseif ( $ result ) { $ this -> out ( '<success>' . __d ( 'cake_installer' , 'Base URL set to \'%s\' successfully.' , $ baseUrl ) . '</success>' ) ; } else { $ this -> out ( '<error>' . __d ( 'cake_installer' , 'Unable to set Base URL, you should change it in %s' , $ path . 'Config' . DS . 'core.php' ) . '</error>' ) ; } return $ result ; }
Create and write base URL of application in the settings file .
55,465
protected function _checkSetSecurKey ( $ path = null ) { if ( empty ( $ path ) && ! file_exists ( $ path ) ) { return false ; } $ checkResult = true ; $ File = new File ( $ path . 'Config' . DS . 'core.php' ) ; $ contents = $ File -> read ( ) ; if ( empty ( $ contents ) ) { return false ; } $ patterns = [ '/(?<![\/]{2})Configure::write\(\'Security.salt\',[\s\'A-z0-9]*\);/' , '/(?<![\/]{2})Configure::write\(\'Security.cipherSeed\',[\s\'A-z0-9]*\);/' , '/(?<![\/]{2})Configure::write\(\'Security.key\',[\s\'A-z0-9]*\);/' ] ; foreach ( $ patterns as $ pattern ) { $ checkResult = $ checkResult && ( bool ) preg_match ( $ pattern , $ contents ) ; } return $ checkResult ; }
Check already written security keys in the settings file .
55,466
protected function _setsecurkey ( $ check = false , $ boot = true ) { $ this -> out ( __d ( 'cake_installer' , 'Setting security keys' ) ) ; $ this -> hr ( ) ; $ path = $ this -> path ; $ resultCheck = $ this -> _checkSetSecurKey ( $ path ) ; if ( $ resultCheck ) { if ( $ check ) { $ this -> out ( '<success>' . __d ( 'cake_installer' , 'This action has already been successfully completed. Skipped.' ) . '</success>' ) ; return true ; } elseif ( $ this -> useActionNotify ) { if ( ! $ this -> _checkSure ( __d ( 'cake_installer' , 'The security keys is set. Rewrite?' ) ) ) { return true ; } } } $ result = true ; if ( $ this -> Project -> securitySalt ( $ path ) === true ) { $ this -> out ( '<success> * ' . __d ( 'cake_installer' , 'Random hash key created for \'Security.salt\'' ) . '</success>' ) ; } else { $ this -> out ( '<error>' . __d ( 'cake_installer' , 'Unable to generate random hash for \'Security.salt\', you should change it in %s' , $ path . 'Config' . DS . 'core.php' ) . '</error>' ) ; $ result = false ; } if ( $ this -> Project -> securityCipherSeed ( $ path ) === true ) { $ this -> out ( '<success> * ' . __d ( 'cake_installer' , 'Random seed created for \'Security.cipherSeed\'' ) . '</success>' ) ; } else { $ this -> out ( '<error>' . __d ( 'cake_installer' , 'Unable to generate random seed for \'Security.cipherSeed\', you should change it in %s' , $ path . 'Config' . DS . 'core.php' ) . '</error>' ) ; $ result = false ; } if ( $ this -> _securityKey ( $ path ) === true ) { $ this -> out ( '<success> * ' . __d ( 'cake_installer' , 'Random key created for \'Security.key\'' ) . '</success>' ) ; } else { $ this -> out ( '<error>' . __d ( 'cake_installer' , 'Unable to generate random key for \'Security.key\', you should change it in %s' , $ path . 'Config' . DS . 'core.php' ) . '</error>' ) ; $ result = false ; } $ this -> hr ( ) ; if ( $ result ) { Configure :: bootstrap ( $ boot ) ; $ this -> _initUiLang ( ) ; $ this -> out ( '<success>' . __d ( 'cake_installer' , 'The security keys is written successfully.' ) . '</success>' ) ; } else { $ this -> out ( '<error>' . __d ( 'cake_installer' , 'The security keys is written unsuccessfully.' ) . '</error>' ) ; } return $ result ; }
Create and write security keys in the settings file .
55,467
protected function _check ( ) { $ result = true ; $ this -> out ( __d ( 'cake_installer' , 'Checking PHP version' ) ) ; $ this -> hr ( ) ; $ phpVesion = $ this -> InstallerCheck -> checkPHPversion ( ) ; if ( $ phpVesion !== null ) { if ( $ phpVesion ) { $ state = '<success>' . __d ( 'cake_installer' , 'Ok' ) . '</success>' ; } else { $ state = '<error>' . __d ( 'cake_installer' , 'Bad' ) . '</error>' ; $ result = false ; } $ state = '[' . $ state . ']' ; $ message = ' * ' . __d ( 'cake_installer' , 'Current PHP version: %s' , PHP_VERSION ) ; $ formattedMessage = $ this -> state -> getState ( $ message , $ state , $ this -> maxWidth - 1 ) ; } else { $ formattedMessage = __d ( 'cake_installer' , 'Ok' ) ; } $ this -> out ( $ formattedMessage , 1 ) ; $ this -> hr ( ) ; $ this -> nl ( 1 ) ; $ this -> out ( __d ( 'cake_installer' , 'Checking PHP extensions' ) ) ; $ this -> hr ( ) ; $ phpModules = $ this -> InstallerCheck -> checkPhpExtensions ( ) ; if ( $ phpModules !== null ) { $ result = true ; $ messages = [ ] ; $ this -> waiting -> animateMessage ( ) ; foreach ( $ phpModules as $ moduleName => $ moduleState ) { switch ( $ moduleState ) { case 2 : $ state = '<success>' . __d ( 'cake_installer' , 'Ok' ) . '</success>' ; break ; case 1 : $ state = '<warning>' . __d ( 'cake_installer' , 'Ok' ) . '</warning>' ; break ; default : $ state = '<error>' . __d ( 'cake_installer' , 'Bad' ) . '</error>' ; $ result = false ; } $ state = '[' . $ state . ']' ; $ message = ' * ' . __d ( 'cake_installer' , 'Checking module is loaded: \'%s\'' , $ moduleName ) ; $ messages [ ] = $ this -> state -> getState ( $ message , $ state , $ this -> maxWidth - 1 ) ; $ this -> waiting -> animateMessage ( ) ; } $ this -> waiting -> hideMessage ( ) ; } else { $ messages = __d ( 'cake_installer' , 'Ok' ) ; } $ this -> out ( $ messages , 1 ) ; $ this -> hr ( ) ; $ this -> nl ( 1 ) ; if ( $ result ) { $ this -> out ( '<success>' . __d ( 'cake_installer' , 'Check completed successfully.' ) . '</success>' ) ; } else { $ this -> out ( '<error>' . __d ( 'cake_installer' , 'Check completed unsuccessfully.' ) . '</error>' ) ; } return $ result ; }
Checking PHP environment .
55,468
protected function _changeDirParam ( $ path = null , $ funcName = null , $ param = null ) { if ( empty ( $ path ) || ! file_exists ( $ path ) || ! in_array ( $ funcName , [ 'chown' , 'chmod' , 'chgrp' ] ) || empty ( $ param ) ) { return false ; } $ result = true ; if ( is_file ( $ path ) || is_dir ( $ path ) ) { $ resultCall = @ call_user_func ( $ funcName , $ path , $ param ) ; if ( $ resultCall ) { if ( is_file ( $ path ) ) { return true ; } } else { $ result = false ; } } else { return false ; } $ oFolder = new Folder ( $ path , false ) ; $ dirContent = $ oFolder -> read ( true , false , true ) ; foreach ( $ dirContent as $ targetPaths ) { foreach ( $ targetPaths as $ targetPath ) { if ( ! $ this -> _changeDirParam ( $ targetPath , $ funcName , $ param ) ) { $ result = false ; } } } return $ result ; }
Recursive change parameters of directory .
55,469
protected function _getTimeZone ( $ useExit = true ) { $ scopeTimeZoneList = [ DateTimeZone :: AFRICA => 'Africa' , DateTimeZone :: AMERICA => 'America' , DateTimeZone :: ANTARCTICA => 'Antarctica' , DateTimeZone :: ARCTIC => 'Arctic' , DateTimeZone :: ASIA => 'Asia' , DateTimeZone :: ATLANTIC => 'Atlantic' , DateTimeZone :: AUSTRALIA => 'Australia' , DateTimeZone :: EUROPE => 'Europe' , DateTimeZone :: INDIAN => 'Indian' , DateTimeZone :: PACIFIC => 'Pacific' , DateTimeZone :: UTC => 'UTC' ] ; $ currentTz = date_default_timezone_get ( ) ; $ currentTzInfoScope = null ; $ currentTzInfo = explode ( '/' , $ currentTz , 2 ) ; if ( count ( $ currentTzInfo ) == 2 ) { $ currentTzInfoScopeName = array_shift ( $ currentTzInfo ) ; $ currentTzInfoScopeKey = array_search ( $ currentTzInfoScopeName , $ scopeTimeZoneList ) ; if ( $ currentTzInfoScopeKey ) { $ currentTzInfoScope = $ currentTzInfoScopeKey ; } } $ inputMessage = __d ( 'cake_installer' , 'Input the number of scope time zone from list' ) ; $ titleMessage = __d ( 'cake_installer' , 'Please choose scope of time zone:' ) ; $ scopeTimeZone = $ this -> inputFromList ( $ this , $ scopeTimeZoneList , $ inputMessage , $ titleMessage , $ currentTzInfoScope , $ useExit ) ; $ timeZoneIds = DateTimeZone :: listIdentifiers ( $ scopeTimeZone ) ; $ timeZoneList = array_combine ( $ timeZoneIds , $ timeZoneIds ) ; $ inputMessage = __d ( 'cake_installer' , 'Input the number of timezone from list' ) ; $ titleMessage = __d ( 'cake_installer' , 'Please choose time zone:' ) ; $ this -> clear ( ) ; return $ this -> inputFromList ( $ this , $ timeZoneList , $ inputMessage , $ titleMessage , $ currentTz , false ) ; }
Return time zone from list .
55,470
protected function _getBaseUrl ( ) { do { $ baseUrl = $ this -> in ( __d ( 'cake_installer' , 'Input base URL (e.g. %s):' , 'http://someapp.fabrikam.com' ) ) ; $ baseUrl = trim ( $ baseUrl ) ; } while ( ! preg_match ( '/http[s]?\:\/\/[A-z0-9\.\/]+/' , $ baseUrl ) ) ; return trim ( $ baseUrl , '/' ) ; }
Return base URL for application .
55,471
protected function _readConfigCore ( $ path = null , $ configPattern = null ) { if ( empty ( $ path ) || empty ( $ configPattern ) ) { return false ; } $ oFile = new File ( $ path . 'Config' . DS . 'core.php' ) ; if ( ! $ oFile -> exists ( ) ) { return false ; } $ contents = $ oFile -> read ( ) ; if ( ! preg_match ( $ configPattern , $ contents , $ match ) || ( count ( $ match ) < 1 ) ) { return false ; } return $ match [ 1 ] ; }
Read configuration from the settings file .
55,472
protected function _writeConfigCore ( $ path = null , $ configTempl = null , $ configValue = null , $ configComment = null ) { if ( empty ( $ path ) || empty ( $ configTempl ) || empty ( $ configValue ) ) { return false ; } $ oFile = new File ( $ path . 'Config' . DS . 'core.php' ) ; if ( ! $ oFile -> exists ( ) ) { return false ; } $ contents = $ oFile -> read ( ) ; $ pattern = '/^[\s]*(?:[\/]{2}|)[\s]*(' . sprintf ( preg_quote ( $ configTempl , '/' ) , '.*' ) . '[\s]*;)/m' ; $ configStr = sprintf ( $ configTempl , $ configValue ) . ';' ; if ( preg_match ( $ pattern , $ contents , $ match ) ) { $ result = str_replace ( $ match [ 0 ] , "\t" . $ configStr , $ contents ) ; } else { $ result = $ contents ; if ( ! empty ( $ configComment ) ) { $ result .= sprintf ( "\n/**\n * %s\n */" , $ configComment ) ; } $ result .= "\n\t" . $ configStr . "\n" ; } return $ oFile -> write ( $ result ) ; }
Create and write configuration in the settings file .
55,473
protected function _writeConfigLanguage ( $ path = null , $ language = null ) { if ( ! $ this -> _writeConfigCore ( $ path , 'Configure::write(\'Config.language\', \'%s\')' , $ language ) ) { return false ; } if ( ! $ this -> _writeConfigCore ( $ path , 'setLocale(LC_ALL, \'%s\')' , $ language ) ) { return false ; } return true ; }
Create and write language of application UI in the settings file .
55,474
public function create ( $ id = null ) { if ( $ id === null ) { if ( $ id = get_the_author_meta ( 'ID' ) ) { return new Author ( new WP_User ( $ id ) ) ; } else { throw new Exception ( 'Please supply an author ID when not within The Loop' ) ; } } return new Author ( new WP_User ( $ id ) ) ; }
Create an author from a Wordpress user ID .
55,475
public function forClass ( string $ class ) : MetaClass { $ cacheName = 'MetaForClass:' . $ class ; $ meta = $ this -> cache -> get ( $ cacheName ) ; if ( ! $ meta instanceof MetaClass ) { $ data = $ this -> source -> forClass ( $ class ) ; $ meta = $ this -> asMeta ( $ data ) ; $ this -> cache -> set ( $ cacheName , $ meta ) ; } return $ meta ; }
Get meta for given class
55,476
private function isComment ( $ line ) { if ( empty ( $ line ) ) return true ; $ is_comment = false ; foreach ( $ this -> _comment_character_list as $ comment_char ) { $ line = trim ( $ line ) ; if ( strpos ( $ line , $ comment_char ) !== false && strpos ( $ line , $ comment_char ) <= 3 ) { $ is_comment = true ; break ; } } return $ is_comment ; }
checks if it s a comment in the config
55,477
private function isConstantValue ( $ value ) : bool { if ( \ is_array ( $ value ) ) { foreach ( $ value as $ item ) { if ( ! $ this -> isConstantValue ( $ item ) ) { return false ; } } return true ; } return $ value === null || is_scalar ( $ value ) ; }
Tests if the given value is a constant value .
55,478
private function addMethod ( string $ method ) : void { if ( ! HttpMethod :: isValid ( $ method ) ) { throw new \ InvalidArgumentException ( "Invalid HTTP request method '$method'" ) ; } $ this -> methods [ ] = $ method ; }
Adds a method to the list of allowed HTTP request methods .
55,479
private function addSegment ( string $ segment ) : void { preg_match_all ( "/\{(?'name'[a-z0-9_]++)(?::(?'pattern'(?:[^{}]++|\{(?&pattern)\})++))?\}/i" , $ segment , $ matches , \ PREG_SET_ORDER | \ PREG_OFFSET_CAPTURE | \ PREG_UNMATCHED_AS_NULL ) ; if ( empty ( $ matches ) ) { $ this -> segments [ ] = $ segment ; $ this -> format .= $ this -> formatEncode ( $ segment ) . '/' ; return ; } $ pattern = $ this -> formatPattern ( $ segment , $ matches ) ; $ this -> patterns [ \ count ( $ this -> segments ) ] = sprintf ( '/%s/' , $ pattern ) ; $ this -> segments [ ] = self :: DYNAMIC_SEGMENT ; }
Appends a path segment to the list of matched path segments for the route .
55,480
private function formatPattern ( string $ segment , array $ matches ) : string { $ fullPattern = $ this -> appendPattern ( '' , $ segment , 0 , $ matches [ 0 ] [ 0 ] [ 1 ] ) ; foreach ( $ matches as $ i => $ match ) { $ name = $ match [ 'name' ] [ 0 ] ; $ pattern = $ match [ 'pattern' ] [ 0 ] ?? '.*' ; $ this -> format .= '%s' ; if ( \ in_array ( $ name , $ this -> parameterNames , true ) ) { throw new \ InvalidArgumentException ( "Duplicate parameter name '$name'" ) ; } if ( ! $ this -> isValidPattern ( $ pattern ) ) { throw new \ InvalidArgumentException ( "Invalid regular expression '$pattern'" ) ; } $ this -> parameterNames [ ] = $ name ; $ fullPattern .= sprintf ( "(?'%s'%s)" , $ name , $ pattern ) ; $ start = $ match [ 0 ] [ 1 ] + \ strlen ( $ match [ 0 ] [ 0 ] ) ; $ length = ( $ matches [ $ i + 1 ] [ 0 ] [ 1 ] ?? \ strlen ( $ segment ) ) - $ start ; $ fullPattern = $ this -> appendPattern ( $ fullPattern , $ segment , $ start , $ length ) ; } $ this -> format .= '/' ; return $ fullPattern ; }
Creates a dynamic segment regular expression based on the provided segment .
55,481
private function appendPattern ( string $ pattern , string $ segment , int $ start , int $ length ) : string { if ( $ length < 1 ) { return $ pattern ; } $ constant = substr ( $ segment , $ start , $ length ) ; $ this -> format .= $ this -> formatEncode ( $ constant ) ; return $ pattern . preg_quote ( $ constant , '/' ) ; }
Appends a static section to the pattern from the given segment .
55,482
private function isValidPattern ( string $ pattern ) : bool { set_error_handler ( function ( int $ severity , string $ message , string $ file , int $ line ) : bool { throw new \ ErrorException ( $ message , 0 , $ severity , $ file , $ line ) ; } , \ E_ALL ) ; try { $ result = preg_match ( "/$pattern/" , '' ) ; } catch ( \ ErrorException $ exception ) { $ errorMessage = sprintf ( "Invalid regular expression '%s': %s" , $ pattern , $ exception -> getMessage ( ) ) ; throw new \ InvalidArgumentException ( $ errorMessage , 0 , $ exception ) ; } finally { restore_error_handler ( ) ; } return $ result !== false ; }
Tells if the given string is a valid regular expression without delimiters .
55,483
public static function createFromCache ( array $ cache ) : self { $ definition = ( new \ ReflectionClass ( static :: class ) ) -> newInstanceWithoutConstructor ( ) ; [ $ definition -> name , $ definition -> methods , $ definition -> segments , $ definition -> patterns , $ definition -> handler , $ definition -> format , $ definition -> parameterNames , ] = $ cache ; return $ definition ; }
Returns a new RouteDefinition instance based on the cached values .
55,484
public function getDefinitionCache ( ) : array { return [ $ this -> name , $ this -> methods , $ this -> segments , $ this -> patterns , $ this -> handler , $ this -> format , $ this -> parameterNames , ] ; }
Returns cached values for the RouteDefinition that can be used to instantiate a new RouteDefinition .
55,485
public function matchPatterns ( array $ segments , array & $ values ) : bool { $ parsed = [ ] ; foreach ( $ this -> patterns as $ i => $ pattern ) { if ( ! preg_match ( $ pattern , $ segments [ $ i ] , $ match ) ) { return false ; } if ( $ match [ 0 ] !== $ segments [ $ i ] ) { return false ; } $ parsed += array_intersect_key ( $ match , array_flip ( $ this -> parameterNames ) ) ; } $ values = $ parsed ; return true ; }
Matches the given segments against the dynamic path segments .
55,486
public function isMethodAllowed ( string $ method ) : bool { if ( \ in_array ( $ method , $ this -> methods , true ) ) { return true ; } if ( $ method === HttpMethod :: HEAD ) { return \ in_array ( HttpMethod :: GET , $ this -> methods , true ) ; } return false ; }
Tells if the given HTTP request method is allowed by the route .
55,487
public function formatUrl ( array $ parameters = [ ] ) : string { $ values = [ ] ; foreach ( $ this -> parameterNames as $ name ) { if ( ! isset ( $ parameters [ $ name ] ) ) { throw new \ InvalidArgumentException ( "Missing route parameter '$name'" ) ; } $ values [ ] = rawurlencode ( $ parameters [ $ name ] ) ; unset ( $ parameters [ $ name ] ) ; } if ( ! empty ( $ parameters ) ) { throw new \ InvalidArgumentException ( 'Unexpected route parameters: ' . implode ( ', ' , array_keys ( $ parameters ) ) ) ; } return vsprintf ( $ this -> format , $ values ) ; }
Returns an encoded URL for the route based on the given parameter values .
55,488
public function addDataAuthorizationCheck ( $ attributes , $ dataKey = null , \ Closure $ callback = null ) { if ( null === $ dataKey ) { $ dataKey = 'item' ; } $ this -> security -> addDataCheck ( $ attributes , $ dataKey , $ callback ) ; return $ this ; }
Check for object in data feature .
55,489
protected function initialiseClient ( array $ config = [ ] ) { if ( ! isset ( $ config [ 'handler' ] ) || ! $ config [ 'handler' ] instanceof HandlerStack ) { $ handlerStack = HandlerStack :: create ( new CurlHandler ( ) ) ; $ handlerStack -> push ( Middleware :: retry ( $ this -> retryDecider ( ) ) ) ; $ config [ 'handler' ] = $ handlerStack ; } return new Client ( $ config ) ; }
Set up retry middleware
55,490
private function catcher ( ) { foreach ( $ this -> tracker -> getRunning ( ) as $ uid => $ request ) { if ( ProcessTools :: isRunning ( $ request -> getPid ( ) ) === false ) { $ this -> ipc -> close ( $ uid , Ipc :: WRITER ) ; try { $ raw_output = $ this -> ipc -> read ( $ uid ) ; $ result = unserialize ( rtrim ( $ raw_output ) ) ; $ this -> ipc -> close ( $ uid , Ipc :: READER ) ; } catch ( Exception $ e ) { $ result = self :: generateSyntheticResult ( $ uid , $ e -> getMessage ( ) , $ request -> getJid ( ) , false ) ; } if ( $ request -> isChain ( ) ) $ this -> evalChain ( $ request , $ result ) ; $ this -> updateTrackerSetCompleted ( $ uid , $ result ) ; $ success = $ result -> success === false ? "error" : "success" ; $ this -> logger -> notice ( "Task " . $ request -> getName ( ) . "(uid: " . $ request -> getUid ( ) . ") ends in $success" ) ; } else { $ current_time = microtime ( true ) ; $ request_max_time = $ request -> getMaxtime ( ) ; $ maxtime = $ request_max_time === null ? $ this -> max_runtime : $ request_max_time ; if ( $ current_time > $ request -> getStartTimestamp ( ) + $ maxtime ) { $ pid = $ request -> getPid ( ) ; $ this -> logger -> warning ( "Killing pid $pid due to maximum exec time reached" , [ "START_TIME" => $ request -> getStartTimestamp ( ) , "CURRENT_TIME" => $ current_time , "MAX_RUNTIME" => $ maxtime ] ) ; $ kill = ProcessTools :: term ( $ pid , $ this -> lagger_timeout ) ; if ( $ kill ) { $ this -> logger -> warning ( "Pid $pid killed" ) ; } else { $ this -> logger -> warning ( "Pid $pid could not be killed" ) ; } $ this -> ipc -> hang ( $ uid ) ; $ result = self :: generateSyntheticResult ( $ uid , "Job killed due to max runtime reached" , $ request -> getJid ( ) , false ) ; if ( $ request -> isChain ( ) ) $ this -> evalChain ( $ request , $ result ) ; $ this -> updateTrackerSetCompleted ( $ uid , $ result ) ; $ this -> logger -> notice ( "Task " . $ request -> getName ( ) . "(uid: $uid) ends in error" ) ; } } } }
Catch results from completed jobs
55,491
public function sendRequest ( RequestInterface $ request ) : void { $ requestId = $ this -> getRequestId ( $ request ) ; $ this -> pendingRequests [ $ requestId ] = $ this -> createPromiseForRequest ( $ request , true ) ; }
Sends the request to the API server . This method is non - blocking and will not wait for the request to actually finish .
55,492
public function fetchResponse ( RequestInterface $ request ) : ResponseInterface { $ requestId = $ this -> getRequestId ( $ request ) ; if ( ! isset ( $ this -> pendingRequests [ $ requestId ] ) ) { $ this -> pendingRequests [ $ requestId ] = $ this -> createPromiseForRequest ( $ request , true ) ; } try { $ response = $ this -> pendingRequests [ $ requestId ] -> wait ( ) ; } finally { unset ( $ this -> pendingRequests [ $ requestId ] ) ; } return $ response ; }
Fetches the response of the request . This method is blocking and will wait for the request to actually finish . If the request has not been sent to the server yet it will be sent with this method call .
55,493
protected function createPromiseForRequest ( RequestInterface $ request , bool $ processApiException ) : PromiseInterface { $ clientRequest = $ this -> createClientRequest ( $ request ) ; $ promise = $ this -> guzzleClient -> sendAsync ( $ clientRequest ) ; $ promise = $ promise -> then ( function ( PsrResponseInterface $ clientResponse ) use ( $ request , $ clientRequest ) : ResponseInterface { return $ this -> processResponse ( $ request , $ clientRequest , $ clientResponse ) ; } , function ( RequestException $ exception ) : void { $ this -> processException ( $ exception ) ; } ) ; if ( $ processApiException ) { $ promise = $ promise -> then ( null , function ( ApiClientException $ exception ) use ( $ request ) : ResponseInterface { return $ this -> processApiClientException ( $ exception , $ request ) ; } ) ; } return $ promise ; }
Creates and returns the promise for the request . This will actually send the request to the API server .
55,494
protected function createClientRequest ( RequestInterface $ request ) : PsrRequestInterface { $ endpoint = $ this -> endpointService -> getEndpointForRequest ( $ request ) ; return new Request ( 'POST' , $ endpoint -> getRequestPath ( ) , $ this -> getRequestHeaders ( $ endpoint ) , $ this -> serializer -> serialize ( $ request , 'json' ) ) ; }
Creates the request actually send through the HTTP client .
55,495
protected function getRequestHeaders ( EndpointInterface $ endpoint ) : array { $ result = [ 'Accept' => 'application/json' , 'Accept-Language' => $ this -> options -> getLocale ( ) , 'Content-Type' => 'application/json' , ] ; if ( $ endpoint -> requiresAuthorizationToken ( ) ) { $ result [ 'Authorization' ] = 'Bearer ' . $ this -> requestAuthorizationToken ( ) ; } return $ result ; }
Returns the request headers to use for the endpoint .
55,496
protected function requestAuthorizationToken ( ) : string { $ result = $ this -> options -> getAuthorizationToken ( ) ; if ( $ result === '' ) { $ authRequest = new AuthRequest ( ) ; $ authRequest -> setAgent ( $ this -> options -> getAgent ( ) ) -> setAccessKey ( $ this -> options -> getAccessKey ( ) ) -> setEnabledModNames ( $ this -> options -> getEnabledModNames ( ) ) ; $ authResponse = $ this -> fetchResponse ( $ authRequest ) ; if ( $ authResponse instanceof AuthResponse ) { $ result = $ authResponse -> getAuthorizationToken ( ) ; $ this -> options -> setAuthorizationToken ( $ result ) ; } } return $ result ; }
Requests the authorization token if it is not already available .
55,497
protected function processResponse ( RequestInterface $ request , PsrRequestInterface $ clientRequest , PsrResponseInterface $ clientResponse ) : ResponseInterface { $ endpoint = $ this -> endpointService -> getEndpointForRequest ( $ request ) ; $ responseContents = $ this -> getContentsFromMessage ( $ clientResponse ) ; try { $ result = $ this -> serializer -> deserialize ( $ responseContents , $ endpoint -> getResponseClass ( ) , 'json' ) ; } catch ( Exception $ e ) { $ requestContents = $ this -> getContentsFromMessage ( $ clientRequest ) ; throw new InvalidResponseException ( $ e -> getMessage ( ) , $ requestContents , $ responseContents , $ e ) ; } return $ result ; }
Processes the response received from the HTTP client .
55,498
protected function processException ( RequestException $ exception ) : void { $ requestContents = $ this -> getContentsFromMessage ( $ exception -> getRequest ( ) ) ; $ responseContents = $ this -> getContentsFromMessage ( $ exception -> getResponse ( ) ) ; if ( $ exception instanceof ConnectException ) { throw new ConnectionException ( $ exception -> getMessage ( ) , $ requestContents , $ exception ) ; } else { $ message = $ this -> extractMessageFromErrorResponse ( $ responseContents , $ exception -> getMessage ( ) ) ; $ statusCode = 0 ; if ( $ exception -> getResponse ( ) instanceof PsrResponseInterface ) { $ statusCode = $ exception -> getResponse ( ) -> getStatusCode ( ) ; } throw $ this -> createApiClientException ( $ statusCode , $ message , $ requestContents , $ responseContents ) ; } }
Processes the exception thrown by the HTTP client .
55,499
protected function extractMessageFromErrorResponse ( string $ responseContents , string $ fallbackMessage ) : string { $ result = $ fallbackMessage ; try { $ errorResponse = $ this -> serializer -> deserialize ( $ responseContents , ErrorResponse :: class , 'json' ) ; if ( $ errorResponse instanceof ErrorResponse ) { $ result = $ errorResponse -> getError ( ) -> getMessage ( ) ; } } catch ( Exception $ e ) { } return $ result ; }
Tries to extract the message from an error response .