idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
31,500
public function reassignToUserId ( ) { if ( ! is_null ( $ this -> reassignToUserIdCache ) ) { return $ this -> reassignToUserIdCache ; } if ( defined ( 'AD_BULK_IMPORT_REASSIGN_USERNAME' ) && $ userId = $ this -> userNameExists ( AD_BULK_IMPORT_REASSIGN_USERNAME ) ) { if ( $ userId ) { return $ userId ; } } $ user = $ this -> db -> get_col ( "SELECT ID FROM " . $ this -> db -> users . " LIMIT 1" ) ; if ( is_array ( $ user ) && ! empty ( $ user ) ) { $ userId = ( int ) array_pop ( $ user ) ; } return $ this -> reassignToUserIdCache = $ userId ; return false ; }
Get an id if the user that should be reassigned all content
31,501
public function scheduleUpdateProfiles ( $ cron = true ) { $ userAccounts = $ this -> getLocalAccounts ( ) ; if ( is_array ( $ userAccounts ) & ! empty ( $ userAccounts ) ) { $ userAccounts = array_chunk ( $ userAccounts , 200 ) ; foreach ( ( array ) $ userAccounts as $ index => $ userChunk ) { if ( $ cron === true ) { if ( ! wp_next_scheduled ( 'ad_integration_bulk_update_profiles' , array ( 'userNames' => $ userChunk ) ) ) { wp_schedule_single_event ( time ( ) + 10 , 'ad_integration_bulk_update_profiles' , array ( 'userNames' => $ userChunk ) ) ; } } else { $ this -> updateProfiles ( $ userChunk ) ; } } } }
Creates a schedule of 200 update profiles in bulk
31,502
public function index ( array $ filters = [ ] , $ orderBy = [ ] , $ groupBy = [ ] ) { $ selection = $ this -> provider -> selectAll ( $ filters , $ orderBy , $ groupBy ) ; $ query = $ this -> provider -> query ( $ selection ) ; return $ query -> getResult ( ) ; }
Serves the index of all entity
31,503
public function beforeSendPerformed ( Swift_Events_SendEvent $ event ) { $ message = $ event -> getMessage ( ) ; $ to = $ this -> filterEmailArray ( ( array ) $ message -> getTo ( ) ) ; $ cc = $ this -> filterEmailArray ( ( array ) $ message -> getCc ( ) ) ; $ bcc = $ this -> filterEmailArray ( ( array ) $ message -> getBcc ( ) ) ; $ message -> setTo ( $ to ) ; $ message -> setCc ( $ cc ) ; $ message -> setBcc ( $ bcc ) ; $ all = $ to + $ cc + $ bcc ; if ( empty ( $ all ) ) { $ event -> cancelBubble ( ) ; } }
Apply whitelist and blacklist to to cc and bcc .
31,504
public static function buildSwift ( $ attachmentPath , $ name ) { $ file = \ Swift_Attachment :: fromPath ( $ attachmentPath ) ; if ( is_string ( $ name ) ) { $ file -> setFilename ( $ name ) ; } return $ file ; }
Builds a Swift_Attachment object with management of filename .
31,505
public function putFileAs ( $ path , $ file , $ name , $ options = [ ] ) { $ stream = fopen ( $ file -> getRealPath ( ) , 'r+' ) ; $ result = $ this -> put ( $ path = trim ( $ path . '/' . $ name , '/' ) , $ stream , $ options ) ; if ( is_resource ( $ stream ) ) { fclose ( $ stream ) ; } return $ result ? $ path : false ; }
Store the uploaded file on the disk with a given name .
31,506
public function keyCheck ( $ apiKey , $ url ) { $ check = $ this -> query ( array ( 'key' => $ apiKey , 'blog' => $ url ) , self :: PATH_KEY , self :: RETURN_VALID ) ; if ( $ check === true ) { $ this -> apiKey = $ apiKey ; $ this -> url = $ url ; $ this -> apiUrl = sprintf ( 'http://%s.%s/%s/' , $ this -> apiKey , self :: AKISMET_URL , self :: AKISMET_API_VERSION ) ; return true ; } else { return false ; } }
Checks if Akismet API key is valid
31,507
public function onCommitEvent ( ObjectsCommitEvent $ event ) { $ this -> identify ( $ event -> getWebserviceId ( ) ) ; return Splash :: commit ( $ event -> getObjectType ( ) , $ event -> getObjectsIds ( ) , $ event -> getAction ( ) , $ event -> getUserName ( ) , $ event -> getComment ( ) ) ; }
Propagate Commit to Splash Server Using Connector Webservice Infos
31,508
public static function bootModelInlineImgTrait ( ) { static :: registerPostconstruct ( function ( $ instance ) { $ instance -> appendInlineImgConfig ( ) ; } ) ; static :: saving ( function ( $ instance ) { foreach ( $ instance -> inlimgCols as $ attr ) { $ instance -> setAttribute ( $ attr , $ instance -> processInlineImgs ( $ instance -> getAttribute ( $ attr ) ) ) ; } } ) ; }
Laravel model boot .
31,509
public function processInlineImgs ( $ text ) { if ( preg_match_all ( '#(<img\s(?>(?!src=)[^>])*?src=")(data:image/(gif|png|jpeg);base64,([\w=+/]++))("[^>].*>)#siUm' , $ text , $ matches , PREG_SET_ORDER ) ) { foreach ( $ matches as $ m ) { if ( ! empty ( $ m [ 4 ] ) ) { if ( preg_match ( '#width:(.*);#siU' , $ m [ 0 ] , $ wm ) ) { $ width = trim ( $ wm [ 1 ] ) ; } $ src = $ m [ 2 ] ; $ base_64 = $ m [ 4 ] ; $ img = \ Image :: make ( base64_decode ( $ base_64 ) ) ; $ img = $ this -> prepareRawInlineImage ( $ img ) ; $ originalWidth = $ img -> width ( ) ; if ( strpos ( $ width , '%' ) !== false ) { $ newWidth = $ originalWidth / 100 * intval ( trim ( str_replace ( '%' , '' , $ width ) ) ) ; } else { $ newWidth = ( int ) trim ( str_replace ( 'px' , '' , $ width ) ) ; } $ resizeWidth = $ this -> maxWidth ; if ( $ newWidth > $ this -> maxWidth ) { $ resizeWidth = $ newWidth ; } $ img -> resize ( $ resizeWidth , null , function ( $ constraint ) { $ constraint -> aspectRatio ( ) ; } ) ; $ img = $ this -> prepareResizedInlineImage ( $ img ) ; $ ext = $ m [ 3 ] ; if ( $ ext == 'jpeg' ) { $ ext = 'jpg' ; } $ filename = $ this -> generateInlineImgFilename ( $ ext ) ; $ this -> app [ 'files' ] -> makeDirectory ( dirname ( $ this -> getInlineImgPath ( $ filename ) ) , 0755 , true , true ) ; $ img -> save ( $ this -> getInlineImgPath ( $ filename ) ) ; $ text = str_replace ( $ src , $ this -> getInlineImgUrl ( $ filename ) , $ text ) ; } } } return $ text ; }
Proces text for inline images .
31,510
public function getControllers ( $ namespace = null ) { if ( null === $ namespace ) { return $ this -> controllers ; } $ controllers = [ ] ; foreach ( $ this -> controllers as $ name => $ controller ) { if ( $ this -> extractNamespace ( $ name , substr_count ( $ namespace , ':' ) + 1 ) === $ namespace ) { $ controllers [ $ name ] = $ controller ; } } return $ controllers ; }
get all controllers
31,511
public function setControllers ( array $ controllers ) { foreach ( $ controllers as $ name => $ controller ) { $ this -> setController ( $ name , $ controller ) ; } }
set and load controllers
31,512
public function load ( $ name ) { if ( null === ( $ path = $ this -> path ( $ name ) ) ) return ; if ( $ this -> fileExists && ( ! file_exists ( $ path ) ) ) { return ; } include_once $ path ; }
Will include file required for class name ;
31,513
public function path ( $ name , $ folder = false ) { $ prefix = $ name ; while ( false !== $ pos = strrpos ( $ prefix , '\\' ) ) { $ prefix = substr ( $ name , 0 , $ pos + 1 ) ; $ relative_class = substr ( $ name , $ pos + 1 ) ; $ mapped_file = $ this -> loadMappedFile ( $ prefix , $ relative_class , $ folder ) ; if ( $ mapped_file ) { return $ mapped_file ; } $ prefix = rtrim ( $ prefix , '\\' ) ; } return false ; }
This method will the path for a class name . Will return the partial path from libs folder ;
31,514
public static function get ( $ config = [ ] ) { if ( isset ( self :: $ _self [ $ hash = md5 ( serialize ( $ config ) ) ] ) ) return self :: $ _self [ $ hash ] ; return new \ mpf \ base \ AutoLoader ( $ config ) ; }
This method is used to get an instance of this class from anywhere without having to initialize the class each time . It will offer different instances for each config .
31,515
public function getColumnOrderLink ( $ column , $ label , $ htmlOptions = array ( ) ) { return Html :: get ( ) -> link ( $ this -> getColumnOrderURL ( $ column ) , $ label , $ htmlOptions ) ; }
Generates a link to change order for this data provider using the order get Key that can be generated automatically or manually by a developer .
31,516
public function getLinkForPage ( $ pageNumber , $ label , $ htmlOptions = array ( ) ) { return Html :: get ( ) -> link ( $ this -> getURLForPage ( $ pageNumber ) , $ label , $ htmlOptions ) ; }
Generates link for a selected page using the GET key generated automatically or manually by a developer .
31,517
public static function validate ( $ input ) { if ( is_string ( $ input ) ) { $ doc = new DOMDocument ( ) ; $ doc -> preserveWhiteSpace = false ; if ( ! @ $ doc -> loadXML ( $ input ) ) { throw InvalidXmlException :: lastError ( ) ; } $ input = $ doc ; } elseif ( ! ( $ input instanceof DOMDocument ) ) { throw InvalidArgumentException :: create ( 'The $input argument must be an instance of DOMDocument, %s given.' , gettype ( $ input ) ) ; } if ( ! @ $ input -> schemaValidate ( self :: SCHEMA ) ) { throw InvalidXmlException :: lastError ( ) ; } }
Validates the annotations XML document .
31,518
private function add ( ) { if ( ( null !== ( $ check = $ this -> tokens -> getToken ( $ this -> tokens -> key ( ) + 1 ) ) ) && ( ( DocLexer :: T_COLON === $ check [ 0 ] ) || ( DocLexer :: T_EQUALS === $ check [ 0 ] ) ) ) { return ; } $ token = $ this -> tokens -> current ( ) ; $ value = $ this -> result -> createElement ( 'value' ) ; if ( null !== ( $ key = $ this -> key ( ) ) ) { $ value -> setAttribute ( 'key' , $ key ) ; } $ this -> current -> appendChild ( $ value ) ; $ text = null ; $ type = null ; switch ( $ token [ 0 ] ) { case DocLexer :: T_FALSE : $ text = '0' ; $ type = 'boolean' ; break ; case DocLexer :: T_FLOAT : $ text = $ token [ 1 ] ; $ type = 'float' ; break ; case DocLexer :: T_IDENTIFIER : $ text = $ token [ 1 ] ; $ type = 'constant' ; break ; case DocLexer :: T_INTEGER : $ text = $ token [ 1 ] ; $ type = 'integer' ; break ; case DocLexer :: T_NULL : $ type = 'null' ; break ; case DocLexer :: T_STRING : $ text = $ token [ 1 ] ; $ type = 'string' ; break ; case DocLexer :: T_TRUE : $ text = '1' ; $ type = 'boolean' ; break ; } $ value -> setAttribute ( 'type' , $ type ) ; if ( null !== $ text ) { $ value -> appendChild ( new DOMText ( $ text ) ) ; } }
Adds a value to the current list or annotation .
31,519
private function key ( ) { $ offset = $ this -> tokens -> key ( ) ; $ op = $ this -> tokens -> getToken ( $ offset - 1 ) ; if ( $ op && isset ( $ this -> tokens [ $ offset - 2 ] ) && ( ( DocLexer :: T_COLON === $ op [ 0 ] ) || ( DocLexer :: T_EQUALS === $ op [ 0 ] ) ) ) { return $ this -> tokens -> getValue ( $ offset - 2 ) ; } return null ; }
Finds the key and returns it .
31,520
private function startList ( ) { $ this -> depth ++ ; $ values = $ this -> result -> createElement ( 'values' ) ; if ( null !== ( $ key = $ this -> key ( ) ) ) { $ values -> setAttribute ( 'key' , $ key ) ; } $ this -> current -> appendChild ( $ values ) ; $ this -> references [ ] = $ this -> current ; $ this -> current = $ values ; }
Beings accepting a nested list of values .
31,521
protected function sendBody ( Stream $ body ) { $ body -> rewind ( ) ; $ bytes = 0 ; if ( $ bytes = $ body -> getSize ( ) && $ bytes < 500 ) { print $ body -> getContents ( ) ; } else { while ( ! $ body -> eof ( ) ) { $ data = $ body -> read ( 1024 ) ; print $ data ; } } }
Sends Body .
31,522
public function addUsersToNewBlogCron ( $ blogId ) { set_time_limit ( 60 * 60 * 60 ) ; global $ wpdb ; $ users = $ wpdb -> get_results ( "SELECT ID FROM $wpdb->users" ) ; foreach ( $ users as $ user ) { $ this -> addDefaultRole ( $ user -> ID , $ blogId ) ; } }
Propagate users to new blog
31,523
public function addDefaultRole ( $ userId , $ blogId = null ) { if ( is_super_admin ( $ userId ) ) { $ role = "administrator" ; } else { $ role = $ this -> defaultRole ; } if ( ! is_numeric ( $ userId ) ) { return false ; } if ( is_numeric ( $ blogId ) ) { if ( is_user_member_of_blog ( $ userId , $ blogId ) === true ) { return false ; } add_user_to_blog ( $ blogId , $ userId , $ role ) ; return true ; } if ( is_null ( $ blogId ) ) { foreach ( get_sites ( ) as $ site ) { if ( is_user_member_of_blog ( $ userId , $ site -> blog_id ) === true ) { continue ; } add_user_to_blog ( $ site -> blog_id , $ userId , $ role ) ; } } return true ; }
Adds the specified userid to a specified or all blogs
31,524
protected function saveArchive ( ) { if ( ! $ this -> archive -> close ( ) || ! $ this -> archive -> open ( $ this -> tempFile ) ) { throw new \ Exception ( "Saving archive failed." ) ; } }
Writes the changes in the zip file to disk .
31,525
public function input ( $ type , $ name , $ value = null ) { $ value = $ this -> inputs ? $ this -> inputs -> get ( $ name , $ value ) : $ value ; $ form = ( new Input ( $ type , $ name ) ) -> value ( $ value ) ; return $ this -> setClass ( $ form ) ; }
constructs Input form element object with any type .
31,526
public function createPrivateKey ( $ passphrase = null , $ type = null , $ bits = null ) { $ options = array ( ) ; if ( $ type ) { $ type = strtolower ( $ type ) ; if ( false === isset ( $ this -> keyTypes [ $ type ] ) ) { throw new InvalidArgumentException ( sprintf ( 'The private key type "%s" is not recognized.' , $ type ) ) ; } $ options [ 'private_key_type' ] = $ this -> keyTypes [ $ type ] ; } if ( $ bits ) { $ options [ 'private_key_bits' ] = $ bits ; } $ this -> clearBufferedMessages ( ) ; if ( false === ( $ resource = openssl_pkey_new ( $ options ) ) ) { throw new RuntimeException ( sprintf ( 'The private key could not be created: %s' , openssl_error_string ( ) ) ) ; } if ( false === openssl_pkey_export ( $ resource , $ private , $ passphrase ) ) { throw new RuntimeException ( sprintf ( 'The private key could not be exported: %s' , openssl_error_string ( ) ) ) ; } openssl_free_key ( $ resource ) ; return $ private ; }
Creates a new private key .
31,527
public function createPrivateKeyFile ( $ file , $ passphrase = null , $ type = null , $ bits = null ) { $ private = $ this -> createPrivateKey ( $ passphrase , $ type , $ bits ) ; if ( false === @ file_put_contents ( $ file , $ private ) ) { $ error = error_get_last ( ) ; throw new RuntimeException ( sprintf ( 'The private key file "%s" could not be written: %s' , $ file , $ error [ 'message' ] ) ) ; } }
Creates a private key and saves it to a file .
31,528
public function extractPublicKey ( $ private , $ passphrase = null ) { $ this -> clearBufferedMessages ( ) ; if ( false === ( $ resource = openssl_pkey_get_private ( $ private , $ passphrase ) ) ) { throw new RuntimeException ( sprintf ( 'The private key could not be processed: %s' , openssl_error_string ( ) ) ) ; } if ( false === ( $ details = openssl_pkey_get_details ( $ resource ) ) ) { throw new RuntimeException ( sprintf ( 'The details of the private key could not be extracted: %s' , openssl_error_string ( ) ) ) ; } openssl_free_key ( $ resource ) ; return $ details [ 'key' ] ; }
Extracts the public key from the private key .
31,529
public function extractPublicKeyToFile ( $ file , $ private , $ passphrase = null ) { $ public = $ this -> extractPublicKey ( $ private , $ passphrase ) ; if ( false === @ file_put_contents ( $ file , $ public ) ) { $ error = error_get_last ( ) ; throw new RuntimeException ( sprintf ( 'The public key file "%s" could not be written: %s' , $ file , $ error [ 'message' ] ) ) ; } }
Extracts the public key and saves it to a file .
31,530
private function compileClosureBlock ( \ Twig_Compiler $ compiler , $ parentName , $ name ) { $ compiler -> addDebugInfo ( $ this ) -> write ( '$' ) -> raw ( $ name ) -> raw ( ' = ' ) -> raw ( '$this->env->getExtension(\'Fxp\Component\Block\Twig\Extension\BlockExtension\')->createNamed(' ) -> raw ( '\'Fxp\Component\Block\Extension\Core\Type\ClosureType\'' ) -> raw ( ', ' ) -> raw ( 'array("data" => function ($blockView) use ($context, $blocks) { $this->block_' ) -> raw ( $ name ) -> raw ( '(array_merge($context, array(\'closure\' => $blockView)), $blocks); }' ) -> raw ( ', "block_name" => ' ) -> string ( $ name ) -> raw ( ', "label" => "")' ) -> raw ( ');' ) -> raw ( "\n" ) -> write ( '$' ) -> raw ( $ parentName ) -> raw ( 'Children[] = array(\'parent\' => $' ) -> raw ( $ parentName ) -> raw ( ', \'child\' => $' ) -> raw ( $ name ) -> raw ( ');' ) -> raw ( "\n" ) ; }
Compile the closure block .
31,531
private function compileLoopBlock ( \ Twig_Compiler $ compiler ) { $ loop = $ this -> getAttribute ( 'loop' ) ; $ compiler -> write ( 'foreach(' ) -> subcompile ( $ loop [ 1 ] ) -> raw ( ' as $key => $value) {' ) -> raw ( "\n" ) -> indent ( ) -> write ( '$context[' ) -> string ( $ loop [ 0 ] ) -> raw ( '] = $value;' ) -> raw ( "\n" ) ; $ this -> compileChildBlock ( $ compiler , '$key' ) ; $ compiler -> outdent ( ) -> write ( '}' ) -> raw ( "\n" ) -> write ( 'unset($context[' ) -> string ( $ loop [ 0 ] ) -> raw ( ']);' ) -> raw ( "\n" ) ; }
Compile the loop block .
31,532
private function compileMasterBlock ( \ Twig_Compiler $ compiler ) { $ name = $ this -> getAttribute ( 'name' ) ; $ compiler -> addDebugInfo ( $ this ) -> write ( 'list($' ) -> raw ( $ name ) -> raw ( ', $' ) -> raw ( $ name ) -> raw ( 'Children) = $this->block_' ) -> raw ( $ name ) -> raw ( '($context, $blocks);' ) -> write ( 'foreach ($' ) -> raw ( $ name ) -> raw ( 'Children as $index => $cConfig) {' ) -> raw ( "\n" ) -> indent ( ) -> write ( '$cConfig[\'parent\']->add($cConfig[\'child\']);' ) -> raw ( "\n" ) -> outdent ( ) -> write ( '}' ) -> raw ( "\n" ) -> write ( '$' ) -> raw ( $ name ) -> raw ( ' = $' ) -> raw ( $ name ) -> raw ( ' ' ) -> raw ( 'instanceof \Fxp\Component\Block\BlockView ? $' ) -> raw ( $ name ) -> raw ( ' : $' ) -> raw ( $ name ) -> raw ( '->createView();' ) -> raw ( "\n" ) -> write ( 'echo $this->env->getExtension(\'Fxp\Component\Block\Twig\Extension\BlockExtension\')->renderer->searchAndRenderBlock(' ) -> raw ( "\n" ) -> indent ( ) -> write ( '$' ) -> raw ( $ name ) -> raw ( ',' ) -> raw ( "\n" ) -> write ( '"widget"' ) -> raw ( ', ' ) -> raw ( "\n" ) -> write ( '' ) -> subcompile ( $ this -> getAttribute ( 'variables' ) ) -> raw ( ')' ) -> raw ( "\n" ) -> outdent ( ) -> write ( ';' ) -> raw ( "\n" ) ; }
Compile the master block .
31,533
private function compileChildBlock ( \ Twig_Compiler $ compiler , $ key = null ) { $ name = $ this -> getAttribute ( 'name' ) ; $ parentName = $ this -> getAttribute ( 'parent_name' ) ; $ key = null !== $ key ? ', ' . $ key : '' ; $ compiler -> addDebugInfo ( $ this ) -> write ( 'list($' ) -> raw ( $ name ) -> raw ( ', $' ) -> raw ( $ name ) -> raw ( 'Children) = $this->block_' ) -> raw ( $ name ) -> raw ( '($context, $blocks' ) -> raw ( $ key ) -> raw ( ');' ) -> raw ( "\n" ) -> write ( '$' ) -> raw ( $ parentName ) -> raw ( 'Children[] = array(\'parent\' => $' ) -> raw ( $ parentName ) -> raw ( ', \'child\' => $' ) -> raw ( $ name ) -> raw ( ');' ) -> raw ( "\n" ) -> write ( '$' ) -> raw ( $ parentName ) -> raw ( 'Children = array_merge($' ) -> raw ( $ parentName ) -> raw ( 'Children, $' ) -> raw ( $ name ) -> raw ( 'Children);' ) -> raw ( "\n" ) ; }
Compile the child block .
31,534
public static function css ( $ string ) { $ string = preg_replace_callback ( '#[^a-zA-Z0-9]#Su' , function ( $ matches ) { $ char = $ matches [ 0 ] ; if ( ! isset ( $ char [ 1 ] ) ) { $ hex = ltrim ( strtoupper ( bin2hex ( $ char ) ) , '0' ) ; if ( 0 === strlen ( $ hex ) ) { $ hex = '0' ; } return '\\' . $ hex . ' ' ; } $ char = iconv ( 'UTF-8' , 'UTF-16BE' , $ char ) ; return '\\' . ltrim ( strtoupper ( bin2hex ( $ char ) ) , '0' ) . ' ' ; } , $ string ) ; return $ string ; }
Escapes untrusted data for inserting into a property value
31,535
public static function text ( $ string ) { $ escaped = htmlspecialchars ( $ string , ENT_QUOTES | ENT_SUBSTITUTE , 'UTF-8' ) ; $ escaped = str_replace ( "/" , "&#x2F;" , $ escaped ) ; return $ escaped ; }
Escapes untrusted data for inserting into html body
31,536
public static function attr ( $ string ) { $ string = preg_replace_callback ( '#[^a-zA-Z0-9,\.\-_]#Su' , function ( $ matches ) { static $ entityMap = array ( 34 => 'quot' , 38 => 'amp' , 60 => 'lt' , 62 => 'gt' , ) ; $ chr = $ matches [ 0 ] ; $ ord = ord ( $ chr ) ; if ( ( $ ord <= 0x1f && $ chr != "\t" && $ chr != "\n" && $ chr != "\r" ) || ( $ ord >= 0x7f && $ ord <= 0x9f ) ) { return '&#xFFFD;' ; } if ( strlen ( $ chr ) == 1 ) { $ hex = strtoupper ( substr ( '00' . bin2hex ( $ chr ) , - 2 ) ) ; } else { $ chr = iconv ( 'UTF-8' , 'UTF-16BE' , $ chr ) ; $ hex = strtoupper ( substr ( '0000' . bin2hex ( $ chr ) , - 4 ) ) ; } $ int = hexdec ( $ hex ) ; if ( array_key_exists ( $ int , $ entityMap ) ) { return sprintf ( '&%s;' , $ entityMap [ $ int ] ) ; } return sprintf ( '&#x%s;' , $ hex ) ; } , $ string ) ; return $ string ; }
Escapes untrusted data for inserting into safe HTML Attribute
31,537
public static function js ( $ string ) { $ string = preg_replace_callback ( '#[^a-zA-Z0-9,\._]#Su' , function ( $ matches ) { $ char = $ matches [ 0 ] ; if ( ! isset ( $ char [ 1 ] ) ) { return '\\x' . strtoupper ( substr ( '00' . bin2hex ( $ char ) , - 2 ) ) ; } $ char = iconv ( 'UTF-8' , 'UTF-16BE' , $ char ) ; return '\\u' . strtoupper ( substr ( '0000' . bin2hex ( $ char ) , - 4 ) ) ; } , $ string ) ; return $ string ; }
Escapes untrusted data for inserting into javascript variable function parameter
31,538
public function getLinks ( $ relation = null ) { $ links = $ this -> getAllLinks ( ) ; if ( null === $ relation ) { return $ links ; } foreach ( $ links as $ key => $ link ) { if ( $ link -> getRelation ( ) !== $ relation ) { unset ( $ links [ $ key ] ) ; } } return $ links ; }
Return links .
31,539
public function getLink ( $ relation ) { $ links = $ this -> getAllLinks ( ) ; foreach ( $ links as $ link ) { if ( $ link -> getRelation ( ) === $ relation ) { return $ link ; } } return null ; }
Return single link .
31,540
private function getAllLinks ( ) { return $ this -> getCachedProperty ( 'links' , function ( ) { $ result = [ ] ; $ nodes = $ this -> query ( 'atom:link' ) ; foreach ( $ nodes as $ node ) { $ result [ ] = $ this -> getExtensions ( ) -> parseElement ( $ this , $ node ) ; } return $ result ; } ) ; }
Return all element links .
31,541
public static function closure ( \ Closure $ transformer , array $ params ) : array { if ( empty ( $ params ) ) { return $ params ; } try { list ( $ args , $ extra ) = self :: interpretFunction ( new \ ReflectionFunction ( $ transformer ) , $ params ) ; return array_merge ( $ args , $ extra ) ; } catch ( \ ReflectionException $ e ) { } return [ ] ; }
Extracts all of the valid arguments for a provided Closure .
31,542
public static function mergeCallable ( callable $ transformer , array $ params , string $ method = 'transform' ) : array { if ( TransformerHelper :: isClosure ( $ transformer ) ) { return static :: mergeClosure ( $ transformer , $ params ) ; } return self :: mergeParameters ( new \ ReflectionMethod ( $ transformer , $ method ) , $ params ) ; }
Merges an indexed array of arguments values with their name . Note the orders MUST match .
31,543
private function buildPathes ( string $ projectPath ) : array { if ( substr ( $ projectPath , - 1 ) !== DIRECTORY_SEPARATOR ) { $ projectPath .= DIRECTORY_SEPARATOR ; } $ pathes = [ ] ; foreach ( $ this -> pathTypes as $ pathType ) { $ pathes [ 'stubbles.' . $ pathType . '.path' ] = $ projectPath . $ pathType ; } return $ pathes ; }
appends directory separator if necessary
31,544
protected function present ( $ command , \ ReflectionMethod $ method , \ ReflectionClass $ class ) { if ( $ method -> isStatic ( ) ) return ; if ( 'action' !== substr ( $ method -> getName ( ) , 0 , 6 ) ) return ; $ params = $ method -> getParameters ( ) ; echo $ this -> getRunPath ( ) . ' ' . $ command . " " . lcfirst ( substr ( $ method -> getName ( ) , 6 ) ) ; foreach ( $ params as $ p ) echo $ this -> paramDetails ( $ p ) ; if ( $ class -> getDocComment ( ) ) { echo "\n" . $ class -> getDocComment ( ) ; } echo "\n\n" ; }
Echo how an action can be called from cli command ;
31,545
protected function paramDetails ( \ ReflectionParameter $ param ) { return ' ' . ( $ param -> isOptional ( ) ? '[' : '' ) . '--' . $ param -> getName ( ) . ( $ param -> isOptional ( ) ? '=' . ( $ param -> isDefaultValueConstant ( ) ? $ param -> getDefaultValueConstantName ( ) : '"' . $ param -> getDefaultValue ( ) . '"' ) : '' ) . ( $ param -> isOptional ( ) ? ']' : '' ) ; }
Get a declaration of the param for cli command ;
31,546
public function set ( string $ name , $ value ) { if ( ! array_key_exists ( $ name , $ this -> map ) ) { throw new \ InvalidArgumentException ( "Setting $name does not exists" ) ; } $ this -> map [ $ name ] = $ value ; }
Set a setting if it does dot exists then throws an exception
31,547
public function setAll ( array $ settings ) { foreach ( $ settings as $ name => $ value ) { if ( is_string ( $ name ) && $ this -> exists ( $ name ) ) { $ this -> set ( $ name , $ value ) ; } } }
Set an array of settings ignores non existent or non - string - key elements
31,548
public function get ( string $ name , $ default = null ) { return ( $ this -> exists ( $ name ) ) ? $ this -> map [ $ name ] : $ default ; }
Obtain a setting
31,549
public function onKernelException ( GetResponseForExceptionEvent $ event ) { $ exception = $ event -> getException ( ) ; if ( $ exception instanceof NotFoundHttpException ) { $ response = $ event -> getResponse ( ) ; $ values = array ( 'status_code' => 404 , 'message' => $ exception -> getMessage ( ) , ) ; $ event -> setResponse ( $ this -> templating -> renderResponse ( 'AlphaLemonThemeEngineBundle:Error:error.html.twig' , $ values , $ response ) ) ; } }
Returns a custom error page for 404 errors
31,550
private function detectBindingName ( \ ReflectionParameter $ param , $ default = null ) { $ annotations = annotationsOf ( $ param ) ; if ( $ annotations -> contain ( 'List' ) ) { return $ annotations -> firstNamed ( 'List' ) -> getValue ( ) ; } if ( $ annotations -> contain ( 'Map' ) ) { return $ annotations -> firstNamed ( 'Map' ) -> getValue ( ) ; } if ( $ annotations -> contain ( 'Named' ) ) { return $ annotations -> firstNamed ( 'Named' ) -> getName ( ) ; } if ( $ annotations -> contain ( 'Property' ) ) { return $ annotations -> firstNamed ( 'Property' ) -> getValue ( ) ; } return $ default ; }
detects name for binding
31,551
private function createTypeMessage ( string $ type , string $ name = null ) : string { return ( ( null !== $ name ) ? ( $ type . ' (named "' . $ name . '")' ) : ( $ type ) ) ; }
creates the complete type message
31,552
private function createParamString ( \ ReflectionParameter $ parameter , string $ type ) : string { $ message = '' ; if ( ! in_array ( $ type , [ PropertyBinding :: TYPE , ConstantBinding :: TYPE , ListBinding :: TYPE , MapBinding :: TYPE ] ) ) { $ message .= $ type . ' ' ; } elseif ( $ parameter -> isArray ( ) ) { $ message .= 'array ' ; } return $ message . '$' . $ parameter -> getName ( ) ; }
creates the called method message
31,553
protected function parseFailedRules ( $ failedRules ) { $ parsedFailedRules = [ ] ; foreach ( $ failedRules as $ field => $ ruleAttributes ) { foreach ( $ ruleAttributes as $ rule => $ attributes ) { $ parsedFailedRules [ $ field ] = strtolower ( $ field . '.' . $ rule ) ; } } return $ parsedFailedRules ; }
Parse failed rules .
31,554
public function attachMember ( User $ user , MemberTag $ memberTag , $ memberId ) { return $ user -> selected_context -> id === $ memberId ; }
Allow User to add their selected context to MemberTag
31,555
public function detachMember ( User $ user , MemberTag $ memberTag , $ memberId ) { return $ user -> selected_context -> id === $ memberId ; }
Allow User to remove MemberTag from their selected context
31,556
public function transform ( Team $ team ) { return [ 'captainName' => "{$team->user->name}" , 'captainId' => $ team -> user_id , 'country' => $ team -> country , 'createdAt' => $ team -> created_at -> toW3cString ( ) , 'id' => $ team -> id , 'name' => $ team -> name , 'timezone' => $ team -> timezone , 'updatedAt' => $ team -> updated_at -> toW3cString ( ) , ] ; }
Transformer to generate JSON response with Team data
31,557
public function createRouter ( App $ app , array $ config = [ ] ) : Router { $ routes = $ this -> mergeRoutes ( $ app , $ this -> buildRoutes ( $ config ) ) ; return new PathRouter ( ... $ this -> generateRouterData ( $ routes ) ) ; }
Create a path router and URI generator from the given routes .
31,558
protected function compileRoute ( Route $ route ) : array { $ regex = '' ; $ prefix = '' ; $ prio = 0 ; $ pre = true ; $ wildcard = false ; foreach ( \ explode ( '/' , $ route -> pattern ) as $ level => $ entry ) { if ( ! $ level ) { continue ; } if ( $ wildcard ) { throw new \ RuntimeException ( 'No additional path segments are allowed after wildcard matcher' ) ; } if ( $ pre ) { $ prefix .= '/' ; } else { $ regex .= '/' ; } $ prio += 1000 ; if ( false === \ strpos ( $ entry , '{' ) ) { if ( $ pre ) { $ prefix .= $ entry ; } else { $ regex .= \ preg_quote ( $ entry , "'" ) ; } $ prio += 2 ; continue ; } $ pre = false ; $ parts = \ preg_split ( "'(\\{[^\\}]+\\})'" , $ entry , - 1 , \ PREG_SPLIT_DELIM_CAPTURE | \ PREG_SPLIT_NO_EMPTY ) ; $ boost = 0 ; foreach ( $ parts as $ part ) { if ( $ part [ 0 ] != '{' ) { $ regex .= \ preg_quote ( $ part , "'" ) ; $ boost += 2 ; continue ; } if ( \ substr ( $ part , - 2 ) == '*}' ) { $ regex .= '(.+)' ; $ wildcard = true ; break ; } $ regex .= '([^/]+)' ; $ boost -= 1 ; } if ( $ wildcard ) { if ( \ count ( $ parts ) !== 1 ) { throw new \ RuntimeException ( 'Wildcard patern must be the only placeholder of the last route level' ) ; } $ prio -= 500 ; } else { $ prio += $ boost ; } } return [ $ route , $ prio , '/' . \ ltrim ( $ prefix , '/' ) , $ regex ] ; }
Compiles a route into a priority static prefix regex part and param names .
31,559
public function getLCIAResult ( $ type , $ module ) { if ( in_array ( $ module , self :: $ allowedModules ) === false ) { throw new \ Exception ( 'Module ' . $ module . ' not allowed' ) ; } $ value = 0 ; if ( ! $ this -> getXmlData ( ) -> LCIAResults ) { return 0 ; } foreach ( $ this -> getXmlData ( ) -> LCIAResults -> LCIAResult as $ result ) { $ resultType = $ result -> referenceToLCIAMethodDataSet -> shortDescription ; $ resultType = ( string ) $ resultType [ 0 ] ; if ( preg_match ( $ type , $ resultType ) ) { foreach ( $ result -> other -> amount as $ amount ) { $ resultModule = ( string ) $ amount -> attributes ( ) -> module ; if ( $ resultModule === $ module ) { $ value = ( float ) $ amount ; return $ value ; } } } else { continue ; } } return $ value ; }
Retrieve the LCIA Result value
31,560
public function getExchangeResult ( $ type , $ module ) { if ( in_array ( $ module , self :: $ allowedModules ) === false ) { throw new \ Exception ( 'Module ' . $ module . ' not allowed' ) ; } $ value = 0 ; if ( ! $ this -> getXmlData ( ) -> exchanges ) { return 0 ; } foreach ( $ this -> getXmlData ( ) -> exchanges -> exchange as $ result ) { $ resultType = $ result -> referenceToFlowDataSet -> shortDescription ; $ resultType = ( string ) $ resultType [ 0 ] ; if ( preg_match ( $ type , $ resultType ) ) { foreach ( $ result -> other -> amount as $ amount ) { $ resultModule = ( string ) $ amount -> attributes ( ) -> module ; if ( $ resultModule === $ module ) { $ value = ( float ) $ amount ; return $ value ; } } } else { continue ; } } return $ value ; }
Retrieve the Exchange Result value
31,561
public function getContextsAttribute ( ) { $ this -> load ( 'members' ) ; return $ this -> members -> map ( function ( $ context ) { $ classIdParts = explode ( '\\' , get_class ( $ context ) ) ; return [ 'id' => $ context -> id , 'role' => $ context -> role , 'status' => $ context -> status , 'team_id' => $ context -> team_id , 'type' => array_pop ( $ classIdParts ) , ] ; } ) ; }
Get the available contexts for the User
31,562
public function getSelectedContextAttribute ( ) { if ( isset ( $ this -> context ) ) { return $ this -> context ; } switch ( $ this -> selected_context_type ) { case 'Member' : return $ this -> context = new MemberContext ( $ this ) ; default : abort ( 401 , 'Context not selected.' ) ; } }
Get the selected context
31,563
public function hasMemberOnTeam ( $ teamId ) { $ membersOnTeam = $ this -> members -> filter ( function ( $ member ) use ( $ teamId ) { return ( $ member -> team_id === $ teamId ) && ( $ member -> status !== "Invited" ) ; } ) ; return $ membersOnTeam -> count ( ) > 0 ; }
Check for existing Member on Team with UUID
31,564
public function getId ( $ offset = null ) { if ( null !== ( $ token = $ this -> getToken ( $ offset ) ) ) { return $ token [ 0 ] ; } return null ; }
Returns the token identifier at the offset .
31,565
public function getKey ( $ offset = null ) { if ( null === $ offset ) { $ offset = $ this -> offset ; } if ( ( null !== ( $ op = $ this -> getId ( -- $ offset ) ) ) && ( ( DocLexer :: T_COLON === $ op ) || ( DocLexer :: T_EQUALS === $ op ) ) ) { return $ this -> getValue ( -- $ offset ) ; } return null ; }
Returns the key for the value at the offset .
31,566
public function getToken ( $ offset = null , array $ default = null ) { if ( null === $ offset ) { $ offset = $ this -> offset ; } if ( isset ( $ this -> tokens [ $ offset ] ) ) { if ( ! isset ( $ this -> tokens [ $ offset ] [ 0 ] ) ) { throw InvalidTokenException :: create ( 'Token #%d is missing its token identifier.' , $ offset ) ; } if ( ! isset ( self :: $ valid [ $ this -> tokens [ $ offset ] [ 0 ] ] ) ) { throw InvalidTokenException :: create ( 'Token #%d does not have a valid token identifier.' , $ offset ) ; } if ( ( isset ( self :: $ hasValue [ $ this -> tokens [ $ offset ] [ 0 ] ] ) ) && ! isset ( $ this -> tokens [ $ offset ] [ 1 ] ) ) { throw InvalidTokenException :: create ( 'Token #%d (%d) is missing its value.' , $ offset , $ this -> tokens [ $ offset ] [ 0 ] ) ; } return $ this -> tokens [ $ offset ] ; } return $ default ; }
Returns the token at the offset or the default given .
31,567
public function getValue ( $ offset = null ) { if ( null === $ offset ) { $ offset = $ this -> offset ; } $ token = $ this -> getToken ( $ offset ) ; if ( ! isset ( self :: $ hasValue [ $ token [ 0 ] ] ) ) { throw LogicException :: create ( 'Token #%d (%d) is not expected to have a value.' , $ offset , $ token [ 0 ] ) ; } switch ( $ token [ 0 ] ) { case DocLexer :: T_FALSE : return false ; case DocLexer :: T_FLOAT : return ( float ) $ token [ 1 ] ; case DocLexer :: T_INTEGER : return ( int ) $ token [ 1 ] ; case DocLexer :: T_IDENTIFIER : case DocLexer :: T_STRING : return $ token [ 1 ] ; case DocLexer :: T_TRUE : return true ; } return null ; }
Returns the processed value of the specified token .
31,568
public function handleToken ( $ invalidTokenBehavior , $ isValid ) { $ status = true ; if ( true !== $ isValid ) { $ status = $ this -> handleInvalidToken ( $ invalidTokenBehavior ) ; } return $ status ; }
Handler entry for handling an token state and behavior passed in . Validation is explicitly not part of this handler . Validation is configurable and so up to your imagination and we don t want to stop that .
31,569
protected function handleInvalidToken ( $ tokenBehavior = self :: TOKEN_BEHAVIOR_DEFAULT ) { switch ( $ tokenBehavior ) { case self :: TOKEN_BEHAVIOR_IGNORE : $ status = true ; break ; case self :: TOKEN_BEHAVIOR_INVALIDATE : $ status = false ; break ; case self :: TOKEN_BEHAVIOR_DENY : default : $ headers = [ 'HTTP/1.0 400 Bad Request' , sprintf ( 'WWW-Authenticate: x-doozr-form-service-token realm="%s"' , $ this -> generateToken ( ) ) , ] ; if ( false === headers_sent ( $ file , $ line ) ) { foreach ( $ headers as $ header ) { header ( $ header ) ; } } exit ; break ; } return $ status ; }
Handles invalid tokens by passed behavior .
31,570
protected function initPanels ( ) { if ( empty ( $ this -> panels ) ) { $ this -> panels = $ this -> corePanels ( ) ; } else { $ corePanels = $ this -> corePanels ( ) ; foreach ( $ corePanels as $ id => $ config ) { if ( isset ( $ this -> panels [ $ id ] ) ) { unset ( $ corePanels [ $ id ] ) ; } } $ this -> panels = array_filter ( array_merge ( $ corePanels , $ this -> panels ) ) ; } foreach ( $ this -> panels as $ id => $ config ) { if ( is_string ( $ config ) ) { $ config = [ 'class' => $ config ] ; } $ config [ 'id' ] = $ id ; $ this -> panels [ $ id ] = Yii :: createObject ( $ config ) ; if ( ! $ this -> panels [ $ id ] instanceof CmsToolbarPanel ) { unset ( $ this -> panels [ $ id ] ) ; } } }
Initializes panels .
31,571
public function destroy ( $ id ) { $ note = Note :: findOrFail ( $ id ) ; $ this -> authorize ( 'manage' , $ note ) ; $ note -> delete ( ) ; return fractal ( $ id , new DeletedTransformer ( ) ) -> withResourceName ( 'deletedNote' ) -> respond ( ) ; }
Delete a Note object
31,572
public function store ( Request $ request ) { $ rules = [ "content" => "required|max:1024" , ] ; $ request -> validate ( $ this -> addPolymorphicRules ( $ rules , 'noteable' , $ request -> noteableType ) ) ; $ note = new Note ( ) ; $ note -> content = $ request -> get ( "content" ) ; $ note -> noteable_id = $ request -> get ( "noteableId" ) ; $ note -> noteable_type = $ request -> get ( "noteableType" ) ; $ this -> authorize ( 'manage' , $ note ) ; $ note -> save ( ) ; return fractal ( $ note , new NoteTransformer ( ) ) -> withResourceName ( 'note' ) -> respond ( ) ; }
Store a new Note
31,573
public function update ( Request $ request , $ id ) { $ request -> validate ( [ "content" => "required|max:1024" ] ) ; $ note = Note :: findOrFail ( $ id ) ; $ note -> content = $ request -> get ( "content" ) ; $ this -> authorize ( 'manage' , $ note ) ; $ note -> save ( ) ; return fractal ( $ note , new NoteTransformer ( ) ) -> withResourceName ( 'note' ) -> respond ( ) ; }
Store an updated Note
31,574
public function reconnection ( $ obj ) : bool { $ resId = $ this -> genID ( $ obj ) ; $ info = $ this -> getMeta ( $ resId ) ; if ( ! $ obj -> connect ( $ info ) ) { $ this -> destroy ( $ obj ) ; return false ; } return true ; }
reconnection to DB server
31,575
public function get ( $ id ) { if ( isset ( $ this -> objects [ $ id ] ) ) { return $ this -> objects [ $ id ] ; } else { return false ; } }
Retrieves an object from the object cache .
31,576
public static function mime_type ( $ file ) { $ handle = finfo_open ( FILEINFO_MIME ) ; $ mime_type = finfo_file ( $ handle , $ file ) ; if ( strpos ( $ mime_type , ';' ) ) { $ mime_type = preg_replace ( '/;.*/' , ' ' , $ mime_type ) ; } return trim ( $ mime_type ) ; }
Fetches the mime type for a certain file
31,577
public function cacheFlushByGroup ( $ group ) { $ group = StringHelper :: toUnderscoreVariable ( get_called_class ( ) ) . '/' . StringHelper :: toUnderscoreVariable ( $ group ) ; $ this -> getCache ( ) -> setGroup ( $ group ) -> clear ( ) ; return $ this ; }
clear cache by group group is can function name
31,578
private function load ( ) { $ this -> cached = [ ] ; $ entities = $ this -> daoGeneric -> getEntities ( $ this -> entityName ) ; foreach ( $ entities as $ one ) { $ id = $ one [ ETypeBase :: A_ID ] ; $ code = $ one [ ETypeBase :: A_CODE ] ; $ this -> cached [ $ code ] = $ id ; } }
Load data and compose id - by - code cache .
31,579
function run ( ) { $ self = $ this ; $ modules = $ this -> modules_enabled ; $ this -> event ( ) -> then ( function ( ) use ( $ self , $ modules ) { $ self -> moduleManager ( ) -> loadModules ( $ modules ) ; } ) ; $ this -> event ( ) -> onFailure ( function ( $ exception , $ event ) { $ this -> _run_handleException ( $ exception , $ event ) ; $ event -> shutdown ( ) ; } ) -> trigger ( EventHeapOfSapi :: EVENT_APP_BOOTSTRAP ) -> trigger ( EventHeapOfSapi :: EVENT_APP_MATCH_REQUEST ) -> trigger ( EventHeapOfSapi :: EVENT_APP_DISPATCH ) -> trigger ( EventHeapOfSapi :: EVENT_APP_RENDER ) -> trigger ( EventHeapOfSapi :: EVENT_APP_FINISH ) ; }
Run Application And Send Response Output
31,580
final protected function _attachDefaultEvents ( ) { if ( $ this -> _isEventAttached ) return ; $ this -> event ( ) -> on ( EventHeapOfSapi :: EVENT_APP_ERROR , function ( \ Exception $ exception = null , $ sapi = null , $ exceptionShouldThrow = true ) { $ exception_code = $ exception -> getCode ( ) ; $ response = $ sapi -> services ( ) -> get ( '/httpResponse' ) ; if ( Status :: _ ( $ response ) -> isSuccess ( ) ) { if ( ! ( is_numeric ( $ exception_code ) && $ exception_code > 100 && $ exception_code <= 600 ) ) $ exception_code = 500 ; $ response -> setStatusCode ( ( $ exception_code ) ? $ exception_code : 500 ) ; } if ( $ exceptionShouldThrow && $ exception instanceof \ Exception ) throw $ exception ; } , self :: LISTENER_THROW_EXCEPTION_PRIORITY ) ; $ this -> doAttachDefaultEvents ( ) ; $ this -> _isEventAttached = true ; }
Initialize To Events
31,581
public function isValid ( $ name = null ) { $ this -> resetInputFilter ( ) -> getInputFilter ( ) -> setData ( $ this -> getValues ( ) ) ; $ names = $ this -> findScenario ( ) ; if ( $ name !== null ) { $ names = array_intersect ( $ names , ( array ) $ name ) ; } $ isValid = $ this -> getInputFilter ( ) -> setValidationGroup ( $ names ) -> isValid ( ) ; $ this -> setValues ( $ this -> getInputFilter ( ) -> getValues ( ) ) ; return $ isValid ; }
Validate inputs .
31,582
public function setValues ( $ values ) { foreach ( $ this -> findScenario ( ) as $ name ) { if ( array_key_exists ( $ name , $ values ) ) { $ this -> $ name = $ values [ $ name ] ; } } return $ this ; }
Setting values into input filter .
31,583
public function getValues ( ) { $ values = [ ] ; foreach ( $ this -> findScenario ( ) as $ name ) { $ values [ $ name ] = $ this -> $ name ; } return $ values ; }
Returns values from the input filter .
31,584
public function setError ( $ name , $ error ) { if ( ! $ this -> getInputFilter ( ) instanceof ErrorMessageInterface ) { throw new NotSupportedException ( sprintf ( 'Method %s::%s() is not supported.' , get_class ( $ this -> getInputFilter ( ) ) , __FUNCTION__ ) ) ; } $ this -> getInputFilter ( ) -> setMessage ( $ name , $ error ) ; return $ this ; }
Set error message for the input .
31,585
protected function attachInputs ( ) { foreach ( $ this -> inputs ( ) as $ input ) { $ this -> getInputFilter ( ) -> add ( $ input ) ; } return $ this ; }
Attaching declaring inputs into input filter .
31,586
protected function findScenario ( $ scenario = null ) { $ scenarios = $ this -> scenarios ( ) ; if ( $ scenario === null ) { $ scenario = $ this -> getScenario ( ) ; } return isset ( $ scenarios [ $ scenario ] ) ? $ scenarios [ $ scenario ] : [ ] ; }
Return current scenario input names .
31,587
public static function install ( array $ driverConfiguration ) { if ( false === self :: validate ( $ driverConfiguration , [ 'classes' ] ) ) { throw new \ Doozr_Exception ( sprintf ( 'Configuration invalid for driver "%s".' , __CLASS__ ) ) ; } $ paths = [ $ driverConfiguration [ 'entities' ] ] ; $ isDevelopmentMode = ( \ Doozr_Kernel :: APP_ENVIRONMENT_DEVELOPMENT === DOOZR_APP_ENVIRONMENT ) ; $ configuration = Setup :: createAnnotationMetadataConfiguration ( $ paths , $ isDevelopmentMode ) ; foreach ( $ driverConfiguration [ 'connections' ] as $ id => $ connectionData ) { self :: $ connection [ $ id ] = EntityManager :: create ( $ connectionData , $ configuration ) ; } return self :: $ connection ; }
The install routine of the driver . All available information for the driver is passed as configuration .
31,588
public function getConnection ( $ id = null ) { if ( null === $ id ) { $ result = self :: $ connection ; } else { if ( false === isset ( self :: $ connection [ $ id ] ) ) { throw new \ Doozr_Exception ( sprintf ( 'EntityManager connection with Id "%s" does not exist!' , $ id ) ) ; } $ result = self :: $ connection [ $ id ] ; } return $ result ; }
Returns a connection by its Id or the whole collection if not Id passed .
31,589
static public function smtp ( $ host = null , $ user = null , $ pass = null , $ port = null , $ ssl = false , $ tls = false ) { if ( ! $ host ) { $ host = Config :: get ( 'email' ) ; } $ debug = false ; if ( is_array ( $ host ) ) { $ user = $ host [ 'user' ] ; $ pass = isset ( $ host [ 'password' ] ) ? $ host [ 'password' ] : $ host [ 'pass' ] ; $ port = isset ( $ host [ 'port' ] ) && $ host [ 'port' ] ? $ host [ 'port' ] : null ; $ ssl = isset ( $ host [ 'ssl' ] ) && $ host [ 'ssl' ] ? $ host [ 'ssl' ] : null ; $ tls = isset ( $ host [ 'tls' ] ) && $ host [ 'tls' ] ? $ host [ 'tls' ] : null ; $ host = $ host [ 'host' ] ; $ debug = isset ( $ host [ 'debugging' ] ) ? $ host [ 'debugging' ] : ( isset ( $ host [ 'debug' ] ) ? $ host [ 'debug' ] : false ) ; } $ instance = Smtp :: instance ( $ host , $ user , $ pass , $ port , $ ssl , $ tls ) ; $ instance -> setDebugging ( $ debug ) ; return $ instance ; }
Constructor - Store connection information
31,590
public function registerPlugin ( $ className ) { if ( ! class_exists ( $ className ) ) { throw new \ Exception ( 'cannot register unknown class as plugin: ' . $ className ) ; } if ( ! is_subclass_of ( $ className , '\KubernetesController\Plugin\AbstractPlugin' ) ) { throw new \ Exception ( 'plugin must inherit from \KuberetesController\Plugin\AbstractPlugin: ' . $ className ) ; } if ( ! in_array ( $ className , $ this -> registeredPlugins ) ) { $ this -> registeredPlugins [ ] = $ className ; } }
Registered plugins class names
31,591
private function onConfigLoaded ( ) { $ this -> log ( 'controller config loaded/updated' ) ; $ this -> stopPlugins ( ) ; if ( ! $ this -> state [ 'config' ] [ 'enabled' ] ) { $ this -> log ( 'controller disabled' ) ; return ; } foreach ( $ this -> state [ 'config' ] [ 'plugins' ] as $ pluginId => $ config ) { if ( ! $ config [ 'enabled' ] ) { continue ; } $ this -> log ( 'loading plugin ' . $ pluginId ) ; foreach ( $ this -> registeredPlugins as $ className ) { if ( $ className :: getPluginId ( ) == $ pluginId ) { $ plugin = new $ className ( $ this ) ; $ this -> plugins [ ] = $ plugin ; $ plugin -> init ( ) ; continue 2 ; } } $ this -> log ( "plugin ${pluginId} is not registered with the controller" ) ; } }
Invoked when config is ADDED or MODIFIED . Re - initializes plugins .
31,592
public function main ( ) { declare ( ticks = 1 ) ; pcntl_signal ( SIGINT , function ( ) { exit ( 0 ) ; } ) ; $ kubernetesClient = $ this -> getKubernetesClient ( ) ; $ storeEnabled = $ this -> getStoreEnabled ( ) ; if ( $ storeEnabled ) { $ this -> store = new Store ( $ this ) ; $ this -> store -> init ( ) ; } $ watches = new \ KubernetesClient \ WatchCollection ( ) ; $ configMapNamespace = $ this -> getConfigMapNamespace ( ) ; $ configMapName = $ this -> getConfigMapName ( ) ; $ storeNamespace = $ this -> getStoreNamespace ( ) ; $ storeName = $ this -> getStoreName ( ) ; $ watch = $ kubernetesClient -> createWatch ( "/api/v1/watch/namespaces/${configMapNamespace}/configmaps/${configMapName}" , [ ] , $ this -> getConfigMapWatchCallback ( ) ) ; $ watches -> addWatch ( $ watch ) ; while ( true ) { usleep ( 100 * 1000 ) ; $ watches -> start ( 1 ) ; if ( ! $ this -> getConfigLoaded ( ) ) { $ this -> log ( "waiting for ConfigMap ${configMapNamespace}/${configMapName} to be present and valid" ) ; sleep ( 5 ) ; continue ; } if ( $ storeEnabled ) { if ( ! $ this -> store -> initialized ( ) ) { $ this -> log ( "waiting for store ConfigMap ${storeNamespace}/${storeName} to be present and valid" ) ; $ this -> store -> init ( ) ; sleep ( 5 ) ; continue ; } } if ( $ storeEnabled ) { $ this -> store -> readWatches ( ) ; } foreach ( $ this -> plugins as $ plugin ) { $ plugin -> preReadWatches ( ) ; $ plugin -> readWatches ( ) ; $ plugin -> postReadWatches ( ) ; if ( $ plugin -> getActionRequired ( ) ) { if ( ! $ plugin -> getLastActionSuccess ( ) && ( ( time ( ) - $ this -> failedActionWaitTime ) <= $ plugin -> getLastActionAttemptTime ( ) ) ) { continue ; } $ settleTime = $ plugin -> getSettleTime ( ) ; $ actionRequiredTime = $ plugin -> getActionRequiredTime ( ) ; if ( $ settleTime > 0 && $ actionRequiredTime > 0 && ( ( time ( ) - $ actionRequiredTime ) <= $ settleTime ) ) { continue ; } $ throttleTime = $ plugin -> getThrottleTime ( ) ; $ lastActionAttemptTime = $ plugin -> getLastActionAttemptTime ( ) ; if ( $ throttleTime > 0 && $ lastActionAttemptTime > 0 && ( ( time ( ) - $ lastActionAttemptTime ) <= $ throttleTime ) ) { continue ; } $ plugin -> invokeAction ( ) ; } } if ( $ storeEnabled ) { $ this -> store -> readWatches ( ) ; } } }
Run loop for the controller
31,593
private function getConfigMapWatchCallback ( ) { return function ( $ event , $ watch ) { switch ( $ event [ 'type' ] ) { case 'ADDED' : case 'MODIFIED' : $ this -> state [ 'config' ] = yaml_parse ( $ event [ 'object' ] [ 'data' ] [ 'config' ] ) ; $ this -> onConfigLoaded ( ) ; break ; case 'DELETED' : $ this -> state [ 'deleted_config' ] = yaml_parse ( $ event [ 'object' ] [ 'data' ] [ 'config' ] ) ; $ this -> state [ 'config' ] = null ; $ this -> onConfigUnloaded ( ) ; break ; } } ; }
The callback for the controller ConfigMap watch
31,594
public function send ( Email $ email ) { if ( null === $ email -> getFrom ( ) ) { $ email -> setFrom ( $ this -> from ) ; } $ message = $ this -> mapper -> fromEmail ( $ email ) ; $ state = $ this -> mailer -> send ( $ message ) ; $ deliveryStatus = ( \ Swift_Events_SendEvent :: RESULT_SUCCESS === $ state ) ; $ email -> setSentState ( $ deliveryStatus ) -> setSentDate ( $ deliveryStatus ? new \ DateTime ( ) : null ) ; return $ email ; }
Sends the mail updating the entity status .
31,595
public function create ( $ chmod = 0755 ) { Argument :: i ( ) -> test ( 1 , 'int' ) ; if ( ! is_int ( $ chmod ) || $ chmod < 0 || $ chmod > 777 ) { Exception :: i ( self :: ERROR_CHMOD_IS_INVALID ) -> addVariable ( $ this -> data ) -> trigger ( ) ; } if ( ! is_dir ( $ this -> data ) ) { mkdir ( $ this -> data , $ chmod , true ) ; } return $ this ; }
Creates a folder given the path
31,596
public function getFiles ( $ regex = null , $ recursive = false ) { Argument :: i ( ) -> test ( 1 , 'string' , 'null' ) -> test ( 2 , 'bool' ) ; $ this -> absolute ( ) ; $ files = array ( ) ; if ( $ handle = opendir ( $ this -> data ) ) { while ( false !== ( $ file = readdir ( $ handle ) ) ) { if ( filetype ( $ this -> data . '/' . $ file ) == 'file' && ( ! $ regex || preg_match ( $ regex , $ file ) ) ) { $ files [ ] = File :: i ( $ this -> data . '/' . $ file ) ; } else if ( $ recursive && $ file != '.' && $ file != '..' && filetype ( $ this -> data . '/' . $ file ) == 'dir' ) { $ subfiles = self :: i ( $ this -> data . '/' . $ file ) ; $ files = array_merge ( $ files , $ subfiles -> getFiles ( $ regex , $ recursive ) ) ; } } closedir ( $ handle ) ; } return $ files ; }
Returns a list of files given the path and optionally the pattern
31,597
public function getFolders ( $ regex = null , $ recursive = false ) { Argument :: i ( ) -> test ( 1 , 'string' , 'null' ) -> test ( 2 , 'bool' ) ; $ this -> absolute ( ) ; $ folders = array ( ) ; if ( $ handle = opendir ( $ this -> data ) ) { while ( false !== ( $ folder = readdir ( $ handle ) ) ) { if ( $ folder != '.' && $ folder != '..' && filetype ( $ this -> data . '/' . $ folder ) == 'dir' && ( ! $ regex || preg_match ( $ regex , $ folder ) ) ) { $ folders [ ] = self :: i ( $ this -> data . '/' . $ folder ) ; if ( $ recursive ) { $ subfolders = self :: i ( $ this -> data . '/' . $ folder ) ; $ folders = array_merge ( $ folders , $ subfolders -> getFolders ( $ regex , $ recursive ) ) ; } } } closedir ( $ handle ) ; } return $ folders ; }
Returns a list of folders given the path and optionally the regular expression
31,598
public function isFolder ( $ path = null ) { Argument :: i ( ) -> test ( 1 , 'string' , 'null' ) ; if ( is_string ( $ path ) ) { return is_dir ( $ this -> data . '/' . $ path ) ; } return is_dir ( $ this -> data ) ; }
Checks to see if this path is a real file
31,599
public function removeFiles ( $ regex = null ) { Argument :: i ( ) -> test ( 1 , 'string' , 'null' ) ; $ files = $ this -> getFiles ( $ regex ) ; if ( empty ( $ files ) ) { return $ this ; } foreach ( $ files as $ file ) { $ file -> remove ( ) ; } return $ this ; }
Removes files given the path and optionally a regular expression