idx
int64 0
60.3k
| question
stringlengths 64
4.24k
| target
stringlengths 5
618
|
|---|---|---|
1,400
|
public static function formatted_timeframe ( $ startStr , $ endStr ) { $ str = null ; if ( $ startStr == $ endStr ) { return null ; } $ startTime = strtotime ( $ startStr -> value ) ; $ endTime = strtotime ( $ endStr -> value ) ; if ( $ startTime == $ endTime ) { return null ; } if ( $ endStr ) { if ( date ( 'Y-m-d' , $ startTime ) == date ( 'Y-m-d' , $ endTime ) ) { $ str = date ( 'g:ia' , $ startTime ) . ' - ' . date ( 'g:ia' , $ endTime ) ; } } else { $ str = date ( 'g:ia' , $ startTime ) ; } return $ str ; }
|
Formatted time frame Returns either a string or null Time frame is only applicable if both start and end time is on the same day
|
1,401
|
public static function ics_from_sscal ( $ cal ) { $ events = $ cal -> Events ( ) ; $ eventsArr = $ events -> toNestedArray ( ) ; $ ics = new ICSExport ( $ eventsArr ) ; return $ ics ; }
|
returns an ICSExport calendar object by supplying a Silverstripe calendar
|
1,402
|
public function all ( ) { $ calendars = PublicCalendar :: get ( ) ; $ events = new ArrayList ( ) ; foreach ( $ calendars as $ cal ) { $ events -> merge ( $ cal -> Events ( ) ) ; } $ eventsArr = $ events -> toNestedArray ( ) ; $ ics = new ICSExport ( $ eventsArr ) ; return $ this -> output ( $ ics , 'all' ) ; }
|
All public calendars
|
1,403
|
private function sendEmail ( OutputInterface $ output , $ content ) { $ output -> writeln ( "Sending an email" ) ; $ transport = $ this -> getTransport ( ) ; $ mailer = \ Swift_Mailer :: newInstance ( $ transport ) ; $ message = \ Swift_Message :: newInstance ( 'Bldr Notify - New Message' ) -> setFrom ( [ 'no-reply@bldr.io' => 'Bldr' ] ) -> setTo ( $ this -> getEmails ( ) ) -> setBody ( "<p>Bldr has a new message for you from the most recent build</p>\n<br /><pre>{$content}</pre>\n" , "text/html" ) -> addPart ( $ content , 'text/plain' ) ; $ result = $ mailer -> send ( $ message ) ; return $ result ; }
|
Sends an email with the given message
|
1,404
|
public static function registerOption ( $ key , $ class ) { if ( empty ( $ key ) ) { throw new Exception \ AnnotationException ( "Option key can not be empty!" ) ; } if ( ! class_exists ( $ class ) ) { throw new Exception \ AnnotationException ( "Class " . $ class . " not found!" ) ; } if ( ! in_array ( "UniMapper\Entity\Reflection\Property\IOption" , class_implements ( $ class ) ) ) { throw new Exception \ AnnotationException ( "Class " . $ class . " should implement UniMapper\Entity\Reflection\Property\IOption!" ) ; } self :: $ options [ $ key ] = $ class ; }
|
Register new property option
|
1,405
|
public static function parseOptions ( $ definition ) { preg_match_all ( '/m:([a-z-]+)(?:\(([^)]*)\))?/i' , $ definition , $ matched , PREG_SET_ORDER ) ; $ result = [ ] ; foreach ( $ matched as $ match ) { if ( array_key_exists ( $ match [ 1 ] , $ result ) ) { throw new Exception \ AnnotationException ( "Duplicate option '" . $ match [ 1 ] . "'!" ) ; } $ result [ $ match [ 1 ] ] = isset ( $ match [ 2 ] ) ? trim ( $ match [ 2 ] ) : null ; } return $ result ; }
|
Find all property options
|
1,406
|
protected function registerTokenRenderer ( $ tokenName , $ callbackName , Renderer $ renderer ) { $ renderer -> registerTokenRenderer ( $ tokenName , [ $ this , $ callbackName ] , $ this -> set -> getName ( ) ) ; }
|
Register token renderer
|
1,407
|
public function getFileSystemFiles ( $ relative_path , $ only_dirs = false ) { $ files = array ( ) ; $ iterator = new \ DirectoryIterator ( ROOT_PATH . "/$relative_path" ) ; foreach ( $ iterator as $ file_info ) { $ file = $ file_info -> getFilename ( ) ; if ( 0 !== strpos ( $ file , '.' ) ) { if ( ! $ only_dirs || $ file_info -> isDir ( ) ) { $ files [ ] = $ file ; } } } return $ files ; }
|
Extracts from the filesystem all the files under a path . If the flag only_dirs is set to true returns only the directories names .
|
1,408
|
public function getLiterals ( $ instance ) { $ path = \ Sifo \ Bootstrap :: $ application . "/$instance" ; $ literals_groups [ 'tpl' ] = $ this -> extractStringsForTranslation ( "$path/templates" , $ instance , true ) ; $ literals_groups [ 'models' ] = $ this -> extractStringsForTranslation ( "$path/models" , $ instance , false ) ; $ literals_groups [ 'controllers' ] = $ this -> extractStringsForTranslation ( "$path/controllers" , $ instance , false ) ; $ literals_groups [ 'forms' ] = $ this -> extractStringsForTranslation ( "$path/config" , $ instance , false ) ; $ sifo_plugins_path = ROOT_PATH . '/vendor/sifophp/sifo/src/Smarty-sifo-plugins' ; $ literals_groups [ 'smarty' ] = $ this -> extractStringsForTranslation ( $ sifo_plugins_path , 'libs' , false ) ; $ instance_plugins = $ path . '/templates/_smarty/plugins' ; if ( is_dir ( $ instance_plugins ) ) { $ literals_groups [ 'smarty' ] = array_merge ( $ literals_groups [ 'smarty' ] , $ this -> extractStringsForTranslation ( $ instance_plugins , $ instance , false ) ) ; } $ final_literals = array ( ) ; foreach ( $ literals_groups as $ group ) { foreach ( $ group as $ literal => $ relative_path ) { if ( array_key_exists ( $ literal , $ final_literals ) ) { $ final_literals [ $ literal ] = ( $ final_literals [ $ literal ] . ", " . $ relative_path ) ; } else { $ final_literals [ $ literal ] = $ relative_path ; } } } return $ final_literals ; }
|
Parses all templates models controllers configs and Smarty plugins searching for strings used inside translation methods and returns them structured in an array .
|
1,409
|
public static function fromString ( $ linestrings , $ linestrings_separator = ";" , $ points_separator = "," , $ coords_separator = " " ) { $ separators = [ $ linestrings_separator , $ points_separator , $ coords_separator ] ; if ( sizeof ( $ separators ) != sizeof ( array_unique ( $ separators ) ) ) throw new GeoSpatialException ( "Error: separators must be different" ) ; $ parsed_linestrings = array_map ( function ( $ linestring ) use ( $ points_separator , $ coords_separator ) { return LineString :: fromString ( $ linestring , $ points_separator , $ coords_separator ) ; } , explode ( $ linestrings_separator , trim ( $ linestrings ) ) ) ; return new static ( $ parsed_linestrings ) ; }
|
A Polygon could be instantiated using a string containing linestrings . es . lat lon lat lon ; lat lon lat lon ; lat lon lat lon
|
1,410
|
protected function html ( string $ html , int $ status = 200 , array $ headers = [ ] ) : ResponseInterface { return $ this -> responseFactory -> createHtmlResponse ( $ html , $ status , $ headers ) ; }
|
Creates html response .
|
1,411
|
protected function response ( $ bodyStream = 'php://memory' , int $ status = 200 , array $ headers = [ ] ) : ResponseInterface { return $ this -> responseFactory -> createResponse ( $ bodyStream , $ status , $ headers ) ; }
|
Creates HTTP response .
|
1,412
|
public function down ( ) { $ this -> db -> createCommand ( "SET foreign_key_checks = 0" ) -> execute ( ) ; $ this -> dropTable ( '{{%property_property_group}}' ) ; $ this -> dropTable ( '{{%property_translation}}' ) ; $ this -> dropTable ( '{{%property}}' ) ; $ this -> dropTable ( '{{%property_group_translation}}' ) ; $ this -> dropTable ( '{{%property_group}}' ) ; $ this -> dropTable ( '{{%property_storage}}' ) ; $ this -> dropTable ( '{{%static_value_translation}}' ) ; $ this -> dropTable ( '{{%static_value}}' ) ; $ this -> dropTable ( ApplicablePropertyModels :: tableName ( ) ) ; $ this -> dropTable ( '{{%property_handlers}}' ) ; $ this -> db -> createCommand ( "SET foreign_key_checks = 1" ) -> execute ( ) ; }
|
Removes all properties related tables
|
1,413
|
public function create ( $ alert , $ recipients , $ wait , $ repeat ) { $ alert [ 'recipients' ] = json_encode ( $ recipients ) ; $ alert [ 'wait' ] = json_encode ( $ wait ) ; $ alert [ 'repeat' ] = json_encode ( $ repeat ) ; return $ this -> post ( 'alerts/configs/' , $ alert ) ; }
|
Create an alert
|
1,414
|
public function bySubject ( $ subjectId , $ subjectType ) { $ type = array ( 'subjectType' => $ subjectType ) ; return $ this -> get ( 'alerts/configs/' . rawurlencode ( $ subjectId ) , $ type ) ; }
|
Get all alerts by subjectId
|
1,415
|
public function triggered ( $ closed = '' , $ subjectType = '' , $ subjectId = '' ) { $ fields = array ( ) ; if ( ! empty ( $ closed ) ) { $ fields [ 'closed' ] = $ closed ; } if ( ! empty ( $ subjectType ) ) { $ fields [ 'subjectType' ] = $ subjectType ; } return $ this -> get ( 'alerts/triggered/' . rawurlencode ( $ subjectId ) , $ fields ) ; }
|
Get triggered alerts
|
1,416
|
public function append ( $ data ) { $ bites = file_put_contents ( $ this -> path , $ data , FILE_APPEND | LOCK_EX ) ; return $ bites !== false ; }
|
Appends data to a file
|
1,417
|
public function getMimeType ( ) { $ finfo = finfo_open ( FILEINFO_MIME_TYPE ) ; $ mime = finfo_file ( $ finfo , $ this -> path ) ; finfo_close ( $ finfo ) ; return $ mime ; }
|
Returns the mime - type
|
1,418
|
public static function toJar ( $ cookies ) { $ result = [ ] ; foreach ( $ cookies as $ name => $ cookie ) { if ( ! $ cookie -> expired ( ) ) { $ result [ ] = static :: _line ( $ name , $ cookie ) ; } } return $ result ? join ( "\n" , $ result ) . "\n" : '' ; }
|
Exports the cookies into a JAR string .
|
1,419
|
protected static function _line ( $ name , $ cookie ) { if ( ! $ cookie -> isValid ( ) ) { throw new RuntimeException ( "Invalid cookie `'{$name}'`." ) ; } $ domain = $ cookie -> domain ( ) ; $ parts = [ $ cookie -> httponly ( ) ? '#HttpOnly_' . $ domain : $ domain , $ domain === '.' ? 'TRUE' : 'FALSE' , $ cookie -> path ( ) ? : '/' , $ cookie -> secure ( ) ? 'TRUE' : 'FALSE' , ( string ) $ cookie -> expires ( ) , $ cookie -> name ( ) , $ cookie -> value ( ) ] ; return join ( "\t" , $ parts ) ; }
|
Creates a cookie JAR line from a name and a SetCookie value .
|
1,420
|
public static function parse ( $ line ) { $ parts = explode ( "\t" , trim ( $ line ) ) ; if ( count ( $ parts ) !== 7 ) { throw new RuntimeException ( "Invalid cookie JAR format." ) ; } $ config = [ ] ; $ config [ 'httponly' ] = '#HttpOnly_' === substr ( $ parts [ 0 ] , 0 , 10 ) ; $ config [ 'domain' ] = $ config [ 'httponly' ] ? substr ( $ parts [ 0 ] , 10 ) : $ parts [ 0 ] ; $ config [ 'path' ] = $ parts [ 2 ] ; $ config [ 'secure' ] = ( $ parts [ 3 ] === 'TRUE' ) ? true : false ; $ config [ 'expires' ] = ( integer ) $ parts [ 4 ] ; $ config [ 'name' ] = $ parts [ 5 ] ; $ config [ 'value' ] = $ parts [ 6 ] ; return $ config ; }
|
Parses a cookie JAR line .
|
1,421
|
public function removeNumber ( int $ index ) : void { unset ( $ this -> numbers [ $ index ] ) ; $ this -> numbers = array_values ( $ this -> numbers ) ; }
|
Removes the given index from the number recipient list .
|
1,422
|
public function getNumber ( int $ index ) : string { if ( $ index >= count ( $ this -> numbers ) ) { throw new \ UndefinedOffsetException ( ) ; } return $ this -> numbers [ $ index ] ; }
|
Returns the number in the given index .
|
1,423
|
public function removeContact ( int $ index ) : void { unset ( $ this -> contacts [ $ index ] ) ; $ this -> contacts = array_values ( $ this -> contacts ) ; }
|
Removes the Contact in the given index and reindexes the array .
|
1,424
|
public function removeGroup ( int $ index ) : void { unset ( $ this -> groups [ $ index ] ) ; $ this -> groups = array_values ( $ this -> groups ) ; }
|
Removes the Group in the given index and reindexes the array .
|
1,425
|
public function getGroup ( int $ index ) : Group { if ( $ index >= count ( $ this -> groups ) ) { throw new \ UndefinedOffsetException ( ) ; } return $ this -> groups [ $ index ] ; }
|
Returns the group in the given index .
|
1,426
|
public function registerEvents ( ) { if ( ! empty ( $ this -> clientEvents ) ) { $ js = [ ] ; foreach ( $ this -> clientEvents as $ event => $ handle ) { $ js [ ] = "jQuery('#{$this->options['id']}').on('{$event}',{$handle});" ; } $ this -> getView ( ) -> registerJs ( implode ( PHP_EOL , $ js ) ) ; } }
|
Register client script handles
|
1,427
|
public function value ( ) { if ( strtolower ( $ this -> name ( ) ) === 'set-cookie' ) { return join ( "\r\n" . $ this -> name ( ) . ': ' , $ this -> data ( ) ) ; } else { return join ( ', ' , $ this -> _data ) ; } }
|
Gets the header s value .
|
1,428
|
public static function parse ( $ value ) { $ values = explode ( ':' , $ value , 2 ) ; if ( count ( $ values ) !== 2 ) { return ; } return new static ( $ values [ 0 ] , trim ( $ values [ 1 ] ) ) ; }
|
Parses a header string value .
|
1,429
|
public static function wrap ( $ header , $ width = 0 ) { if ( $ width <= 0 ) { return $ header ; } $ result = [ ] ; $ lineLength = 0 ; $ parts = preg_split ( '~\s+~' , $ header ) ; while ( $ current = current ( $ parts ) ) { $ next = next ( $ parts ) ; $ lineLength += strlen ( $ current ) ; if ( $ next && ( $ lineLength + strlen ( $ next ) ) > ( $ width - 1 ) ) { $ result [ ] = $ current . Headers :: EOL ; $ lineLength = 0 ; } else { $ result [ ] = $ current ; } } return join ( ' ' , $ result ) ; }
|
Fold a header entry
|
1,430
|
public function getUpdated ( \ DateTimeZone $ timezone = null ) : ? \ DateTime { if ( ! is_null ( $ timezone ) ) { $ returnDate = clone $ this -> updated ; $ returnDate -> setTimeZone ( $ timezone ) ; return $ returnDate ; } return $ this -> updated ?? null ; }
|
Returns when the component was updated last .
|
1,431
|
private function expirationToDateTime ( $ expires ) : DateTimeInterface { if ( $ expires instanceof DateTimeImmutable ) { return $ expires ; } if ( $ expires instanceof DateInterval ) { $ expires = ( new DateTime ) -> add ( $ expires ) ; } elseif ( is_string ( $ expires ) || is_int ( $ expires ) ) { $ expires = new DateTime ( is_numeric ( $ expires ) ? '@' . $ expires : $ expires ) ; } if ( ! $ expires instanceof DateTimeInterface ) { throw new InvalidArgumentException ( 'Invalid cookie expiration time. Cannot be converted to DateTimeInterface.' ) ; } return new DateTimeImmutable ( $ expires -> format ( DateTime :: ISO8601 ) , $ expires -> getTimezone ( ) ) ; }
|
Parses expiration time and returns valid DateTimeInterface implementation .
|
1,432
|
public static function loadParameters ( ) : void { defined ( 'PHUNDER_ROOT_DIR' ) or define ( 'PHUNDER_ROOT_DIR' , __DIR__ . '/../' ) ; defined ( 'PHUNDER_TEMPLATE_DIRECTORY' ) or define ( 'PHUNDER_TEMPLATE_DIRECTORY' , 'templates' ) ; defined ( 'PHUNDER_SESSION_NAME' ) or define ( 'PHUNDER_SESSION_NAME' , 'PHUNDERSESSIONID' ) ; defined ( 'PHUNDER_SESSION_HTTPS' ) or define ( 'PHUNDER_SESSION_HTTPS' , false ) ; defined ( 'PHUNDER_SESSION_REGENERATE_MODE' ) or define ( 'PHUNDER_SESSION_REGENERATE_MODE' , '1' ) ; defined ( 'PHUNDER_SESSION_REGENERATE_REQUEST_AMOUNT' ) or define ( 'PHUNDER_SESSION_REGENERATE_REQUEST_AMOUNT' , '10' ) ; defined ( 'PHUNDER_SESSION_REGENERATE_TIME' ) or define ( 'PHUNDER_SESSION_REGENERATE_TIME' , '600' ) ; }
|
Define undefined Phunder constants
|
1,433
|
public static function buildFilterQuery ( $ params , $ index , $ types ) { self :: filterInput ( $ params ) ; $ storageToId = ( new Query ( ) ) -> from ( PropertyStorage :: tableName ( ) ) -> select ( 'class_name' ) -> where ( [ 'class_name' => array_keys ( $ types ) ] ) -> indexBy ( 'id' ) -> column ( ) ; $ propData = ( new Query ( ) ) -> from ( Property :: tableName ( ) ) -> select ( [ 'id' , 'data_type' , 'storage_id' ] ) -> where ( [ 'id' => array_keys ( $ params ) , 'storage_id' => array_keys ( $ storageToId ) , 'in_search' => 1 ] ) -> indexBy ( 'id' ) -> all ( ) ; $ query = [ 'bool' => [ 'must' => [ ] ] ] ; $ currentLang = LanguageHelper :: getCurrent ( ) ; foreach ( $ params as $ propId => $ values ) { $ q = [ 'bool' => [ 'should' => [ ] ] ] ; switch ( $ storageToId [ $ propData [ $ propId ] [ 'storage_id' ] ] ) { case EAV :: class : foreach ( $ values as $ val ) { $ q [ 'bool' ] [ 'should' ] [ ] = [ 'bool' => [ 'must' => [ [ 'term' => [ self :: STATIC_VALUES_FILED . '.prop_id' => $ propId ] ] , [ 'term' => [ self :: STATIC_VALUES_FILED . '.value_' . $ currentLang . '.raw' => $ val ] ] ] ] ] ; } break ; case StaticValues :: class : foreach ( $ values as $ val ) { $ q [ 'bool' ] [ 'should' ] [ ] = [ 'bool' => [ 'must' => [ [ 'term' => [ self :: STATIC_VALUES_FILED . '.prop_id' => $ propId ] ] , [ 'term' => [ self :: STATIC_VALUES_FILED . '.static_value_id' => $ val ] ] ] ] ] ; } break ; } $ query [ 'bool' ] [ 'must' ] [ ] = $ q ; } return $ a = [ 'index' => $ index , 'body' => [ 'query' => [ 'constant_score' => [ 'filter' => $ query ] ] ] ] ; }
|
Prepares filter query
|
1,434
|
protected static function filterInput ( & $ params ) { $ params = array_filter ( $ params , function ( $ v ) { if ( true === is_array ( $ v ) ) { $ first = reset ( $ v ) ; return ( count ( $ v ) > 0 && false === empty ( $ first ) ) ; } else { return false === empty ( $ v ) ; } } ) ; }
|
Leave only not empty values to work with
|
1,435
|
protected static function dataTypeToIndexField ( $ type ) { $ key = '' ; $ currentLang = LanguageHelper :: getCurrent ( ) ; switch ( $ type ) { case Property :: DATA_TYPE_STRING : $ key = 'str_value_' . $ currentLang ; break ; case Property :: DATA_TYPE_TEXT : $ key = 'txt_value_' . $ currentLang ; break ; case Property :: DATA_TYPE_BOOLEAN : case Property :: DATA_TYPE_INTEGER : $ key = 'value_integer' ; break ; case Property :: DATA_TYPE_FLOAT : $ key = 'value_float' ; break ; case Property :: DATA_TYPE_INVARIANT_STRING : case Property :: DATA_TYPE_PACKED_JSON : $ key = 'utr_text' ; break ; } return $ key ; }
|
Cast property data_type to elastic index column
|
1,436
|
protected static function prepareTypes ( $ config ) { $ list = isset ( $ config [ 'storage' ] ) ? $ config [ 'storage' ] : [ ] ; $ list = is_array ( $ list ) ? $ list : [ $ list ] ; if ( count ( $ list ) == 0 ) { $ list [ ] = StaticValues :: class ; } foreach ( $ list as $ i => $ storageClass ) { $ list [ $ storageClass ] = IndexHelper :: storageClassToType ( $ storageClass ) ; unset ( $ list [ $ i ] ) ; } return $ list ; }
|
Prepares list of types to search against for
|
1,437
|
public function destroy ( $ name ) { if ( ! isset ( $ this -> _storage [ $ name ] ) ) { trigger_error ( "Attempted to destroy non-existent variable $name" , E_USER_ERROR ) ; return ; } unset ( $ this -> _storage [ $ name ] ) ; }
|
Destorys a variable in the context .
|
1,438
|
public function get ( $ uri ) { $ options = array ( CURLOPT_URL => $ this -> domain . '/' . ltrim ( $ uri , '/' ) , CURLOPT_FOLLOWLOCATION => 1 , CURLOPT_RETURNTRANSFER => 1 , ) ; return $ this -> exec ( $ options ) ; }
|
Read data from cauditor API .
|
1,439
|
public function put ( $ uri , array $ data ) { $ json = json_encode ( $ data ) ; $ file = fopen ( 'php://temp' , 'w+' ) ; fwrite ( $ file , $ json , strlen ( $ json ) ) ; fseek ( $ file , 0 ) ; $ options = array ( CURLOPT_URL => $ this -> domain . '/' . ltrim ( $ uri , '/' ) , CURLOPT_FOLLOWLOCATION => 1 , CURLOPT_RETURNTRANSFER => 1 , CURLOPT_PUT => 1 , CURLOPT_INFILE => $ file , CURLOPT_INFILESIZE => strlen ( $ json ) , ) ; $ result = $ this -> exec ( $ options ) ; fclose ( $ file ) ; return $ result ; }
|
Submit the data to cauditor API .
|
1,440
|
public function form_set_error ( $ name = NULL , $ message = '' , $ limit_validation_errors = NULL ) { return form_set_error ( $ name , $ message , $ limit_validation_errors ) ; }
|
Files an error against a form element .
|
1,441
|
public function init ( ) { if ( true === $ this -> beforeInit ( ) ) { HasPropertiesEvent :: on ( HasProperties :: class , HasProperties :: EVENT_AFTER_SAVE , [ $ this , 'onSave' ] ) ; HasPropertiesEvent :: on ( HasProperties :: class , HasProperties :: EVENT_AFTER_UPDATE , [ $ this , 'onUpdate' ] ) ; HasPropertiesEvent :: on ( HasProperties :: class , HasProperties :: EVENT_BEFORE_DELETE , [ $ this , 'onDelete' ] ) ; } }
|
Adds event listeners to perform search index actualization if pre initialization was successful
|
1,442
|
public static function isEqual ( $ value1 , $ value2 , $ roundPrecision = 0 ) { $ equal = false ; if ( static :: floor ( $ value1 , $ roundPrecision ) == static :: floor ( $ value2 , $ roundPrecision ) ) { $ equal = true ; } return $ equal ; }
|
Checks if of two numbers are equal . Optional to set a required precision
|
1,443
|
public function add ( $ data ) { $ columnNum = 0 ; $ rowNum = $ this -> _iterator -> current ( ) -> getRowIndex ( ) ; foreach ( ( array ) $ data as $ value ) { $ this -> _sheet -> setCellValueByColumnAndRow ( $ columnNum ++ , $ rowNum , $ value ) ; } $ this -> _iterator -> next ( ) ; }
|
Adds a row to the content object .
|
1,444
|
public static function groupResult ( array $ original , array $ keys , $ level = 0 ) { $ converted = [ ] ; $ key = $ keys [ $ level ] ; $ isDeepest = sizeof ( $ keys ) - 1 == $ level ; $ level ++ ; $ filtered = [ ] ; foreach ( $ original as $ k => $ subArray ) { $ subArray = ( array ) $ subArray ; if ( ! isset ( $ subArray [ $ key ] ) ) { throw new AssociationException ( "Index '" . $ key . "' not found on level '" . $ level . "'!" ) ; } $ thisLevel = $ subArray [ $ key ] ; if ( is_object ( $ thisLevel ) ) { $ thisLevel = ( string ) $ thisLevel ; } if ( $ isDeepest ) { $ converted [ $ thisLevel ] = $ subArray ; } else { $ converted [ $ thisLevel ] = [ ] ; } $ filtered [ $ thisLevel ] [ ] = $ subArray ; } if ( ! $ isDeepest ) { foreach ( array_keys ( $ converted ) as $ value ) { $ converted [ $ value ] = self :: groupResult ( $ filtered [ $ value ] , $ keys , $ level ) ; } } return $ converted ; }
|
Group associative array
|
1,445
|
public function setValue ( $ value ) { $ this -> selected = $ value ; if ( $ this -> hasChildren ( ) ) { foreach ( $ this -> childNodes as $ child ) { if ( $ child instanceof Select \ Option ) { if ( $ child -> getValue ( ) == $ this -> selected ) { $ child -> select ( ) ; } else { $ child -> deselect ( ) ; } } else if ( $ child instanceof Select \ Optgroup ) { $ options = $ child -> getOptions ( ) ; foreach ( $ options as $ option ) { if ( $ option -> getValue ( ) == $ this -> selected ) { $ option -> select ( ) ; } else { $ option -> deselect ( ) ; } } } } } return $ this ; }
|
Set the selected value of the select form element
|
1,446
|
public function average ( ) { $ flat = $ this -> flatten ( ) ; $ avg = array ( ) ; foreach ( $ flat as $ metric => $ values ) { $ avg [ $ metric ] = ( float ) number_format ( array_sum ( $ values ) / count ( $ values ) , 2 , '.' , '' ) ; } return $ avg ; }
|
Get metric averages .
|
1,447
|
private function createInstaller ( $ files ) { $ this -> say ( "Creating plugin installer" ) ; $ xmlFile = $ this -> target . "/" . str_replace ( 'plug_' , '' , $ this -> plgName ) . ".xml" ; $ this -> replaceInFile ( $ xmlFile ) ; }
|
Generate the installer xml file for the plugin
|
1,448
|
public static function remembered ( Request $ request ) { $ remember = readCookie ( $ request , 'remember_token' ) ; if ( $ remember != null ) { try { $ decrypted = decrypt ( $ remember ) ; $ authConfig = getConfigPath ( 'app' , 'auth' ) ; return Gate :: user ( $ authConfig , $ decrypted ) ; } catch ( Exception $ ex ) { return false ; } } return false ; }
|
Check remember user .
|
1,449
|
protected function responseRedirect ( $ url , $ status = null ) { $ responseWithRedirect = $ this -> _response -> withHeader ( 'Location' , ( string ) $ url ) ; if ( is_null ( $ status ) && $ this -> _response -> getStatusCode ( ) === 200 ) { $ status = 302 ; } if ( ! is_null ( $ status ) ) { return $ responseWithRedirect -> withStatus ( $ status ) ; } return $ responseWithRedirect ; }
|
set redirekt url in response
|
1,450
|
protected function responseJson ( $ data , $ status = null , $ encodingOptions = 0 ) { $ body = $ this -> _response -> getBody ( ) ; $ body -> rewind ( ) ; $ body -> write ( $ json = json_encode ( $ data , $ encodingOptions ) ) ; if ( $ json === false ) { throw new \ RuntimeException ( json_last_error_msg ( ) , json_last_error ( ) ) ; } $ responseWithJson = $ this -> _response -> withHeader ( 'Content-Type' , 'application/json;charset=utf-8' ) ; if ( isset ( $ status ) ) { return $ responseWithJson -> withStatus ( $ status ) ; } return $ responseWithJson ; }
|
transform response for with json - data
|
1,451
|
protected function responseTemplate ( $ template , $ data = array ( ) ) { if ( ! isset ( hubert ( ) -> template ) ) { throw new \ Exception ( "no template engine installed" ) ; } $ html = hubert ( ) -> template -> render ( $ template , $ data ) ; $ this -> _response -> getBody ( ) -> write ( $ html ) ; return $ this -> _response ; }
|
render template in response
|
1,452
|
public function getErrorMetadata ( ) { try { $ metadata = \ Sifo \ Config :: getInstance ( ) -> getConfig ( 'lang/metadata_' . $ this -> getParam ( 'lang' ) ) ; } catch ( Exception_Configuration $ e ) { $ metadata = \ Sifo \ Config :: getInstance ( ) -> getConfig ( 'lang/metadata_en_US' ) ; } $ error_code = $ this -> getParam ( 'code' ) ; return ( isset ( $ metadata [ $ error_code ] ) ) ? $ metadata [ $ error_code ] : false ; }
|
Assign selected error code metadata to page to allow error translations .
|
1,453
|
public function register ( Application $ app ) { $ app [ 'guzzle.base_url' ] = '/' ; if ( ! isset ( $ app [ 'guzzle.plugins' ] ) ) { $ app [ 'guzzle.plugins' ] = array ( ) ; } $ app [ 'guzzle' ] = $ app -> share ( function ( ) use ( $ app ) { if ( ! isset ( $ app [ 'guzzle.services' ] ) ) { $ builder = new ServiceBuilder ( array ( ) ) ; } else { $ builder = ServiceBuilder :: factory ( $ app [ 'guzzle.services' ] ) ; } return $ builder ; } ) ; $ app [ 'guzzle.client' ] = $ app -> share ( function ( ) use ( $ app ) { $ client = new Client ( $ app [ 'guzzle.base_url' ] ) ; foreach ( $ app [ 'guzzle.plugins' ] as $ plugin ) { $ client -> addSubscriber ( $ plugin ) ; } return $ client ; } ) ; }
|
Register Guzzle with Silex
|
1,454
|
public function normalize ( $ string ) { if ( $ string == '' ) return '' ; $ parts = explode ( '%' , $ string ) ; $ ret = array_shift ( $ parts ) ; foreach ( $ parts as $ part ) { $ length = strlen ( $ part ) ; if ( $ length < 2 ) { $ ret .= '%25' . $ part ; continue ; } $ encoding = substr ( $ part , 0 , 2 ) ; $ text = substr ( $ part , 2 ) ; if ( ! ctype_xdigit ( $ encoding ) ) { $ ret .= '%25' . $ part ; continue ; } $ int = hexdec ( $ encoding ) ; if ( isset ( $ this -> preserve [ $ int ] ) ) { $ ret .= chr ( $ int ) . $ text ; continue ; } $ encoding = strtoupper ( $ encoding ) ; $ ret .= '%' . $ encoding . $ text ; } return $ ret ; }
|
Fix up percent - encoding by decoding unreserved characters and normalizing .
|
1,455
|
public function admin_init ( ) { add_settings_section ( 'soter_general' , 'General Settings' , [ $ this , 'render_section_general' ] , 'soter' ) ; add_settings_section ( 'soter_email' , 'Email Settings' , [ $ this , 'render_section_email' ] , 'soter' ) ; add_settings_section ( 'soter_slack' , 'Slack Settings' , [ $ this , 'render_section_slack' ] , 'soter' ) ; add_settings_field ( 'soter_should_nag' , 'Notification Frequency' , [ $ this , 'render_should_nag' ] , 'soter' , 'soter_general' ) ; add_settings_field ( 'soter_ignored_plugins' , 'Ignored Plugins' , [ $ this , 'render_ignored_plugins' ] , 'soter' , 'soter_general' ) ; add_settings_field ( 'soter_ignored_themes' , 'Ignored Themes' , [ $ this , 'render_ignored_themes' ] , 'soter' , 'soter_general' ) ; add_settings_field ( 'soter_email_enabled' , 'Send Email Notifications' , [ $ this , 'render_email_enabled' ] , 'soter' , 'soter_email' ) ; add_settings_field ( 'soter_email_address' , 'Email Address' , [ $ this , 'render_email_address' ] , 'soter' , 'soter_email' ) ; add_settings_field ( 'soter_email_type' , 'Email Type' , [ $ this , 'render_email_type' ] , 'soter' , 'soter_email' ) ; add_settings_field ( 'soter_slack_enabled' , 'Send Slack Notifications' , [ $ this , 'render_slack_enabled' ] , 'soter' , 'soter_slack' ) ; add_settings_field ( 'soter_slack_url' , 'WebHook URL' , [ $ this , 'render_slack_url' ] , 'soter' , 'soter_slack' ) ; }
|
Registers settings sections and fields .
|
1,456
|
public function print_notice_when_no_notifiers_active ( ) { if ( 'settings_page_soter' !== get_current_screen ( ) -> base || $ this -> options -> email_enabled || $ this -> options -> slack_enabled ) { return ; } echo $ this -> template -> render ( 'admin-notice.php' , [ 'type' => 'error' , 'message' => 'All notification channels are currently disabled. Please enable one or more below.' , ] ) ; }
|
Print an admin notice indicating to user that no notifiers are currently enabled .
|
1,457
|
public function render_email_address ( ) { $ placeholder = get_bloginfo ( 'admin_email' ) ; $ current = $ this -> options -> email_address ; $ value = $ placeholder === $ current ? '' : $ current ; echo $ this -> template -> render ( 'options/email-address.php' , compact ( 'placeholder' , 'value' ) ) ; }
|
Renders the email address field .
|
1,458
|
public function render_ignored_plugins ( ) { $ plugins = get_plugins ( ) ; $ plugins = array_map ( function ( $ key , $ value ) { if ( false === strpos ( $ key , '/' ) ) { $ slug = basename ( $ key , '.php' ) ; } else { $ slug = dirname ( $ key ) ; } return [ 'name' => $ value [ 'Name' ] , 'slug' => $ slug , ] ; } , array_keys ( $ plugins ) , $ plugins ) ; echo $ this -> template -> render ( 'options/ignored-packages.php' , [ 'ignored_packages' => $ this -> options -> ignored_plugins , 'packages' => $ plugins , 'type' => 'plugins' , ] ) ; }
|
Renders the ignored plugins field .
|
1,459
|
public function render_ignored_themes ( ) { $ themes = array_map ( function ( $ value ) { return [ 'name' => $ value -> display ( 'Name' ) , 'slug' => $ value -> get_stylesheet ( ) , ] ; } , wp_get_themes ( ) ) ; echo $ this -> template -> render ( 'options/ignored-packages.php' , [ 'ignored_packages' => $ this -> options -> ignored_themes , 'packages' => $ themes , 'type' => 'themes' , ] ) ; }
|
Renders the ignored themes field .
|
1,460
|
public function nodeAttributes ( $ model = false , $ pid = '' , $ uniqueKey = false ) { $ uniqueKey = $ uniqueKey ? $ uniqueKey : self :: $ uniqueKey ++ ; $ model = ( $ model ) ? $ model : $ this -> owner ; $ id = $ model [ $ this -> id ] ; $ nodeId = $ uniqueKey . '-id-' . $ id ; return array ( 'id' => $ nodeId , 'model' => $ model , 'children' => $ model [ $ this -> childrenAttribute ] , 'text' => $ model [ 'name' ] , 'type' => $ model [ 'type' ] == 1 ? 'user' : 'flag' , 'selected' => in_array ( $ model [ $ this -> id ] , $ this -> selectedNodes ) , 'a_attr' => array ( 'class' => 'jstree-clicked' , 'data-id' => $ nodeId , 'href' => [ $ this -> actionPath , $ this -> id => $ id , 'pid' => $ pid ] ) ) ; }
|
Generates attributes for jstree item from owner model .
|
1,461
|
public function generateTree ( $ items , $ relations ) { $ children = ArrayHelper :: map ( $ relations , 'child' , 'parent' ) ; foreach ( $ relations as $ relation ) { if ( ! isset ( $ items [ $ relation [ 'child' ] ] ) || ! isset ( $ items [ $ relation [ 'parent' ] ] ) ) { continue ; } $ tree = $ items [ $ relation [ 'parent' ] ] [ 'childrenTree' ] ; $ tree [ ] = & $ items [ $ relation [ 'child' ] ] ; $ items [ $ relation [ 'parent' ] ] [ 'childrenTree' ] = $ tree ; } return array_diff_key ( $ items , $ children ) ; }
|
Generates children tree .
|
1,462
|
protected function startup ( $ parser ) { $ reflect = new ReflectionClass ( $ parser ) ; $ this -> configBase = 'parsers.' . $ reflect -> getShortName ( ) ; if ( empty ( config ( "{$this->configBase}.parser.name" ) ) ) { $ this -> failed ( "Required parser.name is missing in parser configuration" ) ; } Log :: info ( get_class ( $ this ) . ': ' . 'Received message from: ' . $ this -> parsedMail -> getHeader ( 'from' ) . " with subject: '" . $ this -> parsedMail -> getHeader ( 'subject' ) . "' arrived at parser: " . config ( "{$this->configBase}.parser.name" ) ) ; }
|
Generalize the local config based on the parser class object .
|
1,463
|
protected function createWorkingDir ( ) { $ uuid = Uuid :: generate ( 4 ) ; $ this -> tempPath = "/tmp/abuseio-{$uuid}/" ; $ this -> fs = new Filesystem ; if ( ! $ this -> fs -> makeDirectory ( $ this -> tempPath ) ) { return $ this -> failed ( "Unable to create directory {$this->tempPath}" ) ; } return true ; }
|
Setup a working directory for the parser
|
1,464
|
protected function isKnownFeed ( ) { if ( $ this -> feedName === false ) { return $ this -> failed ( "Parser did not set the required feedName value" ) ; } if ( empty ( config ( "{$this->configBase}.feeds.{$this->feedName}" ) ) ) { $ this -> warningCount ++ ; Log :: warning ( get_class ( $ this ) . ': ' . "The feed referred as '{$this->feedName}' is not configured in the parser " . config ( "{$this->configBase}.parser.name" ) . ' therefore skipping processing of this e-mail' ) ; return false ; } return true ; }
|
Check if the feed specified is known in the parser config .
|
1,465
|
protected function hasArfMail ( ) { if ( $ this -> arfMail === false ) { $ this -> warningCount ++ ; Log :: warning ( get_class ( $ this ) . ': ' . "The feed referred as '{$this->feedName}' has an ARF requirement that was not met" ) ; return false ; } else { return true ; } }
|
Check if a valid arfMail was passed along which is required when called .
|
1,466
|
protected function isEnabledFeed ( ) { if ( config ( "{$this->configBase}.feeds.{$this->feedName}.enabled" ) !== true ) { Log :: warning ( get_class ( $ this ) . ': ' . "The feed '{$this->feedName}' is disabled in the configuration of parser " . config ( "{$this->configBase}.parser.name" ) . ' therefore skipping processing of this e-mail' ) ; return false ; } return true ; }
|
Check and see if a feed is enabled .
|
1,467
|
protected function hasRequiredFields ( $ report ) { if ( is_array ( config ( "{$this->configBase}.feeds.{$this->feedName}.fields" ) ) ) { $ columns = array_filter ( config ( "{$this->configBase}.feeds.{$this->feedName}.fields" ) ) ; if ( count ( $ columns ) > 0 ) { foreach ( $ columns as $ column ) { if ( ! isset ( $ report [ $ column ] ) ) { Log :: warning ( get_class ( $ this ) . ': ' . config ( "{$this->configBase}.parser.name" ) . " feed '{$this->feedName}' " . "says $column is required but is missing, therefore skipping processing of this incident" ) ; $ this -> warningCount ++ ; return false ; } } } } return true ; }
|
Check if all required fields are in the report .
|
1,468
|
protected function applyFilters ( $ report , $ removeEmpty = true ) { if ( ( ! empty ( config ( "{$this->configBase}.feeds.{$this->feedName}.filters" ) ) ) && ( is_array ( config ( "{$this->configBase}.feeds.{$this->feedName}.filters" ) ) ) ) { $ filter_columns = array_filter ( config ( "{$this->configBase}.feeds.{$this->feedName}.filters" ) ) ; foreach ( $ filter_columns as $ column ) { if ( ! empty ( $ report [ $ column ] ) ) { unset ( $ report [ $ column ] ) ; } } } if ( $ removeEmpty ) { foreach ( $ report as $ field => $ value ) { if ( $ value == "" && ! is_bool ( $ value ) ) { unset ( $ report [ $ field ] ) ; } } } return $ report ; }
|
Filter the unwanted and empty fields from the report .
|
1,469
|
private function getItem ( $ name ) { if ( $ this -> geoip_data == NULL ) $ this -> retrievefromCache ( ) ; return $ this -> geoip_data -> $ name ; }
|
generic property retriever .
|
1,470
|
private function retrievefromCache ( ) { if ( class_exists ( '\\Cache' ) ) { $ cache_key = 'laravel-4-freegeoip-' . $ this -> ip ; if ( \ Cache :: has ( $ cache_key ) ) $ this -> geoip_data = \ Cache :: get ( $ cache_key ) ; else { $ this -> geoip_data = $ this -> resolve ( $ this -> ip ) ; \ Cache :: put ( $ cache_key , $ this -> geoip_data , 60 * 60 ) ; } } else $ this -> geoip_data = $ this -> resolve ( $ this -> ip ) ; }
|
check if the Cache class exists and use caching mechanism if there is otherwise just call the API directly .
|
1,471
|
function resolve ( $ ip ) { $ url = \ Config :: get ( 'laravel-4-freegeoip::freegeoipURL' ) . $ ip ; $ ch = curl_init ( ) ; curl_setopt ( $ ch , CURLOPT_URL , $ url ) ; curl_setopt ( $ ch , CURLOPT_RETURNTRANSFER , 1 ) ; curl_setopt ( $ ch , CURLOPT_CONNECTTIMEOUT , \ Config :: get ( 'laravel-4-freegeoip::timeout' ) ) ; $ file_contents = curl_exec ( $ ch ) ; curl_close ( $ ch ) ; $ data = json_decode ( $ file_contents ) ; if ( $ data == NULL ) throw new \ Exception ( "Problems in retrieving data from http://freegeoip.net" ) ; return $ data ; }
|
call the freegeoip . net for data retrieve it as JSON and convert it to stdclass .
|
1,472
|
public function get ( $ identifier ) { if ( ! isset ( $ this -> managers [ $ identifier ] ) ) throw new InvalidArgumentException ( 'A manager with that identifier does not exist.' ) ; return $ this -> managers [ $ identifier ] ; }
|
Get manager by the given identifier .
|
1,473
|
public function load ( ) { $ data = [ ] ; $ settings = $ this -> database -> select ( 'SELECT * FROM ' . $ this -> table ) ; foreach ( $ settings as $ setting ) { $ id = $ setting -> id ; $ value = $ setting -> value ; $ decoded = json_decode ( $ value , 1 , 512 ) ; if ( is_array ( $ decoded ) ) { $ value = $ decoded ; } Arr :: set ( $ data , $ id , $ value ) ; } return $ data ; }
|
Fetch the settings from the database
|
1,474
|
public function buildRouter ( ) : HTTPRouter { $ request = new HTTPInputRequestDefault ( ) ; $ response = new HTTPOutputResponseDefault ( $ request ) ; $ errHandler = new HTTPErrorHandlerDefault ( ) ; $ router = new HTTPRouterDefault ( $ request , $ response , $ errHandler ) ; $ authorizationDisabled = new AuthorizationDisabled ( ) ; $ router -> addRoute ( new HTTPRouteExample ( $ request , $ response , $ authorizationDisabled ) ) ; return $ router ; }
|
Build and return Router .
|
1,475
|
public function get ( ) { if ( $ this -> requiredType == self :: TYPE_DEFAULT ) { $ this -> requiredType = ( extension_loaded ( 'gmp' ) ? self :: TYPE_GMP : self :: TYPE_NATIVE ) ; } return $ this -> requiredType ; }
|
Return required number base type
|
1,476
|
public function set ( $ requiredType ) { if ( ! in_array ( $ requiredType , $ this -> validTypes ) ) { throw new \ InvalidArgumentException ( "{$requiredType} is not a supported number type" ) ; } if ( $ requiredType == self :: TYPE_GMP && ! extension_loaded ( 'gmp' ) ) { throw new \ InvalidArgumentException ( 'GMP not supported' ) ; } $ this -> requiredType = $ requiredType ; return $ this ; }
|
Set the required number base type
|
1,477
|
public function parseContents ( $ contents ) { if ( ! is_string ( $ contents ) ) return array ( null , null ) ; switch ( $ contents ) { case 'Empty' : return array ( 'empty' , '' ) ; case 'Inline' : return array ( 'optional' , 'Inline | #PCDATA' ) ; case 'Flow' : return array ( 'optional' , 'Flow | #PCDATA' ) ; } list ( $ content_model_type , $ content_model ) = explode ( ':' , $ contents ) ; $ content_model_type = strtolower ( trim ( $ content_model_type ) ) ; $ content_model = trim ( $ content_model ) ; return array ( $ content_model_type , $ content_model ) ; }
|
Convenience function that transforms single - string contents into separate content model and content model type
|
1,478
|
public function mergeInAttrIncludes ( & $ attr , $ attr_includes ) { if ( ! is_array ( $ attr_includes ) ) { if ( empty ( $ attr_includes ) ) $ attr_includes = array ( ) ; else $ attr_includes = array ( $ attr_includes ) ; } $ attr [ 0 ] = $ attr_includes ; }
|
Convenience function that merges a list of attribute includes into an attribute array .
|
1,479
|
public function makeLookup ( $ list ) { if ( is_string ( $ list ) ) $ list = func_get_args ( ) ; $ ret = array ( ) ; foreach ( $ list as $ value ) { if ( is_null ( $ value ) ) continue ; $ ret [ $ value ] = true ; } return $ ret ; }
|
Convenience function that generates a lookup table with boolean true as value .
|
1,480
|
protected function getFileAsset ( $ filePath ) { $ file = new \ SplFileInfo ( $ filePath ) ; if ( ! $ file -> isReadable ( ) || $ file -> isDir ( ) ) { return null ; } $ filePath = $ file -> getRealPath ( ) ; return new FileAsset ( $ filePath ) ; }
|
Get a File Asset
|
1,481
|
public function copyLanguage ( $ dir , $ target ) { $ path = $ this -> getSourceFolder ( ) . "/" . $ dir ; $ files = array ( ) ; $ hdl = opendir ( $ path ) ; while ( $ entry = readdir ( $ hdl ) ) { $ p = $ path . "/" . $ entry ; if ( substr ( $ entry , 0 , 1 ) != '.' ) { if ( ! is_file ( $ p ) ) { $ this -> _mkdir ( $ target . "/" . $ dir . "/" . $ entry ) ; $ fileHdl = opendir ( $ p ) ; while ( $ file = readdir ( $ fileHdl ) ) { if ( substr ( $ file , 0 , 1 ) != '.' && strpos ( $ file , $ this -> ext . "." ) ) { $ files [ ] = array ( $ entry => $ file ) ; $ this -> _copy ( $ p . "/" . $ file , $ target . "/" . $ dir . "/" . $ entry . "/" . $ file ) ; } } closedir ( $ fileHdl ) ; } } } closedir ( $ hdl ) ; return $ files ; }
|
Copy language files
|
1,482
|
public function xmlOverride ( $ matches ) { $ xml = false ; for ( $ i = count ( $ this -> tokens ) - 1 ; $ i >= 0 ; $ i -- ) { $ tok = $ this -> tokens [ $ i ] ; $ name = $ tok [ 0 ] ; if ( $ name === 'COMMENT' ) { continue ; } $ lastChar = $ tok [ 1 ] [ strlen ( $ tok [ 1 ] ) - 1 ] ; if ( ! ( ctype_space ( $ lastChar ) || $ lastChar === '(' || $ lastChar === '{' ) ) { break ; } if ( ! $ this -> check ( '/<[!?a-zA-Z0-9_]/' ) ) { break ; } $ xml = true ; } if ( ! $ xml ) { $ this -> record ( $ matches [ 0 ] , 'OPERATOR' ) ; $ this -> posShift ( strlen ( $ matches [ 0 ] ) ) ; return ; } $ subscanner = new XmlScanner ( ) ; $ subscanner -> string ( $ this -> string ( ) ) ; $ subscanner -> pos ( $ this -> pos ( ) ) ; $ subscanner -> xmlLiteral = true ; $ subscanner -> init ( ) ; $ subscanner -> main ( ) ; $ tagged = $ subscanner -> tagged ( ) ; $ this -> record ( $ tagged , 'XML' , true ) ; $ this -> pos ( $ subscanner -> pos ( ) ) ; }
|
Scala has XML literals .
|
1,483
|
public function getVariant ( ) { if ( $ this -> isLanguageWildcard ( ) ) { return str_replace ( '-*' , '' , $ this -> serverPref -> getVariant ( ) ) ; } elseif ( $ this -> clientWildcardOrAbsent ( ) ) { return $ this -> serverPref -> getVariant ( ) ; } else { return $ this -> clientPref -> getVariant ( ) ; } }
|
Get the shared variant for this pair .
|
1,484
|
private function isLanguageWildcard ( ) { return PreferenceInterface :: LANGUAGE === $ this -> fromField && PreferenceInterface :: PARTIAL_WILDCARD === $ this -> serverPref -> getPrecedence ( ) ; }
|
Returns true if the match was by partial language wildcard .
|
1,485
|
protected function assertPropertyValue ( $ property , $ value ) { $ this -> getPropertiesInfo ( ) ; if ( $ this -> _constraintsValidationEnabled ) { $ constraintsViolations = ConstraintsReader :: validatePropertyValue ( $ this , $ property , $ value ) ; if ( $ constraintsViolations -> count ( ) ) { $ errorMessage = "Argument given is invalid; its constraints validation failed for property $property with the following messages: \"" ; $ errorMessageList = array ( ) ; foreach ( $ constraintsViolations as $ violation ) { $ errorMessageList [ ] = $ violation -> getMessage ( ) ; } $ errorMessage .= implode ( "\", \n\"" , $ errorMessageList ) . "\"." ; throw new \ InvalidArgumentException ( $ errorMessage ) ; } } }
|
Validates the given value compared to given property constraints . If the value is not valid an InvalidArgumentException will be thrown .
|
1,486
|
protected function updatePropertyAssociation ( $ property , array $ values ) { $ this -> getPropertiesInfo ( ) ; $ oldValue = empty ( $ values [ 'oldValue' ] ) ? null : $ values [ 'oldValue' ] ; $ newValue = empty ( $ values [ 'newValue' ] ) ? null : $ values [ 'newValue' ] ; $ association = $ this -> _associationsList [ $ property ] ; if ( ! empty ( $ association ) ) { $ associatedProperty = $ association [ 'property' ] ; switch ( $ association [ 'association' ] ) { case 'inverted' : $ invertedGetMethod = 'get' . ucfirst ( $ associatedProperty ) ; $ invertedSetMethod = 'set' . ucfirst ( $ associatedProperty ) ; if ( $ oldValue !== null && $ oldValue -> $ invertedGetMethod ( ) === $ this ) { $ oldValue -> $ invertedSetMethod ( null ) ; } if ( $ newValue !== null && $ newValue -> $ invertedGetMethod ( ) !== $ this ) { $ newValue -> $ invertedSetMethod ( $ this ) ; } break ; case 'mapped' : $ itemName = $ association [ 'itemName' ] ; $ mappedGetMethod = 'get' . ucfirst ( $ associatedProperty ) ; $ mappedAddMethod = 'add' . ucfirst ( $ itemName ) ; $ mappedRemoveMethod = 'remove' . ucfirst ( $ itemName ) ; if ( $ oldValue !== null && CollectionManager :: collectionContains ( $ this , $ oldValue -> $ mappedGetMethod ( ) ) ) { $ oldValue -> $ mappedRemoveMethod ( $ this ) ; } if ( $ newValue !== null && ! CollectionManager :: collectionContains ( $ this , $ newValue -> $ mappedGetMethod ( ) ) ) { $ newValue -> $ mappedAddMethod ( $ this ) ; } break ; } } }
|
Update the property associated to the given property . You can pass the old or the new value given to the property .
|
1,487
|
private function getPropertiesInfo ( ) { if ( ! $ this -> _automatedBehaviorInitialized ) { $ classInfo = Reader :: getClassInformation ( $ this ) ; $ this -> _accessProperties = $ classInfo [ 'accessProperties' ] ; $ this -> _collectionsItemNames = $ classInfo [ 'collectionsItemNames' ] ; $ this -> _associationsList = $ classInfo [ 'associationsList' ] ; $ this -> _initialPropertiesValues = $ classInfo [ 'initialPropertiesValues' ] ; $ this -> _initializationNeededArguments = $ classInfo [ 'initializationNeededArguments' ] ; if ( $ this -> _constraintsValidationEnabled === null ) { $ this -> _constraintsValidationEnabled = $ classInfo [ 'constraintsValidationEnabled' ] ; } $ this -> _automatedBehaviorInitialized = true ; } }
|
Get every information needed from this class .
|
1,488
|
private function defineType ( $ array = false , $ optional = false ) : int { $ type = ( $ optional ) ? InputArgument :: OPTIONAL : InputArgument :: REQUIRED ; if ( $ array ) { $ type = InputArgument :: IS_ARRAY | $ type ; } return $ type ; }
|
Defines type of an argument or option based on options
|
1,489
|
private function parseParameters ( ) : array { $ arguments = [ ] ; $ options = [ ] ; $ signatureArguments = $ this -> getParameters ( ) ; foreach ( $ signatureArguments as $ value ) { $ item = [ ] ; $ matches = [ ] ; $ exploded = explode ( ':' , $ value ) ; if ( count ( $ exploded ) > 0 && preg_match ( $ this -> argumentsMatcher , $ exploded [ 0 ] , $ matches ) ) { $ item [ 'name' ] = $ matches [ 1 ] ; $ item [ 'type' ] = $ this -> defineType ( $ matches [ 2 ] === '[]' , $ matches [ 3 ] === '=' ) ; $ item [ 'default' ] = $ matches [ 4 ] !== '' ? $ matches [ 4 ] : null ; $ item [ 'description' ] = count ( $ exploded ) === 2 ? $ exploded [ 1 ] : null ; if ( $ matches [ 2 ] === '[]' && $ item [ 'default' ] !== null ) { $ item [ 'default' ] = explode ( ',' , $ item [ 'default' ] ) ; } if ( substr ( $ exploded [ 0 ] , 0 , 2 ) === '--' ) { $ options [ ] = $ item ; } else { $ arguments [ ] = $ item ; } } } return [ 'arguments' => $ arguments , 'options' => $ options , ] ; }
|
Parses arguments and options from signature string returns an array with definitions
|
1,490
|
protected function bootstrap ( ) { if ( $ this -> _isBooted ) { return ; } swoole_set_process_name ( $ this -> name . ':master' ) ; $ this -> installSignals ( ) ; $ this -> _isBooted = true ; }
|
bootstrap the worker
|
1,491
|
protected function installSignals ( ) { $ worker = $ this ; swoole_process :: signal ( SIGTERM , function ( ) use ( $ worker ) { $ worker -> stop ( ) ; } ) ; swoole_process :: signal ( SIGINT , function ( ) use ( $ worker ) { $ worker -> stop ( ) ; } ) ; swoole_process :: signal ( SIGQUIT , function ( ) use ( $ worker ) { $ worker -> stop ( ) ; } ) ; swoole_process :: signal ( SIGCHLD , function ( ) use ( $ worker ) { $ worker -> handleWorkerExit ( ) ; } ) ; }
|
register master signal handlers
|
1,492
|
protected function handleWorkerExit ( ) { $ result = swoole_process :: wait ( ) ; if ( ! empty ( $ this -> _noRestartProcesses [ $ result [ 'pid' ] ] ) ) { unset ( $ this -> _noRestartProcesses [ $ result [ 'pid' ] ] ) ; return ; } if ( $ result [ 'signal' ] > 0 ) { if ( $ this -> restartPolicy & self :: RESTART_ON_SIGNAL ) { $ this -> forkOneWorker ( ) ; } } else { if ( $ result [ 'code' ] > 0 ) { $ this -> _errors [ ] = microtime ( true ) ; if ( $ this -> restartPolicy & self :: RESTART_ON_ERROR && ! $ this -> _disableRestartOnError ) { if ( $ this -> tooManyErrors ( ) ) { $ this -> _disableRestartOnError = true ; } else { $ this -> forkOneWorker ( ) ; } } } else { if ( $ this -> restartPolicy & self :: RESTART_ON_EXIT ) { $ this -> forkOneWorker ( ) ; } } } }
|
handler worker exit signal
|
1,493
|
protected function forkOneWorker ( ) { $ worker = $ this ; $ process = new swoole_process ( function ( swoole_process $ process ) use ( $ worker ) { swoole_set_process_name ( $ worker -> name . ':worker' ) ; call_user_func ( $ worker -> _work , $ process ) ; } , false , false ) ; $ pid = $ process -> start ( ) ; if ( $ pid === false ) { return false ; } $ this -> _workers ++ ; $ this -> _workerProcesses [ $ pid ] = $ process ; return true ; }
|
create a worker process
|
1,494
|
protected function tooManyErrors ( ) { $ count = count ( $ this -> _errors ) ; if ( $ count < $ this -> maxErrorTimes ) { return false ; } return ( $ this -> _errors [ $ count - 1 ] - $ this -> _errors [ $ count - $ this -> maxErrorTimes ] ) <= $ this -> errorInterval ; }
|
whether exceed the maximum error frequency
|
1,495
|
public function withRequestTarget ( $ requestTarget ) { $ request = clone $ this ; if ( preg_match ( '~^(?:[a-z]+:)?//~i' , $ requestTarget ) ) { $ result = parse_url ( $ requestTarget ) ; if ( isset ( $ result [ 'user' ] ) ) { $ result [ 'username' ] = $ result [ 'user' ] ; unset ( $ result [ 'user' ] ) ; } if ( isset ( $ result [ 'pass' ] ) ) { $ result [ 'password' ] = $ result [ 'pass' ] ; unset ( $ result [ 'pass' ] ) ; } foreach ( $ result as $ method => $ value ) { $ request -> $ method ( $ value ) ; } $ request -> mode ( 'absolute' ) ; return $ request ; } if ( preg_match ( "~^(?:(?P<username>[^:]+)(?::(?P<password>[^@]+))?@)?(?P<host>[^/]+)$~" , $ requestTarget , $ matches ) ) { $ request -> username ( $ matches [ 'username' ] ? : null ) ; $ request -> password ( $ matches [ 'password' ] ? : null ) ; $ request -> host ( $ matches [ 'host' ] ) ; $ request -> mode ( 'authority' ) ; return $ request ; } if ( $ requestTarget === '*' ) { $ request -> mode ( 'asterisk' ) ; return $ request ; } $ parts = explode ( '#' , $ requestTarget ) ; if ( isset ( $ parts [ 1 ] ) ) { $ request -> fragment ( $ parts [ 1 ] ) ; } $ parts = explode ( '?' , $ parts [ 0 ] ) ; if ( isset ( $ parts [ 1 ] ) ) { $ request -> query ( $ parts [ 1 ] ) ; } $ request -> path ( $ parts [ 0 ] ) ; return $ request ; }
|
Returns a new instance with the specific request - target .
|
1,496
|
protected function decode ( $ response ) { $ lines = array_slice ( explode ( "\n" , trim ( $ response ) ) , 1 ) ; $ result = [ ] ; foreach ( $ lines as $ line ) { if ( $ line [ 0 ] == '-' ) { $ result [ ] = trim ( ltrim ( $ line , '- ' ) ) ; } else { $ key = strtok ( $ line , ': ' ) ; if ( $ key ) { $ value = ltrim ( trim ( strtok ( '' ) ) , ' ' ) ; if ( is_numeric ( $ value ) ) { $ value = $ value + 0 ; } $ result [ $ key ] = $ value ; } } } return $ result ; }
|
Decodes the YAML string into an array of data .
|
1,497
|
private function partialLangMatches ( $ fromField , MatchedPreferenceInterface $ matchedPreference , PreferenceInterface $ newClientPref ) { $ serverPref = $ matchedPreference -> getServerPreference ( ) ; $ oldClientPref = $ matchedPreference -> getClientPreference ( ) ; list ( $ clientMainLang ) = explode ( '-' , $ newClientPref -> getVariant ( ) ) ; list ( $ serverMainLang ) = explode ( '-' , $ serverPref -> getVariant ( ) ) ; return PreferenceInterface :: LANGUAGE === $ fromField && PreferenceInterface :: PARTIAL_WILDCARD === $ serverPref -> getPrecedence ( ) && $ clientMainLang == $ serverMainLang && $ newClientPref -> getPrecedence ( ) > $ oldClientPref -> getPrecedence ( ) ; }
|
Returns true if the server preference contains a partial language that matches the language in the client preference .
|
1,498
|
public static function createFrom ( Storage $ persistenceProvider , Storage $ cacheProvider , LoggerInterface $ logger = null ) { $ userAgentHandlerChain = $ cacheProvider -> load ( 'UserAgentHandlerChain' ) ; if ( ! ( $ userAgentHandlerChain instanceof UserAgentHandlerChain ) ) { $ userAgentHandlerChain = self :: init ( ) ; $ cacheProvider -> save ( 'UserAgentHandlerChain' , $ userAgentHandlerChain , 3600 ) ; } $ userAgentHandlerChain -> setLogger ( $ logger ) ; foreach ( $ userAgentHandlerChain -> getHandlers ( ) as $ handler ) { $ handler -> setLogger ( $ logger ) -> setPersistenceProvider ( $ persistenceProvider ) ; } return $ userAgentHandlerChain ; }
|
Create a \ Wurfl \ Handlers \ Chain \ UserAgentHandlerChain
|
1,499
|
public function getProperty ( $ name ) { if ( ! $ this -> hasProperty ( $ name ) ) { return ; } if ( strstr ( $ name , '.' ) ) { $ value = false ; @ eval ( '$value = ' . $ this -> resolveArrayPath ( $ name ) . ';' ) ; return $ value ; } if ( $ this -> isArray ( ) ) { return $ this -> object [ $ name ] ; } else { return $ this -> object -> $ name ; } }
|
Get Property .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.