idx
int64
0
60.3k
question
stringlengths
92
4.62k
target
stringlengths
7
635
2,200
public function map ( callable $ valueMapper , callable $ keyMapper = null ) : self { return new self ( new MappingIterator ( $ this -> getIterator ( ) , $ valueMapper , $ keyMapper ) , $ this -> type ) ; }
returns a new sequence which maps each element using the given mapper
2,201
public function mapKeys ( callable $ keyMapper ) : self { return new self ( new MappingIterator ( $ this -> getIterator ( ) , null , $ keyMapper ) , $ this -> type ) ; }
returns a new sequence which maps each key using the given mapper
2,202
public function append ( $ other ) : self { if ( is_array ( $ this -> elements ) && ! is_array ( $ other ) && ! ( $ other instanceof \ Traversable ) ) { $ all = $ this -> elements ; $ all [ ] = $ other ; return new self ( $ all ) ; } $ appendIterator = new \ AppendIterator ( ) ; $ appendIterator -> append ( $ this -> getIterator ( ) ) ; $ appendIterator -> append ( castToIterator ( $ other ) ) ; return new self ( $ appendIterator , $ this -> type ) ; }
appends any value creating a new combined sequence
2,203
public function peek ( callable $ valueConsumer , callable $ keyConsumer = null ) : self { return new self ( new Peek ( $ this -> getIterator ( ) , $ valueConsumer , $ keyConsumer ) , $ this -> type ) ; }
allows consumer to receive the value before any further operations are applied
2,204
public function each ( callable $ consumer ) : int { $ calls = 0 ; foreach ( $ this -> elements as $ key => $ element ) { $ calls ++ ; if ( false === $ consumer ( $ element , $ key ) ) { break ; } } return $ calls ; }
invokes consumer for each element
2,205
public function reduce ( callable $ accumulate = null , $ identity = null ) { if ( null === $ accumulate ) { return new Reducer ( $ this ) ; } $ result = $ identity ; foreach ( $ this -> elements as $ key => $ element ) { $ result = $ accumulate ( $ result , $ element , $ key ) ; } return $ result ; }
reduces all elements of the sequence to a single value
2,206
public function collect ( Collector $ collector = null ) { if ( null === $ collector ) { return new Collectors ( $ this ) ; } foreach ( $ this -> elements as $ key => $ element ) { $ collector -> accumulate ( $ element , $ key ) ; } return $ collector -> finish ( ) ; }
collects all elements into a structure defined by given collector
2,207
public function count ( ) : int { $ amount = 0 ; foreach ( $ this -> elements as $ key => $ element ) { $ amount ++ ; } return $ amount ; }
returns number of elements in sequence
2,208
public function getIterator ( ) : \ Traversable { if ( $ this -> elements instanceof \ Iterator ) { return $ this -> elements ; } if ( $ this -> elements instanceof \ Traversable ) { return new \ IteratorIterator ( $ this -> elements ) ; } return new \ ArrayIterator ( $ this -> elements ) ; }
returns an iterator on this sequence
2,209
public function withProperty ( string $ property , $ value ) : self { return new self ( $ this -> class , $ this -> properties -> put ( $ property , $ value ) , $ this -> injectionStrategy , $ this -> instanciator ) ; }
Add a property to be injected in the new object
2,210
public function build ( ) : object { $ object = $ this -> instanciator -> build ( $ this -> class , $ this -> properties ) ; $ parameters = $ this -> instanciator -> parameters ( $ this -> class ) ; $ properties = $ this -> properties -> filter ( function ( string $ property ) use ( $ parameters ) { return ! $ parameters -> contains ( $ property ) ; } ) ; $ refl = new ReflectionObject ( $ object , $ properties , $ this -> injectionStrategy ) ; return $ refl -> build ( ) ; }
Return a new instance of the class
2,211
public function properties ( ) : SetInterface { $ refl = new \ ReflectionClass ( $ this -> class ) ; $ properties = Set :: of ( 'string' ) ; foreach ( $ refl -> getProperties ( ) as $ property ) { $ properties = $ properties -> add ( $ property -> getName ( ) ) ; } return $ properties ; }
Return all the properties defined on the class
2,212
protected function generateSearchForm ( ) { $ dir = $ this -> bundle -> getPath ( ) ; $ parts = explode ( '\\' , $ this -> entity ) ; $ entityClass = array_pop ( $ parts ) ; $ entityNamespace = implode ( '\\' , $ parts ) ; $ target = sprintf ( '%s/Form/Search/%sSearch.php' , $ dir , $ entityClass ) ; $ this -> renderFile ( 'form/FormSearch.php.twig' , $ target , array ( 'fields' => $ this -> getFieldsFromMetadata ( $ this -> metadata ) , 'bundle' => $ this -> bundle -> getName ( ) , 'entity' => $ this -> entity , 'entity_class' => $ entityClass , 'namespace' => $ this -> bundle -> getNamespace ( ) , 'entity_namespace' => $ entityNamespace , 'format' => $ this -> format , 'form_type_name' => strtolower ( str_replace ( '\\' , '_' , $ this -> bundle -> getNamespace ( ) ) . ( $ parts ? '_' : '' ) . implode ( '_' , $ parts ) . '_' . $ this -> entity ) , ) ) ; }
Generates the search form class in the final bundle .
2,213
public function Delete ( $ RoleID = FALSE ) { if ( ! $ this -> _Permission ( ) ) return ; $ this -> Title ( T ( 'Delete Role' ) ) ; $ this -> AddSideMenu ( 'dashboard/role' ) ; $ Role = $ this -> RoleModel -> GetByRoleID ( $ RoleID ) ; if ( $ Role -> Deletable == '0' ) $ this -> Form -> AddError ( 'You cannot delete this role.' ) ; $ this -> Form -> AddHidden ( 'RoleID' , $ RoleID ) ; $ this -> AffectedUsers = $ this -> RoleModel -> GetUserCount ( $ RoleID ) ; $ this -> OrphanedUsers = $ this -> RoleModel -> GetUserCount ( $ RoleID , TRUE ) ; $ this -> ReplacementRoles = $ this -> RoleModel -> GetByNotRoleID ( $ RoleID ) ; if ( $ this -> Form -> AuthenticatedPostBack ( ) ) { if ( $ this -> OrphanedUsers > 0 ) { $ Validation = new Gdn_Validation ( ) ; $ Validation -> ApplyRule ( 'ReplacementRoleID' , 'Required' , 'You must choose a replacement role for orphaned users.' ) ; $ Validation -> Validate ( $ this -> Form -> FormValues ( ) ) ; $ this -> Form -> SetValidationResults ( $ Validation -> Results ( ) ) ; } if ( $ this -> Form -> ErrorCount ( ) == 0 ) { $ this -> RoleModel -> Delete ( $ RoleID , $ this -> Form -> GetValue ( 'ReplacementRoleID' ) ) ; $ this -> RedirectUrl = Url ( 'dashboard/role' ) ; $ this -> InformMessage ( T ( 'Deleting role...' ) ) ; } } $ this -> Render ( ) ; }
Remove a role .
2,214
public function DefaultRoles ( ) { $ this -> Permission ( 'Garden.Settings.Manage' ) ; $ this -> AddSideMenu ( '' ) ; $ this -> Title ( T ( 'Default Roles' ) ) ; $ RoleModel = new RoleModel ( ) ; $ this -> SetData ( 'RoleData' , $ RoleModel -> Get ( ) ) ; if ( $ this -> Form -> AuthenticatedPostBack ( ) === FALSE ) { $ DefaultRoles = C ( 'Garden.Registration.DefaultRoles' ) ; $ this -> Form -> SetValue ( 'DefaultRoles' , $ DefaultRoles ) ; $ GuestRolesData = $ RoleModel -> GetByUserID ( 0 ) ; $ GuestRoles = ConsolidateArrayValuesByKey ( $ GuestRolesData , 'RoleID' ) ; $ this -> Form -> SetValue ( 'GuestRoles' , $ GuestRoles ) ; $ ApplicantRoleID = C ( 'Garden.Registration.ApplicantRoleID' , '' ) ; $ this -> Form -> SetValue ( 'ApplicantRoleID' , $ ApplicantRoleID ) ; } else { $ DefaultRoles = $ this -> Form -> GetFormValue ( 'DefaultRoles' ) ; $ ApplicantRoleID = $ this -> Form -> GetFormValue ( 'ApplicantRoleID' ) ; SaveToConfig ( array ( 'Garden.Registration.DefaultRoles' => $ DefaultRoles , 'Garden.Registration.ApplicantRoleID' => $ ApplicantRoleID ) ) ; $ GuestRoles = $ this -> Form -> GetFormValue ( 'GuestRoles' ) ; $ UserModel = new UserModel ( ) ; $ UserModel -> SaveRoles ( 0 , $ GuestRoles , FALSE ) ; $ this -> InformMessage ( T ( "Saved" ) ) ; } $ this -> Render ( ) ; }
Manage default role assignments .
2,215
public function DefaultRolesWarning ( ) { $ DefaultRolesWarning = FALSE ; $ DefaultRoles = C ( 'Garden.Registration.DefaultRoles' ) ; if ( ! is_array ( $ DefaultRoles ) || count ( $ DefaultRoles ) == 0 ) { $ DefaultRolesWarning = TRUE ; } elseif ( ! C ( 'Garden.Registration.ApplicantRoleID' ) && C ( 'Garden.Registration.Method' ) == 'Approval' ) { $ DefaultRolesWarning = TRUE ; } else { $ RoleModel = new RoleModel ( ) ; $ GuestRoles = $ RoleModel -> GetByUserID ( 0 ) ; if ( $ GuestRoles -> NumRows ( ) == 0 ) $ DefaultRolesWarning = TRUE ; } if ( $ DefaultRolesWarning ) { echo '<div class="Messages Errors"><ul><li>' , sprintf ( T ( 'No default roles.' , 'You don\'t have your default roles set up. To correct this problem click %s.' ) , Anchor ( T ( 'here' ) , 'dashboard/role/defaultroles' ) ) , '</div>' ; } }
Show a warning if default roles are not setup yet .
2,216
public function Edit ( $ RoleID = FALSE ) { if ( ! $ this -> _Permission ( ) ) return ; if ( $ this -> Head && $ this -> Head -> Title ( ) == '' ) $ this -> Head -> Title ( T ( 'Edit Role' ) ) ; $ this -> AddSideMenu ( 'dashboard/role' ) ; $ PermissionModel = Gdn :: PermissionModel ( ) ; $ this -> Role = $ this -> RoleModel -> GetByRoleID ( $ RoleID ) ; $ this -> AddJsFile ( 'jquery.gardencheckboxgrid.js' ) ; $ this -> Form -> SetModel ( $ this -> RoleModel ) ; $ this -> Form -> AddHidden ( 'RoleID' , $ RoleID ) ; $ LimitToSuffix = ! $ this -> Role || $ this -> Role -> CanSession == '1' ? '' : 'View' ; if ( $ this -> Form -> AuthenticatedPostBack ( ) === FALSE ) { $ this -> SetData ( 'PermissionData' , $ PermissionModel -> GetPermissionsEdit ( $ RoleID ? $ RoleID : 0 , $ LimitToSuffix ) , true ) ; $ this -> Form -> SetData ( $ this -> Role ) ; } else { if ( $ RoleID = $ this -> Form -> Save ( ) ) { $ this -> InformMessage ( T ( 'Your changes have been saved.' ) ) ; $ this -> RedirectUrl = Url ( 'dashboard/role' ) ; $ this -> SetData ( 'PermissionData' , $ PermissionModel -> GetPermissionsEdit ( $ RoleID , $ LimitToSuffix ) , true ) ; } } $ this -> Render ( ) ; }
Edit a role .
2,217
public function Index ( $ RoleID = NULL ) { $ this -> Permission ( 'Garden.Settings.Manage' ) ; $ this -> AddSideMenu ( 'dashboard/role' ) ; $ this -> AddJsFile ( 'jquery.tablednd.js' ) ; $ this -> AddJsFile ( 'jquery-ui.js' ) ; $ this -> Title ( T ( 'Roles & Permissions' ) ) ; if ( ! $ RoleID ) $ RoleData = $ this -> RoleModel -> Get ( ) -> ResultArray ( ) ; else { $ Role = $ this -> RoleModel -> GetID ( $ RoleID ) ; $ RoleData = array ( $ Role ) ; } $ this -> SetData ( 'Roles' , $ RoleData ) ; $ this -> Render ( ) ; }
Show list of roles .
2,218
public function getError ( ) { if ( $ this -> errorCode !== null || $ this -> success === false ) { return [ 'code' => $ this -> errorCode === null ? self :: UNKNOWN_ERROR_CODE : $ this -> errorCode , 'message' => $ this -> errorMessage === null ? self :: UNKNOWN_ERROR_MSG : $ this -> errorMessage ] ; } else { return null ; } }
Gets the error
2,219
public function renderHelp ( ) { echo $ this -> renderVersion ( ) ; echo Line :: begin ( 'Usage:' , Line :: YELLOW ) -> nl ( ) ; echo Line :: begin ( ) -> indent ( 2 ) -> text ( 'generator [context:]subject [options]' ) -> nl ( 2 ) ; echo Line :: begin ( 'Options:' , Line :: YELLOW ) -> nl ( ) ; echo Line :: begin ( ) -> indent ( 2 ) -> text ( '--help' , Line :: MAGENTA ) -> to ( 21 ) -> text ( '-h' , Line :: MAGENTA ) -> text ( 'Display this help message.' ) -> nl ( 2 ) ; echo Line :: begin ( 'Available generators:' , Line :: YELLOW ) -> nl ( ) ; foreach ( $ this -> generators as $ name => $ config ) { echo Line :: begin ( ) -> indent ( 2 ) -> text ( $ name , Line :: MAGENTA ) -> to ( 24 ) -> text ( Generator :: create ( $ name , $ config ) -> getDescription ( ) ) -> nl ( ) ; } }
Displays the command help .
2,220
public function getTempPath ( ) { if ( ! isset ( $ this -> _tempPath ) ) { $ hash = md5 ( microtime ( true ) ) ; $ this -> _tempPath = "{$this->basePath}/{$this->tempDir}/{$hash}" ; } return $ this -> _tempPath ; }
Returns the path for storing the generated files .
2,221
protected function initTemplates ( ) { foreach ( $ this -> templates as $ template => $ templatePath ) { $ this -> templates [ $ template ] = $ this -> normalizePath ( $ templatePath ) ; } if ( ! isset ( $ this -> templates [ 'default' ] ) ) { $ this -> templates [ 'default' ] = realpath ( dirname ( __DIR__ ) . '/../templates/default' ) ; } }
Initializes the templates .
2,222
protected function initGenerators ( ) { $ this -> generators = \ CMap :: mergeArray ( self :: $ _builtInGenerators , $ this -> generators ) ; $ this -> providers = \ CMap :: mergeArray ( self :: $ _builtInProviders , $ this -> providers ) ; Generator :: setConfig ( \ Yii :: createComponent ( array ( 'class' => '\crisu83\yii_caviar\components\Config' , 'basePath' => $ this -> getTempPath ( ) , 'generators' => $ this -> generators , 'providers' => $ this -> providers , 'templates' => $ this -> templates , 'attributes' => array ( 'template' => $ this -> defaultTemplate , ) , ) ) ) ; }
Initializes the generators .
2,223
protected function runGenerator ( $ name , array $ config , array $ args ) { echo $ this -> renderVersion ( ) ; if ( ! isset ( $ args [ 0 ] ) ) { $ this -> usageError ( "You must specify a subject for what you are generating." ) ; } list ( $ config [ 'context' ] , $ config [ 'subject' ] ) = strpos ( $ args [ 0 ] , ':' ) !== false ? explode ( ':' , $ args [ 0 ] ) : array ( 'app' , $ args [ 0 ] ) ; echo Line :: begin ( 'Running generator' , Line :: YELLOW ) -> nl ( ) ; echo Line :: begin ( ) -> indent ( 2 ) -> text ( "Generating $name '{$args[0]}'." ) -> nl ( 2 ) ; $ generator = Generator :: create ( $ name , $ config ) ; if ( ! $ generator -> validate ( ) ) { $ generator -> renderErrors ( ) ; } $ files = $ generator -> generate ( ) ; $ this -> save ( $ files ) ; }
Runs a specific generator with the given configuration .
2,224
protected function save ( array $ files ) { echo Line :: begin ( 'Saving generated files ...' , Line :: GREEN ) -> end ( ) ; foreach ( $ files as $ file ) { $ file -> save ( ) ; } echo Line :: begin ( ) -> nl ( ) ; echo Line :: begin ( 'Copying generated files ...' , Line :: GREEN ) -> nl ( ) ; $ fileList = $ this -> buildFileList ( $ this -> getTempPath ( ) , $ this -> basePath ) ; $ this -> copyFiles ( $ fileList ) ; echo Line :: begin ( 'Removing temporary files ...' , Line :: GREEN ) -> nl ( ) ; $ this -> removeDirectory ( $ this -> getTempPath ( ) ) ; }
Saves the given files in a temporary folder copies them to the project root and deletes the temporary folder .
2,225
private function handleDevError ( PowerOnException $ e ) { $ response = $ this -> _container [ 'Response' ] ; $ view = $ this -> _container [ 'View' ] ; $ view -> set ( 'exception' , $ e ) ; $ response -> render ( $ view -> getCoreRenderedTemplate ( 'Template' . DS . 'Error' . DS . 'default.phtml' , 'Template' . DS . 'Layout' . DS . 'layout.phtml' ) , $ e -> getCode ( ) ) ; }
Renderiza un error en entorno desarrollo
2,226
private function handleExternalError ( \ Exception $ e ) { $ reflection = new \ ReflectionClass ( $ e ) ; echo '<header>' ; echo '<h1>Exception: ' . $ reflection -> getName ( ) . '</h1>' ; echo '<h2>Message: ' . $ e -> getMessage ( ) . '</h2>' ; echo '<h3>' . $ e -> getFile ( ) . ':' . $ e -> getLine ( ) . '</h3>' ; echo '</header>' ; if ( method_exists ( $ e , 'getContext' ) ) { echo 'Debug:' ; ! d ( $ e -> getContext ( ) ) ; } }
Renderiza un error externo al framework
2,227
public function process ( ContainerBuilder $ container ) { $ this -> container = $ container ; foreach ( $ container -> getDefinitions ( ) as $ definition ) { if ( $ definition -> isSynthetic ( ) || $ definition -> isAbstract ( ) ) { continue ; } $ definition -> setArguments ( $ this -> processArguments ( $ definition -> getArguments ( ) ) ) ; $ definition -> setMethodCalls ( $ this -> processArguments ( $ definition -> getMethodCalls ( ) ) ) ; $ definition -> setProperties ( $ this -> processArguments ( $ definition -> getProperties ( ) ) ) ; $ definition -> setFactory ( $ this -> processFactory ( $ definition -> getFactory ( ) ) ) ; } foreach ( $ container -> getAliases ( ) as $ id => $ alias ) { $ aliasId = ( string ) $ alias ; if ( $ aliasId !== $ defId = $ this -> getDefinitionId ( $ aliasId ) ) { $ container -> setAlias ( $ id , new Alias ( $ defId , $ alias -> isPublic ( ) ) ) ; } } }
Processes the ContainerBuilder to replace references to aliases with actual service references .
2,228
private function processArguments ( array $ arguments ) { foreach ( $ arguments as $ k => $ argument ) { if ( is_array ( $ argument ) ) { $ arguments [ $ k ] = $ this -> processArguments ( $ argument ) ; } elseif ( $ argument instanceof Reference ) { $ defId = $ this -> getDefinitionId ( $ id = ( string ) $ argument ) ; if ( $ defId !== $ id ) { $ arguments [ $ k ] = new Reference ( $ defId , $ argument -> getInvalidBehavior ( ) ) ; } } } return $ arguments ; }
Processes the arguments to replace aliases .
2,229
public static function defrost ( $ frozenObject ) { try { if ( false === ( $ _object = @ gzuncompress ( @ base64_decode ( $ frozenObject ) ) ) ) { $ _object = $ frozenObject ; } if ( static :: isFrozen ( $ _object ) ) { return unserialize ( $ _object ) ; } if ( false !== ( $ _xml = @ simplexml_load_string ( $ _object ) ) ) { return $ _xml ; } } catch ( \ Exception $ _ex ) { } return $ frozenObject ; }
Object defroster . Warms up those chilly objects .
2,230
public static function isFrozen ( $ value ) { $ _result = @ unserialize ( $ value ) ; return ! ( false === $ _result && $ value != serialize ( false ) ) ; }
Tests if a value is frozen
2,231
public function validate ( $ subject ) : bool { $ nodeValidator = new NodeValidator ( $ this -> schema [ 'not' ] , $ this -> rootSchema ) ; if ( $ nodeValidator -> validate ( $ subject ) ) { return false ; } return true ; }
Validates subject against not
2,232
public static function clear ( $ file = false ) { if ( $ file && self :: isFile ( $ file ) ) { $ f = @ fopen ( $ file , "r+" ) ; if ( $ f !== false ) { ftruncate ( $ f , 0 ) ; fclose ( $ f ) ; return true ; } } return false ; }
Empty a file .
2,233
public static function extension ( $ file = false ) { if ( $ file && self :: isFile ( $ file ) ) { return pathinfo ( $ file , PATHINFO_EXTENSION ) ; } return false ; }
Get the extension of a given file .
2,234
public static function extract ( $ file = false , $ destination = false ) { if ( $ file ) { if ( ! $ destination ) { $ destination = __DIR__ ; } if ( ! Folder :: isFolder ( $ destination ) ) { if ( ! Folder :: create ( $ destination ) ) { return false ; } } $ zip = new \ ZipArchive ; $ res = $ zip -> open ( $ file ) ; if ( $ res === true ) { $ zip -> extractTo ( $ destination ) ; $ zip -> close ( ) ; return true ; } } return false ; }
Extract a given zip file .
2,235
public static function size ( $ file = false , $ format = 'bytes' ) { if ( $ file && self :: isFile ( $ file ) ) { $ size = filesize ( $ file ) ; switch ( $ format ) { case 'bytes' : return $ size ; break ; case 'kb' : return Number :: round ( ( $ size / 1024 ) , 2 ) ; break ; case 'mb' : return Number :: round ( ( $ size / 1048576 ) , 2 ) ; break ; } } return false ; }
Get size of a given file .
2,236
private function getSelect ( array $ where ) : string { $ table = $ this -> getCollection ( ) ; $ whereDetails = ! empty ( $ where ) ? ' WHERE ' . $ this -> genWhere ( $ where ) : '' ; return "SELECT * FROM $table $whereDetails" ; }
Generate basic select query
2,237
public function select ( array $ where = [ ] , array $ nosql_options = [ ] ) { $ query = $ this -> getSelect ( $ where ) ; $ statement = $ this -> getInstance ( ) -> prepare ( $ query ) ; foreach ( $ where as $ key => $ value ) { $ statement -> bindValue ( ":where_$key" , $ value , $ this -> isPdoInt ( $ value ) ) ; } $ statement -> execute ( ) ; return $ statement -> fetchAll ( PDO :: FETCH_OBJ ) ; }
Run a select statement against the database
2,238
public function rawSQL ( array $ arguments ) { $ this -> setRawDefaults ( $ arguments ) ; list ( $ query , $ bind , $ fetch ) = $ arguments ; $ statement = $ this -> getInstance ( ) -> prepare ( $ query ) ; $ statement -> execute ( $ bind ) ; return ( true === $ fetch ) ? $ statement -> fetchAll ( PDO :: FETCH_OBJ ) : $ statement -> rowCount ( ) ; }
Execute raw query without generation useful for some advanced operations
2,239
private function genInsert ( array $ data ) : string { $ table = $ this -> getCollection ( ) ; $ fieldNames = implode ( ',' , array_keys ( $ data ) ) ; $ fieldDetails = ':' . implode ( ', :' , array_keys ( $ data ) ) ; return "INSERT INTO $table ($fieldNames) VALUES ($fieldDetails)" ; }
Generate INSERT query by array
2,240
private function genLine ( array $ array , string $ glue , string $ name ) : string { $ line = '' ; $ i = 0 ; foreach ( $ array as $ key => $ value ) { $ line .= ( ( $ i === 0 ) ? null : $ glue ) . "$key = :${name}_$key" ; $ i = 1 ; } return $ line ; }
Generate the line by provided keys
2,241
private function genUpdate ( array $ data , array $ where ) : string { $ table = $ this -> getCollection ( ) ; $ fieldDetails = ! empty ( $ data ) ? $ this -> genFields ( $ data ) : '' ; $ whereDetails = ! empty ( $ where ) ? ' WHERE ' . $ this -> genWhere ( $ where ) : '' ; return "UPDATE $table SET $fieldDetails $whereDetails" ; }
Generate update query
2,242
public function delete ( array $ where ) { $ table = $ this -> getCollection ( ) ; $ whereDetails = ! empty ( $ where ) ? ' WHERE ' . $ this -> genWhere ( $ where ) : '' ; $ statement = $ this -> getInstance ( ) -> prepare ( "DELETE FROM $table $whereDetails" ) ; foreach ( $ where as $ key => $ value ) { $ statement -> bindValue ( ":where_$key" , $ value , $ this -> isPdoInt ( $ value ) ) ; } $ statement -> execute ( ) ; return $ statement -> rowCount ( ) ; }
Delete rows from database
2,243
public function setArray ( array $ array ) { $ this -> array = array_values ( $ array ) ; $ this -> arraySize = count ( $ this -> array ) ; $ this -> rewind ( ) ; return $ this ; }
Only array values where used and returned
2,244
public function getFormattedPhone ( ) { $ parts = [ $ this -> formatPhoneNumber ( $ this -> phone ) ] ; if ( isset ( $ this -> formattedExtension ) ) { $ parts [ ] = $ this -> formattedExtension ; } return implode ( ' ' , $ parts ) ; }
Get formatted phone .
2,245
public function deprecate ( $ project , $ image , Compute_DeprecationStatus $ postBody , $ optParams = array ( ) ) { $ params = array ( 'project' => $ project , 'image' => $ image , 'postBody' => $ postBody ) ; $ params = array_merge ( $ params , $ optParams ) ; return $ this -> call ( 'deprecate' , array ( $ params ) , "Compute_Operation" ) ; }
Sets the deprecation status of an image .
2,246
public function setVariable ( string $ key , $ value ) : ContextInterface { $ this -> variables [ $ key ] = $ value ; return $ this ; }
Store the variable with the given key
2,247
public function addVariables ( array $ variables ) : ContextInterface { $ this -> variables = array_merge ( $ this -> variables , $ variables ) ; return $ this ; }
Set all variables from the given dictionary
2,248
public function handle ( Client $ client , $ index , $ alias ) { $ client -> getIndex ( $ index ) -> removeAlias ( $ alias ) ; }
Handle remove alias command
2,249
protected function mergeConfigs ( array $ configs ) { $ mergedConfig = array ( ) ; foreach ( $ configs as $ config ) { $ mergedConfig = array_merge_recursive ( $ mergedConfig , $ config ) ; } return array ( $ mergedConfig ) ; }
merges muliple configs without loosing keys
2,250
public function switchDb ( $ db_name ) { $ self = $ this ; return $ this -> app [ 'mongo' ] = $ this -> app -> share ( function ( ) use ( $ db_name , $ self ) { return new Db ( $ db_name , $ self -> client , $ self -> app ) ; } ) ; }
Change database helper
2,251
protected function filterResponse ( $ request , $ type = "text/*" , $ callback ) { $ response = $ this -> controller -> execute ( $ request ) ; $ array = call_user_func_array ( $ callback , array ( $ response -> getStatus ( ) , $ response -> getHeaders ( ) , $ response -> getBody ( ) ) ) ; return new Http \ Response ( $ array [ 0 ] , $ array [ 1 ] , $ array [ 2 ] ) ; }
Helper to modify the response via a callback
2,252
public function add ( $ name , $ dependencyUnit , $ arguments = array ( ) ) { if ( is_object ( $ dependencyUnit ) ) { $ dependencyClass = get_class ( $ dependencyUnit ) ; } else { $ dependencyClass = $ dependencyUnit ; } if ( ! is_array ( $ arguments ) ) $ arguments = array ( 'arguments' => $ arguments ) ; $ this -> _dependencies [ $ name ] = array_merge ( $ arguments , array ( 'className' => $ dependencyClass , 'object' => ! empty ( $ arguments [ 'object' ] ) ? $ arguments [ 'object' ] : null ) ) ; }
Add dependency declaration to current container
2,253
protected function demergePasswordAndSalt ( $ mergedPasswordSalt ) { if ( empty ( $ mergedPasswordSalt ) ) { return array ( '' , '' ) ; } $ password = $ mergedPasswordSalt ; $ salt = '' ; $ saltBegins = strrpos ( $ mergedPasswordSalt , '{' ) ; if ( false !== $ saltBegins && $ saltBegins + 1 < strlen ( $ mergedPasswordSalt ) ) { $ salt = substr ( $ mergedPasswordSalt , $ saltBegins + 1 , - 1 ) ; $ password = substr ( $ mergedPasswordSalt , 0 , $ saltBegins ) ; } return array ( $ password , $ salt ) ; }
Demerges a merge password and salt string .
2,254
protected function calculateLimitTiles ( ) { $ so = $ this -> imageGeoZone -> getSudOuestPoint ( ) ; $ this -> soTile = self :: $ gpm -> LatLonToTile ( $ so -> getLatitude ( ) , $ so -> getLongitude ( ) , $ this -> zoom ) ; $ ne = $ this -> imageGeoZone -> getNordEstPoint ( ) ; $ this -> neTile = self :: $ gpm -> LatLonToTile ( $ ne -> getLatitude ( ) , $ ne -> getLongitude ( ) , $ this -> zoom ) ; $ this -> soTileInfo = self :: $ gpm -> TileLatLonBounds ( $ this -> soTile [ 'x' ] , $ this -> soTile [ 'y' ] , $ this -> zoom ) ; $ this -> soTileInfo [ 'min' ] [ 'lat' ] = $ this -> soTileInfo [ 'min' ] [ 'lat' ] * - 1 ; $ this -> soTileInfo [ 'max' ] [ 'lat' ] = $ this -> soTileInfo [ 'max' ] [ 'lat' ] * - 1 ; $ this -> neTileInfo = self :: $ gpm -> TileLatLonBounds ( $ this -> neTile [ 'x' ] , $ this -> neTile [ 'y' ] , $ this -> zoom ) ; $ this -> neTileInfo [ 'min' ] [ 'lat' ] = $ this -> neTileInfo [ 'min' ] [ 'lat' ] * - 1 ; $ this -> neTileInfo [ 'max' ] [ 'lat' ] = $ this -> neTileInfo [ 'max' ] [ 'lat' ] * - 1 ; $ this -> tilesGeoZone = new GeoZone ( $ this -> soTileInfo [ 'max' ] [ 'lat' ] , $ this -> neTileInfo [ 'min' ] [ 'lat' ] , $ this -> soTileInfo [ 'min' ] [ 'lon' ] , $ this -> neTileInfo [ 'max' ] [ 'lon' ] ) ; }
Calcule les emplacements des tuiles limites SUDOUEST et NORDEST
2,255
public function offsetGet ( $ mixOffset ) { return isset ( $ this -> mixValue [ $ mixOffset ] ) ? $ this -> mixValue [ $ mixOffset ] : null ; }
Offset Exists Method
2,256
public function getRawContent ( ) : string { if ( ! $ this -> rawContentIsFetched ) { $ this -> setRawContent ( file_get_contents ( 'php://input' ) ) ; $ this -> rawContentIsFetched = true ; } return parent :: getRawContent ( ) ; }
Returns the raw content from request .
2,257
private static function parseUrl ( array $ serverVars ) : UrlInterface { $ uriAndQueryString = explode ( '?' , self :: fixRequestUri ( $ serverVars [ 'REQUEST_URI' ] ) , 2 ) ; $ hostAndPort = explode ( ':' , $ serverVars [ 'HTTP_HOST' ] , 2 ) ; return Url :: fromParts ( Scheme :: parse ( 'http' . ( isset ( $ serverVars [ 'HTTPS' ] ) && $ serverVars [ 'HTTPS' ] !== '' && $ serverVars [ 'HTTPS' ] !== 'off' ? 's' : '' ) ) , Host :: parse ( $ hostAndPort [ 0 ] ) , count ( $ hostAndPort ) > 1 ? intval ( $ hostAndPort [ 1 ] ) : null , UrlPath :: parse ( $ uriAndQueryString [ 0 ] ) , count ( $ uriAndQueryString ) > 1 ? $ uriAndQueryString [ 1 ] : null ) ; }
Parses an array with server variables into a url .
2,258
private static function parseHeaders ( array $ serverVars ) : HeaderCollectionInterface { $ headers = new HeaderCollection ( ) ; $ headersArray = self :: getHeadersArray ( $ serverVars ) ; foreach ( $ headersArray as $ name => $ value ) { $ headers -> add ( strval ( $ name ) , $ value ) ; } return $ headers ; }
Parses an array with headers into a header collection .
2,259
private static function getHeadersArray ( array $ serverVars ) : array { $ headersArray = [ ] ; if ( function_exists ( 'getallheaders' ) ) { return getallheaders ( ) ; } foreach ( $ serverVars as $ name => $ value ) { if ( substr ( $ name , 0 , 5 ) === 'HTTP_' ) { $ headersArray [ str_replace ( ' ' , '-' , ucwords ( strtolower ( str_replace ( '_' , ' ' , substr ( $ name , 5 ) ) ) ) ) ] = $ value ; } } return $ headersArray ; }
Returns all headers as an array .
2,260
private static function parseParameters ( array $ parametersArray ) : ParameterCollectionInterface { $ parameters = new ParameterCollection ( ) ; foreach ( $ parametersArray as $ parameterName => $ parameterValue ) { $ parameters -> set ( strval ( $ parameterName ) , strval ( is_array ( $ parameterValue ) ? $ parameterValue [ 0 ] : $ parameterValue ) ) ; } return $ parameters ; }
Parses an array with parameters into a parameter collection .
2,261
private static function parseCookies ( array $ cookiesArray ) : RequestCookieCollectionInterface { $ cookies = new RequestCookieCollection ( ) ; foreach ( $ cookiesArray as $ cookieName => $ cookieValue ) { $ cookies -> set ( strval ( $ cookieName ) , new RequestCookie ( strval ( $ cookieValue ) ) ) ; } return $ cookies ; }
Parses an array with cookies into a cookie collection .
2,262
private static function parseUploadedFiles ( array $ filesArray ) : UploadedFileCollectionInterface { $ uploadedFiles = new UploadedFileCollection ( ) ; foreach ( $ filesArray as $ uploadedFileName => $ uploadedFileInfo ) { $ uploadedFile = self :: parseUploadedFile ( $ uploadedFileInfo ) ; if ( $ uploadedFile === null ) { continue ; } $ uploadedFiles -> set ( strval ( $ uploadedFileName ) , $ uploadedFile ) ; } return $ uploadedFiles ; }
Parses an array with files info an uploaded files collection .
2,263
private static function parseUploadedFile ( array $ uploadedFileInfo ) : ? UploadedFileInterface { $ error = is_array ( $ uploadedFileInfo [ 'error' ] ) ? $ uploadedFileInfo [ 'error' ] [ 0 ] : $ uploadedFileInfo [ 'error' ] ; $ error = intval ( $ error ) ; if ( $ error !== 0 ) { if ( isset ( self :: $ fileUploadErrors [ $ error ] ) ) { throw new ServerEnvironmentException ( 'File upload failed: ' . self :: $ fileUploadErrors [ $ error ] ) ; } return null ; } $ path = is_array ( $ uploadedFileInfo [ 'tmp_name' ] ) ? $ uploadedFileInfo [ 'tmp_name' ] [ 0 ] : $ uploadedFileInfo [ 'tmp_name' ] ; if ( ! is_uploaded_file ( $ path ) ) { return null ; } $ originalName = is_array ( $ uploadedFileInfo [ 'name' ] ) ? $ uploadedFileInfo [ 'name' ] [ 0 ] : $ uploadedFileInfo [ 'name' ] ; $ size = is_array ( $ uploadedFileInfo [ 'size' ] ) ? $ uploadedFileInfo [ 'size' ] [ 0 ] : $ uploadedFileInfo [ 'size' ] ; $ result = new UploadedFile ( FilePath :: parse ( strval ( $ path ) ) , strval ( $ originalName ) , intval ( $ size ) ) ; return $ result ; }
Parses an array with file info into an uploaded file .
2,264
private static function fixRequestUri ( string $ requestUri ) : string { return preg_replace_callback ( '|[^a-zA-Z0-9-._~:/?[\\]@!$&\'()*+,;=%]|' , function ( array $ matches ) { return '%' . sprintf ( '%02X' , ord ( $ matches [ 0 ] ) ) ; } , $ requestUri ) ; }
Fixes a request uri string to conform with RFC 3986 .
2,265
public function selectAction ( ) { $ selectFieldProviders = $ this -> get ( 'phlexible_elementtype.select_field_providers' ) ; $ data = [ ] ; foreach ( $ selectFieldProviders -> all ( ) as $ selectFieldProvider ) { $ data [ ] = [ 'name' => $ selectFieldProvider -> getName ( ) , 'title' => $ selectFieldProvider -> getTitle ( $ this -> getUser ( ) -> getInterfaceLanguage ( 'en' ) ) , ] ; } return new JsonResponse ( [ 'functions' => $ data ] ) ; }
Return available functions .
2,266
public function functionAction ( Request $ request ) { $ selectFieldProviders = $ this -> get ( 'phlexible_elementtype.select_field_providers' ) ; $ providerName = $ request -> get ( 'provider' ) ; $ siterootId = $ request -> get ( 'siterootId' ) ; $ language = $ request -> get ( 'language' ) ; $ interfaceLanguage = $ this -> getUser ( ) -> getInterfaceLanguage ( 'en' ) ; $ provider = $ selectFieldProviders -> get ( $ providerName ) ; $ data = $ provider -> getData ( $ siterootId , $ interfaceLanguage , $ language ) ; return new JsonResponse ( [ 'data' => $ data ] ) ; }
Return selectfield data for lists .
2,267
public function isTablet ( $ userAgent = null ) { $ this -> setDetectionType ( self :: DETECTION_TYPE_MOBILE ) ; foreach ( self :: $ tabletDevices as $ _regex ) { if ( $ this -> match ( $ _regex , $ userAgent ) ) { return true ; } } return false ; }
Check if the device is a tablet . Return true if any type of tablet device is detected .
2,268
protected function getAvailableFilters ( ) { $ filters = [ ] ; foreach ( $ this -> config [ 'allowed_filters' ] as $ key ) { if ( ! isset ( $ this -> filterSets [ $ key ] ) ) { continue ; } $ set = $ this -> filterSets [ $ key ] ; $ explanation = [ ] ; foreach ( $ set [ 'filters' ] as $ filter => $ properties ) { switch ( $ filter ) { case 'thumbnail' : $ explanation [ ] = $ properties [ 'size' ] [ 0 ] . ' X ' . $ properties [ 'size' ] [ 0 ] ; break ; case 'relative_resize' : $ heighten = ( isset ( $ properties [ 'heighten' ] ) ) ? $ properties [ 'heighten' ] : '~' ; $ widen = ( isset ( $ properties [ 'widen' ] ) ) ? $ properties [ 'widen' ] : '~' ; $ explanation [ ] = $ widen . ' X ' . $ heighten ; break ; } } $ filters [ $ key . ' (' . implode ( ', ' , $ explanation ) . ')' ] = $ key ; } return $ filters ; }
Formats the available filters
2,269
public function decode ( $ data , $ format , array $ context = array ( ) ) { $ result = null ; parse_str ( $ data , $ result ) ; return $ result ; }
Decodes a string into PHP data
2,270
public static function getCacheInfo ( array $ blockPathInfos , array $ pBlockConfig ) { $ configCacheName = ConfigInterface :: CONFIG_CACHE_NAME ; $ configCacheTtlName = ConfigInterface :: CONFIG_CACHE_TTL_NAME ; $ configCacheTypeName = ConfigInterface :: CONFIG_CACHE_TYPE_NAME ; $ cacheInfo = array ( ) ; if ( ! self :: isCacheEnabled ( $ pBlockConfig ) ) { $ cacheConfig = Agl :: app ( ) -> getConfig ( 'core-layout/blocks/' . ConfigInterface :: CONFIG_CACHE_NAME ) ; if ( $ cacheConfig === NULL ) { return $ cacheInfo ; } } else { $ cacheConfig = $ pBlockConfig [ $ configCacheName ] ; } $ request = Agl :: getRequest ( ) ; $ cacheInfo [ $ configCacheTtlName ] = ( isset ( $ cacheConfig [ $ configCacheTtlName ] ) and ctype_digit ( $ cacheConfig [ $ configCacheTtlName ] ) ) ? ( int ) $ cacheConfig [ $ configCacheTtlName ] : 0 ; $ type = ( isset ( $ cacheConfig [ $ configCacheTypeName ] ) ) ? $ cacheConfig [ $ configCacheTypeName ] : ConfigInterface :: CONFIG_CACHE_TYPE_STATIC ; $ cacheInfo [ CacheInterface :: CACHE_KEY ] = static :: CACHE_FILE_PREFIX . $ blockPathInfos [ 1 ] . CacheInterface :: CACHE_KEY_SEPARATOR . $ blockPathInfos [ 2 ] ; if ( Agl :: isModuleLoaded ( Agl :: AGL_MORE_POOL . '/locale/locale' ) ) { $ cacheInfo [ CacheInterface :: CACHE_KEY ] .= CacheInterface :: CACHE_KEY_SEPARATOR . Agl :: getSingleton ( Agl :: AGL_MORE_POOL . '/locale' ) -> getLanguage ( ) ; } if ( $ type == ConfigInterface :: CONFIG_CACHE_TYPE_DYNAMIC ) { $ cacheInfo [ CacheInterface :: CACHE_KEY ] .= CacheInterface :: CACHE_KEY_SEPARATOR . \ Agl \ Core \ Data \ String :: rewrite ( $ request -> getReq ( ) ) ; if ( Request :: isAjax ( ) ) { $ cacheInfo [ CacheInterface :: CACHE_KEY ] .= CacheInterface :: CACHE_KEY_SEPARATOR . ConfigInterface :: CONFIG_CACHE_KEY_AJAX ; } } return $ cacheInfo ; }
Return a TTL and a cache key .
2,271
public static function isCacheEnabled ( $ pBlockConfig ) { $ configCacheName = ConfigInterface :: CONFIG_CACHE_NAME ; return ( is_array ( $ pBlockConfig ) and Agl :: app ( ) -> isCacheEnabled ( ) and isset ( $ pBlockConfig [ $ configCacheName ] ) and is_array ( $ pBlockConfig [ $ configCacheName ] ) ) ; }
Check if the cache is enabled for the passed block configuration array .
2,272
public static function checkAcl ( $ pGroupId , $ pBlockId ) { $ blockConfig = Agl :: app ( ) -> getConfig ( 'core-layout/blocks/' . $ pGroupId . '#' . $ pBlockId ) ; if ( is_array ( $ blockConfig ) and isset ( $ blockConfig [ 'acl' ] ) ) { $ auth = Agl :: getAuth ( ) ; $ acl = Agl :: getSingleton ( Agl :: AGL_CORE_POOL . '/auth/acl' ) ; if ( ! $ acl -> isAllowed ( $ auth -> getRole ( ) , $ blockConfig [ 'acl' ] ) ) { return false ; } } return true ; }
Check if the current user can access the block with its Acl configuration .
2,273
public function getView ( ) { if ( $ this -> _view === NULL ) { $ this -> _view = Registry :: get ( 'view' ) ; } return $ this -> _view ; }
Get the parent View class .
2,274
public function render ( ) { extract ( $ this -> _vars ) ; $ path = APP_PATH . Agl :: APP_TEMPLATE_DIR . static :: APP_HTTP_DIR . DS . $ this -> _file ; require ( $ path ) ; }
Extract variables and include the template in the current page .
2,275
public function hasPresenter ( ) : bool { static $ hasPresenter ; if ( is_bool ( $ hasPresenter ) ) { return $ hasPresenter ; } if ( $ this -> icons_type != 'select2' ) { return false ; } $ className = $ this -> icons_presenter_class ; $ hasPresenter = class_exists ( $ className ) && app ( $ className ) instanceof IconSetInterface ; return $ hasPresenter ; }
Determine if icon presenter exists for current group .
2,276
public function getPresenter ( ) : ? IconSetInterface { static $ presenter ; if ( $ presenter instanceof IconSetInterface ) { return $ presenter ; } return $ presenter = $ this -> hasPresenter ( ) ? app ( $ this -> icons_presenter_class ) : null ; }
Get the icons presenter instance .
2,277
public function hasFileIcon ( string $ key ) : bool { return $ this -> file_icons instanceof Collection && $ this -> file_icons -> has ( $ key ) ; }
Determine if category group has icon with given key .
2,278
public function addCancelLink ( $ url , $ label = "Cancel" ) { $ this -> actions -> removeByname ( "cancellink" ) ; $ cancellink = new AnchorField ( "cancellink" , $ label , $ url ) ; $ this -> actions -> unshift ( $ cancellink ) ; }
Add a link to go back
2,279
public function setAllowedTickets ( SS_List $ tickets ) { $ this -> fields -> removeByName ( "TicketID" ) ; $ this -> fields -> unshift ( new DropdownField ( "TicketID" , "Ticket" , $ tickets -> toArray ( ) ) ) ; }
Remove the ticket hidden field and add a dropdown containing the available tickets .
2,280
public function getOutputFile ( ) { if ( ! $ this -> outputFile ) { $ dir = rtrim ( dirname ( $ this -> getFile ( ) ) , '/\\' ) ; $ file = basename ( $ this -> getFile ( ) ) ; $ basename = substr ( $ file , 0 , strpos ( $ file , '.' ) ) ; $ this -> outputFile = $ dir . '/' . $ basename . '.bmp' ; } return $ this -> outputFile ; }
Get the output file
2,281
public function Refresh ( ) { $ LocalName = $ this -> Current ( ) ; $ ApplicationWhiteList = Gdn :: ApplicationManager ( ) -> EnabledApplicationFolders ( ) ; $ PluginWhiteList = Gdn :: PluginManager ( ) -> EnabledPluginFolders ( ) ; $ ForceRemapping = TRUE ; $ this -> Set ( $ LocalName , $ ApplicationWhiteList , $ PluginWhiteList , $ ForceRemapping ) ; }
Reload the locale system
2,282
public function Set ( $ LocaleName , $ ApplicationWhiteList , $ PluginWhiteList , $ ForceRemapping = FALSE ) { $ this -> Locale = $ LocaleName ; $ LocaleSources = $ this -> GetLocaleSources ( $ LocaleName , $ ApplicationWhiteList , $ PluginWhiteList , $ ForceRemapping ) ; $ Codeset = C ( 'Garden.LocaleCodeset' , 'UTF8' ) ; $ CurrentLocale = str_replace ( '-' , '_' , $ LocaleName ) ; $ SetLocale = $ CurrentLocale . '.' . $ Codeset ; setlocale ( LC_TIME , $ SetLocale , $ CurrentLocale ) ; if ( ! is_array ( $ LocaleSources ) ) $ LocaleSources = array ( ) ; $ this -> Unload ( ) ; $ ConfLocaleOverride = PATH_CONF . '/locale.php' ; $ Count = count ( $ LocaleSources ) ; for ( $ i = 0 ; $ i < $ Count ; ++ $ i ) { if ( $ ConfLocaleOverride != $ LocaleSources [ $ i ] && file_exists ( $ LocaleSources [ $ i ] ) ) $ this -> Load ( $ LocaleSources [ $ i ] , FALSE ) ; } if ( file_exists ( $ ConfLocaleOverride ) ) $ this -> Load ( $ ConfLocaleOverride , TRUE ) ; $ this -> DeveloperMode = C ( 'Garden.Locales.DeveloperMode' , FALSE ) ; if ( $ this -> DeveloperMode ) { $ this -> DeveloperContainer = new Gdn_Configuration ( ) ; $ this -> DeveloperContainer -> Splitting ( FALSE ) ; $ this -> DeveloperContainer -> Caching ( FALSE ) ; $ DeveloperCodeFile = PATH_CACHE . "/locale-developer-{$LocaleName}.php" ; if ( ! file_exists ( $ DeveloperCodeFile ) ) touch ( $ DeveloperCodeFile ) ; $ this -> DeveloperContainer -> Load ( $ DeveloperCodeFile , 'Definition' , TRUE ) ; } if ( $ this -> DeveloperMode ) $ this -> DeveloperContainer -> MassImport ( $ this -> LocaleContainer -> Get ( '.' ) ) ; $ this -> FireEvent ( 'AfterSet' ) ; }
Defines and loads the locale .
2,283
public function SetTranslation ( $ Code , $ Translation = '' , $ Save = FALSE ) { if ( ! is_array ( $ Code ) ) $ Code = array ( $ Code => $ Translation ) ; $ this -> LocaleContainer -> SaveToConfig ( $ Code , NULL , $ Save ) ; }
Assigns a translation code .
2,284
public function Unload ( ) { if ( $ this -> LocaleContainer instanceof Gdn_Configuration ) $ this -> LocaleContainer -> AutoSave ( FALSE ) ; $ this -> LocaleContainer = new Gdn_Configuration ( ) ; $ this -> LocaleContainer -> Splitting ( FALSE ) ; $ this -> LocaleContainer -> Caching ( FALSE ) ; }
Clears out the currently loaded locale settings .
2,285
public static function equals ( $ knownString , $ userInput ) { if ( ! is_string ( $ knownString ) ) { $ knownString = ( string ) $ knownString ; } if ( ! is_string ( $ userInput ) ) { $ userInput = ( string ) $ userInput ; } if ( function_exists ( 'hash_equals' ) ) { return hash_equals ( $ knownString , $ userInput ) ; } $ knownLength = mb_strlen ( $ knownString ) ; if ( mb_strlen ( $ userInput ) !== $ knownLength ) { return false ; } $ result = 0 ; for ( $ i = 0 ; $ i < $ knownLength ; ++ $ i ) { $ result |= ( ord ( $ knownString [ $ i ] ) ^ ord ( $ userInput [ $ i ] ) ) ; } return 0 === $ result ; }
Compares two strings using a constant - time algorithm .
2,286
private function getCache ( $ configPath ) { if ( ! isset ( $ this -> cacheList [ $ configPath ] ) ) { $ cachePath = $ this -> getCachePath ( $ configPath ) ; $ this -> cacheList [ $ configPath ] = new ConfigCache ( $ cachePath , true ) ; } return $ this -> cacheList [ $ configPath ] ; }
Get ConfigCache fot config files
2,287
public static function showProgressBar ( $ percentage , int $ numDecimalPlaces ) { $ percentageStringLength = 4 ; if ( $ numDecimalPlaces > 0 ) { $ percentageStringLength += ( $ numDecimalPlaces + 1 ) ; } $ percentageString = number_format ( $ percentage , $ numDecimalPlaces ) . '%' ; $ percentageString = str_pad ( $ percentageString , $ percentageStringLength , " " , STR_PAD_LEFT ) ; $ percentageStringLength += 3 ; $ terminalWidth = `tput cols` ; $ barWidth = $ terminalWidth - ( $ percentageStringLength ) - 2 ; $ numBars = round ( ( $ percentage ) / 100 * ( $ barWidth ) ) ; $ numEmptyBars = $ barWidth - $ numBars ; $ barsString = '[' . str_repeat ( "=" , ( $ numBars ) ) . str_repeat ( " " , ( $ numEmptyBars ) ) . ']' ; echo "($percentageString) " . $ barsString . "\r" ; }
Display a progress bar in the CLI . This will dynamically take up the full width of the terminal and if you keep calling this function it will appear animated as the progress bar keeps writing over the top of itself .
2,288
protected function _checkInclude ( $ include ) { $ request = Request :: instance ( ) ; if ( isset ( $ include [ 'no' ] ) ) { if ( in_array ( '.' . $ request -> src , $ include [ 'no' ] ) || in_array ( '.' . $ request -> src . '.' . $ request -> controller , $ include [ 'no' ] ) || in_array ( '.' . $ request -> src . '.' . $ request -> controller . '.' . $ request -> action , $ include [ 'no' ] ) || in_array ( '.' . $ request -> controller , $ include [ 'no' ] ) || in_array ( '.' . $ request -> controller . '.' . $ request -> action , $ include [ 'no' ] ) ) { return false ; } else { return true ; } } if ( isset ( $ include [ 'yes' ] ) ) { if ( in_array ( '.' . $ request -> src , $ include [ 'yes' ] ) || in_array ( '.' . $ request -> src . '.' . $ request -> controller , $ include [ 'yes' ] ) || in_array ( '.' . $ request -> src . '.' . $ request -> controller . '.' . $ request -> action , $ include [ 'yes' ] ) || in_array ( '.' . $ request -> controller , $ include [ 'yes' ] ) || in_array ( '.' . $ request -> controller . '.' . $ request -> action , $ include [ 'yes' ] ) ) { return true ; } else { return false ; } } return true ; }
check if the library can be included
2,289
public function quote ( $ value , $ type = DB :: PARAM_AUTO ) { if ( is_array ( $ value ) ) return sprintf ( '(%s)' , implode ( ', ' , array_map ( function ( $ v ) use ( $ this , $ type ) { return $ this -> quote ( $ v , $ type ) ; } , $ value ) ) ) ; $ type = ( $ type == DB :: PARAM_AUTO ) ? $ this -> quotedType ( $ value ) : $ type ; switch ( $ type ) { case DB :: PARAM_STR : $ value = $ this -> escapeString ( $ value ) ; break ; case DB :: PARAM_DATE : case DB :: PARAM_TIME : case DB :: PARAM_DATETIME : switch ( $ type ) { case DB :: PARAM_DATE : $ format = 'Y-m-d' ; break ; case DB :: PARAM_TIME : $ format = 'H:i:s' ; break ; default : $ format = 'Y-m-d H:i:s' ; } if ( interface_exists ( '\\DateTimeInterface' ) and $ value instanceof \ DateTimeInterface or $ value instanceof \ DateTime ) $ value = $ value -> format ( $ format ) ; else { $ dt = date_create ( $ value ) ; if ( $ dt === false ) $ dt = new \ DateTime ; if ( is_int ( $ value ) ) $ dt -> setTimestamp ( $ value ) ; $ value = $ dt -> format ( $ format ) ; } break ; case DB :: PARAM_INT : $ value = intval ( $ value ) ; break ; case DB :: PARAM_BOOL : $ value = $ value ? 1 : 0 ; break ; case DB :: PARAM_FLOAT : $ value = floatval ( $ value ) ; break ; case DB :: PARAM_NULL : $ value = 'NULL' ; break ; default : throw new \ UnexpectedValueException ( 'Invalid parameter value' ) ; } return ( $ type & DB :: PARAM_STR ) ? "'$value'" : $ value ; }
Quote parameter according to type to protect against injections
2,290
public function value ( ) { return substr ( $ this -> path , strlen ( $ this -> path ) - 1 , 1 ) . '|' . $ this -> name . '|' . $ this -> contentType ; }
Which value orm save in the database
2,291
public function save ( ) { if ( $ this -> _oldFile != $ this -> path . $ this -> name ) { unlink ( $ this -> _oldFile ) ; } file_put_contents ( $ this -> path . $ this -> name , $ this -> content ) ; }
Save the file on the HDD
2,292
public function getFilePath ( $ field , $ absolute = false ) { if ( empty ( $ this -> $ field ) || is_file ( $ this -> $ field ) ) { return $ this -> $ field ; } return $ this -> getUploadPath ( $ absolute ) . $ this -> $ field ; }
Gets a file s path
2,293
public function cloneFilesFor ( Entity $ clone ) { foreach ( $ this -> getAsserts ( ) as $ field => $ asserts ) { if ( is_file ( $ this -> $ field ) ) { $ path = $ this -> getUploadPath ( ) ; $ file = $ this -> $ field ; $ extension = @ array_pop ( explode ( '.' , $ file ) ) ; while ( file_exists ( $ path . $ file ) ) { $ file = $ this -> generateFilename ( $ extension ) ; } $ clone -> $ field = $ path . $ file ; copy ( $ this -> $ field , $ clone -> $ field ) ; } } }
Copies this model s files for another model
2,294
protected function moveFile ( UploadedFile $ file ) { $ path = $ this -> getUploadPath ( ) ; $ name = $ this -> generateFilename ( $ path , $ file -> guessExtension ( ) ) ; while ( file_exists ( $ path . $ name ) ) { $ name = $ this -> generateFilename ( $ extension ) ; } $ file -> move ( $ path , $ name ) ; return $ name ; }
Moves a file in its right place with a generated name
2,295
protected function fileUpload ( $ field , UploadedFile $ file ) { $ tempField = '_' . $ field ; $ this -> $ tempField = $ this -> $ field ; $ this -> $ field = $ file ; }
File upload callback Attaches the uploaded file to the model for validation and resizes it according to validation constraints if it is an image
2,296
protected function fileUpdate ( ) { foreach ( $ this -> getAsserts ( ) as $ field => $ asserts ) { if ( $ this -> $ field instanceof UploadedFile ) { $ tempField = '_' . $ field ; $ tempFile = $ this -> getFilePath ( $ tempField , true ) ; is_file ( $ tempFile ) && unlink ( $ tempFile ) ; $ this -> bean -> removeProperty ( $ tempField ) ; $ this -> $ field = $ this -> moveFile ( $ this -> $ field ) ; } } }
RedBean update method Uploads files
2,297
protected function fileDelete ( ) { foreach ( $ this -> getAsserts ( ) as $ field => $ asserts ) { $ file = $ this -> getFilePath ( $ field , true ) ; is_file ( $ file ) && unlink ( $ file ) ; } }
RedBean deletion method Deletes files
2,298
private function generateFilename ( $ path , $ extension ) { $ file = '' ; while ( ! $ file || is_file ( $ path . $ file ) ) { $ file = uniqid ( ) . '.' . $ extension ; } return $ file ; }
Generates unique file name
2,299
protected function setLocation ( ) { if ( ! $ this -> location ) { $ this -> location = $ this -> module . $ this -> theme . $ this -> resourceName ; } }
Set location property when it s null or missing .