idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
26,200
public function map ( string $ requested , string $ replacement ) : void { $ this -> maps [ $ this -> normalize ( $ requested ) ] = $ this -> normalize ( $ replacement ) ; }
Map the requested name to the replacement name . When the requested name is retrieved the replacement name will be used to build the instance .
26,201
public function getDependenciesFor ( string $ name , int $ useStoredDependencies = self :: USE_STORED_DEPENDENCIES ) : array { $ name = $ this -> getDefinitiveName ( $ name ) ; try { $ reflection = new ReflectionClass ( $ name ) ; } catch ( Throwable $ e ) { throw new ContainerException ( sprintf ( 'Could not create instance for class `%s`.' , $ name ) ) ; } $ constructor = $ reflection -> getConstructor ( ) ; if ( ! $ constructor ) { return [ ] ; } $ parameters = $ constructor -> getParameters ( ) ; $ relationships = [ ] ; $ dependencies = [ ] ; foreach ( $ parameters as $ parameter ) { $ class = $ parameter -> getClass ( ) ; if ( $ class === null ) { if ( ! $ parameter -> isOptional ( ) ) { throw new ContainerException ( sprintf ( 'Cannot inject value for non-optional constructor parameter `$%s` without a default value.' , $ parameter -> name ) ) ; } $ dependencies [ ] = $ parameter -> getDefaultValue ( ) ; continue ; } $ dependencyName = $ this -> getDefinitiveName ( $ class -> name ) ; $ this -> storeRelationship ( $ name , $ dependencyName ) ; $ relationships [ ] = $ dependencyName ; if ( $ useStoredDependencies === self :: USE_NEW_DEPENDENCIES ) { $ dependencies [ ] = $ this -> build ( $ dependencyName ) ; } elseif ( $ useStoredDependencies === self :: USE_STORED_DEPENDENCIES ) { $ dependencies [ ] = $ this -> get ( $ dependencyName ) ; } else { throw new ContainerException ( sprintf ( 'Invalid dependency type value passed: `%d`.' , $ useStoredDependencies ) ) ; } } return $ dependencies ; }
Get the dependencies for an instance based on the constructor . Optionally use stored dependencies or always create new ones .
26,202
public function store ( $ instance , string $ name = null ) : void { if ( $ name === null ) { $ name = get_class ( $ instance ) ; } $ name = $ this -> getDefinitiveName ( $ name ) ; $ this -> instances [ $ name ] = $ instance ; }
Store the provided instance with the provided id or the class name of the object .
26,203
public function clear ( string $ name ) : void { $ name = $ this -> getDefinitiveName ( $ name ) ; if ( ! $ this -> has ( $ name ) ) { throw NotFoundException :: fromId ( $ name ) ; } unset ( $ this -> instances [ $ name ] ) ; $ this -> clearRelationship ( $ name ) ; }
Clear the requested instance .
26,204
public function clearExcept ( array $ keep ) : void { $ kept = [ ] ; foreach ( $ keep as $ name ) { $ name = $ this -> getDefinitiveName ( $ name ) ; if ( ! $ this -> has ( $ name ) ) { throw NotFoundException :: fromId ( $ name ) ; } $ kept [ $ name ] = $ this -> get ( $ name ) ; } $ this -> instances = $ kept ; }
Clear all instances except those provided .
26,205
protected function storeRelationship ( string $ class , string $ dependency ) : void { $ this -> relationships [ $ class ] [ $ dependency ] = true ; if ( isset ( $ this -> relationships [ $ class ] [ $ dependency ] ) && isset ( $ this -> relationships [ $ dependency ] [ $ class ] ) ) { throw new ContainerException ( sprintf ( 'Cyclical dependency found between `%s` and `%s`.' , $ class , $ dependency ) ) ; } }
Store the relationship between the two items .
26,206
protected function clearRelationship ( string $ name ) : void { unset ( $ this -> relationships [ $ name ] ) ; foreach ( $ this -> relationships as $ left => & $ objectNames ) { if ( isset ( $ objectNames [ $ name ] ) ) { unset ( $ objectNames [ $ name ] ) ; } } }
Clear the relationship for the provided id .
26,207
protected function defineClass ( $ fields ) { $ definition = $ this -> schema [ DocumentEntity :: SH_INSTANTIATION ] ; if ( is_string ( $ definition ) ) { return $ definition ; } if ( ! is_array ( $ fields ) ) { return $ this -> class ; } $ defined = $ this -> class ; foreach ( $ definition as $ field => $ child ) { if ( array_key_exists ( $ field , $ fields ) ) { $ defined = $ child ; break ; } } return $ defined ; }
Define document class using it s fieldset and definition .
26,208
public function isCachable ( string $ url , string $ httpMethod ) : bool { return $ httpMethod === ClientInterface :: HTTP_GET && $ this -> getCache ( ) !== null ; }
Determine whether cache should be attempted .
26,209
public static function getContrastYIQ ( $ hexColor ) : string { $ hexColor = str_replace ( '#' , '' , $ hexColor ) ; $ r = hexdec ( substr ( $ hexColor , 0 , 2 ) ) ; $ g = hexdec ( substr ( $ hexColor , 2 , 2 ) ) ; $ b = hexdec ( substr ( $ hexColor , 4 , 2 ) ) ; $ yiq = ( ( $ r * 299 ) + ( $ g * 587 ) + ( $ b * 114 ) ) / 1000 ; return ( $ yiq >= 128 ) ? 'black' : 'white' ; }
Determines if the contrasting color to be used based on a HEX color code
26,210
protected function setAuthors ( $ docBlock , $ authors ) { $ newAuthors = array_unique ( array_values ( $ authors ) ) ; $ lines = \ explode ( "\n" , $ docBlock ) ; $ lastAuthor = 0 ; $ indention = ' * @author ' ; $ cleaned = [ ] ; foreach ( $ lines as $ number => $ line ) { if ( \ strpos ( $ line , '@author' ) === false ) { continue ; } $ lastAuthor = $ number ; $ suffix = \ trim ( \ substr ( $ line , ( \ strpos ( $ line , '@author' ) + 7 ) ) ) ; $ indention = \ substr ( $ line , 0 , ( \ strlen ( $ line ) - \ strlen ( $ suffix ) ) ) ; $ index = $ this -> searchAuthor ( $ line , $ newAuthors ) ; if ( false === $ index ) { $ lines [ $ number ] = null ; $ cleaned [ ] = $ number ; } else { unset ( $ newAuthors [ $ index ] ) ; } } $ lines = $ this -> addNewAuthors ( $ lines , $ newAuthors , $ cleaned , $ lastAuthor , $ indention ) ; return \ implode ( "\n" , \ array_filter ( $ lines , function ( $ value ) { return null !== $ value ; } ) ) ; }
Set the author information in doc block .
26,211
protected function addNewAuthors ( array $ lines , array $ newAuthors , array $ emptyLines , $ lastAuthor , $ indention ) { if ( empty ( $ newAuthors ) ) { return $ lines ; } foreach ( $ emptyLines as $ number ) { if ( null === $ author = \ array_shift ( $ newAuthors ) ) { break ; } $ lines [ $ number ] = $ indention . $ author ; } if ( ( int ) $ lastAuthor === 0 ) { $ lastAuthor = ( \ count ( $ lines ) - 2 ) ; } if ( 0 === ( $ count = count ( $ newAuthors ) ) ) { return $ lines ; } $ lines = array_merge ( array_slice ( $ lines , 0 , ++ $ lastAuthor ) , array_fill ( 0 , $ count , null ) , array_slice ( $ lines , $ lastAuthor ) ) ; while ( $ author = \ array_shift ( $ newAuthors ) ) { $ lines [ $ lastAuthor ++ ] = $ indention . $ author ; } return $ lines ; }
Add new authors to a buffer .
26,212
private function searchAuthor ( $ line , $ authors ) { foreach ( $ authors as $ index => $ author ) { list ( $ name , $ email ) = \ explode ( ' <' , $ author ) ; $ name = \ trim ( $ name ) ; $ email = \ trim ( \ substr ( $ email , 0 , - 1 ) ) ; if ( ( \ strpos ( $ line , $ name ) !== false ) && ( \ strpos ( $ line , $ email ) !== false ) ) { unset ( $ authors [ $ index ] ) ; return $ index ; } } return false ; }
Search the author in line in the passed array and return the index of the match or false if none matches .
26,213
protected function getEngineOptions ( ) { $ config = ProjectX :: getProjectConfig ( ) ; $ engine = $ config -> getEngine ( ) ; $ options = $ config -> getOptions ( ) ; return isset ( $ options [ $ engine ] ) ? $ options [ $ engine ] : [ ] ; }
Get environment engine options .
26,214
protected function executeEngineCommand ( $ command , $ service = null , $ options = [ ] , $ quiet = false , $ localhost = false ) { if ( $ command instanceof CommandBuilder ) { $ command = $ command -> build ( ) ; } $ engine = $ this -> getEngineInstance ( ) ; if ( $ engine instanceof DockerEngineType && ! $ localhost ) { $ results = $ engine -> execRaw ( $ command , $ service , $ options , $ quiet ) ; } else { $ results = $ this -> _exec ( $ command ) ; } $ this -> validateTaskResult ( $ results ) ; return $ results ; }
Execute environment engine command .
26,215
protected function createRelationFromList ( $ object , $ relation , $ list , $ class , $ column , $ create = false ) { $ object -> $ relation ( ) -> removeAll ( ) ; foreach ( $ list as $ name ) { $ name = trim ( $ name ) ; if ( ! empty ( $ name ) ) { $ obj = $ class :: get ( ) -> find ( $ column , $ name ) ; if ( empty ( $ obj ) && $ create ) { $ obj = $ class :: create ( ) ; $ obj -> $ column = $ name ; $ obj -> write ( ) ; } if ( ! empty ( $ obj ) ) { $ object -> $ relation ( ) -> add ( $ obj ) ; } } } }
Generate the selected relation from the provided array of values
26,216
public function makeDefinition ( ) { $ children = $ this -> findChildren ( true , true ) ; if ( empty ( $ children ) ) { return $ this -> schema -> getClass ( ) ; } uasort ( $ children , [ $ this , 'sortChildren' ] ) ; $ commonFields = $ this -> schema -> getReflection ( ) -> getSchema ( ) ; $ definition = [ ] ; foreach ( $ children as $ schema ) { $ fields = $ schema -> getReflection ( ) -> getSchema ( ) ; if ( empty ( $ fields ) ) { throw new DefinitionException ( "Child document '{$schema->getClass()}' of '{$this->schema->getClass()}' does not have any fields" ) ; } $ uniqueField = null ; if ( empty ( $ commonFields ) ) { $ commonFields = $ fields ; $ uniqueField = key ( $ fields ) ; } else { foreach ( $ fields as $ field => $ type ) { if ( ! isset ( $ commonFields [ $ field ] ) ) { if ( empty ( $ uniqueField ) ) { $ uniqueField = $ field ; } $ commonFields [ $ field ] = true ; } } } if ( empty ( $ uniqueField ) ) { throw new DefinitionException ( "Child document '{$schema->getClass()}' of '{$this->schema->getClass()}' does not have any unique field" ) ; } $ definition [ $ uniqueField ] = $ schema -> getClass ( ) ; } return $ definition ; }
Compile information required to resolve class instance using given set of fields . Fields based definition will analyze unique fields in every child model to create association between model class and required set of fields . Only document from same collection will be involved in definition creation . Definition built only for child of first order .
26,217
public function findChildren ( bool $ sameCollection = false , bool $ directChildren = false ) { $ result = [ ] ; foreach ( $ this -> schemas as $ schema ) { if ( ! $ schema instanceof DocumentSchema ) { continue ; } $ reflection = $ schema -> getReflection ( ) ; if ( $ reflection -> isSubclassOf ( $ this -> schema -> getClass ( ) ) ) { if ( $ sameCollection && ! $ this -> compareCollection ( $ schema ) ) { continue ; } if ( $ directChildren && $ reflection -> getParentClass ( ) -> getName ( ) != $ this -> schema -> getClass ( ) ) { continue ; } $ result [ ] = $ schema ; } } return $ result ; }
Get Document child classes .
26,218
public function findPrimary ( bool $ sameCollection = true ) : string { $ primary = $ this -> schema -> getClass ( ) ; foreach ( $ this -> schemas as $ schema ) { if ( ! $ schema instanceof DocumentSchema ) { continue ; } if ( $ this -> schema -> getReflection ( ) -> isSubclassOf ( $ schema -> getClass ( ) ) ) { if ( $ sameCollection && ! $ this -> compareCollection ( $ schema ) ) { continue ; } $ primary = $ schema -> getClass ( ) ; } } return $ primary ; }
Find primary class needed to represent model and model childs .
26,219
protected function compareCollection ( DocumentSchema $ document ) { if ( $ document -> getDatabase ( ) != $ this -> schema -> getDatabase ( ) ) { return false ; } return $ document -> getCollection ( ) == $ this -> schema -> getCollection ( ) ; }
Check if both document schemas belongs to same collection . Documents without declared collection must be counted as documents from same collection .
26,220
private function sortChildren ( DocumentSchema $ childA , DocumentSchema $ childB ) { return count ( $ childA -> getReflection ( ) -> getSchema ( ) ) > count ( $ childB -> getReflection ( ) -> getSchema ( ) ) ; }
Sort child documents in order or declared fields .
26,221
public function authorizeUrl ( ) { $ request_token = $ this -> oauth ( 'oauth/request_token' , array ( 'oauth_callback' => $ this -> callbackUrl ) ) ; if ( $ request_token ) { Session :: put ( 'oauth_token' , $ request_token [ 'oauth_token' ] ) ; Session :: put ( 'oauth_token_secret' , $ request_token [ 'oauth_token_secret' ] ) ; $ url = $ this -> url ( 'oauth/authorize' , array ( 'oauth_token' => $ request_token [ 'oauth_token' ] ) ) ; return $ url ; } throw new TwitterOAuthException ( $ request_token ) ; }
Generate request_token and build authorize URL .
26,222
private function encodeAppAuthorization ( $ consumer ) { $ key = $ consumer -> key ; $ secret = $ consumer -> secret ; return base64_encode ( $ key . ':' . $ secret ) ; }
Encode application authorization header with base64 .
26,223
public function dump ( Graph $ graph , $ file , $ format = PlantUML :: FORMAT_TXT ) { $ format = $ format ? : self :: FORMAT_TXT ; try { $ content = implode ( PHP_EOL , $ graph -> toArray ( ) ) . PHP_EOL ; if ( self :: FORMAT_UML === $ format ) { $ url = sprintf ( 'http://www.plantuml.com/plantuml/uml/%s' , $ this -> urlEncode ( $ content ) ) ; if ( false !== fwrite ( $ file , $ url . PHP_EOL ) ) { return fclose ( $ file ) ; } return false ; } if ( self :: FORMAT_TXT === $ format ) { if ( false !== fwrite ( $ file , $ content ) ) { return fclose ( $ file ) ; } return false ; } if ( in_array ( $ format , [ self :: FORMAT_PNG , self :: FORMAT_SVG , self :: FORMAT_ATXT , self :: FORMAT_UTXT ] , true ) ) { if ( null === $ this -> java ) { return false ; } $ prefix = sys_get_temp_dir ( ) . '/' . uniqid ( ) ; $ txtPath = $ prefix . '.txt' ; $ pngPath = $ prefix . '.' . $ format ; $ clean = function ( ) use ( $ txtPath , $ pngPath ) { $ this -> fs -> remove ( [ $ txtPath , $ pngPath ] ) ; } ; $ this -> fs -> dumpFile ( $ txtPath , $ content ) ; $ builder = new ProcessBuilder ( ) ; $ builder -> add ( $ this -> java ) -> add ( '-jar' ) -> add ( __DIR__ . '/../Resources/lib/plantuml.1.2017.19.jar' ) -> add ( $ txtPath ) ; if ( self :: FORMAT_SVG === $ format ) { $ builder -> add ( '-tsvg' ) ; } if ( self :: FORMAT_ATXT === $ format ) { $ builder -> add ( '-txt' ) ; } if ( self :: FORMAT_UTXT === $ format ) { $ builder -> add ( '-utxt' ) ; } $ plantUml = $ builder -> getProcess ( ) ; $ plantUml -> run ( ) ; if ( $ plantUml -> isSuccessful ( ) ) { if ( false !== $ png = fopen ( $ pngPath , 'r' ) ) { if ( 0 !== stream_copy_to_stream ( $ png , $ file ) ) { $ clean ( ) ; return fclose ( $ file ) ; } } } else { $ this -> logger -> error ( $ plantUml -> getErrorOutput ( ) ) ; } $ clean ( ) ; return false ; } return false ; } catch ( \ Exception $ e ) { return false ; } }
Dump array data
26,224
private function urlAppend3bytes ( $ b1 , $ b2 , $ b3 ) { $ c1 = $ b1 >> 2 ; $ c2 = ( ( $ b1 & 0x3 ) << 4 ) | ( $ b2 >> 4 ) ; $ c3 = ( ( $ b2 & 0xF ) << 2 ) | ( $ b3 >> 6 ) ; $ c4 = $ b3 & 0x3F ; return implode ( [ $ this -> urlEncode6bit ( $ c1 & 0x3F ) , $ this -> urlEncode6bit ( $ c2 & 0x3F ) , $ this -> urlEncode6bit ( $ c3 & 0x3F ) , $ this -> urlEncode6bit ( $ c4 & 0x3F ) , ] ) ; }
Url append 3bytes
26,225
private function urlEncode6bit ( $ b ) { if ( $ b < 10 ) { return chr ( 48 + $ b ) ; } $ b -= 10 ; if ( $ b < 26 ) { return chr ( 65 + $ b ) ; } $ b -= 26 ; if ( $ b < 26 ) { return chr ( 97 + $ b ) ; } $ b -= 26 ; if ( $ b == 0 ) { return '-' ; } if ( $ b == 1 ) { return '_' ; } return '?' ; }
Url encode 6bit
26,226
public function comment ( string $ comment = '' ) : Writer { $ comment = trim ( $ comment ) ; if ( ! empty ( $ comment ) ) { $ comment = ' ' . $ comment ; } return $ this -> line ( trim ( '#' . $ comment ) ) ; }
Add a comment to the output buffer .
26,227
public function spacers ( int $ count = 1 ) : Writer { for ( $ x = 0 ; $ x < $ count ; $ x ++ ) { $ this -> spacer ( ) ; } return $ this ; }
Add multiple spacers to the output buffer .
26,228
public function lines ( array $ lines ) : Writer { foreach ( $ lines as $ line ) { $ this -> line ( $ line ) ; } return $ this ; }
Add multiple lines .
26,229
public function getCompositions ( SchemaBuilder $ builder ) : array { $ result = [ ] ; foreach ( $ this -> reflection -> getSchema ( ) as $ field => $ type ) { if ( is_string ( $ type ) && $ builder -> hasSchema ( $ type ) ) { $ result [ $ field ] = new CompositionDefinition ( DocumentEntity :: ONE , $ type ) ; } if ( is_array ( $ type ) && isset ( $ type [ 0 ] ) && $ builder -> hasSchema ( $ type [ 0 ] ) ) { $ result [ $ field ] = new CompositionDefinition ( DocumentEntity :: MANY , $ type [ 0 ] ) ; } } return $ result ; }
Find all composition definitions attention method require builder instance in order to properly check that embedded class exists .
26,230
protected function packDefaults ( SchemaBuilder $ builder , array $ overwriteDefaults = [ ] ) : array { $ compositions = $ this -> getCompositions ( $ builder ) ; $ userDefined = $ overwriteDefaults + $ this -> getDefaults ( ) ; $ mutators = $ this -> getMutators ( ) ; $ defaults = [ ] ; foreach ( $ this -> getFields ( ) as $ field => $ type ) { $ default = is_array ( $ type ) ? [ ] : null ; if ( array_key_exists ( $ field , $ userDefined ) ) { $ default = $ userDefined [ $ field ] ; } $ defaults [ $ field ] = $ this -> mutateValue ( $ builder , $ compositions , $ userDefined , $ mutators , $ field , $ default ) ; } return $ defaults ; }
Entity default values .
26,231
public function packCompositions ( SchemaBuilder $ builder ) : array { $ result = [ ] ; foreach ( $ this -> getCompositions ( $ builder ) as $ name => $ composition ) { $ result [ $ name ] = $ composition -> packSchema ( ) ; } return $ result ; }
Pack compositions into simple array definition .
26,232
protected function packAggregations ( SchemaBuilder $ builder ) : array { $ result = [ ] ; foreach ( $ this -> getAggregations ( ) as $ name => $ aggregation ) { if ( ! $ builder -> hasSchema ( $ aggregation -> getClass ( ) ) ) { throw new SchemaException ( "Aggregation {$this->getClass()}.'{$name}' refers to undefined document '{$aggregation->getClass()}'" ) ; } if ( $ builder -> getSchema ( $ aggregation -> getClass ( ) ) -> isEmbedded ( ) ) { throw new SchemaException ( "Aggregation {$this->getClass()}.'{$name}' refers to non storable document '{$aggregation->getClass()}'" ) ; } $ result [ $ name ] = $ aggregation -> packSchema ( ) ; } return $ result ; }
Pack aggregations into simple array definition .
26,233
protected function mutateValue ( SchemaBuilder $ builder , array $ compositions , array $ userDefined , array $ mutators , string $ field , $ default ) { if ( isset ( $ mutators [ DocumentEntity :: MUTATOR_SETTER ] [ $ field ] ) ) { try { $ setter = $ mutators [ DocumentEntity :: MUTATOR_SETTER ] [ $ field ] ; $ default = call_user_func ( $ setter , $ default ) ; return $ default ; } catch ( \ Exception $ exception ) { } } if ( isset ( $ mutators [ DocumentEntity :: MUTATOR_ACCESSOR ] [ $ field ] ) ) { $ default = $ this -> accessorDefault ( $ default , $ mutators [ DocumentEntity :: MUTATOR_ACCESSOR ] [ $ field ] ) ; } if ( isset ( $ compositions [ $ field ] ) ) { if ( is_null ( $ default ) && ! array_key_exists ( $ field , $ userDefined ) ) { $ default = [ ] ; } $ default = $ this -> compositionDefault ( $ default , $ compositions [ $ field ] , $ builder ) ; return $ default ; } return $ default ; }
Ensure default value using associated mutators or pass thought composition .
26,234
protected function compositionDefault ( $ default , CompositionDefinition $ composition , SchemaBuilder $ builder ) { if ( ! is_array ( $ default ) ) { if ( $ composition -> getType ( ) == DocumentEntity :: MANY ) { return [ ] ; } return null ; } if ( $ composition -> getType ( ) == DocumentEntity :: MANY ) { return $ default ; } $ embedded = $ builder -> getSchema ( $ composition -> getClass ( ) ) ; if ( ! $ embedded instanceof self ) { return $ default ; } if ( $ embedded -> getClass ( ) == $ this -> getClass ( ) ) { if ( ! empty ( $ default ) ) { throw new SchemaException ( "Possible recursion issue in '{$this->getClass()}', model refers to itself (has default value)" ) ; } return null ; } return $ embedded -> packDefaults ( $ builder , $ default ) ; }
Ensure default value for composite field
26,235
public function hasMany ( array $ params ) { foreach ( $ params as $ param ) { if ( ! $ this -> has ( $ param ) ) { return false ; } } return true ; }
Checks whether several parameters are defined at once
26,236
public function setMany ( array $ params ) { foreach ( $ params as $ key => $ value ) { $ this -> set ( $ key , $ value ) ; } return $ this ; }
Append many parameters
26,237
public function fieldLabels ( $ includerelations = true ) { $ labels = parent :: fieldLabels ( $ includerelations ) ; $ tagLabels = array ( 'Title' => _t ( 'Tag.TITLE' , 'Title' ) , 'Description' => _t ( 'Tag.DESCRIPTION' , 'Description' ) , 'Impression' => _t ( 'Tag.IMPRESSION' , 'Impression image' ) , ) ; return array_merge ( $ tagLabels , $ labels ) ; }
Setup the fieldlabels correctly .
26,238
protected function calculateUpdatedAuthors ( $ path , $ authors ) { return \ array_merge ( \ array_intersect_key ( $ this -> extractAuthorsFor ( $ path ) , $ authors ) , $ authors ) ; }
Calculate the updated author map .
26,239
public function calculate ( int $ callsMade , int $ callsLimit ) { $ callPercentage = floatval ( $ callsMade / $ callsLimit ) ; $ limitPercentage = floatval ( ( $ callsLimit - $ this -> processes - $ this -> buffer ) / $ callsLimit ) ; return $ callPercentage > $ limitPercentage ? ( $ this -> processes * $ this -> cycle ) : $ this -> cycle ; }
Calculate the time in seconds between each request .
26,240
public function getUserParams ( Mage_Api2_Model_Request $ request ) { $ userParamsObj = new stdClass ( ) ; $ userParamsObj -> type = null ; $ userParamsObj -> id = null ; if ( $ this -> isApplicableToRequest ( $ request ) ) { $ userParamsObj -> id = $ this -> getHelper ( ) -> getCustomerSession ( ) -> getCustomerId ( ) ; $ userParamsObj -> type = self :: USER_TYPE_CUSTOMER ; } return $ userParamsObj ; }
Process request and figure out an API user type and its identifier
26,241
public function isApplicableToRequest ( Mage_Api2_Model_Request $ request ) { if ( Mage :: app ( ) -> getStore ( ) -> isAdmin ( ) ) { return false ; } $ this -> getHelper ( ) -> getCoreSession ( ) ; return $ this -> getHelper ( ) -> getCustomerSession ( ) -> isLoggedIn ( ) ; }
Check if request contains authentication info for adapter
26,242
private function getResultSetWithoutSlaveColumnId ( array $ rows , $ slaveColumnId ) { $ result = array ( ) ; foreach ( $ rows as $ row ) { if ( isset ( $ row [ $ slaveColumnId ] ) ) { unset ( $ row [ $ slaveColumnId ] ) ; } $ result [ ] = $ row ; } return $ result ; }
Returns a result - set excluding slave column id name
26,243
public static function build ( $ file , $ autoCreate = true ) { $ storage = new CacheFile ( new NativeSerializer ( ) , $ file , $ autoCreate ) ; $ cache = new CacheEngine ( new ArrayCache ( ) , new ArraySignature ( ) , $ storage ) ; $ cache -> initialize ( ) ; return $ cache ; }
Builds cache instance
26,244
public function NewsArchive ( $ limit = 5 , $ random = null , $ related = null ) { if ( $ limit === 0 ) { $ limit = null ; } $ params = $ this -> owner -> getURLParams ( ) ; $ otherNews = null ; if ( $ related ) { $ otherNews = $ this -> owner -> getNews ( ) ; } if ( ( $ otherNews && $ otherNews -> Tags ( ) -> count ( ) ) || ! $ related ) { return $ this -> getArchiveItems ( $ otherNews , $ limit , $ random , $ related , $ params ) ; } }
Get all or a limited set of items .
26,245
public function NewsArchiveByHolderID ( $ holderID = null , $ limit = 5 ) { $ filter = array ( 'Live' => 1 , 'NewsHolderPageID' => $ holderID , 'PublishFrom:LessThan' => SS_Datetime :: now ( ) -> Rfc2822 ( ) , ) ; if ( $ limit === 0 ) { $ limit = null ; } if ( class_exists ( 'Translatable' ) ) { $ filter [ 'Locale' ] = Translatable :: get_current_locale ( ) ; } $ news = News :: get ( ) -> filter ( $ filter ) -> limit ( $ limit ) ; if ( $ news -> count ( ) === 0 ) { return null ; } return $ news ; }
Get all the items from a single newsholderPage .
26,246
public static function getUriFromGlobals ( array $ serverParams ) : UriInterface { $ uri = new Uri ( '' ) ; $ uri = $ uri -> withScheme ( isset ( $ serverParams [ 'HTTPS' ] ) && $ serverParams [ 'HTTPS' ] !== 'off' ? 'https' : 'http' ) ; $ hasPort = false ; if ( isset ( $ serverParams [ 'HTTP_HOST' ] ) ) { $ hostHeaderParts = explode ( ':' , $ serverParams [ 'HTTP_HOST' ] , 2 ) ; $ uri = $ uri -> withHost ( $ hostHeaderParts [ 0 ] ) ; if ( count ( $ hostHeaderParts ) > 1 ) { $ hasPort = true ; $ uri = $ uri -> withPort ( ( int ) $ hostHeaderParts [ 1 ] ) ; } } elseif ( isset ( $ serverParams [ 'SERVER_NAME' ] ) ) { $ uri = $ uri -> withHost ( $ serverParams [ 'SERVER_NAME' ] ) ; } elseif ( isset ( $ serverParams [ 'SERVER_ADDR' ] ) ) { $ uri = $ uri -> withHost ( $ serverParams [ 'SERVER_ADDR' ] ) ; } if ( ! $ hasPort && isset ( $ serverParams [ 'SERVER_PORT' ] ) ) { $ uri = $ uri -> withPort ( $ serverParams [ 'SERVER_PORT' ] ) ; } $ hasQuery = false ; if ( isset ( $ serverParams [ 'REQUEST_URI' ] ) ) { $ requestUriParts = explode ( '?' , $ serverParams [ 'REQUEST_URI' ] , 2 ) ; $ uri = $ uri -> withPath ( $ requestUriParts [ 0 ] ) ; if ( count ( $ requestUriParts ) > 1 ) { $ hasQuery = true ; $ uri = $ uri -> withQuery ( $ requestUriParts [ 1 ] ) ; } } if ( ! $ hasQuery && isset ( $ serverParams [ 'QUERY_STRING' ] ) ) { $ uri = $ uri -> withQuery ( $ serverParams [ 'QUERY_STRING' ] ) ; } return $ uri ; }
Get a Uri populated with values from server params .
26,247
public function updateAccountMenu ( $ menu ) { $ curr_action = $ this -> owner -> request -> param ( "Action" ) ; $ menu -> add ( new ArrayData ( array ( "ID" => 11 , "Title" => _t ( 'Checkout.Addresses' , 'Addresses' ) , "Link" => $ this -> owner -> Link ( "addresses" ) , "LinkingMode" => ( $ curr_action == "addresses" ) ? "current" : "link" ) ) ) ; }
Add links to account menu
26,248
public function updateEditAccountForm ( $ form ) { $ company_field = TextField :: create ( "Company" , _t ( 'CheckoutUsers.Company' , "Company" ) ) ; $ company_field -> setRightTitle ( _t ( "Checkout.Optional" , "Optional" ) ) ; $ form -> Fields ( ) -> insertBefore ( $ company_field , "FirstName" ) ; $ phone_field = TextField :: create ( "PhoneNumber" , _t ( "CheckoutUsers.PhoneNumber" , "Phone Number" ) ) ; $ phone_field -> setRightTitle ( _t ( "Checkout.Optional" , "Optional" ) ) ; $ form -> Fields ( ) -> add ( $ phone_field ) ; }
Add fields used by this module to the profile editing form
26,249
protected function loadFile ( $ path ) { $ composerJson = $ this -> fileData ( $ path ) ; return ( null === $ composerJson ) ? null : ( array ) \ json_decode ( $ composerJson , true ) ; }
Read the . json file and return it as array .
26,250
function generateNextTemp ( \ Doctrine \ ORM \ QueryBuilder $ qb , $ field ) { $ temporaryMask = $ this -> getTemporaryMask ( ) . '-{000}' ; return $ this -> generate ( $ qb , $ temporaryMask , $ field , self :: MODE_NEXT ) ; }
Generates the last sequence temporaly according to the parameters
26,251
public function getCodeAsString ( ) { switch ( $ this -> getCode ( ) ) { case self :: BURIED : return 'Buried' ; break ; case self :: NOT_FOUND : return 'Not Found' ; break ; case self :: EXPECTED_CRLF : return 'Expected CRLF' ; break ; case self :: JOB_TOO_BIG : return 'Job Too Big' ; break ; case self :: DEADLINE_SOON : return 'Deadline Soon' ; break ; case self :: TIMED_OUT : return 'Timed Out' ; break ; case self :: TUBE_NAME_TOO_LONG : return 'Tube Name Too Long' ; break ; case self :: NOT_IGNORED : return 'Not Ignored' ; break ; case self :: OUT_OF_MEMORY : return 'Out of Memory' ; break ; case self :: INTERNAL_ERROR : return 'Internal Error' ; break ; case self :: BAD_FORMAT : return 'Bad Format' ; break ; case self :: UNKNOWN_COMMAND : return 'Unknown Command' ; break ; case self :: SERVER_OFFLINE : return 'Server Offline' ; break ; case self :: SERVER_READ : return 'Server Read Error' ; break ; case self :: SERVER_WRITE : return 'Server Write Error' ; break ; default : return 'Unknown' ; break ; } }
Get a string representation of a given code
26,252
public static function factory ( array $ source , array $ definitions , $ translator ) { return new self ( $ source , $ definitions , new DefinitionParser ( new ConstraintFactory ( ) ) , $ translator ) ; }
Builds an instance
26,253
public function clear ( ) { $ this -> statusCode = self :: HTTP_OK ; $ this -> headers = [ ] ; $ this -> cookies = [ ] ; $ this -> content = null ; $ this -> sent = false ; }
Clears the response
26,254
private function sendHeaders ( ) { if ( ! headers_sent ( ) ) { http_response_code ( $ this -> statusCode ) ; foreach ( $ this -> headers as $ header ) { header ( $ header ) ; } foreach ( $ this -> cookies as $ cookie ) { call_user_func_array ( "setcookie" , $ cookie ) ; } } }
Sends the response headers
26,255
private function sendConfig ( ) { if ( $ this -> content !== null ) { if ( ( $ this -> content instanceof stdClass ) || is_array ( $ this -> content ) ) { $ content = ob_get_contents ( ) ; if ( empty ( $ content ) ) { $ this -> contentType ( "application/json" ) ; $ this -> content = json_encode ( $ this -> content ) ; } } } }
Configures the response before sending
26,256
private function sendContent ( ) { if ( $ this -> content !== null ) { if ( $ this -> content instanceof View ) { $ this -> content -> render ( ) ; } else if ( ( $ this -> content instanceof stdClass ) || is_array ( $ this -> content ) ) { echo "<pre>" ; print_r ( $ this -> content ) ; echo "</pre>" ; } else { echo $ this -> content ; } } }
Sends the content of the response
26,257
public function formatExceptionData ( GeneratedError $ e ) { $ filePath = $ e -> getFile ( ) ; if ( $ filePath && file_exists ( $ filePath ) ) { $ lines = file ( $ filePath ) ; $ start = $ e -> getLine ( ) - 4 ; $ lines = array_slice ( $ lines , $ start < 0 ? 0 : $ start , 7 ) ; } else { $ lines = array ( "Cannot open the file ($filePath) in which the exception occurred " ) ; } return array ( 'type' => '' , 'message' => $ e -> getMessage ( ) , 'code' => $ e -> getCode ( ) , 'file' => $ filePath , 'line' => $ e -> getLine ( ) , 'surrounding_lines' => $ lines ) ; }
Returns exception data as an array
26,258
public function release ( $ delay = 10 , $ priority = 5 ) { return $ this -> getConnection ( ) -> release ( $ this -> getId ( ) , $ priority , $ delay ) ; }
Release the job
26,259
private function handle ( $ method , array $ arguments , $ default ) { $ property = substr ( $ method , 3 ) ; $ property = TextUtils :: snakeCase ( $ property ) ; $ start = substr ( $ method , 0 , 3 ) ; if ( $ start == 'get' ) { if ( $ property === false ) { throw new LogicException ( 'Attempted to call a getter on undefined property' ) ; } if ( $ this -> has ( $ property ) ) { return $ this -> container [ $ property ] ; } else { return $ default ; } } else if ( $ start == 'set' ) { if ( $ this -> once === true && $ this -> has ( $ property ) ) { throw new RuntimeException ( sprintf ( 'You can write to "%s" only once' , $ property ) ) ; } if ( array_key_exists ( 0 , $ arguments ) ) { $ value = $ arguments [ 0 ] ; } else { throw new UnderflowException ( sprintf ( 'The virtual setter for "%s" expects at least one argument, which would be a value. None supplied.' , $ property ) ) ; } if ( isset ( $ arguments [ 1 ] ) ) { $ value = Filter :: sanitize ( $ value , $ arguments [ 1 ] ) ; } $ this -> container [ $ property ] = $ value ; return $ this ; } else { if ( $ this -> strict == true ) { throw new RuntimeException ( sprintf ( 'Virtual method name must start either from "get" or "set". You provided "%s"' , $ method ) ) ; } } }
Handles the Data Value object logic
26,260
private function initHandler ( SaveHandlerInterface $ handler ) { return session_set_save_handler ( array ( $ handler , 'open' ) , array ( $ handler , 'close' ) , array ( $ handler , 'read' ) , array ( $ handler , 'write' ) , array ( $ handler , 'destroy' ) , array ( $ handler , 'gc' ) ) ; }
Initializes the session storage adapter
26,261
public function start ( array $ options = array ( ) ) { if ( $ this -> isStarted ( ) === false ) { if ( ! empty ( $ options ) ) { $ this -> setCookieParams ( $ options ) ; } if ( ! session_start ( ) ) { return false ; } } $ this -> session = & $ _SESSION ; $ this -> sessionValidator -> write ( $ this ) ; return true ; }
Starts a new session or continues existing one
26,262
public function setMany ( array $ collection ) { foreach ( $ collection as $ key => $ value ) { $ this -> set ( $ key , $ value ) ; } return $ this ; }
Set many keys at once
26,263
public function hasMany ( array $ keys ) { foreach ( $ keys as $ key ) { if ( ! $ this -> has ( $ key ) ) { return false ; } } return true ; }
Determines whether all keys present in the session storage
26,264
public function get ( $ key , $ default = false ) { if ( $ this -> has ( $ key ) !== false ) { return $ this -> session [ $ key ] ; } else { return $ default ; } }
Reads data from a session
26,265
public function remove ( $ key ) { if ( $ this -> has ( $ key ) ) { unset ( $ this -> session [ $ key ] ) ; return true ; } else { return false ; } }
Removes a key from the storage
26,266
public function setCookieParams ( array $ params ) { $ defaults = $ this -> getCookieParams ( ) ; $ params = array_merge ( $ defaults , $ params ) ; return session_set_cookie_params ( intval ( $ params [ 'lifetime' ] ) , $ params [ 'path' ] , $ params [ 'domain' ] , ( bool ) $ params [ 'secure' ] , ( bool ) $ params [ 'httponly' ] ) ; }
Returns cookie parameters for the session
26,267
public function destroy ( ) { if ( $ this -> cookieBag -> has ( $ this -> getName ( ) ) ) { $ this -> cookieBag -> remove ( $ this -> getName ( ) ) ; } return session_destroy ( ) ; }
Destroys the session
26,268
public function getUserBag ( ) { $ userBag = new UserBag ( ) ; $ userBag -> setLogin ( $ this -> cookieBag -> get ( self :: CLIENT_LOGIN_KEY ) ) -> setPasswordHash ( $ this -> cookieBag -> get ( self :: CLIENT_LOGIN_PASSWORD_HASH_KEY ) ) ; return $ userBag ; }
Returns user bag
26,269
public function isStored ( ) { foreach ( $ this -> getKeys ( ) as $ key ) { if ( ! $ this -> cookieBag -> has ( $ key ) ) { return false ; } } if ( ! $ this -> isValidSignature ( $ this -> cookieBag -> get ( self :: CLIENT_LOGIN_KEY ) , $ this -> cookieBag -> get ( self :: CLIENT_LOGIN_PASSWORD_HASH_KEY ) , $ this -> cookieBag -> get ( self :: CLIENT_TOKEN_KEY ) ) ) { return false ; } return true ; }
Checks whether data is stored
26,270
public function clear ( ) { $ keys = $ this -> getKeys ( ) ; foreach ( $ keys as $ key ) { $ this -> cookieBag -> remove ( $ key ) ; } return true ; }
Clears all related data from cookies
26,271
public function store ( $ login , $ passwordHash ) { $ data = array ( self :: CLIENT_LOGIN_KEY => $ login , self :: CLIENT_LOGIN_PASSWORD_HASH_KEY => $ passwordHash , self :: CLIENT_TOKEN_KEY => $ this -> makeToken ( $ login , $ passwordHash ) ) ; foreach ( $ data as $ key => $ value ) { $ this -> cookieBag -> set ( $ key , $ value , self :: CLIENT_LIFETIME ) ; } }
Stores auth data on client machine
26,272
protected function parseModes ( ) { foreach ( $ this -> modeDirs as $ dir ) { $ absDir = $ this -> fileLocator -> locate ( $ dir ) ; $ finder = Finder :: create ( ) -> files ( ) -> in ( $ absDir ) -> notName ( "*test.js" ) -> name ( '*.js' ) ; foreach ( $ finder as $ file ) { $ this -> addModesFromFile ( $ dir , $ file ) ; } } if ( $ this -> env == 'prod' ) { $ this -> cacheDriver -> save ( static :: CACHE_MODES_NAME , $ this -> getModes ( ) ) ; } }
Parse editor mode from dir
26,273
protected function addModesFromFile ( $ dir , $ file ) { $ dir = $ this -> parseDir ( $ dir ) ; $ jsContent = $ file -> getContents ( ) ; preg_match_all ( '#defineMIME\(\s*(\'|")([^\'"]+)(\'|")#' , $ jsContent , $ modes ) ; if ( count ( $ modes [ 2 ] ) ) { foreach ( $ modes [ 2 ] as $ mode ) { $ this -> addMode ( $ mode , $ dir . "/" . $ file -> getRelativePathname ( ) ) ; } } $ this -> addMode ( $ file -> getRelativePath ( ) , $ dir . "/" . $ file -> getRelativePathname ( ) ) ; if ( $ this -> env == 'prod' ) { $ this -> cacheDriver -> save ( static :: CACHE_MODES_NAME , $ this -> getThemes ( ) ) ; } }
Parse editor modes from dir
26,274
protected function parseThemes ( ) { foreach ( $ this -> themesDirs as $ dir ) { $ absDir = $ this -> fileLocator -> locate ( $ dir ) ; $ finder = Finder :: create ( ) -> files ( ) -> in ( $ absDir ) -> name ( '*.css' ) ; foreach ( $ finder as $ file ) { $ this -> addTheme ( $ file -> getBasename ( '.css' ) , $ file -> getPathname ( ) ) ; } } if ( $ this -> env == 'prod' ) { $ this -> cacheDriver -> save ( static :: CACHE_THEMES_NAME , $ this -> getThemes ( ) ) ; } }
Parse editor themes from dir
26,275
public static function baseConvert ( $ number , $ fromBase , $ toBase , $ precision = - 1 ) { $ converter = new self ( $ fromBase , $ toBase ) ; $ converter -> setPrecision ( $ precision ) ; return $ converter -> convert ( $ number ) ; }
Converts the provided number from base to another .
26,276
public function convert ( $ number ) { $ integer = ( string ) $ number ; $ fractions = null ; $ sign = '' ; if ( in_array ( substr ( $ integer , 0 , 1 ) , [ '+' , '-' ] , true ) ) { $ sign = $ integer [ 0 ] ; $ integer = substr ( $ integer , 1 ) ; } if ( ( $ pos = strpos ( $ integer , '.' ) ) !== false ) { $ fractions = substr ( $ integer , $ pos + 1 ) ; $ integer = substr ( $ integer , 0 , $ pos ) ; } return $ this -> convertNumber ( $ sign , $ integer , $ fractions ) ; }
Converts the number provided as a string from source base to target base .
26,277
private function convertNumber ( $ sign , $ integer , $ fractions ) { try { $ result = implode ( '' , $ this -> convertInteger ( $ this -> source -> splitString ( $ integer ) ) ) ; if ( $ fractions !== null ) { $ result .= '.' . implode ( '' , $ this -> convertFractions ( $ this -> source -> splitString ( $ fractions ) ) ) ; } } catch ( DigitList \ InvalidDigitException $ ex ) { return false ; } return $ sign . $ result ; }
Converts the different parts of the number and handles invalid digits .
26,278
protected function populateCommonDocs ( string $ padding , string $ commondocs ) : string { $ output = '' ; if ( is_dir ( $ commondocs ) ) { $ h = opendir ( $ commondocs ) ; while ( $ dir = readdir ( $ h ) ) { $ folder = $ commondocs . DIRECTORY_SEPARATOR . $ dir ; if ( $ dir !== '.' && $ dir !== '..' && is_dir ( $ folder ) ) { $ output .= "\n" . $ padding . "Alias /$dir \"$folder\"\n" . $ padding . "<Directory \"$folder\">\n" . $ padding . " AllowOverride All\n" . $ padding . " Require all granted\n" . $ padding . "</Directory>\n" ; } } closedir ( $ h ) ; } return $ output ; }
Populates all subfolders in commondocs folder as Alias Apache primitives .
26,279
public static function hasSubstring ( $ haystack , $ needles , $ characterEncoding = 'UTF-8' ) { foreach ( ( array ) $ needles as $ needle ) { if ( $ needle == '' ) { continue ; } if ( mb_strpos ( $ haystack , $ needle , 0 , $ characterEncoding ) !== false ) { return true ; } } return false ; }
Checks if the given string contains the given substring .
26,280
public static function startsWith ( $ haystack , $ needles ) { foreach ( ( array ) $ needles as $ needle ) { if ( $ needle == '' ) { continue ; } $ substring = mb_substr ( $ haystack , 0 , mb_strlen ( $ needle ) ) ; if ( self :: doesStringMatchNeedle ( $ substring , $ needle ) ) { return true ; } } return false ; }
Checks if the given string begins with the given substring .
26,281
public static function matchesPattern ( $ pattern , $ givenString ) { if ( $ pattern == $ givenString ) { return true ; } $ pattern = preg_quote ( $ pattern , '#' ) ; $ pattern = str_replace ( '\*' , '.*' , $ pattern ) . '\z' ; return ( bool ) preg_match ( '#^' . $ pattern . '#' , $ givenString ) ; }
Check if the given string matches the given pattern .
26,282
protected function createListItem ( $ class , $ text ) { $ li = new NodeElement ( ) ; $ li -> openTag ( 'li' ) -> addAttribute ( 'class' , $ class ) -> finalize ( false ) ; if ( $ text !== null ) { $ li -> setText ( $ text ) ; } return $ li -> closeTag ( ) ; }
Creates list item
26,283
protected function renderList ( $ class , array $ children ) { $ ul = new NodeElement ( ) ; $ ul -> openTag ( 'ul' ) -> addAttribute ( 'class' , $ class ) -> finalize ( true ) -> appendChildren ( $ children ) -> closeTag ( ) ; return $ ul -> render ( ) ; }
Creates a list
26,284
public static function get_include_files ( $ directory , $ exclude_underscore = false ) { $ return = [ 'files' => [ ] , 'directories' => [ ] , ] ; if ( ! is_dir ( $ directory ) ) { return $ return ; } $ directory_iterator = new \ DirectoryIterator ( $ directory ) ; foreach ( $ directory_iterator as $ file ) { if ( $ file -> isDot ( ) ) { continue ; } if ( $ file -> isDir ( ) ) { $ return [ 'directories' ] [ ] = $ file -> getPathname ( ) ; continue ; } if ( 'php' !== $ file -> getExtension ( ) ) { continue ; } if ( $ exclude_underscore ) { if ( 0 === strpos ( $ file -> getBasename ( ) , '_' ) ) { continue ; } } $ return [ 'files' ] [ ] = $ file -> getPathname ( ) ; } return $ return ; }
Return included files and directories
26,285
public static function get_template_parts ( $ directory , $ exclude_underscore = false ) { if ( ! is_dir ( $ directory ) ) { return ; } $ files = static :: get_include_files ( $ directory , $ exclude_underscore ) ; foreach ( $ files [ 'files' ] as $ file ) { $ file = realpath ( $ file ) ; $ template_name = str_replace ( [ trailingslashit ( realpath ( get_template_directory ( ) ) ) , '.php' ] , '' , $ file ) ; \ get_template_part ( $ template_name ) ; } foreach ( $ files [ 'directories' ] as $ directory ) { static :: get_template_parts ( $ directory , $ exclude_underscore ) ; } }
get_template_part php files
26,286
public static function glob_recursive ( $ path ) { $ files = [ ] ; if ( preg_match ( '/\\' . DIRECTORY_SEPARATOR . 'vendor$/' , $ path ) ) { return $ files ; } foreach ( glob ( $ path . '/*' ) as $ file ) { if ( is_dir ( $ file ) ) { $ files = array_merge ( $ files , static :: glob_recursive ( $ file ) ) ; } elseif ( preg_match ( '/\.php$/' , $ file ) ) { $ files [ ] = $ file ; } } return $ files ; }
Returns PHP file list
26,287
public static function getValidatorErrorMessage ( $ validator ) { $ messages = $ validator -> errors ( ) ; $ msgArr = $ messages -> all ( ) ; $ arr = [ ] ; foreach ( $ msgArr as $ k => $ v ) { $ arr [ ] = $ v ; } $ ret = implode ( "," , $ arr ) ; return $ ret ; }
make Validator Error Message Readable
26,288
public static function randStr ( $ len = 6 , $ format = 'ALL' ) { switch ( strtoupper ( $ format ) ) { case 'ALL' : $ chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~' ; break ; case 'CHAR' : $ chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~' ; break ; case 'NUMBER' : $ chars = '0123456789' ; break ; default : $ chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~' ; break ; } mt_srand ( ( double ) microtime ( ) * 1000000 * getmypid ( ) ) ; $ randStr = "" ; while ( strlen ( $ randStr ) < $ len ) $ randStr .= substr ( $ chars , ( mt_rand ( ) % strlen ( $ chars ) ) , 1 ) ; return $ randStr ; }
generate random string of 6 digits
26,289
public static function formatResultData ( AjaxChoiceListFormatterInterface $ formatter , ChoiceListView $ choiceListView ) { $ result = [ ] ; foreach ( $ choiceListView -> choices as $ i => $ choiceView ) { if ( $ choiceView instanceof ChoiceGroupView ) { $ group = $ formatter -> formatGroupChoice ( $ choiceView ) ; foreach ( $ choiceView -> choices as $ j => $ subChoiceView ) { $ group = $ formatter -> addChoiceInGroup ( $ group , $ subChoiceView ) ; } if ( ! $ formatter -> isEmptyGroup ( $ group ) ) { $ result [ ] = $ group ; } } else { $ result [ ] = $ formatter -> formatChoice ( $ choiceView ) ; } } return $ result ; }
Format the result data .
26,290
public function pluck ( $ field , $ indexField = null ) { $ fieldsFormat = $ field ; $ usingFormatting = preg_match_all ( '/{(\w+\.\w+|\w+)}/' , $ field , $ matches ) ; $ fields = [ ] ; if ( $ usingFormatting ) { $ fields = $ matches [ 1 ] ; foreach ( $ fields as $ formatField ) { if ( ( $ pos = strpos ( $ formatField , '.' ) ) !== false ) { $ replaceFormatField = substr ( $ formatField , $ pos + 1 ) ; $ fieldsFormat = str_replace ( $ formatField , $ replaceFormatField , $ fieldsFormat ) ; } } } else { $ fields = [ $ field ] ; } $ selectFields = $ fields ; if ( $ indexField != null && ! in_array ( $ indexField , $ selectFields ) ) { $ selectFields [ ] = $ indexField ; } $ this -> selectFields ( $ selectFields ) ; $ returnIndexField = $ indexField ; if ( ! empty ( $ returnIndexField ) ) { if ( ( $ pos = strpos ( $ returnIndexField , '.' ) ) !== false ) { $ returnIndexField = substr ( $ returnIndexField , $ pos + 1 ) ; } } $ returnFields = [ ] ; foreach ( $ fields as $ returnField ) { if ( ( $ pos = strpos ( $ returnField , '.' ) ) !== false ) { $ returnField = substr ( $ returnField , $ pos + 1 ) ; } $ returnFields [ ] = $ returnField ; } $ fieldResults = [ ] ; $ results = $ this -> find ( ) ; foreach ( $ results as $ result ) { $ value = null ; if ( ! $ usingFormatting ) { $ value = $ result -> { $ returnFields [ 0 ] } ; } else { $ value = $ fieldsFormat ; foreach ( $ returnFields as $ returnField ) { $ value = str_replace ( "{" . $ returnField . "}" , $ result -> $ returnField , $ value ) ; } } if ( $ returnIndexField != null ) { $ fieldResults [ $ result -> $ returnIndexField ] = $ value ; } else { $ fieldResults [ ] = $ value ; } } return $ fieldResults ; }
Obtiene una columna de los resultados en un array
26,291
public function insert ( array $ fields = [ ] ) { $ query = new InsertQuery ( $ this -> getTable ( ) ) ; $ query -> fields ( ! empty ( $ fields ) ? $ fields : $ this -> getFields ( ) ) ; return $ this -> connection -> exec ( $ query ) ; }
Inserta un nuevo registro
26,292
public function update ( array $ fields = [ ] ) { $ query = new UpdateQuery ( $ this -> getTable ( ) ) ; $ query -> fields ( ! empty ( $ fields ) ? $ fields : $ this -> getFields ( ) ) ; $ query -> whereConditionGroup ( $ this -> getWhereConditionGroup ( ) ) ; return $ this -> connection -> exec ( $ query ) ; }
Actualiza un registro
26,293
public function delete ( ) { $ query = new DeleteQuery ( $ this -> getTable ( ) ) ; $ query -> whereConditionGroup ( $ this -> getWhereConditionGroup ( ) ) ; return $ this -> connection -> exec ( $ query ) ; }
Borra un registro
26,294
protected function getPhpFiles ( $ path ) { if ( is_dir ( $ path ) ) { return new RegexIterator ( new RecursiveIteratorIterator ( new RecursiveDirectoryIterator ( $ path , RecursiveDirectoryIterator :: SKIP_DOTS ) , RecursiveIteratorIterator :: SELF_FIRST , RecursiveIteratorIterator :: CATCH_GET_CHILD ) , '/^.+\.php$/i' , RecursiveRegexIterator :: GET_MATCH ) ; } else { return [ ] ; } }
return an iterator of php files in the provided paths and subpaths
26,295
protected function dumpLangArray ( $ source , $ code = '' ) { if ( $ this -> config ( 'array_shorthand' , true ) === false ) { return $ source ; } $ tokens = token_get_all ( $ source ) ; $ brackets = [ ] ; for ( $ i = 0 ; $ i < count ( $ tokens ) ; $ i ++ ) { $ token = $ tokens [ $ i ] ; if ( $ token === '(' ) { $ brackets [ ] = false ; } elseif ( $ token === ')' ) { $ token = array_pop ( $ brackets ) ? ']' : ')' ; } elseif ( is_array ( $ token ) && $ token [ 0 ] === T_ARRAY ) { $ a = $ i + 1 ; if ( isset ( $ tokens [ $ a ] ) && $ tokens [ $ a ] [ 0 ] === T_WHITESPACE ) { $ a ++ ; } if ( isset ( $ tokens [ $ a ] ) && $ tokens [ $ a ] === '(' ) { $ i = $ a ; $ brackets [ ] = true ; $ token = '[' ; } } $ code .= is_array ( $ token ) ? $ token [ 1 ] : $ token ; } $ code = preg_replace ( '/^ |\G /m' , ' ' , $ code ) ; $ code = preg_replace ( '/=\>\s\n\s{4,}\[/m' , '=> [' , $ code ) ; return $ code ; }
Convert the arrays to the shorthand syntax .
26,296
public function addDatabase ( string $ name , MongoDatabase $ database ) : MongoManager { if ( isset ( $ this -> databases [ $ name ] ) ) { throw new ODMException ( "Database '{$name}' already exists" ) ; } $ this -> databases [ $ name ] = $ database ; return $ this ; }
Add new database in a database pull database name will be automatically selected from given instance .
26,297
public function database ( string $ database = null ) : MongoDatabase { if ( empty ( $ database ) ) { $ database = $ this -> config -> defaultDatabase ( ) ; } $ database = $ this -> config -> resolveAlias ( $ database ) ; if ( isset ( $ this -> databases [ $ database ] ) ) { return $ this -> databases [ $ database ] ; } if ( ! $ this -> config -> hasDatabase ( $ database ) ) { throw new ODMException ( "Unable to initiate MongoDatabase, no presets for '{$database}' found" ) ; } $ options = $ this -> config -> databaseOptions ( $ database ) ; return $ this -> createDatabase ( $ database , $ options [ 'server' ] , $ options [ 'database' ] , $ options [ 'driverOptions' ] ?? [ ] , $ options [ 'options' ] ?? [ ] ) ; }
Create specified or select default instance of MongoDatabase .
26,298
public function getDatabases ( ) : array { $ result = [ ] ; foreach ( $ this -> config -> databaseNames ( ) as $ name ) { $ result [ ] = $ this -> database ( $ name ) ; } return $ result ; }
Get every know database .
26,299
public function encryptValue ( $ value ) { $ iv_size = mcrypt_get_iv_size ( MCRYPT_RIJNDAEL_256 , MCRYPT_MODE_ECB ) ; $ iv = mcrypt_create_iv ( $ iv_size , MCRYPT_RAND ) ; $ text = mcrypt_encrypt ( MCRYPT_RIJNDAEL_256 , $ this -> salt , $ value , MCRYPT_MODE_ECB , $ iv ) ; return trim ( base64_encode ( $ text ) ) ; }
Encrypts a value