idx
int64 0
60.3k
| question
stringlengths 64
4.24k
| target
stringlengths 5
618
|
|---|---|---|
57,200
|
public function detectConfiguration ( ) { if ( empty ( $ this -> file_readers ) ) { $ this -> file_readers = [ JsonReader :: class => new JsonReader ( ) , GraphMLReader :: class => new GraphMLReader ( ) , BpmnReader :: class => new BpmnReader ( ) , ] ; } if ( $ this -> file_list === null ) { $ dh = opendir ( $ this -> base_dir ) ; if ( ! $ dh ) { throw new RuntimeException ( 'Cannot open base dir: ' . $ this -> base_dir ) ; } $ this -> file_list = [ ] ; while ( ( $ file = readdir ( $ dh ) ) !== false ) { if ( $ file [ 0 ] != '.' ) { $ this -> file_list [ ] = $ file ; } } closedir ( $ dh ) ; } }
|
Scan for the configuration and build list of files but do not load the files .
|
57,201
|
public function loadConfiguration ( ) : array { $ this -> detectConfiguration ( ) ; $ machine_type_table = [ ] ; foreach ( $ this -> file_list as $ file ) { if ( preg_match ( '/^(.*)\.json(\.php)?$/i' , $ file , $ m ) ) { $ machine_type = $ m [ 1 ] ; $ machine_def = [ ] ; $ include_queue = [ $ file ] ; $ included_files = [ ] ; $ postprocess_list = [ ] ; $ errors = [ ] ; while ( ( $ include = array_shift ( $ include_queue ) ) !== null ) { if ( ! is_array ( $ include ) ) { $ include_file = $ include ; $ include_opts = [ ] ; } else { $ include_file = $ include [ 'file' ] ; $ include_opts = $ include ; } if ( ! empty ( $ included_files [ $ include_file ] ) ) { throw new RuntimeException ( "Cyclic dependency found when including \"$include_file\"." ) ; } else { $ included_files [ $ include_file ] = true ; } if ( $ include_file [ 0 ] != '/' ) { $ include_file = $ this -> base_dir . $ include_file ; } $ reader = null ; $ parsed_content = $ this -> parseFile ( $ machine_type , $ include_file , $ include_opts , $ reader ) ; if ( ! empty ( $ parsed_content [ 'include' ] ) ) { foreach ( $ parsed_content [ 'include' ] as $ new_include ) { $ include_queue [ ] = $ new_include ; } } $ machine_def = array_replace_recursive ( $ parsed_content , $ machine_def ) ; if ( $ reader ) { $ postprocess_list [ spl_object_hash ( $ reader ) ] = $ reader ; } } foreach ( $ postprocess_list as $ postprocessor ) { $ postprocessor -> postprocessDefinition ( $ machine_type , $ machine_def , $ errors ) ; } if ( ! empty ( $ errors ) ) { $ machine_def [ 'errors' ] = $ errors ; } $ machine_type_table [ $ machine_type ] = $ machine_def ; } } ksort ( $ machine_type_table ) ; return $ machine_type_table ; }
|
Load the configuration from the JSON files .
|
57,202
|
public static function string ( $ value , $ max_length = null ) { $ value = filter_var ( trim ( $ value ) , FILTER_SANITIZE_STRING ) ; if ( $ max_length && mb_strlen ( $ value ) > $ max_length ) { $ value = mb_substr ( $ value , 0 , $ max_length ) ; } return $ value ; }
|
Filter string applies FILTER_SANITIZE_STRING
|
57,203
|
public static function typecast ( & $ value , $ type ) { switch ( $ type ) { case Validate :: TYPE_INT : case Validate :: TYPE_UINT : $ value = intval ( $ value ) ; break ; case Validate :: TYPE_FLOAT : $ value = floatval ( $ value ) ; break ; case Validate :: TYPE_DOUBLE : $ value = doubleval ( $ value ) ; break ; case Validate :: TYPE_BOOLEAN : $ value = boolval ( $ value ) ; break ; case Validate :: TYPE_UNIX_TIMESTAMP : $ value = intval ( $ value ) + ( \ Phramework \ Phramework :: getTimezoneOffset ( ) * 60 ) ; break ; } }
|
Typecast a value
|
57,204
|
public static function castEntry ( $ entry , $ model ) { if ( ! $ entry ) { return $ entry ; } $ timestamp_format = \ Phramework \ Phramework :: getSetting ( 'timestamp_format' , null , 'Y-m-d\TH:i:s\Z' ) ; foreach ( $ model as $ k => $ v ) { if ( ! isset ( $ entry [ $ k ] ) ) { continue ; } Filter :: typecast ( $ entry [ $ k ] , $ v ) ; if ( $ v === Validate :: TYPE_UNIX_TIMESTAMP ) { $ converted = gmdate ( $ timestamp_format , $ entry [ $ k ] ) ; $ entry [ $ k . '_formatted' ] = $ converted ; } } return $ entry ; }
|
Type cast entry s attributes based on the provided model
|
57,205
|
public static function cast ( $ list , $ model ) { if ( ! $ list ) { return $ list ; } foreach ( $ list as $ k => & $ v ) { $ v = self :: castEntry ( $ v , $ model ) ; } return $ list ; }
|
Type cast each entry of list based on the provided model
|
57,206
|
public function all ( string $ path , $ handler , string $ name = null ) : Route { $ route = new Route ( $ path , $ handler , [ ] , $ name ) ; $ this -> adapter -> addRoute ( $ route ) ; return $ route ; }
|
Adds a route for all http method .
|
57,207
|
public function create ( $ taxonomy ) { if ( ! ( $ taxonomy instanceof stdClass ) ) { $ taxonomy = get_taxonomy ( $ taxonomy ) ; } return new Taxonomy ( $ taxonomy , $ this -> termFactory ) ; }
|
Create a new Taxonomy object .
|
57,208
|
public function apply ( $ testable , array $ config = array ( ) ) { $ tokens = $ testable -> tokens ( ) ; foreach ( $ this -> inspector as $ inspector ) { if ( isset ( $ inspector [ 'tokens' ] ) ) { $ byToken = $ testable -> findAll ( $ inspector [ 'tokens' ] ) ; } else { $ byToken = array ( ) ; } if ( isset ( $ inspector [ 'content' ] ) ) { $ byContent = $ testable -> findAllContent ( $ inspector [ 'content' ] ) ; } else { $ byContent = array ( ) ; } foreach ( array_merge ( $ byToken , $ byContent ) as $ id ) { $ token = $ tokens [ $ id ] ; $ isPHP = $ testable -> isPHP ( $ token [ 'line' ] ) ; if ( $ isPHP && empty ( $ token [ 'isString' ] ) ) { $ pattern = String :: insert ( $ inspector [ 'regex' ] , array ( 'content' => preg_quote ( $ token [ 'content' ] , "/" ) , ) ) ; $ firstId = $ id - $ inspector [ 'relativeTokens' ] [ 'before' ] ; $ firstId = ( $ firstId < 0 ) ? 0 : $ firstId ; $ length = $ inspector [ 'relativeTokens' ] [ 'length' ] ; $ inspectTokens = array_slice ( $ tokens , $ firstId , $ length ) ; $ html = null ; foreach ( $ inspectTokens as $ htmlToken ) { $ html .= $ htmlToken [ 'content' ] ; } if ( preg_match ( $ pattern , $ html ) === 0 ) { $ this -> addViolation ( array ( 'message' => String :: insert ( $ inspector [ 'message' ] , $ token ) , 'line' => $ token [ 'line' ] , ) ) ; } } } } }
|
With lots of various rules we created 4 various rulesets for operators . If one of the tokens or content is found we use the given regex on the joined array .
|
57,209
|
function sendRequest ( BambooHTTPRequest $ request ) { $ response = parent :: sendRequest ( $ request ) ; if ( $ response -> isError ( ) ) { $ error = [ ] ; $ error [ ] = $ response -> statusCode ; $ error [ ] = "BambooHR Error" ; $ error [ ] = $ response -> getErrorMessage ( ) ; throw new BambooHRException ( implode ( " - " , $ error ) , 1 ) ; } return $ response ; }
|
Perform the request described by the BambooHTTPRequest . Return a BambooHTTPResponse describing the response .
|
57,210
|
public function getPixel ( $ x , $ y ) { $ driver = $ this -> getDriver ( ) ; return $ driver -> getPixel ( $ this -> resource , $ x , $ y ) ; }
|
Get pixel value of given coordinate
|
57,211
|
protected function autodetectDriver ( $ knownDrivers ) { foreach ( $ knownDrivers as $ knownDriver ) { try { $ driver = new $ knownDriver ( ) ; if ( $ driver instanceof DriverInterface ) { return $ driver ; } } catch ( \ Exception $ e ) { continue ; } } return null ; }
|
Auto detect driver
|
57,212
|
public static function ul ( $ data = [ ] , $ class = null ) { $ out = [ ] ; if ( is_string ( $ data ) ) { $ data = ( array ) $ data ; } if ( ! empty ( $ data ) ) { if ( ! empty ( $ class ) ) { $ out [ ] = sprintf ( '<ul class="%s">' , $ class ) ; } else { $ out [ ] = '<ul>' ; } foreach ( $ data as $ item ) { $ out [ ] = sprintf ( '<li>%s</li>' , $ item ) ; } $ out [ ] = '</ul>' ; } return join ( "\n" , $ out ) ; }
|
Generate an HTML unordered list from an array .
|
57,213
|
protected function _getExistsConfig ( ) { $ defaultConfigsDBconn = $ this -> _getDefaultConfigs ( ) ; $ customConfigsDBconn = $ this -> ConfigInstaller -> getCustomConnectionsConfig ( ) ; $ configsDBconn = $ defaultConfigsDBconn + $ customConfigsDBconn + [ 'test' => $ defaultConfigsDBconn [ 'default' ] ] ; $ currConfigDBconn = $ this -> ConfigInstaller -> getListDbConnConfigs ( ) ; $ existConfigDBconn = array_intersect_key ( $ configsDBconn , array_flip ( $ currConfigDBconn ) ) ; if ( empty ( $ existConfigDBconn ) ) { $ existConfigDBconn = array_intersect_key ( $ configsDBconn , [ 'default' => null ] ) ; } return $ existConfigDBconn ; }
|
Return existing connection configuration to create
|
57,214
|
protected function _checkPcrePattern ( $ pattern = null ) { if ( empty ( $ pattern ) ) { return null ; } $ result = true ; try { $ matchResult = @ preg_match ( $ pattern , 'some text' ) ; if ( $ matchResult === false ) { $ result = false ; } } catch ( Exception $ exception ) { $ result = false ; } return $ result ; }
|
Check PCRE pattern
|
57,215
|
protected function _verify ( $ config = null , $ labels = null , $ name = null ) { $ this -> clear ( ) ; if ( empty ( $ name ) ) { $ name = '-' ; } $ this -> out ( ) ; $ this -> hr ( ) ; $ this -> out ( __d ( 'cake_installer' , 'The following database configuration will be created:' ) ) ; $ this -> hr ( ) ; $ this -> out ( __d ( 'cake_installer' , 'Database Configuration: %s' , ucfirst ( $ name ) ) ) ; $ this -> hr ( ) ; $ data = [ [ __d ( 'cake_installer' , 'Parameter name' ) , __d ( 'cake_installer' , 'Parameter value' ) , ] ] ; foreach ( $ config as $ param => $ value ) { $ label = $ param ; if ( isset ( $ labels [ $ param ] ) ) { $ label = $ labels [ $ param ] ; } $ data [ ] = [ $ this -> _prepareParamLabel ( $ label , 30 ) , $ this -> _prepareParamValue ( $ param , $ value , 30 ) ] ; } $ this -> helper ( 'table' ) -> output ( $ data ) ; $ this -> hr ( ) ; $ looksOk = $ this -> in ( __d ( 'cake_installer' , 'Look okay?' ) , [ 'y' , 'n' ] , 'y' ) ; if ( strtolower ( $ looksOk ) === 'y' ) { return true ; } return false ; }
|
Output verification message
|
57,216
|
protected function _prepareParamLabel ( $ label = null , $ length = 0 ) { $ truncateOpt = [ 'ellipsis' => '...' , 'exact' => false , 'html' => false ] ; if ( empty ( $ label ) || ( $ length <= 0 ) ) { return $ label ; } $ label = CakeText :: truncate ( $ label , $ length , $ truncateOpt ) ; return $ label ; }
|
Return label truncated to the length
|
57,217
|
protected function _exportParamValue ( $ value = null , $ length = 0 ) { $ truncateOpt = [ 'ellipsis' => '...' , 'exact' => false , 'html' => false ] ; $ valueText = var_export ( $ value , true ) ; $ valueType = Debugger :: getType ( $ value ) ; switch ( $ valueType ) { case 'string' : if ( ctype_digit ( $ value ) ) { $ valueText = ( int ) $ value ; } break ; case 'resource' : case 'unknown' : $ valueText = 'null' ; break ; } if ( $ length > 0 ) { $ valueText = CakeText :: truncate ( $ valueText , $ length , $ truncateOpt ) ; } return $ valueText ; }
|
Returns parameter value prepared to save and truncated to the length .
|
57,218
|
public function bake ( $ configs ) { if ( ! is_dir ( $ this -> path ) ) { $ this -> out ( '<error>' . __d ( 'cake_installer' , '%s not found' , $ this -> path ) . '</error>' ) ; return false ; } $ filename = $ this -> path . 'database.php' ; $ oldConfigs = [ ] ; if ( file_exists ( $ filename ) ) { config ( 'database' ) ; $ db = new $ this -> databaseClassName ; $ temp = get_class_vars ( get_class ( $ db ) ) ; foreach ( $ temp as $ configName => $ info ) { $ oldConfigs [ $ configName ] = $ info ; } } foreach ( $ oldConfigs as $ oldConfigName => $ oldConfig ) { foreach ( $ configs as $ configName => $ configInfo ) { if ( $ oldConfigName === $ configName ) { unset ( $ oldConfigs [ $ oldConfigName ] ) ; } } } $ configs = array_merge ( $ oldConfigs , $ configs ) ; $ out = "<?php\n" ; $ out .= "class DATABASE_CONFIG {\n\n" ; foreach ( $ configs as $ name => $ config ) { $ out .= "\tpublic \${$name} = [\n" ; foreach ( $ config as $ param => $ value ) { $ valueText = $ this -> _exportParamValue ( $ value , 0 ) ; $ out .= "\t\t'{$param}' => " . $ valueText . ",\n" ; } $ out .= "\t];\n" ; } $ out .= "}\n" ; $ filename = $ this -> path . 'database.php' ; return $ this -> createFile ( $ filename , $ out ) ; }
|
Assembles and writes database . php
|
57,219
|
public static function file_put_contents ( string $ filename , $ data , int $ flags = 0 , $ context = null ) { $ dir = dirname ( $ filename ) ; if ( ! is_dir ( $ dir ) ) { if ( ! mkdir ( $ dir , 0777 , true ) ) { throw new Exception ( "Could not create directory $dir" ) ; } } file_put_contents ( $ filename , $ data , $ flags , $ context ) ; }
|
creates parent directories if they don t exist
|
57,220
|
public function loadDbFixture ( string $ fixturePath ) { list ( $ fixtureFormat , $ fixtureData ) = $ this -> loadFixtureData ( $ fixturePath ) ; $ this -> db -> dbConnect ( ) ; $ this -> db -> dbLoadFixture ( $ fixtureFormat , $ fixtureData ) ; }
|
Load fixture to database .
|
57,221
|
public function loadFixtureData ( string $ fixturePath ) : array { $ fixturePath = $ this -> fixturesRootPath . '/' . $ fixturePath ; $ fixtureFormat = $ this -> detectFormat ( $ fixturePath ) ; $ fixtureData = null ; switch ( $ fixtureFormat ) { case DbItf :: FIXTURE_FORMAT_JSON : $ fixtureData = $ this -> decode ( $ this -> loadJson ( $ fixturePath ) ) ; break ; case DbItf :: FIXTURE_FORMAT_TXT : $ fixtureData = $ this -> loadTxt ( $ fixturePath ) ; break ; case DbItf :: FIXTURE_FORMAT_PHP : $ fixtureData = require $ fixturePath ; break ; case DbItf :: FIXTURE_FORMAT_SQL : $ fixtureData = $ this -> loadSql ( $ fixturePath ) ; break ; } return [ $ fixtureFormat , $ fixtureData ] ; }
|
Load fixture file from disk .
|
57,222
|
public function detectFormat ( string $ fixturePath ) : string { $ info = new SplFileInfo ( $ fixturePath ) ; $ extension = $ info -> getExtension ( ) ; $ knownFormats = [ DbItf :: FIXTURE_FORMAT_JSON , DbItf :: FIXTURE_FORMAT_PHP , DbItf :: FIXTURE_FORMAT_SQL , DbItf :: FIXTURE_FORMAT_TXT , ] ; if ( ! in_array ( $ extension , $ knownFormats ) ) { throw new FixtureLoaderEx ( "Unknown fixture format: $extension." ) ; } return $ extension ; }
|
Detect fixture format based on its extension .
|
57,223
|
public function loadJson ( string $ fixturePath ) : string { if ( ! file_exists ( $ fixturePath ) ) { throw new FixtureLoaderEx ( "Fixture $fixturePath does not exist." ) ; } $ lines = file ( $ fixturePath ) ; $ endLine = - 1 ; foreach ( $ lines as $ lineNo => $ data ) { if ( substr ( $ data , 0 , 2 ) === '--' ) { $ endLine = $ lineNo ; } else { break ; } } if ( $ endLine != - 1 ) { array_splice ( $ lines , 0 , $ endLine + 1 ) ; } return implode ( "\n" , $ lines ) ; }
|
Load JSON fixture .
|
57,224
|
public function loadSql ( string $ fixturePath ) : array { if ( ! file_exists ( $ fixturePath ) ) { throw new FixtureLoaderEx ( "Fixture $fixturePath does not exist." ) ; } $ handle = @ fopen ( $ fixturePath , 'r' ) ; if ( ! $ handle ) { throw new FixtureLoaderEx ( "Error opening fixture $fixturePath." ) ; } $ sqlArr = [ ] ; $ index = 0 ; while ( ( $ sql = fgets ( $ handle ) ) !== false ) { if ( substr ( $ sql , 0 , 2 ) == '--' ) { continue ; } $ isMultiLineSql = array_key_exists ( $ index , $ sqlArr ) ; $ isEndOfSql = substr ( $ sql , - 2 , 1 ) == ';' ; if ( $ isMultiLineSql ) { $ sqlArr [ $ index ] .= $ sql ; } else { $ sqlArr [ $ index ] = $ sql ; } if ( $ isEndOfSql ) { $ sqlArr [ $ index ] = trim ( $ sqlArr [ $ index ] ) ; ++ $ index ; } } fclose ( $ handle ) ; return $ sqlArr ; }
|
Get array of SQL statements form fixture file .
|
57,225
|
public function getCommitsSince ( $ rev ) { $ log = $ this -> execute ( "hg log -r tip:{$rev} --config ui.verbose=false" ) ; $ this -> repository_type = 'hg' ; return $ this -> parseLog ( $ log ) ; }
|
Get the list of Mercurial commits for the repository as a structured array since a specific revision
|
57,226
|
public function getChangedFiles ( $ rev ) { $ raw_changes = $ this -> execute ( 'hg status --change ' . $ rev ) ; $ this -> repository_type = 'hg' ; $ changes = [ ] ; foreach ( $ raw_changes as $ key => $ change ) { $ exploded_change = explode ( ' ' , $ change ) ; $ changes [ $ key ] [ 'type' ] = $ exploded_change [ 0 ] ; $ changes [ $ key ] [ 'path' ] = $ exploded_change [ 1 ] ; } return $ changes ; }
|
Get the list of files changed with the type of change for a given revision . Results are returned as a structured array .
|
57,227
|
protected function createNormalizedArray ( array $ rawPayload , AdapterInterface $ adapter ) { $ metadata = $ this -> extractMetadata ( $ rawPayload , $ adapter ) ; return [ 'id' => $ this -> extractId ( $ rawPayload ) , 'type' => $ metadata -> type , 'properties' => $ this -> extractProperties ( $ rawPayload , $ metadata ) ] ; }
|
Creates a normalized array from an raw array payload .
|
57,228
|
public function admit ( $ identifier , $ password ) { $ user = $ this -> repository -> getByIdentifier ( $ identifier ) ; if ( $ user instanceof UserInterface && $ this -> hasher -> verify ( $ password , $ user -> getPasswordHash ( ) ) ) { $ this -> admitUser ( $ user ) ; return true ; } else if ( is_object ( $ user ) && ! $ user instanceof UserInterface ) { throw new \ RuntimeException ( 'Your users must implement "Laasti\Warden\Users\UserInterface".' ) ; } return false ; }
|
Attempts to log in user from supplied credentials
|
57,229
|
public function admitUser ( UserInterface $ user ) { $ this -> currentUser = $ user ; $ this -> session -> set ( $ user -> getId ( ) ) ; return true ; }
|
Log in the provided user no questions asked
|
57,230
|
public function isAdmitted ( UserInterface $ user = null ) { if ( is_null ( $ user ) ) { return ! $ this -> currentUser ( ) instanceof GuestUser ; } return $ user -> getIdentifier ( ) === $ this -> currentUser ( ) -> getIdentifier ( ) ; }
|
Checks if a user is logged in
|
57,231
|
public function grantAccess ( $ roleOrPermission , UserInterface $ user = null ) { $ user = $ user ? : $ this -> currentUser ( ) ; if ( is_array ( $ roleOrPermission ) && $ this -> grantAccessByRoles ( $ roleOrPermission , $ user ) ) { return true ; } else if ( is_array ( $ roleOrPermission ) && $ this -> grantAccessByPermissions ( $ roleOrPermission , $ user ) ) { return true ; } else if ( $ this -> grantAccessByRole ( $ roleOrPermission , $ user ) ) { return true ; } else if ( $ this -> grantAccessByPermission ( $ roleOrPermission , $ user ) ) { return true ; } return false ; }
|
Grants access by roles or permissions . Be careful to use different names for roles and permissions You could UPPERCASE your roles and lowercase your permissions .
|
57,232
|
public function grantAccessByPermission ( $ permission , UserInterface $ user = null ) { $ user = $ user ? : $ this -> currentUser ( ) ; return in_array ( $ permission , $ this -> gatherPermissions ( $ user ) ) ; }
|
Check if user has the permission
|
57,233
|
public function grantAccessByPermissions ( $ permissions , UserInterface $ user = null ) { $ user = $ user ? : $ this -> currentUser ; return count ( array_diff ( $ permissions , $ this -> gatherPermissions ( $ user ) ) ) === 0 ; }
|
Check if user has all permissions
|
57,234
|
public function grantAccessByRoles ( $ roles , UserInterface $ user = null ) { $ user = $ user ? : $ this -> currentUser ( ) ; return count ( array_diff ( $ roles , $ user -> getRoles ( ) ) ) === 0 ; }
|
Check if user has all roles
|
57,235
|
public function grantAccessByRole ( $ role , UserInterface $ user = null ) { $ user = $ user ? : $ this -> currentUser ( ) ; return in_array ( $ role , $ user -> getRoles ( ) ) ; }
|
Check if user has the role
|
57,236
|
protected function setUserFromSession ( ) { $ id = $ this -> session -> get ( ) ; if ( $ id ) { $ user = $ this -> repository -> getById ( $ this -> session -> get ( ) ) ; if ( $ user instanceof UserInterface ) { $ this -> admitUser ( $ user ) ; return ; } } $ this -> currentUser = new GuestUser ( ) ; }
|
Retrieve logged in user
|
57,237
|
protected function gatherPermissions ( UserInterface $ user = null ) { $ user = $ user ? : $ this -> currentUser ( ) ; $ roles = $ user -> getRoles ( ) ; $ permissions = $ user -> getPermissions ( ) ; foreach ( $ roles as $ role ) { if ( isset ( $ this -> roleDictionary [ $ role ] ) ) { $ permissions = array_merge ( $ permissions , $ this -> roleDictionary [ $ role ] ) ; } } return $ permissions ; }
|
Gather permissions from user roles
|
57,238
|
public function setConfig ( IConfigureRutes $ config ) { $ this -> configure -> setActual ( $ this -> actual ) ; $ this -> configure -> load ( $ config ) ; $ this -> configure -> transform ( ) ; $ this -> configure -> rutes ( ) ; return $ this ; }
|
Estableser configuracion de las rutas .
|
57,239
|
public function run ( ) { $ this -> executor -> setActual ( $ this -> actual ) ; $ this -> executor -> setPeticion ( $ this -> peticion ) ; $ this -> executor -> setCallback ( $ this -> configure -> getConfig ( ) ) ; $ this -> executor -> exist ( ) ; $ this -> executor -> compare ( ) ; $ this -> executor -> execute ( ) ; return $ this ; }
|
Ejecutar peticion de un contralador .
|
57,240
|
public static function fromString ( $ uri ) { if ( is_string ( $ uri ) === false ) { throw new Exception ( '$uri is not a string' ) ; } $ uri = explode ( ':' , $ uri , 2 ) ; $ scheme = strtolower ( $ uri [ 0 ] ) ; $ schemeSpecific = isset ( $ uri [ 1 ] ) === true ? $ uri [ 1 ] : '' ; if ( in_array ( $ scheme , array ( 'http' , 'https' ) ) === false ) { throw new Exception ( "Invalid scheme: '$scheme'" ) ; } $ schemeHandler = new Http ( $ scheme , $ schemeSpecific ) ; return $ schemeHandler ; }
|
Creates a Http from the given string
|
57,241
|
public function valid ( ) { return $ this -> validateUsername ( ) && $ this -> validatePassword ( ) && $ this -> validateHost ( ) && $ this -> validatePort ( ) && $ this -> validatePath ( ) && $ this -> validateQuery ( ) && $ this -> validateFragment ( ) ; }
|
Validate the current URI from the instance variables . Returns true if and only if all parts pass validation .
|
57,242
|
public function addReplaceQueryParameters ( array $ queryParams ) { $ queryParams = array_merge ( $ this -> getQueryAsArray ( ) , $ queryParams ) ; return $ this -> setQuery ( $ queryParams ) ; }
|
Add or replace params in the query string for the current URI and return the old query .
|
57,243
|
public function removeQueryParameters ( array $ queryParamKeys ) { $ queryParams = array_diff_key ( $ this -> getQueryAsArray ( ) , array_fill_keys ( $ queryParamKeys , 0 ) ) ; return $ this -> setQuery ( $ queryParams ) ; }
|
Remove params in the query string for the current URI and return the old query .
|
57,244
|
public static function passwordChanged ( ModelEvent $ event ) { $ user = $ event -> getModel ( ) ; if ( ! $ user -> _changedPassword ) { return ; } $ app = $ user -> getApp ( ) ; $ auth = $ app [ 'auth' ] ; $ req = $ auth -> getRequest ( ) ; $ ip = $ req -> ip ( ) ; $ userAgent = $ req -> agent ( ) ; $ event = new AccountSecurityEvent ( ) ; $ event -> user_id = $ user -> id ( ) ; $ event -> type = AccountSecurityEvent :: CHANGE_PASSWORD ; $ event -> ip = $ ip ; $ event -> user_agent = $ userAgent ; $ event -> save ( ) ; $ auth -> signOutAllSessions ( $ user ) ; $ user -> markSignedOut ( ) ; $ currentUser = $ auth -> getCurrentUser ( ) ; if ( $ currentUser -> id ( ) == $ user -> id ( ) ) { $ auth -> logout ( ) ; } $ user -> sendEmail ( 'password-changed' , [ 'ip' => $ ip ] ) ; }
|
Sends the user a notification and records a security event if the password was changed .
|
57,245
|
public function groups ( ) { $ return = [ 'everyone' ] ; $ groups = GroupMember :: where ( 'user_id' , $ this -> id ( ) ) -> sort ( '`group` ASC' ) -> all ( ) ; foreach ( $ groups as $ group ) { $ return [ ] = $ group -> group ; } return $ return ; }
|
Gets the groups this user is a member of .
|
57,246
|
public function isMemberOf ( $ group ) { if ( $ group == 'everyone' ) { return true ; } return GroupMember :: where ( 'group' , $ group ) -> where ( 'user_id' , $ this -> id ( ) ) -> count ( ) == 1 ; }
|
Checks if the user is a member of a group .
|
57,247
|
protected function getMailerParams ( ) { $ app = $ this -> getApp ( ) ; return [ 'base_url' => $ app [ 'base_url' ] , 'siteEmail' => $ app [ 'config' ] -> get ( 'app.email' ) , 'email' => $ this -> email , 'username' => $ this -> name ( true ) , 'to' => [ [ 'email' => $ this -> email , 'name' => $ this -> name ( true ) , ] , ] , ] ; }
|
Gets the mailer parameters when sending email to this user .
|
57,248
|
public function postSubmit ( FormEvent $ event ) { $ data = $ event -> getData ( ) ; if ( $ this -> itemDataClass !== null ) { $ itemMetadata = $ this -> getClassMetadata ( $ this -> itemDataClass ) ; if ( $ itemMetadata !== null ) { $ this -> cleanupCollection ( $ data , $ itemMetadata ) ; } } }
|
This method bind after form submit to clean empty translation entities .
|
57,249
|
private function cleanupCollection ( & $ collection , $ classMetadata ) { $ notNullableStringProperties = array ( ) ; $ nullableStringProperties = array ( ) ; $ otherProperties = array ( ) ; foreach ( $ classMetadata -> getFieldNames ( ) as $ fieldName ) { $ fieldMapping = $ classMetadata -> getFieldMapping ( $ fieldName ) ; if ( isset ( $ fieldMapping [ 'id' ] ) && $ fieldMapping [ 'id' ] === true ) { continue ; } if ( in_array ( $ fieldMapping [ 'fieldName' ] , $ this -> autoRemoveIgnoreFields ) || $ fieldMapping [ 'fieldName' ] === $ this -> localePropertyPath ) { continue ; } if ( $ fieldMapping [ 'nullable' ] ) { if ( $ fieldMapping [ 'type' ] === 'string' ) { $ nullableStringProperties [ ] = $ fieldMapping [ 'fieldName' ] ; } else { $ otherProperties [ ] = $ fieldMapping [ 'fieldName' ] ; } } else { if ( $ fieldMapping [ 'type' ] === 'string' ) { $ notNullableStringProperties [ ] = $ fieldMapping [ 'fieldName' ] ; } else { $ otherProperties [ ] = $ fieldMapping [ 'fieldName' ] ; } } } $ toRemove = array ( ) ; foreach ( $ collection as $ entity ) { $ allNullableStringsAreNull = true ; foreach ( $ nullableStringProperties as $ pp ) { $ value = $ this -> propertyAccessor -> getValue ( $ entity , $ pp ) ; if ( trim ( $ value ) === '' ) { $ this -> propertyAccessor -> setValue ( $ entity , $ pp , null ) ; } else { $ allNullableStringsAreNull = false ; } } $ allNotNullableStringsAreNull = true ; foreach ( $ notNullableStringProperties as $ pp ) { $ value = $ this -> propertyAccessor -> getValue ( $ entity , $ pp ) ; if ( $ value !== null ) { if ( trim ( $ value ) !== '' ) { $ allNotNullableStringsAreNull = false ; } } else { $ this -> propertyAccessor -> setValue ( $ entity , $ pp , '' ) ; } } $ otherAreNull = true ; foreach ( $ otherProperties as $ pp ) { $ value = $ this -> propertyAccessor -> getValue ( $ entity , $ pp ) ; if ( $ value !== null ) { $ otherAreNull = false ; } } if ( $ allNullableStringsAreNull && $ allNotNullableStringsAreNull && $ otherAreNull ) { $ toRemove [ ] = $ entity ; if ( null !== $ this -> objectManager && $ this -> objectManager -> contains ( $ entity ) ) { $ this -> objectManager -> remove ( $ entity ) ; } } } $ this -> removeFromCollection ( $ collection , $ toRemove ) ; }
|
This method cleans empty translation entities .
|
57,250
|
private function removeFromCollection ( & $ collection , $ items ) { if ( is_array ( $ collection ) ) { foreach ( $ items as $ item ) { foreach ( $ collection as $ index => $ v ) { if ( spl_object_hash ( $ item ) == spl_object_hash ( $ v ) ) { unset ( $ collection [ $ index ] ) ; } } } } else { foreach ( $ items as $ item ) { $ collection -> removeElement ( $ item ) ; } } }
|
Remove items from collection .
|
57,251
|
public function getFileContents ( ) { if ( $ this -> fileContentsCache === null && $ filePath = $ this -> getFile ( ) ) { if ( ! File :: exists ( $ filePath ) ) { return null ; } $ this -> fileContentsCache = File :: read ( $ filePath ) ; } return $ this -> fileContentsCache ; }
|
Returns the full contents of the file for this frame if it s known .
|
57,252
|
public function fakePostHack ( ) { if ( $ this -> isPost ( ) ) { $ altmethod = $ this -> getPost ( '_method' ) ; if ( $ altmethod && $ altmethod != 'POST' ) { if ( $ this -> isValidHttpMethod ( $ altmethod ) ) { $ _SERVER [ 'REQUEST_METHOD' ] = $ altmethod ; $ this -> setRawData ( $ this -> getPost ( ) ) ; return true ; } } } }
|
some people like to do PUT and PATCH requests via POST beings html form method attribute only accepts GET|POST
|
57,253
|
protected function render ( $ name , $ variables = [ ] ) { $ twig = $ this -> getServiceContainer ( ) -> getTwig ( ) ; return $ twig -> render ( $ name , array_merge ( $ this -> getGlobalTwigVariables ( ) , $ variables ) ) ; }
|
Renders the given twig template with global and given variables
|
57,254
|
private function routeCurrentFrame ( ) { $ this -> logger -> debug ( "Routing frame" ) ; $ opcode = $ this -> currentFrame -> getOpcode ( ) ; if ( $ opcode === DataFrame :: OPCODE_TEXT || $ opcode === DataFrame :: OPCODE_BINARY || $ opcode === DataFrame :: OPCODE_CONTINUE ) { if ( $ this -> currentMessage === null ) { $ this -> logger -> debug ( "No message, creating new" ) ; $ this -> currentMessage = new Message ( $ this -> logger , $ this -> currentFrame ) ; } else { $ this -> logger -> debug ( "Adding frame to message" ) ; $ this -> currentMessage -> addFrame ( $ this -> currentFrame ) ; } if ( $ this -> currentMessage -> isComplete ( ) ) { $ this -> logger -> debug ( "Message completed, routing" ) ; $ this -> handleMessage ( $ this -> currentMessage ) ; $ this -> currentMessage = null ; } else { $ this -> logger -> debug ( "Message not completed yet" ) ; } } elseif ( $ opcode === DataFrame :: OPCODE_CLOSE ) { $ this -> handleClientCloseFrame ( $ this -> currentFrame ) ; } elseif ( $ opcode === DataFrame :: OPCODE_PING ) { $ this -> handlePingFrame ( $ this -> currentFrame ) ; } elseif ( $ opcode === DataFrame :: OPCODE_PONG ) { $ this -> handlePongFrame ( $ this -> currentFrame ) ; } else { throw new WebSocketException ( "Non-RFC or reserved opcode, or first message frame with continue opcode" , DataFrame :: CODE_PROTOCOL_ERROR ) ; } $ this -> currentFrame = null ; $ this -> logger -> debug ( "Frame routing completed" ) ; }
|
Takes care of current frame .
|
57,255
|
protected function processInputBuffer ( ) { $ this -> logger -> debug ( "Processing WS request..." ) ; try { if ( $ this -> currentFrame === null ) { $ this -> logger -> debug ( "Creating new frame in client" ) ; $ this -> currentFrame = new NetworkFrame ( $ this -> logger , $ this -> inputBuffer ) ; } if ( ! $ this -> currentFrame -> isComplete ( ) ) { $ this -> logger -> debug ( "Frame not completed yet, skipping processing" ) ; return true ; } if ( ! $ this -> currentFrame -> isMasked ( ) ) { throw new WebSocketException ( "Client to server frames must be masked" , DataFrame :: CODE_PROTOCOL_ERROR ) ; } $ this -> routeCurrentFrame ( ) ; return empty ( $ this -> inputBuffer ) ; } catch ( Exception $ e ) { $ this -> handleWebSocketException ( $ e ) ; return true ; } }
|
Process WebSocket data stream collecting frames until final message is reached . It parses one frame at a time and it s code is messy due to WebSocket protocol craziness .
|
57,256
|
public function setAsFloat ( $ value ) { if ( ! ( is_numeric ( $ value ) || $ value instanceof NumericTypeInterface ) ) { throw new \ InvalidArgumentException ( 'value is not numeric' ) ; } $ val = is_object ( $ value ) ? $ value -> asFloatType ( ) -> get ( ) : floatval ( $ value ) ; $ intVal = pow ( 10 , $ this -> precision -> get ( ) ) * $ val ; parent :: set ( $ intVal ) ; return $ this ; }
|
Set currency value upscaling into an integer for internal storage
|
57,257
|
public function display ( ) { $ formatter = new \ NumberFormatter ( $ this -> locale -> get ( ) , \ NumberFormatter :: CURRENCY ) ; $ formatter -> setSymbol ( \ NumberFormatter :: CURRENCY_SYMBOL , $ this -> symbol -> get ( ) ) ; $ formatter -> setAttribute ( \ NumberFormatter :: FRACTION_DIGITS , $ this -> precision -> get ( ) ) ; return new StringType ( sprintf ( $ this -> displayFormat , $ formatter -> format ( $ this -> getAsFloat ( ) ) ) ) ; }
|
Return currency amount formatted for display
|
57,258
|
public function registerPath ( $ path ) { $ this -> paths [ ] = Normalizer :: path ( ( string ) $ path , true ) ; return $ this ; }
|
Register an path for search of modules .
|
57,259
|
public function findFile ( $ class ) { if ( substr ( $ class , - 7 ) !== '\\Module' ) { return false ; } $ path = Normalizer :: path ( $ class , false ) . '.php' ; foreach ( $ this -> paths as $ dir ) { $ file = $ dir . $ path ; if ( is_readable ( $ file ) ) { return $ file ; } } return false ; }
|
Finds the path to the file where the Module class is defined .
|
57,260
|
protected function setDataAccessSettings ( ) { $ access = $ this -> getData ( 'settings.access' ) ; if ( is_array ( $ access ) ) { $ string = '' ; foreach ( $ access as $ role_id => $ patterns ) { foreach ( $ patterns as $ pattern ) { $ string .= "$role_id $pattern" . PHP_EOL ; } } $ this -> setData ( 'settings.access' , trim ( $ string ) ) ; } }
|
Prepare and set data for access field
|
57,261
|
protected function setDataMultilineTextSettings ( $ setting ) { $ data = $ this -> getData ( "settings.$setting" ) ; if ( is_array ( $ data ) ) { $ string = '' ; foreach ( $ data as $ key => $ value ) { $ list = implode ( ',' , ( array ) $ value ) ; $ string .= "$key $list" . PHP_EOL ; } $ this -> setData ( "settings.$setting" , trim ( $ string ) ) ; } }
|
Prepare and set data for textarea fields
|
57,262
|
private static function buildPluginData ( $ key , $ data ) { if ( is_array ( $ data ) ) { $ name = $ key ; $ attributes = $ data ; } else { $ name = $ data ; $ attributes = [ ] ; } return [ 'name' => $ name , 'attributes' => $ attributes ] ; }
|
Helper to build plugin data
|
57,263
|
public function applyFilters ( App $ cdl ) : void { $ settings = $ this -> getTypeSettings ( ) ; foreach ( $ settings [ 'fields' ] as $ field ) { if ( ! isset ( $ field [ 'filters' ] ) ) { continue ; } foreach ( $ field [ 'filters' ] as $ key => $ filter ) { $ data = self :: buildPluginData ( $ key , $ filter ) ; if ( $ cdl -> hasFilter ( $ data [ 'name' ] ) ) { $ filterObject = $ cdl -> getFilter ( $ data [ 'name' ] ) ; $ filt = new $ filterObject ( $ this , $ field [ 'name' ] , $ data [ 'attributes' ] ) ; $ filt -> apply ( ) ; } } } }
|
Applies the filters to the fields
|
57,264
|
public function applyCalculators ( App $ cdl ) : void { $ settings = $ this -> getTypeSettings ( ) ; foreach ( $ settings [ 'fields' ] as $ field ) { if ( ! isset ( $ field [ 'calculations' ] ) ) { continue ; } foreach ( $ field [ 'calculations' ] as $ key => $ calculation ) { $ data = self :: buildPluginData ( $ key , $ calculation ) ; if ( $ cdl -> hasCalculator ( $ data [ 'name' ] ) ) { $ calcObject = $ cdl -> getCalculator ( $ data [ 'name' ] ) ; $ calc = new $ calcObject ( $ this , $ field [ 'name' ] , $ data [ 'attributes' ] ) ; $ calc -> apply ( ) ; } } } }
|
Applies the calculators to the fields
|
57,265
|
public function doValidation ( App $ cdl ) : bool { $ settings = $ this -> getTypeSettings ( ) ; foreach ( $ settings [ 'fields' ] as $ field ) { if ( ! isset ( $ field [ 'validation' ] ) ) { continue ; } foreach ( $ field [ 'validation' ] as $ key => $ validation ) { $ data = self :: buildPluginData ( $ key , $ validation ) ; if ( $ cdl -> hasValidation ( $ data [ 'name' ] ) ) { $ validationObject = $ cdl -> getValidation ( $ data [ 'name' ] ) ; array_push ( $ this -> validations , new $ validationObject ( $ this , $ field [ 'name' ] , $ data [ 'attributes' ] ) ) ; } } } $ error = false ; foreach ( $ this -> validations as $ validation ) { $ error = $ validation -> doValidation ( ) || $ error ; } return $ error ; }
|
Executes all validations for this model
|
57,266
|
public function getValidationMessage ( ) : array { $ fields = [ ] ; foreach ( $ this -> validations as $ validation ) { if ( $ validation -> getStatus ( ) == Validation :: ERROR ) { if ( ! isset ( $ fields [ $ validation -> getField ( ) ] ) ) { $ fields [ $ validation -> getField ( ) ] = [ ] ; } var_dump ( $ validation -> getMessage ( ) ) ; array_push ( $ fields [ $ validation -> getField ( ) ] , $ validation -> getMessage ( ) ) ; } } return $ fields ; }
|
Returns a list of validation messages for every field which failed its validation
|
57,267
|
public function newInstance ( $ attributes = [ ] , $ exists = false ) : Model { $ model = parent :: newInstance ( $ attributes , $ exists ) ; $ model -> applyTypeSettings ( ) ; return $ model ; }
|
Propagates the table settings to the children
|
57,268
|
public function applyTypeSettings ( ) : void { $ settings = $ this -> getTypeSettings ( ) ; $ this -> setTable ( $ settings [ 'table' ] ) ; $ this -> setConnection ( $ settings [ 'connection' ] ) ; }
|
Applies the type - settings to the current model
|
57,269
|
public function getListItemData ( $ mode , $ segment , $ children = false ) { $ data = [ 'Dropdown' => false , 'HashLink' => false ] ; $ itemStyles = [ 'navbar.nav-item' ] ; $ linkStyles = [ 'navbar.nav-link' ] ; $ menuStyles = [ 'navbar.dropdown-menu' ] ; if ( $ this -> isActive ( $ mode ) ) { $ linkStyles [ ] = 'navbar.active' ; } if ( $ children && $ this -> ShowSubMenus ) { $ itemStyles [ ] = 'navbar.dropdown' ; $ linkStyles [ ] = 'navbar.dropdown-toggle' ; $ data [ 'Dropdown' ] = true ; $ data [ 'DropdownID' ] = $ this -> getDropdownID ( $ segment ) ; $ data [ 'HashLink' ] = ( boolean ) $ this -> AddTopLinkToSub ; } $ data [ 'ItemClass' ] = $ this -> styles ( $ itemStyles , true ) ; $ data [ 'LinkClass' ] = $ this -> styles ( $ linkStyles , true ) ; $ data [ 'MenuClass' ] = $ this -> styles ( $ menuStyles , true ) ; return ArrayData :: create ( $ data ) ; }
|
Answers the template data for the current list item .
|
57,270
|
public function getMenuLinkClass ( $ mode , $ dropdown = false ) { $ styles = [ 'navbar.dropdown-item' ] ; if ( $ dropdown ) { $ styles [ ] = 'navbar.dropdown-toggle' ; } elseif ( $ this -> isActive ( $ mode ) ) { $ styles [ ] = 'navbar.active' ; } return $ this -> styles ( $ styles , true ) ; }
|
Answers an array of class names for a menu link .
|
57,271
|
public function getMenu ( $ level = 1 ) { if ( $ controller = $ this -> getCurrentController ( PageController :: class ) ) { return $ controller -> getMenu ( $ level ) -> exclude ( 'HideFromMainMenu' , 1 ) ; } }
|
Answers the menu list with the specified level from the current controller .
|
57,272
|
public function authenticate ( ) { if ( empty ( $ this -> authResult ) ) { if ( $ this -> hasIdentity ( ) ) { $ this -> clearIdentity ( ) ; } return new Result ( Result :: FAILURE_UNCATEGORIZED , null , [ 'no result set' ] ) ; } if ( $ this -> hasIdentity ( ) ) { $ this -> clearIdentity ( ) ; } if ( $ this -> authResult -> isValid ( ) ) { $ this -> getStorage ( ) -> write ( $ this -> authResult -> getIdentity ( ) ) ; } $ result = $ this -> authResult ; $ this -> authResult = null ; return $ result ; }
|
Authenticates and provides an authentication result
|
57,273
|
public function connect ( $ renew = false ) { if ( ! $ renew && $ this -> isConnnected ( ) ) { return $ this ; } else if ( $ renew && $ this -> isConnnected ( ) ) { $ this -> close ( ) ; } $ this -> beforeConnect ( ) ; $ this -> socket = stream_socket_client ( $ this -> target , $ errno , $ errstr , 0 , $ this -> connect_flag , $ this -> context ) ; if ( ! $ this -> socket || $ errno ) { Yii :: error ( "connect error($this->target) $errstr $errno" , 'beyod' ) ; $ this -> trigger ( Server :: ON_CONNECT_FAILED , new ErrorEvent ( [ 'code' => $ errno , 'errstr' => $ errstr ] ) ) ; return ; } stream_set_blocking ( $ this -> socket , 0 ) ; if ( $ this -> isTCP ( ) || $ this -> isUnix ( ) ) { $ this -> timeoutLimit ( ) ; Yii :: $ app -> eventLooper -> addFdEvent ( $ this -> socket , EventLooper :: EV_WRITE , [ $ this , 'checkConnectResult' ] ) ; } else { Yii :: $ app -> eventLooper -> addFdEvent ( $ this -> socket , EventLooper :: EV_READ , [ $ this , 'readBuffer' ] ) ; } if ( $ this -> sendBuffer ) { $ this -> baseWrite ( ) ; } return $ this ; }
|
Start connecting to remote server . All event bindings should be set before connect .
|
57,274
|
public function checkConnectResult ( $ sock , $ flag , $ arg ) { $ this -> connectComplete ( ) ; $ this -> removeEventLooper ( ) ; $ sock = socket_import_stream ( $ this -> socket ) ; $ code = socket_get_option ( $ sock , SOL_SOCKET , SO_ERROR ) ; $ errstr = socket_strerror ( $ code ) ; if ( $ code ) { Yii :: warning ( $ this -> target . " connect failed($code), $errstr" , 'beyod' ) ; $ this -> trigger ( Server :: ON_CONNECT_FAILED , new ErrorEvent ( [ 'code' => $ code , 'errstr' => $ errstr ] ) ) ; return ; } $ this -> status = static :: STATUS_ESTABLISHED ; $ this -> id = static :: generateId ( ) ; static :: $ count ++ ; static :: $ connections [ $ this -> id ] = $ this ; $ this -> peer = stream_socket_get_name ( $ this -> socket , true ) ; $ this -> local = stream_socket_get_name ( $ this -> socket , false ) ; Yii :: debug ( 'connected to ' . $ this -> target . ', ' . $ this , 'beyod' ) ; $ this -> trigger ( Server :: ON_CONNECT , new IOEvent ( ) ) ; Yii :: $ app -> eventLooper -> addFdEvent ( $ this -> socket , EventLooper :: EV_READ , [ $ this , 'readBuffer' ] ) ; $ this -> afterConnected ( ) ; }
|
Check the result of the connection .
|
57,275
|
public function readBuffer ( ) { $ buffer = fread ( $ this -> socket , $ this -> read_buffer_size ) ; if ( $ buffer === '' || $ buffer === false ) { if ( feof ( $ this -> socket ) || ! is_resource ( $ this -> socket ) ) { $ this -> removeEventLooper ( ) ; $ this -> status = static :: STATUS_CLOSED ; $ event = new CloseEvent ( [ 'by' => CloseEvent :: BY_PEER , ] ) ; $ this -> trigger ( Server :: ON_CLOSE , $ event ) ; $ this -> destroy ( ) ; } return false ; } else { $ this -> recvBuffer .= $ buffer ; } if ( $ this -> _pipe && ! $ this -> _pipe -> isClosed ( ) ) { return $ this -> _pipe -> send ( $ buffer , true ) ; } while ( $ this -> recvBuffer ) { try { $ len = $ this -> parser ? call_user_func ( [ $ this -> parser , 'input' ] , $ this -> recvBuffer , $ this ) : strlen ( $ this -> recvBuffer ) ; if ( $ len === 0 ) { return ; } } catch ( \ Exception $ e ) { $ this -> recvBuffer = '' ; $ event = new ErrorEvent ( [ 'code' => $ e -> getCode ( ) , 'errstr' => $ e -> getMessage ( ) ] ) ; $ this -> trigger ( Server :: ON_BAD_PACKET , $ event ) ; return ; } $ message = substr ( $ this -> recvBuffer , 0 , $ len ) ; $ this -> recvBuffer = substr ( $ this -> recvBuffer , $ len ) ; if ( $ this -> parser ) { try { $ message = call_user_func ( [ $ this -> parser , 'decode' ] , $ message , $ this ) ; } catch ( \ Exception $ e ) { $ this -> recvBuffer = '' ; $ event = new ErrorEvent ( [ 'code' => $ e -> getCode ( ) , 'errstr' => $ e -> getMessage ( ) ] ) ; $ this -> trigger ( Server :: ON_BAD_PACKET , $ event ) ; return ; } } $ this -> response_at = microtime ( true ) ; $ event = new MessageEvent ( $ this ) ; $ event -> message = $ message ; $ this -> trigger ( Server :: ON_MESSAGE , $ event ) ; } }
|
When the buffer has data readable Read it and try to parse the packet and trigger the onMessage event if one or more valid packet are received .
|
57,276
|
public function send ( $ message , $ raw = false ) { if ( ! $ raw && $ this -> parser ) { $ message = call_user_func ( [ $ this -> parser , 'encode' ] , $ message , $ this ) ; } if ( $ message === false || $ message === null ) { return false ; } $ message = ( string ) $ message ; if ( $ this -> isUDP ( ) ) { return stream_socket_sendto ( $ this -> socket , $ message ) ; } if ( $ this -> bufferIsFull ( ) ) { if ( $ this -> _pipe ) { $ this -> _pipe -> pauseRecv ( ) ; } $ this -> trigger ( Server :: ON_BUFFER_FULL , new IOEvent ( ) ) ; return false ; } if ( ! $ this -> isConnnected ( ) ) { $ this -> sendBuffer .= $ message ; return ; } if ( $ this -> sendBuffer === '' ) { $ len = fwrite ( $ this -> socket , $ message ) ; if ( $ len === strlen ( $ message ) ) { return true ; } else if ( $ len > 0 ) { $ this -> sendBuffer = substr ( $ message , $ len ) ; Yii :: $ app -> eventLooper -> add ( $ this -> socket , EventLooper :: EV_WRITE , [ $ this , 'baseWrite' ] ) ; } else { $ error = error_get_last ( ) ; $ event = new ErrorEvent ( [ 'code' => $ error [ 'type' ] , 'errstr' => $ error [ 'message' ] , ] ) ; $ this -> trigger ( Server :: ON_ERROR , $ event ) ; if ( ! is_resource ( $ this -> socket ) || feof ( $ this -> socket ) ) { $ this -> status = static :: STATUS_CLOSED ; $ this -> removeEventLooper ( ) ; $ event = new CloseEvent ( [ 'by' => CloseEvent :: BY_PEER , ] ) ; $ this -> trigger ( Server :: ON_CLOSE , $ event ) ; $ this -> destroy ( ) ; return false ; } } return $ len ; } else { if ( $ this -> bufferIsFull ( ) ) { $ this -> trigger ( Server :: ON_BUFFER_FULL , new IOEvent ( ) ) ; return false ; } $ this -> sendBuffer .= $ message ; return strlen ( $ message ) ; } }
|
send mesage to peer .
|
57,277
|
public function close ( ) { if ( $ this -> isUDP ( ) ) { Yii :: warning ( "Clos UDP connection is meaningless." , 'beyod' ) ; return ; } $ this -> status = static :: STATUS_CLOSED ; $ this -> removeEventLooper ( ) ; $ this -> trigger ( Server :: ON_CLOSE , new CloseEvent ( ) ) ; $ this -> destroy ( ) ; }
|
close the connection
|
57,278
|
public function sendRequest ( $ request ) { if ( ! $ request ) { throw new InvalidArgumentException ( 'No data was passed into the provision request' ) ; } return $ this -> client -> post ( $ this -> prv_url , [ 'Content-type' => 'text/xml' , 'Content-length' => strlen ( $ request ) , 'MMProvision-Access-Token' => $ this -> prv_token , ] , $ request ) ; }
|
Send provision request
|
57,279
|
public function getSearchProperties ( ) { static $ props ; if ( null !== $ props ) { return $ props ; } $ props = [ ] ; foreach ( $ this -> getProperties ( ) as $ key => $ property ) { if ( false === $ property -> isSearchProperty ( ) ) { continue ; } $ props [ $ key ] = $ property ; } return $ props ; }
|
Gets all properties that are flagged for storage in search .
|
57,280
|
public function merge ( Setting $ merge ) { foreach ( $ merge as $ key => $ value ) { if ( Arrays :: exists ( $ key , $ this -> data ) ) { if ( is_int ( $ key ) ) { $ this -> data [ ] = $ value ; } elseif ( $ value instanceof self && $ this -> data [ $ key ] instanceof self ) { $ this -> data [ $ key ] -> merge ( $ value ) ; } else { if ( $ value instanceof self ) { $ this -> data [ $ key ] = new static ( $ value -> toArray ( ) , $ this -> allowModifications ) ; } else { $ this -> data [ $ key ] = $ value ; } } } else { if ( $ value instanceof self ) { $ this -> data [ $ key ] = new static ( $ value -> toArray ( ) , $ this -> allowModifications ) ; } else { $ this -> data [ $ key ] = $ value ; } $ this -> count ++ ; } } return $ this ; }
|
Merge another Setting with this one .
|
57,281
|
public function generate ( stdClass $ serviceData ) { $ this -> createFileFromTemplate ( [ "destination" => $ serviceData -> formDestination , "templateDestination" => __DIR__ . '/../templates/service/form.hctpl' , "content" => [ "nameSpace" => $ serviceData -> formNameSpace , "className" => $ serviceData -> formName , "formID" => $ serviceData -> formID , "multiLanguage" => $ serviceData -> multiLanguage , "formFields" => $ this -> getFormFields ( $ serviceData ) , "serviceRouteName" => $ serviceData -> serviceRouteName ] , ] ) ; return $ serviceData -> formDestination ; }
|
Creating form manager
|
57,282
|
private function getFormFields ( stdClass $ data ) { $ output = '' ; $ output .= $ this -> getFields ( $ data -> mainModel , $ data -> translationsLocation , array_merge ( $ this -> getAutoFill ( ) , [ 'id' ] ) , file_get_contents ( __DIR__ . '/../templates/service/form/basic.field.hctpl' ) ) ; if ( isset ( $ data -> mainModel -> multiLanguage ) ) $ output .= $ this -> getFields ( $ data -> mainModel -> multiLanguage , $ data -> translationsLocation , array_merge ( $ this -> getAutoFill ( ) , [ 'id' , 'record_id' , 'language_code' ] ) , file_get_contents ( __DIR__ . '/../templates/service/form/multi.field.hctpl' ) ) ; return $ output ; }
|
Get form manager form fields from model
|
57,283
|
public function generate ( $ name , array $ params = [ ] , $ absolute = false ) { $ config = $ this -> container -> get ( 'Config' ) ; $ path = '' ; if ( $ config -> has ( 'app.basepath' ) ) { $ path = $ config -> get ( 'app.basepath' ) ; } $ path .= $ this -> container -> get ( 'HttpDispatcher' ) -> generate ( $ name , $ params ) ; if ( $ absolute === true ) { $ uristr = ( string ) $ this -> request -> getUri ( ) ; $ part = substr ( $ uristr , 0 , strpos ( $ uristr , '/' , 8 ) ) ; $ path = $ part . $ path ; } return $ path ; }
|
Return a URI based on a route name
|
57,284
|
public function internalRedirect ( $ uri ) { if ( is_string ( $ uri ) ) { $ uri = $ this -> request -> getUri ( ) -> withPath ( $ uri ) ; return $ this -> request -> withUri ( $ uri ) ; } elseif ( $ uri instanceof UriInterface ) { return $ this -> request -> withUri ( $ uri ) ; } else { throw new InvalidArgumentException ( 'URI should be a string or instance of Psr\Http\Message\UriInterface' ) ; } }
|
Generate a request for internal redirection .
|
57,285
|
public function apply ( $ testable , array $ config = array ( ) ) { $ message = 'Tabs can only appear at the beginning of the line' ; $ lines = $ testable -> lines ( ) ; $ tokens = $ testable -> tokens ( ) ; $ currLine = 1 ; $ allowTabs = true ; foreach ( $ tokens as $ token ) { $ content = str_replace ( "\r\n" , "\n" , $ token [ 'content' ] ) ; $ isNewLine = ( $ token [ 'line' ] > $ currLine || ( $ token [ 'id' ] === T_WHITESPACE && preg_match ( '/\n/' , $ content ) ) ) ; if ( $ isNewLine ) { $ currLine = $ token [ 'line' ] ; $ allowTabs = true ; } if ( $ token [ 'id' ] !== T_WHITESPACE ) { $ allowTabs = false ; continue ; } if ( $ allowTabs ) { $ isInvalidTab = ! preg_match ( '/^(\n?\t?)+ *$/' , $ content ) ; } else { $ isInvalidTab = preg_match ( '/\t/' , $ content ) ; } if ( $ isInvalidTab ) { $ this -> addViolation ( array ( 'message' => $ message , 'line' => $ token [ 'line' ] , ) ) ; } } }
|
Will iterate over each line checking if tabs are only first
|
57,286
|
public function getUri ( ) { $ uri = rtrim ( parse_url ( $ _SERVER [ 'REQUEST_URI' ] , PHP_URL_PATH ) , '/' ) ; $ baseUri = $ this -> getBaseUri ( ) ; $ uri = str_replace ( $ baseUri , '' , $ uri ) ? : '/' ; return $ uri ; }
|
To get uri
|
57,287
|
public function url ( $ path ) { $ protocol = "http" . $ this -> isSecure ( ) ; return $ protocol . $ _SERVER [ 'HTTP_HOST' ] . $ this -> getBaseUri ( ) . $ path ; }
|
To get URL link
|
57,288
|
public function setErrorReporting ( ) { if ( true === $ this -> _config -> getConfigData ( 'development_environment' ) ) { error_reporting ( E_ALL ) ; ini_set ( 'display_errors' , 'On' ) ; ErrorHandler :: register ( ) ; } else { error_reporting ( E_ALL ) ; ini_set ( 'display_errors' , 'Off' ) ; ini_set ( 'log_errors' , 'On' ) ; ini_set ( 'error_log' , ROOT . DS . 'tmp' . DS . 'logs' . DS . 'error.log' ) ; } }
|
Sets error reporting
|
57,289
|
private function stripSlashesDeep ( $ value ) { $ value = is_array ( $ value ) ? array_map ( array ( $ this , 'stripSlashesDeep' ) , $ value ) : stripslashes ( $ value ) ; return $ value ; }
|
Check for Magic Quotes and remove them
|
57,290
|
public function removeMagicQuotes ( ) { if ( get_magic_quotes_gpc ( ) ) { $ _GET = $ this -> stripSlashesDeep ( $ _GET ) ; $ _POST = $ this -> stripSlashesDeep ( $ _POST ) ; $ _COOKIE = $ this -> stripSlashesDeep ( $ _COOKIE ) ; } }
|
Removes magic quotes from requests
|
57,291
|
public function unregisterGlobals ( ) { if ( ini_get ( 'register_globals' ) ) { $ array = array ( '_SESSION' , '_POST' , '_GET' , '_COOKIE' , '_REQUEST' , '_SERVER' , '_ENV' , '_FILES' ) ; foreach ( $ array as $ value ) { foreach ( $ GLOBALS [ $ value ] as $ key => $ var ) { if ( $ var === $ GLOBALS [ $ key ] ) { unset ( $ GLOBALS [ $ key ] ) ; } } } } }
|
Check register globals and remove them
|
57,292
|
public function addRoute ( $ request , $ destinationController ) { $ explodedDestination = explode ( '/' , $ destinationController ) ; if ( file_exists ( CONTROLLERS . DS . ucfirst ( $ explodedDestination [ 0 ] ) . '_Controller.php' ) ) { $ this -> _routes [ $ request ] = $ destinationController ; } else { throw new RoutingException ( 'Non existant MVC route specified: ' . $ destinationController ) ; } }
|
Adds a non - standard MVC route for example request xxx to yyy_Controller .
|
57,293
|
public function applyStaticRouting ( & $ request ) { if ( isset ( $ this -> _staticRoutes [ $ request ] ) ) { $ request = $ this -> _staticRoutes [ $ request ] ; $ request = 'app' . DS . 'pages' . DS . $ request ; return true ; } return false ; }
|
Apply static routes .
|
57,294
|
public function applyRouting ( & $ request , & $ action = null , & $ urlArray = null ) { if ( isset ( $ this -> _routes [ strtolower ( $ request ) ] ) ) { $ route = $ this -> _routes [ strtolower ( $ request ) ] ; $ explodedTarget = explode ( '/' , $ route ) ; if ( isset ( $ explodedTarget [ 1 ] ) ) { $ action = $ explodedTarget [ 1 ] ; } $ request = $ explodedTarget [ 0 ] ; $ request = ucfirst ( $ request ) . '_Controller' ; if ( count ( $ explodedTarget ) > 2 ) { $ routeParams = array_slice ( $ explodedTarget , 2 ) ; $ urlArray = array_merge ( $ routeParams , $ urlArray ) ; } return true ; } return false ; }
|
Apply user - defined MVC routes .
|
57,295
|
private function createResolver ( array $ config , ContainerInterface $ container ) { $ resolvers = [ ] ; if ( isset ( $ config [ 'resolvers' ] ) ) { $ resolvers = $ this -> createResolvers ( $ config [ 'resolvers' ] , $ container ) ; } $ aggregate = new Resolver \ AggregateResolver ( ) ; foreach ( $ resolvers as $ resolver ) { $ aggregate -> attach ( $ resolver ) ; } if ( $ aggregate -> hasType ( Resolver \ DefaultResolver :: class ) ) { $ defaultResolver = $ aggregate -> fetchByType ( Resolver \ DefaultResolver :: class ) ; } else { $ defaultResolver = new Resolver \ DefaultResolver ( ) ; $ aggregate -> attach ( $ defaultResolver , 0 ) ; } if ( isset ( $ config [ 'paths' ] ) && is_array ( $ config [ 'paths' ] ) ) { $ this -> injectResolverPaths ( $ config [ 'paths' ] , $ defaultResolver ) ; } if ( isset ( $ config [ 'suffix' ] ) && is_string ( $ config [ 'suffix' ] ) && ! empty ( $ config [ 'suffix' ] ) ) { $ defaultResolver -> setSuffix ( $ config [ 'suffix' ] ) ; } if ( isset ( $ config [ 'separator' ] ) && is_string ( $ config [ 'separator' ] ) && ! empty ( $ config [ 'separator' ] ) ) { $ defaultResolver -> setSeparator ( $ config [ 'separator' ] ) ; } return $ aggregate ; }
|
Create the aggregate resolver to use with the Mustache instance .
|
57,296
|
private function createResolvers ( array $ config , ContainerInterface $ container ) { $ resolvers = [ ] ; foreach ( $ config as $ resolver ) { if ( $ resolver instanceof Resolver \ ResolverInterface ) { $ resolvers [ ] = $ resolver ; continue ; } if ( ! is_string ( $ resolver ) ) { continue ; } if ( $ container -> has ( $ resolver ) ) { $ resolvers [ ] = $ container -> get ( $ resolver ) ; continue ; } if ( class_exists ( $ resolver ) ) { $ resolvers [ ] = new $ resolver ( ) ; continue ; } } return $ resolvers ; }
|
Create resolvers from configuration .
|
57,297
|
private function injectResolverPaths ( $ config , Resolver \ DefaultResolver $ resolver ) { foreach ( $ config as $ index => $ paths ) { $ namespace = is_numeric ( $ index ) ? null : $ index ; foreach ( ( array ) $ paths as $ path ) { $ resolver -> addTemplatePath ( $ path , $ namespace ) ; } } }
|
Inject paths into the default resolver .
|
57,298
|
private function injectPragmas ( array $ config , Pragma \ PragmaCollection $ pragmas , ContainerInterface $ container ) { if ( ! isset ( $ config [ 'pragmas' ] ) || ! is_array ( $ config [ 'pragmas' ] ) ) { return ; } foreach ( $ config [ 'pragmas' ] as $ pragma ) { if ( $ pragma instanceof Pragma \ PragmaInterface ) { $ pragmas -> add ( $ pragma ) ; continue ; } if ( ! is_string ( $ pragma ) ) { continue ; } if ( $ container -> has ( $ pragma ) ) { $ pragmas -> add ( $ container -> get ( $ pragma ) ) ; continue ; } if ( class_exists ( $ pragma ) ) { $ pragmas -> add ( new $ pragma ( ) ) ; continue ; } } }
|
Injects configured pragmas into the pragma collection .
|
57,299
|
private function injectLexer ( array $ config , Mustache $ mustache , ContainerInterface $ container ) { if ( isset ( $ config [ 'lexer' ] ) ) { if ( is_string ( $ config [ 'lexer' ] ) && $ container -> has ( $ config [ 'lexer' ] ) ) { $ mustache -> setLexer ( $ container -> get ( $ config [ 'lexer' ] ) ) ; return ; } if ( $ config [ 'lexer' ] instanceof Lexer ) { $ mustache -> setLexer ( $ config [ 'lexer' ] ) ; } if ( is_string ( $ config [ 'lexer' ] ) && class_exists ( $ config [ 'lexer' ] ) ) { $ mustache -> setLexer ( new $ config [ 'lexer' ] ( ) ) ; } } if ( ! array_key_exists ( 'disable_strip_whitespace' , $ config ) ) { return ; } $ mustache -> getLexer ( ) -> disableStripWhitespace ( ( bool ) $ config [ 'disable_strip_whitespace' ] ) ; }
|
Inject the lexer if needed and potentially set the disable strip whitespace flag .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.