idx
int64
0
60.3k
question
stringlengths
92
4.62k
target
stringlengths
7
635
1,300
public static function doInsert ( $ criteria , ConnectionInterface $ con = null ) { if ( null === $ con ) { $ con = Propel :: getServiceContainer ( ) -> getWriteConnection ( KstrukturTableMap :: DATABASE_NAME ) ; } if ( $ criteria instanceof Criteria ) { $ criteria = clone $ criteria ; } else { $ criteria = $ criteria -> buildCriteria ( ) ; } $ query = KstrukturQuery :: create ( ) -> mergeWith ( $ criteria ) ; return $ con -> transaction ( function ( ) use ( $ con , $ query ) { return $ query -> doInsert ( $ con ) ; } ) ; }
Performs an INSERT on the database given a Kstruktur or Criteria object .
1,301
public function recreate ( ) { $ this -> riakCursor = $ this -> collection -> getRiakCollection ( ) -> find ( $ this -> query , $ this -> fields ) ; if ( $ this -> hint !== null ) { $ this -> riakCursor -> hint ( $ this -> hint ) ; } if ( $ this -> immortal !== null ) { $ this -> riakCursor -> immortal ( $ this -> immortal ) ; } foreach ( $ this -> options as $ key => $ value ) { $ this -> riakCursor -> addOption ( $ key , $ value ) ; } if ( $ this -> batchSize !== null ) { $ this -> riakCursor -> batchSize ( $ this -> batchSize ) ; } if ( $ this -> limit !== null ) { $ this -> riakCursor -> limit ( $ this -> limit ) ; } if ( $ this -> skip !== null ) { $ this -> riakCursor -> skip ( $ this -> skip ) ; } if ( $ this -> slaveOkay !== null ) { $ this -> setRiakCursorSlaveOkay ( $ this -> slaveOkay ) ; } if ( $ this -> readPreference !== null ) { if ( $ this -> readPreferenceTags !== null ) { $ this -> riakCursor -> setReadPreference ( $ this -> readPreference , $ this -> readPreferenceTags ) ; } else { $ this -> riakCursor -> setReadPreference ( $ this -> readPreference ) ; } } if ( $ this -> snapshot ) { $ this -> riakCursor -> snapshot ( ) ; } if ( $ this -> sort !== null ) { $ this -> riakCursor -> sort ( $ this -> sort ) ; } if ( $ this -> tailable !== null ) { $ this -> riakCursor -> tailable ( $ this -> tailable ) ; } if ( $ this -> timeout !== null ) { $ this -> riakCursor -> timeout ( $ this -> timeout ) ; } }
Recreates the internal RiakCursor .
1,302
public function toArray ( $ useIdentifierKeys = null ) { $ originalUseIdentifierKeys = $ this -> useIdentifierKeys ; $ useIdentifierKeys = isset ( $ useIdentifierKeys ) ? ( boolean ) $ useIdentifierKeys : $ this -> useIdentifierKeys ; $ cursor = $ this ; $ this -> useIdentifierKeys = true ; $ results = $ this -> retry ( function ( ) use ( $ cursor , $ useIdentifierKeys ) { return iterator_to_array ( $ cursor , $ useIdentifierKeys ) ; } , true ) ; $ this -> useIdentifierKeys = $ originalUseIdentifierKeys ; return $ results ; }
Return the cursor s results as an array .
1,303
public function getModel ( ) { $ Model = $ this -> Model ; $ table = $ this -> model -> getTable ( ) ; return \ VextSchema :: getExtJsModel ( $ table ) ; }
Retrieve model information for ExtJs
1,304
protected function filterQuery ( & $ query , $ filters ) { $ table = $ this -> model -> getTable ( ) ; foreach ( $ filters as $ property => $ value ) { $ type = DB :: connection ( ) -> getDoctrineColumn ( $ table , $ property ) -> getType ( ) -> getName ( ) ; $ property = $ table . '.' . $ property ; if ( str_contains ( $ type , 'time' ) ) { $ start = date ( 'Y-m-d H:i:s' , strtotime ( $ value -> start ) ) ; $ end = date ( 'Y-m-d H:i:s' , strtotime ( $ value -> end ) ) ; $ query -> whereBetween ( $ property , array ( $ start , $ end ) ) ; } else if ( $ type === 'integer' ) { $ query -> where ( $ property , $ value ) ; } else { $ query -> where ( $ property , 'ilike' , '%' . $ value . '%' ) ; } } return $ query ; }
Sets filters for query
1,305
protected function getKeyFromInput ( ) { $ Model = $ this -> Model ; $ key = $ this -> model -> getKeyName ( ) ; $ id = Input :: get ( $ key ) ; return $ id ; }
Retrieve primary key from client - side data
1,306
public function beforeFilter ( Event $ event ) { parent :: beforeFilter ( $ event ) ; $ this -> Crud -> addListener ( 'Users.Users' , [ 'mailer' => 'Users.User' ] ) ; $ this -> Crud -> mapAction ( 'signup' , [ 'className' => 'CrudUsers.Register' , 'view' => 'Users.signup' , 'saveOptions' => [ 'fieldList' => [ 'username' , 'email' , 'password' ] ] , 'messages' => [ 'success' => [ 'text' => __ ( 'Please check your e-mail to validate your account' ) ] , 'error' => [ 'text' => __ ( 'An error occurred while creating the account' ) ] ] , ] ) ; $ this -> Crud -> mapAction ( 'signin' , [ 'className' => 'CrudUsers.Login' , 'view' => 'Users.signin' , 'messages' => [ 'success' => [ 'text' => __ ( 'Login successful. Please validate your email address.' ) ] , 'error' => [ 'text' => __ ( 'Your username or password is incorrect.' ) ] ] , ] ) ; $ this -> Crud -> mapAction ( 'signout' , [ 'className' => 'CrudUsers.Logout' , 'messages' => [ 'success' => [ 'text' => __ ( 'You are now signed out.' ) ] , ] , ] ) ; $ this -> Crud -> mapAction ( 'sendRecovery' , [ 'className' => 'CrudUsers.ForgotPassword' , ] ) ; $ this -> Crud -> mapAction ( 'changePassword' , [ 'className' => 'CrudUsers.ResetPassword' , 'findMethod' => 'token' , ] ) ; $ this -> Crud -> mapAction ( 'verify' , [ 'className' => 'CrudUsers.Verify' , 'findMethod' => 'token' , ] ) ; }
Before filter method
1,307
public static function Trxp ( array $ r , array $ p , array & $ trp ) { $ tr = [ ] ; IAU :: Tr ( $ r , $ tr ) ; IAU :: Rxp ( $ tr , $ p , $ trp ) ; return ; }
- - - - - - - - i a u T r x p - - - - - - - -
1,308
public function render ( ) { if ( ! is_readable ( $ this -> template ) || ! is_file ( $ this -> template ) ) { throw new \ RuntimeException ( 'Cannot read template ' . $ this -> template ) ; } ob_start ( ) ; include $ this -> template ; return ob_get_clean ( ) ; }
Renders template and returns renderer content .
1,309
public function resolvePath ( $ path ) { if ( $ path [ 0 ] == '/' ) { throw new \ InvalidArgumentException ( 'Cannot resolve absolute path.' ) ; } $ segments = $ this -> getPathSegments ( ) ; if ( ! empty ( $ segments ) ) { array_pop ( $ segments ) ; } $ path = trim ( $ path , '/' ) ; foreach ( explode ( '/' , trim ( $ path , '/' ) ) as $ segment ) { if ( $ segment == '.' ) { continue ; } elseif ( $ segment == '..' && ! empty ( $ segments ) && end ( $ segments ) != '..' ) { array_pop ( $ segments ) ; } else { $ segments [ ] = $ segment ; } } return implode ( '/' , $ segments ) ; }
Resolves a relative path based on the path of this resource .
1,310
public static function satisfies ( $ required_version , $ operator = '>=' ) { $ current_version = self :: woo_version ( ) ; return ( bool ) version_compare ( $ current_version , $ required_version , $ operator ) ; }
Test version compatibility
1,311
public static function check_dependency ( $ plugin_file_array ) { $ plugins = ( array ) get_option ( 'active_plugins' ) ; foreach ( ( array ) $ plugin_file_array as $ file ) { $ found = false ; foreach ( $ plugins as $ plugin ) { if ( false !== strpos ( $ plugin , $ file ) ) { $ found = true ; break ; } } if ( ! $ found ) { return false ; } } return true ; }
Check dependency for active plugins .
1,312
public static function property ( $ property = null ) { $ property = strtolower ( $ property ) ; return array_key_exists ( $ property , static :: $ properties ) ? static :: $ properties [ $ property ] : null ; }
Get any browser property
1,313
protected static function get_from_browscap ( ) { $ cache = \ Cache :: forge ( static :: $ config [ 'cache' ] [ 'identifier' ] . '.browscap' , static :: $ config [ 'cache' ] [ 'driver' ] ) ; try { $ browscap = $ cache -> get ( ) ; } catch ( \ Exception $ e ) { $ browscap = static :: $ config [ 'browscap' ] [ 'enabled' ] ? static :: parse_browscap ( ) : array ( ) ; } $ search = array ( '\*' , '\?' ) ; $ replace = array ( '.*' , '.' ) ; $ result = false ; foreach ( $ browscap as $ browser => $ properties ) { $ pattern = '@^' . str_replace ( $ search , $ replace , preg_quote ( $ browser , '@' ) ) . '$@i' ; if ( preg_match ( $ pattern , static :: $ user_agent ) ) { $ properties [ 'browser' ] = $ browser ; if ( array_key_exists ( 'Parent' , $ properties ) ) { if ( $ properties [ 'Parent' ] > 0 ) { $ parent = array_slice ( $ browscap , $ properties [ 'Parent' ] , 1 ) ; unset ( $ properties [ 'Parent' ] ) ; $ properties = array_merge ( current ( $ parent ) , $ properties ) ; $ properties [ 'browser' ] = key ( $ parent ) ; } } $ properties = \ Arr :: replace_key ( $ properties , array_flip ( static :: $ keys ) ) ; $ result = array_merge ( static :: $ properties , $ properties ) ; break ; } } return $ result ; }
use the parsed php_browscap . ini file to find a user agent match
1,314
public function loadClass ( $ className ) { try { $ bFile = strtolower ( $ className ) ; if ( ! empty ( $ this -> classes [ $ bFile ] ) ) { $ path = null ; $ path = $ this -> classes [ $ bFile ] ; require_once $ path ; if ( ! class_exists ( $ className , false ) && ! interface_exists ( $ className , false ) ) { throw new \ Exception ( 'Wrong use of Autoloads, the class "' . $ className . '" should be declared in the given file "' . $ path . '". Please use Class Loader correctly.' ) ; } } } catch ( Exception $ e ) { log_error ( $ e , 'loading_class_' . $ className ) ; } }
Load class file
1,315
public function setClass ( $ className , $ classPath ) { $ className = strtolower ( $ className ) ; $ path = null ; if ( existsPathOf ( LIBSDIR . $ classPath . '/' . $ className . '.php' , $ path ) || existsPathOf ( LIBSDIR . $ classPath . '.php' , $ path ) || existsPathOf ( LIBSDIR . $ classPath . '_class.php' , $ path ) || existsPathOf ( LIBSDIR . $ classPath , $ path ) ) { $ this -> classes [ $ className ] = $ path ; } else { throw new \ Exception ( "ClassLoader : File \"{$classPath}\" of class \"{$className}\" not found." ) ; } return true ; }
Set the file path to the class
1,316
public static function set ( ClassLoader $ loader ) { if ( static :: $ loader ) { static :: $ loader -> unregister ( ) ; } static :: $ loader = $ loader ; if ( static :: $ loader ) { static :: $ loader -> register ( true ) ; } }
Set the active autoloader
1,317
public function Base_GetAppSettingsMenuItems_Handler ( $ Sender ) { $ Menu = & $ Sender -> EventArguments [ 'SideMenu' ] ; $ Menu -> AddItem ( 'Forum' , T ( 'Forum' ) ) ; $ Menu -> AddLink ( 'Forum' , T ( 'Tagging' ) , 'settings/tagging' , 'Garden.Settings.Manage' ) ; }
Add the Tagging admin menu option .
1,318
public function DiscussionController_AfterDiscussionBody_Handler ( $ Sender ) { if ( C ( 'Plugins.Tagging.DisableInline' , FALSE ) ) return ; if ( ! property_exists ( $ Sender -> EventArguments [ 'Object' ] , 'CommentID' ) ) { $ DiscussionID = property_exists ( $ Sender , 'DiscussionID' ) ? $ Sender -> DiscussionID : 0 ; if ( ! $ DiscussionID ) return ; $ TagModule = new TagModule ( $ Sender ) ; echo $ TagModule -> InlineDisplay ( ) ; } }
Show tags after discussion body .
1,319
public function DiscussionModel_BeforeSaveDiscussion_Handler ( $ Sender , $ Args ) { $ FormPostValues = GetValue ( 'FormPostValues' , $ Args , array ( ) ) ; $ TagsString = trim ( strtolower ( GetValue ( 'Tags' , $ FormPostValues , '' ) ) ) ; $ NumTagsMax = C ( 'Plugin.Tagging.Max' , 5 ) ; if ( StringIsNullOrEmpty ( $ TagsString ) && C ( 'Plugins.Tagging.Required' ) ) { $ Sender -> Validation -> AddValidationResult ( 'Tags' , 'You must specify at least one tag.' ) ; } else { $ Tags = TagModel :: SplitTags ( $ TagsString ) ; if ( ! TagModel :: ValidateTags ( $ Tags ) ) { $ Sender -> Validation -> AddValidationResult ( 'Tags' , '@' . T ( 'ValidateTag' , 'Tags cannot contain commas.' ) ) ; } elseif ( count ( $ Tags ) > $ NumTagsMax ) { $ Sender -> Validation -> AddValidationResult ( 'Tags' , '@' . sprintf ( T ( 'You can only specify up to %s tags.' ) , $ NumTagsMax ) ) ; } else { } } }
Validate tags when saving a discussion .
1,320
public function PluginController_TagSearch_Create ( $ Sender , $ q , $ id = false ) { $ CategorySearch = C ( 'Plugins.Tagging.CategorySearch' , FALSE ) ; if ( $ CategorySearch ) $ CategoryID = GetIncomingValue ( 'CategoryID' ) ; $ Query = $ q ; $ Data = array ( ) ; $ Database = Gdn :: Database ( ) ; if ( $ Query ) { $ Test = Gdn :: SQL ( ) -> Limit ( 1 ) -> Get ( 'Tag' ) -> FirstRow ( DATASET_TYPE_ARRAY ) ; if ( isset ( $ Test [ 'Type' ] ) ) { Gdn :: SQL ( ) -> Where ( "nullif(Type, '') is null" ) ; } $ TagQuery = Gdn :: SQL ( ) -> Select ( 'TagID, Name' ) -> From ( 'Tag' ) -> Like ( 'Name' , str_replace ( array ( '%' , '_' ) , array ( '\%' , '_' ) , $ Query ) , strlen ( $ Query ) > 2 ? 'both' : 'right' ) -> Limit ( 20 ) ; if ( $ CategorySearch ) $ TagQuery -> Where ( 'CategoryID' , $ CategoryID ) ; $ TagData = $ TagQuery -> Get ( ) ; foreach ( $ TagData as $ Tag ) { $ Data [ ] = array ( 'id' => $ id ? $ Tag -> TagID : $ Tag -> Name , 'name' => $ Tag -> Name ) ; } } $ Database -> CloseConnection ( ) ; header ( "Content-type: application/json" ) ; echo json_encode ( $ Data ) ; exit ( ) ; }
Search results for tagging autocomplete .
1,321
public function PostController_AfterDiscussionFormOptions_Handler ( $ Sender ) { if ( in_array ( $ Sender -> RequestMethod , array ( 'discussion' , 'editdiscussion' , 'question' ) ) ) { $ TagModel = new TagModel ; $ Tags = $ TagModel -> GetWhere ( array ( 'Type' => NULL ) , 'CountDiscussions' , 'desc' , C ( 'Plugins.Tagging.ShowLimit' , 100 ) ) -> Result ( DATASET_TYPE_ARRAY ) ; $ TagsHtml = ( count ( $ Tags ) ) ? '' : T ( 'No tags have been created yet.' ) ; $ ShowTags = array ( ) ; if ( is_array ( $ Tags ) ) { foreach ( $ Tags as $ Tag ) { $ ShowTags [ ] = $ Tag [ 'Name' ] ; } unset ( $ Tags ) ; asort ( $ ShowTags ) ; } echo '<div class="Form-Tags P">' ; echo $ Sender -> Form -> Label ( 'Tags' , 'Tags' ) ; echo $ Sender -> Form -> TextBox ( 'Tags' , array ( 'maxlength' => 255 ) ) ; echo Wrap ( Anchor ( T ( 'Show popular tags' ) , '#' ) , 'span' , array ( 'class' => 'ShowTags' ) ) ; foreach ( $ ShowTags as $ Tag ) { $ TagsHtml .= Anchor ( $ Tag , '#' , 'AvailableTag' , array ( 'data-name' => $ Tag ) ) . ' ' ; } echo Wrap ( $ TagsHtml , 'div' , array ( 'class' => 'Hidden AvailableTags' ) ) ; echo '</div>' ; } }
Add the tag input to the discussion form .
1,322
public function Controller_Index ( $ Sender ) { $ Sender -> Title ( 'Tagging' ) ; $ Sender -> AddSideMenu ( 'settings/tagging' ) ; $ Sender -> AddCSSFile ( 'plugins/Tagging/design/tagadmin.css' ) ; $ Sender -> AddJSFile ( 'plugins/Tagging/js/admin.js' ) ; $ SQL = Gdn :: SQL ( ) ; $ Sender -> Form -> Method = 'get' ; $ Sender -> Form -> InputPrefix = '' ; list ( $ Offset , $ Limit ) = OffsetLimit ( $ Sender -> Request -> Get ( 'Page' ) , 100 ) ; $ Sender -> SetData ( '_Limit' , $ Limit ) ; if ( $ Search = $ Sender -> Request -> Get ( 'Search' ) ) { $ SQL -> Like ( 'Name' , $ Search , 'right' ) ; } $ Data = $ SQL -> Select ( 't.*' ) -> From ( 'Tag t' ) -> OrderBy ( 't.Name' , 'asc' ) -> OrderBy ( 't.CountDiscussions' , 'desc' ) -> Limit ( $ Limit , $ Offset ) -> Get ( ) -> ResultArray ( ) ; $ Sender -> SetData ( 'Tags' , $ Data ) ; if ( $ Search = $ Sender -> Request -> Get ( 'Search' ) ) { $ SQL -> Like ( 'Name' , $ Search , 'right' ) ; } $ Sender -> SetData ( 'RecordCount' , $ SQL -> GetCount ( 'Tag' ) ) ; $ Sender -> Render ( 'tagging' , '' , 'plugins/Tagging' ) ; }
List all tags and allow searching
1,323
public function Controller_Add ( $ Sender ) { $ Sender -> AddSideMenu ( 'settings/tagging' ) ; $ Sender -> Title ( 'Add Tag' ) ; $ TagModel = new TagModel ; $ Sender -> Form -> SetModel ( $ TagModel ) ; if ( $ Sender -> Form -> AuthenticatedPostBack ( ) ) { $ TagName = $ Sender -> Form -> GetFormValue ( 'Name' ) ; if ( ! TagModel :: ValidateTag ( $ TagName ) ) $ Sender -> Form -> AddError ( '@' . T ( 'ValidateTag' , 'Tags cannot contain commas.' ) ) ; if ( $ TagModel -> GetWhere ( array ( 'Name' => $ TagName ) ) -> NumRows ( ) > 0 ) { $ Sender -> Form -> AddError ( 'The specified tag name is already in use.' ) ; } $ Saved = $ Sender -> Form -> Save ( ) ; if ( $ Saved ) $ Sender -> InformMessage ( T ( 'Your changes have been saved.' ) ) ; } $ Sender -> Render ( 'addedit' , '' , 'plugins/Tagging' ) ; }
Add a Tag
1,324
public function Controller_Edit ( $ Sender ) { $ Sender -> AddSideMenu ( 'settings/tagging' ) ; $ Sender -> Title ( T ( 'Edit Tag' ) ) ; $ TagID = GetValue ( 1 , $ Sender -> RequestArgs ) ; $ TagModel = new TagModel ; $ Sender -> Form -> SetModel ( $ TagModel ) ; $ Tag = $ TagModel -> GetID ( $ TagID ) ; $ Sender -> Form -> SetData ( $ Tag ) ; $ Sender -> Form -> AddHidden ( 'TagID' , $ TagID ) ; if ( $ Sender -> Form -> AuthenticatedPostBack ( ) ) { $ TagData = $ Sender -> Form -> GetFormValue ( 'Name' ) ; if ( ! TagModel :: ValidateTag ( $ TagData ) ) $ Sender -> Form -> AddError ( '@' . T ( 'ValidateTag' , 'Tags cannot contain commas.' ) ) ; if ( $ TagModel -> GetWhere ( array ( 'TagID <>' => $ TagID , 'Name' => $ TagData ) ) -> NumRows ( ) > 0 ) { $ Sender -> SetData ( 'MergeTagVisible' , TRUE ) ; if ( ! $ Sender -> Form -> GetFormValue ( 'MergeTag' ) ) { $ Sender -> Form -> AddError ( 'The specified tag name is already in use.' ) ; } } if ( $ Sender -> Form -> Save ( ) ) $ Sender -> InformMessage ( T ( 'Your changes have been saved.' ) ) ; } $ Sender -> Render ( 'addedit' , '' , 'plugins/Tagging' ) ; }
Edit a Tag
1,325
public function Controller_Delete ( $ Sender ) { $ Sender -> Permission ( 'Garden.Settings.Manage' ) ; $ TagID = GetValue ( 1 , $ Sender -> RequestArgs ) ; $ TagModel = new TagModel ( ) ; $ Tag = $ TagModel -> GetID ( $ TagID , DATASET_TYPE_ARRAY ) ; if ( $ Sender -> Form -> AuthenticatedPostBack ( ) ) { $ SQL = Gdn :: SQL ( ) ; $ SQL -> Delete ( 'TagDiscussion' , array ( 'TagID' => $ TagID ) ) ; $ SQL -> Delete ( 'Tag' , array ( 'TagID' => $ TagID ) ) ; $ Sender -> InformMessage ( FormatString ( T ( '<b>{Name}</b> deleted.' ) , $ Tag ) ) ; $ Sender -> JsonTarget ( "#Tag_{$Tag['TagID']}" , NULL , 'Remove' ) ; } $ Sender -> SetData ( 'Title' , T ( 'Delete Tag' ) ) ; $ Sender -> Render ( 'delete' , '' , 'plugins/Tagging' ) ; }
Delete a Tag
1,326
public function setTypeHandler ( $ type , TypeHandler $ typeHandler ) { if ( ! is_string ( $ type ) || empty ( $ type ) ) throw new \ InvalidArgumentException ( "Type must be defined as a string" ) ; $ this -> typeHandlers [ $ type ] = $ typeHandler ; }
Associates a type handler to a given type
1,327
public function addAlias ( $ type , $ alias ) { if ( ! is_string ( $ type ) || empty ( $ type ) ) throw new \ InvalidArgumentException ( "Type must be defined as a string" ) ; if ( ! is_string ( $ alias ) || empty ( $ alias ) ) throw new \ InvalidArgumentException ( "Alias must be defined as a string" ) ; $ this -> aliases [ $ alias ] = $ type ; }
Stores a new alias for a given type
1,328
public function getTypeHandler ( $ type_or_alias ) { if ( array_key_exists ( $ type_or_alias , $ this -> aliases ) ) $ type_or_alias = $ this -> aliases [ $ type_or_alias ] ; if ( ! array_key_exists ( $ type_or_alias , $ this -> typeHandlers ) ) return false ; return $ this -> typeHandlers [ $ type_or_alias ] ; }
Obtains the type handler assigned to a type
1,329
public function setQueryBuilder ( \ pwf \ components \ querybuilder \ interfaces \ SelectBuilder $ builder ) { $ this -> queryBuilder = $ builder ; return $ this ; }
Set query builder
1,330
public static function cleanFilename ( $ filename , $ replacement = '-' ) { $ filename = str_replace ( "\0" , '' , $ filename ) ; $ filename = preg_replace ( '#[^a-zA-Z0-9._-]+#' , $ replacement , $ filename ) ; if ( strlen ( $ filename ) > 255 ) { $ ext = substr ( $ filename , strrpos ( $ filename , '.' ) ) ; $ name = substr ( $ filename , 0 , 255 - strlen ( $ ext ) ) ; $ filename = $ name . $ ext ; } return $ filename ; }
Cleans a filename and replace special characters
1,331
public static function incrementFilename ( $ path ) { $ i = 1 ; $ dir = dirname ( $ path ) ; $ filename = basename ( $ path ) ; if ( preg_match ( '#^(\d+)-(.*)$#' , basename ( $ path ) , $ matches ) ) { $ i = ( int ) $ matches [ 1 ] ; $ filename = $ matches [ 2 ] ; } do { $ target = rtrim ( $ dir , '/' ) . '/' . self :: cleanFilename ( $ i ++ . '-' . $ filename ) ; } while ( file_exists ( $ target ) ) ; return $ target ; }
Adds or increment a prefixed integer in the path
1,332
public function end ( $ processed = null ) { $ this -> end = ( float ) microtime ( true ) ; $ this -> updateEstimate ( $ processed ) ; }
Call this method immediately after the end of each chunk being processed
1,333
public function interval ( $ interval , $ processed = null ) { $ this -> begin = 0.0 ; $ this -> end = $ interval ; $ this -> updateEstimate ( $ processed ) ; }
Alternative way to set observed time
1,334
protected function updateEstimate ( $ processed = null ) { $ previous = $ processed !== null ? $ processed : $ this -> estimate ; $ time = ( $ this -> end - $ this -> begin ) ; $ observed = $ previous / $ time ; $ this -> average = $ this -> updateExponentialAverage ( $ this -> average , $ observed ) ; $ this -> estimate = ( int ) round ( $ this -> average * $ this -> target , 0 ) ; $ this -> clampEstimate ( ) ; $ this -> logger -> notice ( 'Chunk size update: {p}, {d}/{n}s, {r}/{nr} -> {e} {c}' , [ 'p' => $ previous , 'd' => $ time , 'n' => $ this -> target , 'r' => $ observed , 'nr' => $ previous / $ this -> target , 'e' => $ this -> estimate , 'c' => ( $ this -> clamped ? '(clamped)' : '' ) ] ) ; $ this -> checkPause ( ) ; $ this -> begin = null ; $ this -> end = null ; }
Updates the current estimate of the correct chunk size
1,335
protected function checkPause ( ) { $ this -> paused = false ; if ( $ this -> options [ 'pause_always' ] ) { usleep ( $ this -> options [ 'pause_always' ] ) ; $ this -> paused = true ; } }
Pause if necessary
1,336
protected function clampEstimate ( ) { $ this -> clamped = false ; if ( $ this -> estimate > $ this -> options [ 'max' ] ) { $ this -> clamped = true ; $ this -> estimate = ( int ) $ this -> options [ 'max' ] ; } if ( $ this -> estimate < $ this -> options [ 'min' ] ) { $ this -> clamped = true ; $ this -> estimate = ( int ) $ this -> options [ 'min' ] ; } }
Clamp the current estimate according to the options
1,337
private function getFilesMaxAge ( $ path , $ names = array ( ) , $ default = 0 ) { $ finder = new Finder ( ) ; $ finder -> files ( ) -> in ( realpath ( $ path ) ) -> ignoreDotFiles ( true ) ; foreach ( $ names as $ name ) { $ finder -> name ( $ name ) ; } $ ages = array ( ) ; foreach ( $ finder as $ file ) { $ ages [ ] = filemtime ( $ file ) ; } return max ( array_merge ( $ ages , array ( $ default ) ) ) ; }
Get max_age with a Finder instance
1,338
public function process ( FormInterface $ form , Request $ request ) { if ( $ request -> isMethod ( 'POST' ) ) { $ form -> submit ( $ request ) ; if ( $ form -> isValid ( ) ) { $ this -> bannerManager -> add ( $ form -> getData ( ) ) ; return true ; } } return false ; }
Process banner form .
1,339
private function generateVideoPreview ( HCResources $ resource , string $ storagePath , string $ previewPath ) { $ fullPreviewPath = $ storagePath . 'video-previews/' . $ previewPath ; if ( ! file_exists ( $ fullPreviewPath ) ) mkdir ( $ fullPreviewPath , 0755 , true ) ; $ videoPreview = $ fullPreviewPath . '/preview_frame.jpg' ; if ( ! file_exists ( $ videoPreview ) ) { $ videoPath = $ storagePath . $ resource -> path ; $ ffmpeg = FFMpeg :: create ( [ 'ffmpeg.binaries' => '/usr/bin/ffmpeg' , 'ffprobe.binaries' => '/usr/bin/ffprobe' , 'timeout' => 3600 , 'ffmpeg.threads' => 12 , ] ) ; $ video = $ ffmpeg -> open ( $ storagePath . $ resource -> path ) ; $ duration = $ video -> getFFProbe ( ) -> format ( $ videoPath ) -> get ( 'duration' ) ; $ video -> frame ( TimeCode :: fromSeconds ( rand ( 1 , $ duration ) ) ) -> save ( $ videoPreview ) ; $ resource -> mime_type = 'image/jpg' ; $ resource -> path = $ videoPreview ; } }
generating video preview
1,340
public function regenerateVideoPreview ( string $ id ) { $ resource = HCResources :: findOrFail ( $ id ) ; $ storagePath = storage_path ( 'app/' ) ; $ previewPath = str_replace ( '-' , '/' , $ resource -> id ) ; if ( file_exists ( $ storagePath . 'video-previews/' . $ previewPath ) ) removeDirectory ( $ storagePath . 'video-previews/' . $ previewPath ) ; if ( file_exists ( $ storagePath . 'cache/' . $ previewPath ) ) removeDirectory ( $ storagePath . 'cache/' . $ previewPath ) ; $ this -> generateVideoPreview ( $ resource , $ storagePath , $ previewPath ) ; return [ "success" => true ] ; }
Regenerating video preview
1,341
public function add ( $ conf ) { if ( empty ( $ conf ) ) { return ; } $ this -> config = array_merge ( $ this -> config , $ conf ) ; }
Add configuration to this object
1,342
public function hasSource ( $ source , $ package = null ) { try { return ! ! static :: getFilePath ( $ source , $ package ) ; } catch ( Exception $ e ) { return false ; } }
Check if source is available
1,343
public function load ( $ source , $ cached = true ) { try { $ path = static :: getFilePath ( $ source ) ; if ( class_exists ( '\Orpheus\Cache\FSCache' , true ) ) { $ cache = new \ Orpheus \ Cache \ FSCache ( 'config' , strtr ( $ source , '/\\' , '--' ) , filemtime ( $ path ) ) ; if ( ! static :: $ caching || ! $ cached || ! $ cache -> get ( $ parsed ) ) { $ parsed = static :: parse ( $ path ) ; $ cache -> set ( $ parsed ) ; } } else { $ parsed = static :: parse ( $ path ) ; } $ this -> add ( $ parsed ) ; return true ; } catch ( CacheException $ e ) { log_error ( $ e , 'Caching parsed source ' . $ source , false ) ; } catch ( Exception $ e ) { log_error ( $ e , 'Caching parsed source ' . $ source , false ) ; } return false ; }
Load new configuration from source
1,344
public static function buildFrom ( $ package , $ source , $ cached = true , $ silent = false ) { if ( get_called_class ( ) === get_class ( ) ) { throw new \ Exception ( 'Use a subclass of ' . get_class ( ) . ' to build your configuration' ) ; } $ newConf = new static ( ) ; if ( $ silent && ! $ newConf -> hasSource ( $ source , $ package ) ) { return null ; } $ newConf -> loadFrom ( $ package , $ source , $ cached ) ; return $ newConf ; }
Build new configuration source from package
1,345
public static function build ( $ source , $ minor = false , $ cached = true ) { if ( get_called_class ( ) === get_class ( ) ) { throw new \ Exception ( 'Use a subclass of ' . get_class ( ) . ' to build your configuration' ) ; } if ( ! $ minor ) { if ( ! isset ( static :: $ main ) ) { static :: $ main = new static ( ) ; $ GLOBALS [ 'CONFIG' ] = & static :: $ main ; } static :: $ main -> load ( $ source , $ cached ) ; return static :: $ main ; } $ newConf = new static ( ) ; $ newConf -> load ( $ source , $ cached ) ; return $ newConf ; }
Build new configuration source
1,346
public static function get ( $ key , $ default = null ) { if ( ! isset ( static :: $ main ) ) { return $ default ; } return isset ( static :: $ main -> $ key ) ? static :: $ main -> $ key : $ default ; }
Get configuration from the main configuration object
1,347
public static function getFilePath ( $ source , $ package = null ) { if ( is_readable ( $ source ) ) { return $ source ; } $ configFile = $ source . '.' . static :: $ extension ; $ path = null ; if ( $ package ) { $ path = VENDORPATH . $ package . '/' . CONFDIR . $ configFile ; } else { foreach ( static :: $ repositories as $ repos ) { if ( is_readable ( $ repos . $ configFile ) ) { $ path = $ repos . $ configFile ; } } if ( ! $ path ) { $ path = pathOf ( CONFDIR . $ configFile , true ) ; } } if ( ! $ path || ! is_file ( $ path ) || ! is_readable ( $ path ) ) { throw new \ Exception ( 'Unable to find config source "' . $ source . '"' ) ; } return $ path ; }
Get the file path
1,348
public function date ( $ date , $ format = null ) { $ datetime = DateTimeUtil :: getDateTime ( $ date ) ; if ( empty ( $ format ) ) { $ format = $ this -> cfg [ 'date_format' ] ; } if ( $ format == 'rel' ) { $ date = DateTimeUtil :: getRelTime ( $ datetime ) ; } else { $ date = $ datetime -> format ( $ format ) ; } return $ date ; }
return a formatted date
1,349
public function dollar ( $ str ) { $ this -> debug -> groupCollapsed ( __CLASS__ . '->' . __FUNCTION__ , $ str ) ; $ str = preg_replace ( '/[^\d.-]/' , '' , $ str ) ; $ num = floatval ( $ str ) ; $ str = '$' . number_format ( $ num , 2 ) ; $ this -> debug -> groupEnd ( ) ; return $ str ; }
return a formatted dollar ammount
1,350
public function mask ( $ string , $ repeat = true , $ numShow = 4 , $ maskChar = 'x' ) { if ( strlen ( $ string ) > $ numShow ) { $ string = ( $ repeat ? str_repeat ( $ maskChar , strlen ( $ string ) - $ numShow ) : $ maskChar ) . substr ( $ string , - $ numShow ) ; } return $ string ; }
Mask a string such as an account or cc - num
1,351
public function configure ( Configuration $ configuration ) { foreach ( $ this -> nsMap as $ type => $ map ) { if ( ! count ( $ map ) ) { continue ; } $ method = 'get' . ucfirst ( $ type ) . 'NamespacesMap' ; if ( ! method_exists ( $ configuration , $ method ) ) { throw new InvalidArgumentException ( 'Invalid type of structure namespaces map: ' . $ type ) ; } $ nsMap = $ configuration -> $ method ( ) ; $ nsMap -> add ( $ map ) ; } }
Apply namespaces map configuration to given structures configuration object
1,352
protected function setupConfig ( ) { $ path = realpath ( __DIR__ . "/../../config/gravatar-helper.php" ) ; $ this -> publishes ( [ $ path => config_path ( "gravatar-helper.php" ) ] ) ; $ this -> mergeConfigFrom ( $ path , 'gravatar-helper' ) ; }
Setup the package config .
1,353
public function setUnixSocket ( ? string $ socket ) : MySQL { if ( ! $ this -> _supportedAttributes -> get ( 'unix_socket' ) -> validateValue ( $ socket ) ) { throw new ArgumentException ( 'socket' , $ socket , 'Invalid unix socket!' ) ; } $ this -> _attributes [ 'unix_socket' ] = $ socket ; return $ this ; }
Sets the unix socket . If you want to use it do not define a host!
1,354
public function setCharset ( string $ charset = 'UTF8' ) : MySQL { if ( ! $ this -> _supportedAttributes -> get ( 'charset' ) -> validateValue ( $ charset ) ) { throw new ArgumentException ( 'charset' , $ charset , 'Invalid charset!' ) ; } $ this -> _attributes [ 'charset' ] = $ charset ; return $ this ; }
Sets the connection charset .
1,355
public function setAuthUserName ( ? string $ user ) : MySQL { if ( ! $ this -> _supportedAttributes -> get ( 'user' ) -> validateValue ( $ user ) ) { throw new ArgumentException ( 'user' , \ str_repeat ( '*' , min ( 64 , \ mb_strlen ( $ user , 'utf-8' ) ) ) , 'Invalid auth user!' ) ; } $ this -> _attributes [ 'user' ] = $ user ; return $ this ; }
Sets the auth DBMS login user name .
1,356
public function setAuthPassword ( ? string $ password ) : MySQL { if ( ! $ this -> _supportedAttributes -> get ( 'password' ) -> validateValue ( $ password ) ) { throw new ArgumentException ( 'password' , \ str_repeat ( '*' , min ( 48 , \ mb_strlen ( $ password , 'utf-8' ) ) ) , 'Invalid auth password!' ) ; } $ this -> _attributes [ 'password' ] = $ password ; return $ this ; }
Sets the auth DBMS login password .
1,357
public function execute ( InputInterface $ input , OutputInterface $ output ) { $ assetsDirectory = str_replace ( '/' , DIRECTORY_SEPARATOR , 'web/bundles' ) ; $ manager = $ this -> getDocumentManager ( ) ; $ assetFactory = $ this -> getAssetFactory ( ) ; if ( $ input -> getOption ( 'clear' ) ) { $ output -> writeln ( 'Clearing assets from the content repository. This should NEVER be used in a production environment unless you know what you\'re doing!' ) ; if ( $ assetNode = $ manager -> find ( null , '/asset' ) ) { $ manager -> remove ( $ assetNode ) ; $ manager -> flush ( ) ; $ manager -> clear ( ) ; } } $ batchSize = ( int ) $ input -> getOption ( 'batchSize' ) ? : self :: $ defaultBatchSize ; $ assetFileArray = $ this -> getAssetFileArray ( $ assetsDirectory ) ; if ( count ( $ assetFileArray ) === 0 ) { $ output -> writeln ( 'No assets to move, please run the assets:install command first.' ) ; return 1 ; } $ output -> writeln ( 'Moving assets into content repository...' ) ; $ progress = new ProgressBar ( $ output , count ( $ assetFileArray ) ) ; $ progress -> setFormat ( 'verbose' ) ; $ progress -> start ( ) ; foreach ( array_chunk ( $ assetFileArray , $ batchSize ) as $ chunk ) { foreach ( $ chunk as $ fileArr ) { $ file = $ fileArr [ 'file' ] ; $ linkedLocation = $ fileArr [ 'linkedLocation' ] ; $ parentPath = $ file -> getPath ( ) ; if ( $ linkedLocation ) { $ needle = DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR ; $ pos = strpos ( $ parentPath , $ needle ) ; $ parentPath = $ linkedLocation . DIRECTORY_SEPARATOR . substr ( $ parentPath , $ pos + strlen ( $ needle ) ) ; } $ parentPath = str_replace ( $ assetsDirectory . DIRECTORY_SEPARATOR , '' , $ parentPath ) ; $ parentPath = str_replace ( '\\' , '/' , $ parentPath ) ; $ parentNode = $ this -> findOrCreateNode ( 'asset/' . $ parentPath ) ; $ asset = $ assetFactory -> create ( $ file ) ; $ asset -> copyContentFromFile ( $ file ) -> setParentDocument ( $ parentNode ) -> setNodename ( $ file -> getBasename ( ) ) ; $ manager -> persist ( $ asset ) ; $ progress -> advance ( ) ; } $ manager -> flush ( ) ; $ manager -> clear ( ) ; } $ this -> deleteDirectoryContents ( $ assetsDirectory ) ; $ progress -> finish ( ) ; $ output -> writeln ( "\nFinished!" ) ; return 0 ; }
Moves assets into the content repository
1,358
public function findOrCreateNode ( $ path ) { if ( $ node = $ this -> getDocumentManager ( ) -> find ( null , $ path ) ) { return $ node ; } NodeHelper :: createPath ( $ this -> getDocumentManager ( ) -> getPhpcrSession ( ) , $ path ) ; return $ this -> findOrCreateNode ( $ path ) ; }
Finds or creates a node
1,359
public function deleteDirectoryContents ( $ path ) { $ dir = new \ RecursiveDirectoryIterator ( $ path ) ; $ iterator = new \ RecursiveIteratorIterator ( $ dir , \ RecursiveIteratorIterator :: CHILD_FIRST ) ; foreach ( $ iterator as $ object ) { if ( ! in_array ( $ object -> getBasename ( ) , [ '.' , '..' ] ) ) { if ( $ object -> isLink ( ) || $ object -> isFile ( ) ) { unlink ( $ object -> getPathname ( ) ) ; } else if ( $ object -> isDir ( ) ) { rmdir ( $ object -> getPathname ( ) ) ; } } } }
Deletes a directories contents
1,360
public function resolve ( $ value , $ default = 'value' ) { $ callable = $ this -> getCallable ( $ value ) ; if ( is_array ( $ callable ) && is_callable ( $ callable [ 0 ] ) ) { if ( count ( $ callable ) === 1 ) { return call_user_func ( $ callable [ 0 ] ) ; } else { return call_user_func_array ( $ callable [ 0 ] , $ callable [ 1 ] ) ; } } return $ default === 'value' ? $ value : $ default ; }
Attempts to resolve the value using callables
1,361
public function fullName ( $ lastNameFirst = false ) { if ( ! Wasabi :: setting ( 'Core.User.has_firstname_lastname' ) ) { return $ this -> username ; } if ( $ lastNameFirst ) { return $ this -> lastname . ', ' . $ this -> firstname ; } return $ this -> firstname . ' ' . $ this -> lastname ; }
Get the full name of the user .
1,362
public function getGroupNames ( ) { if ( empty ( $ this -> groups ) ) { return [ ] ; } $ result = [ ] ; foreach ( $ this -> groups as $ group ) { $ result [ ] = $ group -> name ; } return $ result ; }
Get an array of group names the user belongs to .
1,363
public function getAccessLevel ( $ url = null ) { if ( $ url === null ) { $ url = Wasabi :: getCurrentUrlArray ( ) ; } $ path = guardian ( ) -> getPathFromUrl ( $ url ) ; if ( ! array_key_exists ( $ path , $ this -> permissions ) ) { return 0 ; } return $ this -> permissions [ $ path ] ; }
Returns the access level of the user for the given plugin controller action path .
1,364
protected function migrate ( Component $ component ) { $ path = str_replace ( base_path ( ) , '' , ( new Migrator ( $ component ) ) -> getPath ( ) ) ; $ this -> call ( 'migrate' , [ '--path' => $ path , '--database' => $ this -> option ( 'database' ) , '--pretend' => $ this -> option ( 'pretend' ) , '--force' => $ this -> option ( 'force' ) , ] ) ; if ( $ this -> option ( 'seed' ) ) { $ this -> call ( 'component:seed' , [ 'component' => $ component -> getName ( ) ] ) ; } }
Run the migration from the specified component .
1,365
public function register ( $ binding ) { $ finder = new FileFinder ( new Filesystem , $ this -> container [ 'config' ] [ 'view.paths.style' ] ) ; $ finder -> addExtension ( 'yml' ) ; $ this -> container -> bind ( 'view.viewfinder' , new FileFinder ( new Filesystem , $ this -> container [ 'config' ] [ 'view.paths.view' ] ) ) ; $ this -> container -> bind ( 'view.stylefinder' , $ finder ) ; $ this -> container -> bind ( 'view.styleparser' , 'Encore\View\Parser\Style\Yaml' ) ; $ this -> container -> bind ( 'view' , function ( ) { return new Manager ( $ this -> container [ 'view.viewfinder' ] , $ this -> container [ 'view.viewparser' ] , $ this -> container [ 'view.stylefinder' ] , $ this -> container [ 'view.styleparser' ] ) ; } ) ; }
Register bindings into the container
1,366
private function getEntityIdentifierValue ( $ entity ) { $ entityMetaData = $ this -> entityManager -> getEntityMetadataRegister ( ) -> getEntityMetadata ( $ entity ) ; return $ entityMetaData ? $ entityMetaData -> getIdentifierValue ( ) : null ; }
if identifier value does not exist null is now returned to prevent error
1,367
public function exception ( Throwable $ error , $ extra = [ ] ) { $ messages = $ error -> getMessage ( ) ; $ traces = $ error -> getTrace ( ) ; $ serverInfo = $ this -> getServerInfo ( ) ; $ backtrace = [ ] ; if ( is_array ( $ traces ) ) { foreach ( $ traces as $ line ) { if ( ! isset ( $ line [ 'file' ] ) ) { $ line [ 'file' ] = 'unlisted file' ; } if ( ! isset ( $ line [ 'line' ] ) ) { $ line [ 'line' ] = 'unlisted' ; } $ backtrace [ ] = $ line [ 'file' ] ; $ backtrace [ ] = 'line::' . $ line [ 'line' ] ; if ( isset ( $ line [ 'class' ] ) ) { $ backtrace [ ] = sprintf ( '%s::%s' , $ line [ 'class' ] , $ line [ 'function' ] ) ; } if ( ! empty ( $ line [ 'args' ] ) ) { $ lineArgs = $ line [ 'args' ] ; $ args = [ ] ; foreach ( $ lineArgs as $ i => $ arg ) { $ args [ ] = $ i . ' ->' . $ this -> typeToString ( $ arg ) ; } $ backtrace [ ] = 'Args::' . implode ( ', ' , $ args ) ; } else { $ backtrace [ ] = 'Args::None' ; } $ backtrace [ ] = '' ; } } $ backtrace = implode ( "\n" , $ backtrace ) ; $ errorDetails = [ 1 => $ messages , 2 => $ messages . $ serverInfo , 3 => $ messages . $ serverInfo . $ backtrace ] ; $ this -> log ( self :: ERR , $ errorDetails , $ extra ) ; return $ this ; }
Log an exception triggered by ZF2 for administrative purposes .
1,368
protected function typeToString ( $ type ) { if ( is_object ( $ type ) ) { return sprintf ( 'Object::%s' , get_class ( $ type ) ) ; } if ( is_array ( $ type ) ) { $ types = [ ] ; foreach ( $ type as $ key => $ item ) { $ types [ ] = sprintf ( '%s => %s' , $ key , $ this -> typeToString ( $ item ) ) ; } return 'Array(' . implode ( ', ' , $ types ) . ')' ; } if ( is_bool ( $ type ) ) { return sprintf ( 'Boolean::%s' , $ type ? 'True' : 'False' ) ; } if ( is_int ( $ type ) || is_float ( $ type ) ) { return sprintf ( 'Integer::%s' , ( string ) $ type ) ; } if ( $ type === null ) { return 'null' ; } return "'$type'" ; }
Convert type data to a string .
1,369
protected function getPlugins ( array $ config ) { if ( ! isset ( $ config [ 'plugins' ] ) || ! is_array ( $ config [ 'plugins' ] ) ) { throw new \ RuntimeException ( 'Configuration must contain "plugins" key referencing an array' , self :: ERR_PLUGINS_NONARRAY ) ; } $ filtered = array_filter ( $ config [ 'plugins' ] , function ( $ plugin ) { return ! $ plugin instanceof PluginInterface ; } ) ; if ( $ filtered ) { throw new \ RuntimeException ( 'Configuration "plugins" key must contain only objects' . ' implementing \Phergie\Irc\Bot\React\PluginInterface' , self :: ERR_PLUGINS_NONPLUGINS ) ; } return $ config [ 'plugins' ] ; }
Validates and extracts plugins from configuration .
1,370
protected function getFilter ( array $ config ) { if ( ! isset ( $ config [ 'filter' ] ) || ! $ config [ 'filter' ] instanceof FilterInterface ) { throw new \ RuntimeException ( 'Configuration must contain a "filter" key referencing an object' . ' implementing \Phergie\Irc\Plugin\EventFilter\FilterInterface' , self :: ERR_FILTER_INVALID ) ; } return $ config [ 'filter' ] ; }
Validates and extracts filter from configuration .
1,371
public function getSubscribedEvents ( ) { $ events = array ( ) ; $ self = $ this ; foreach ( $ this -> plugins as $ plugin ) { foreach ( array_keys ( $ plugin -> getSubscribedEvents ( ) ) as $ event ) { if ( isset ( $ events [ $ event ] ) ) { continue ; } $ events [ $ event ] = function ( ) use ( $ event , $ self ) { $ self -> handleEvent ( $ event , func_get_args ( ) ) ; } ; } } return $ events ; }
Returns callbacks that invoke a central handler for events to which contained plugins subscribe .
1,372
public function handleEvent ( $ event , array $ args ) { $ logger = $ this -> getLogger ( ) ; $ eventObjects = array_filter ( $ args , function ( $ arg ) { return $ arg instanceof EventInterface ; } ) ; if ( ! $ eventObjects ) { $ logger -> info ( 'Event emitted without EventInterface argument' , array ( 'event' => $ event , 'args' => $ args , ) ) ; } else { $ eventObject = reset ( $ eventObjects ) ; if ( $ this -> filter -> filter ( $ eventObject ) === false ) { $ logger -> info ( 'Event did not pass filter, skipping' , array ( 'event' => $ event , 'args' => $ args , ) ) ; return ; } else { $ logger -> info ( 'Event passed filter, forwarding' , array ( 'event' => $ event , 'args' => $ args , ) ) ; } } $ callbacks = $ this -> getEventHandlers ( $ event ) ; foreach ( $ callbacks as $ callback ) { $ logger -> info ( 'Forwarding event to callback' , array ( 'event' => $ event , 'args' => $ args , 'callback' => $ callback , ) ) ; call_user_func_array ( $ callback , $ args ) ; } }
Applies filters to events and forwards those that pass to contained plugins .
1,373
protected function getEventHandlers ( $ event ) { $ logger = $ this -> getLogger ( ) ; $ handlers = array ( ) ; foreach ( $ this -> plugins as $ plugin ) { $ callbacks = $ plugin -> getSubscribedEvents ( ) ; if ( ! is_array ( $ callbacks ) ) { $ logger -> warning ( 'Plugin returns non-array value for event callbacks' , array ( 'plugin' => get_class ( $ plugin ) , 'callbacks' => $ callbacks , ) ) ; continue ; } if ( ! isset ( $ callbacks [ $ event ] ) ) { $ logger -> debug ( 'Plugin does not handle event' , array ( 'plugin' => get_class ( $ plugin ) , 'event' => $ event , ) ) ; continue ; } $ callback = $ callbacks [ $ event ] ; $ pluginCallback = array ( $ plugin , $ callback ) ; if ( is_callable ( $ pluginCallback ) ) { $ handlers [ ] = $ pluginCallback ; } elseif ( is_callable ( $ callback ) ) { $ handlers [ ] = $ callback ; } else { $ logger -> warning ( 'Plugin returns invalid event callback' , array ( 'plugin' => get_class ( $ plugin ) , 'event' => $ event , 'callback' => $ callback , ) ) ; } } return $ handlers ; }
Returns handlers from contained plugins for a specified event .
1,374
public function setLogger ( LoggerInterface $ logger ) { parent :: setLogger ( $ logger ) ; foreach ( $ this -> plugins as $ plugin ) { if ( ! ( $ plugin instanceof LoggerAwareInterface ) ) { continue ; } $ plugin -> setLogger ( $ logger ) ; } }
Set Logger Interface
1,375
public function setEventEmitter ( EventEmitterInterface $ emitter ) { parent :: setEventEmitter ( $ emitter ) ; foreach ( $ this -> plugins as $ plugin ) { if ( ! ( $ plugin instanceof EventEmitterAwareInterface ) ) { continue ; } $ plugin -> setEventEmitter ( $ emitter ) ; } }
Set Event Emitter Interface
1,376
public function setClient ( ClientInterface $ client ) { parent :: setClient ( $ client ) ; foreach ( $ this -> plugins as $ plugin ) { if ( ! ( $ plugin instanceof ClientAwareInterface ) ) { continue ; } $ plugin -> setClient ( $ client ) ; } }
Set Client Interface
1,377
public function setEventQueueFactory ( EventQueueFactoryInterface $ queueFactory ) { parent :: setEventQueueFactory ( $ queueFactory ) ; foreach ( $ this -> plugins as $ plugin ) { if ( ! ( $ plugin instanceof EventQueueFactoryAwareInterface ) ) { continue ; } $ plugin -> setEventQueueFactory ( $ queueFactory ) ; } }
Set Event Queue Factory
1,378
public function setLoop ( LoopInterface $ loop ) { parent :: setLoop ( $ loop ) ; foreach ( $ this -> plugins as $ plugin ) { if ( ! ( $ plugin instanceof LoopAwareInterface ) ) { continue ; } $ plugin -> setLoop ( $ loop ) ; } }
Set Loop Interface
1,379
protected function getReleaseId ( $ releaseName ) { $ releaseId = null ; $ releaseNames = array ( ) ; $ releases = $ this -> client -> api ( 'repo' ) -> releases ( ) -> all ( $ this -> owner , $ this -> repository ) ; foreach ( $ releases as $ release ) { if ( $ release [ 'name' ] == $ releaseName ) { $ releaseId = $ release [ 'id' ] ; } $ releaseNames [ ] = $ release [ 'name' ] ; } if ( empty ( $ releaseId ) ) { throw new BuildException ( sprintf ( 'Unable to determine release id for name "%s". Valid release names: "%s"' , $ releaseName , implode ( '", "' , $ releaseNames ) ) ) ; } return $ releaseId ; }
Determines the id of a release based on its name .
1,380
protected function filterContentsByType ( $ contents , $ type ) { return Collection :: make ( $ contents ) -> where ( 'type' , $ type ) -> fetch ( 'path' ) -> values ( ) -> all ( ) ; }
Filter directory contents by type .
1,381
public function setStarted ( $ val ) { if ( ( $ val instanceof \ DateTime ) ) { $ this -> started = $ val ; } else if ( is_string ( $ val ) && ! empty ( $ val ) ) { try { $ this -> started = new \ DateTime ( $ val ) ; } catch ( \ Exception $ e ) { $ this -> started = null ; } } else { $ this -> started = null ; } return $ this ; }
Set date time when was the activity started .
1,382
public function setStopped ( $ val ) { if ( ( $ val instanceof \ DateTime ) ) { $ this -> stopped = $ val ; } else if ( is_string ( $ val ) && ! empty ( $ val ) ) { try { $ this -> stopped = new \ DateTime ( $ val ) ; } catch ( \ Exception $ e ) { $ this -> stopped = null ; } } else { $ this -> stopped = null ; } return $ this ; }
Set date time when was the activity stopped .
1,383
public function getDuration ( ) { $ started = ( is_null ( $ this -> started ) ) ? new \ DateTime ( 'now' ) : $ this -> started ; $ stopped = ( is_null ( $ this -> stopped ) ) ? new \ DateTime ( 'now' ) : $ this -> stopped ; return $ started -> diff ( $ stopped ) ; }
Retrieve duration between started and stopped . If stopped is NULL calculates duration up to now .
1,384
public function getDurationFormatted ( ) { $ duration = $ this -> getDuration ( ) ; if ( $ duration -> d == 0 && $ duration -> h == 0 && $ duration -> i == 0 ) { return 'Less than minute' ; } $ ret = '' ; if ( $ duration -> d == 1 ) { $ ret .= 'One day' ; } else if ( $ duration -> d > 1 ) { $ ret .= $ duration -> d . ' days' ; } if ( $ duration -> h == 1 ) { if ( ! empty ( $ ret ) ) { $ ret .= ', one hour' ; } else { $ ret .= 'One hour' ; } } else if ( $ duration -> h > 1 ) { if ( ! empty ( $ ret ) ) { $ ret .= ', ' . $ duration -> h . ' hours' ; } else { $ ret .= $ duration -> h . ' hours' ; } } if ( $ duration -> i == 1 ) { if ( ! empty ( $ ret ) ) { $ ret .= ', one minute' ; } else { $ ret .= 'One minute' ; } } else if ( $ duration -> i > 1 ) { if ( ! empty ( $ ret ) ) { $ ret .= ', ' . $ duration -> i . ' minutes' ; } else { $ ret .= $ duration -> i . ' minutes' ; } } return $ ret ; }
Retrieve duration as formatted string .
1,385
public function isWithinOneDay ( ) { $ started = ( is_null ( $ this -> started ) ) ? new \ DateTime ( 'now' ) : $ this -> started ; $ stopped = ( is_null ( $ this -> stopped ) ) ? new \ DateTime ( 'now' ) : $ this -> stopped ; return ( $ started -> format ( 'Y-m-d' ) === $ stopped -> format ( 'Y-m-d' ) ) ; }
Returns TRUE if activity is started and stopped within one day .
1,386
public function getUrl ( string $ path = null , array $ params = [ ] ) : Uri { $ pathParams = $ this -> getPathParams ( $ params ) ; $ queryParams = $ this -> getQueryParams ( $ params ) ; $ path .= ! empty ( $ pathParams ) ? '/' . $ pathParams : '' ; if ( ! empty ( $ path ) && $ path [ 0 ] !== '/' ) { $ path = '/' . $ path ; } return $ this -> uri -> withPath ( $ path ) -> withQuery ( $ queryParams ) ; }
Performs the path and query parameter processing before returning the final path .
1,387
public function attach ( SplObserver $ observer ) { if ( ! isset ( $ this -> __observers ) ) { $ this -> __observers = new SplObjectStorage ; } $ this -> __observers -> attach ( $ observer ) ; }
Attach an observer model .
1,388
public function detach ( SplObserver $ observer ) { if ( ! isset ( $ this -> __observers ) ) { $ this -> __observers = new SplObjectStorage ; } $ this -> __observers -> detach ( $ observer ) ; }
Detach an observer model .
1,389
public function notify ( ) { if ( ! isset ( $ this -> __observers ) ) { $ this -> __observers = new SplObjectStorage ; } foreach ( $ this -> __observers as $ observer ) { $ observer -> update ( $ this ) ; } }
Notify all registered observers .
1,390
protected function registerListener ( ) { $ this -> registerListenCommand ( ) ; $ this -> app -> singleton ( 'queue.listener' , function ( $ app ) { return new Listener ( $ app -> basePath ( ) ) ; } ) ; }
Register the queue listener .
1,391
public function redirect ( $ url , $ msg = '' , $ msgType = 'message' , $ moved = false ) { if ( trim ( $ msg ) ) { $ this -> enqueueMessage ( $ msg , $ msgType ) ; } if ( count ( $ this -> _messageQueue ) ) { $ session = $ this -> getSession ( ) ; $ session -> set ( 'application.queue' , $ this -> _messageQueue ) ; } $ container = $ this -> getContainer ( ) ; $ profiler = $ container -> has ( 'profiler' ) ? $ container -> get ( 'profiler' ) : false ; if ( $ profiler ) { $ profiler -> mark ( 'redirect' ) ; $ profiler -> dump ( $ this -> get ( 'uri.current' ) ) ; } parent :: redirect ( $ url , $ moved ) ; }
Redirige le navigateur vers une nouvelle adresse .
1,392
protected function doExecute ( ) { $ container = $ this -> getContainer ( ) ; if ( $ container -> has ( 'logger' ) ) { $ this -> setLogger ( $ container -> get ( 'logger' ) ) ; } $ container -> get ( 'config' ) -> merge ( $ this -> config ) ; $ this -> setConfiguration ( $ container -> get ( 'config' ) ) ; $ session = $ container -> get ( 'session' ) ; $ this -> setSession ( $ session ) ; $ this -> sessionCleanUp ( ) ; $ session -> start ( ) ; if ( $ this -> input -> get ( 'stayAlive' , false , 'bool' ) === true ) { echo "1" ; $ this -> close ( ) ; } if ( $ session -> isNew ( ) || $ session -> get ( 'state' ) === null ) { $ session -> set ( 'state' , new Registry ) ; } $ this -> loginWithCookie ( ) ; $ user = $ session -> get ( 'user' ) ; if ( $ user ) { $ language = $ user -> params -> get ( 'language' ) ; $ helper = new LanguageHelper ; if ( $ language && $ helper -> exists ( $ language , JPATH_ROOT ) ) { $ this -> set ( 'language' , $ language ) ; } $ timezone = $ user -> params -> get ( 'timezone' ) ; if ( $ timezone ) { $ this -> set ( 'timezone' , $ timezone ) ; } } @ date_default_timezone_set ( $ this -> get ( 'timezone' , 'Europe/Paris' ) ) ; $ controller = $ this -> route ( ) ; $ this -> checkUserRequireReset ( $ controller ) ; $ this -> _activeController = strtolower ( $ controller -> getName ( ) ) ; try { $ profiler = $ this -> container -> has ( 'profiler' ) ? $ this -> container -> get ( 'profiler' ) : false ; if ( $ profiler ) { $ profiler -> mark ( 'beforeControllerExecute' ) ; } $ result = $ controller -> execute ( ) ; if ( $ profiler ) { $ profiler -> mark ( 'afterControllerExecute' ) ; } $ this -> render ( $ result ) ; } catch ( \ Exception $ e ) { $ this -> raiseError ( $ e -> getMessage ( ) , $ e -> getCode ( ) , $ e ) ; } }
Effectue la logique de l application .
1,393
protected function render ( $ result ) { $ profiler = $ this -> container -> has ( 'profiler' ) ? $ this -> container -> get ( 'profiler' ) : false ; if ( $ profiler ) { $ profiler -> mark ( 'beforeRender' ) ; } if ( is_string ( $ result ) ) { $ this -> mimeType = 'text/html' ; $ data = $ result ; } elseif ( is_object ( $ result ) || is_array ( $ result ) ) { $ r = ( object ) $ result ; $ this -> mimeType = 'application/json' ; if ( property_exists ( $ r , 'status' ) ) { switch ( $ r -> status ) { case 400 : $ status = '400 Bad Request' ; break ; case 401 : $ status = '401 Unauthorized' ; break ; case 403 : $ status = '403 Forbidden' ; break ; case 404 : $ status = '404 Not found' ; break ; case 500 : $ status = '500 Internal Server Error' ; break ; default : $ status = '200 OK' ; break ; } $ this -> setHeader ( 'status' , $ status ) ; if ( is_object ( $ result ) ) { unset ( $ result -> status ) ; } else { unset ( $ result [ 'status' ] ) ; } } $ data = json_encode ( $ result ) ; } else { $ text = ( new LanguageFactory ( ) ) -> getText ( ) ; $ this -> raiseError ( $ text -> translate ( 'APP_ERROR_INVALID_RESULT' ) ) ; } $ this -> setBody ( $ data ) ; if ( $ profiler ) { $ profiler -> mark ( 'afterRender' ) ; } }
Effectue le rendu de l application .
1,394
public function zipAction ( Request $ request ) { $ filename = basename ( $ request -> get ( 'filename' ) ) ; $ path = $ this -> container -> getParameter ( 'phlexible_media_manager.temp_dir' ) ; $ filepath = $ path . '/' . $ filename ; if ( ! $ filename || ! file_exists ( $ filepath ) ) { return $ this -> createNotFoundException ( ) ; } $ response = new BinaryFileResponse ( $ filepath , 200 , array ( 'Content-Type' => 'application/zip' ) ) ; $ response -> setContentDisposition ( ResponseHeaderBag :: DISPOSITION_ATTACHMENT ) ; return $ response ; }
Stream file .
1,395
public function offsetGet ( $ id ) { $ value = parent :: offsetGet ( $ id ) ; if ( is_object ( $ value ) ) { $ this -> initialize ( $ value ) ; } return $ value ; }
Override Pimple s offsetGet to add support for initializers
1,396
public function findDataByNames ( array $ names , array $ modCombinationIds = [ ] ) : array { $ result = [ ] ; if ( count ( $ names ) > 0 ) { $ columns = [ 'm.id AS id' , 'm.name AS name' , 'mc.order AS order' ] ; $ queryBuilder = $ this -> entityManager -> createQueryBuilder ( ) ; $ queryBuilder -> select ( $ columns ) -> from ( Machine :: class , 'm' ) -> innerJoin ( 'm.modCombinations' , 'mc' ) -> andWhere ( 'm.name IN (:names)' ) -> setParameter ( 'names' , array_values ( $ names ) ) ; if ( count ( $ modCombinationIds ) > 0 ) { $ queryBuilder -> andWhere ( 'mc.id IN (:modCombinationIds)' ) -> setParameter ( 'modCombinationIds' , array_values ( $ modCombinationIds ) ) ; } $ result = $ this -> mapMachineDataResult ( $ queryBuilder -> getQuery ( ) -> getResult ( ) ) ; } return $ result ; }
Finds the data of the machines with the specified names .
1,397
protected function mapMachineDataResult ( array $ machineData ) : array { $ result = [ ] ; foreach ( $ machineData as $ data ) { $ result [ ] = MachineData :: createFromArray ( $ data ) ; } return $ result ; }
Maps the query result to instances of MachineData .
1,398
public function removeOrphans ( ) : void { $ machineIds = $ this -> findOrphanedIds ( ) ; if ( count ( $ machineIds ) > 0 ) { $ this -> removeIds ( $ machineIds ) ; } }
Removes any orphaned machines i . e . machines no longer used by any combination .
1,399
protected function removeIds ( array $ machineIds ) : void { $ queryBuilder = $ this -> entityManager -> createQueryBuilder ( ) ; $ queryBuilder -> delete ( Machine :: class , 'm' ) -> andWhere ( 'm.id IN (:machineIds)' ) -> setParameter ( 'machineIds' , array_values ( $ machineIds ) ) ; $ queryBuilder -> getQuery ( ) -> execute ( ) ; }
Removes the machines with the specified ids from the database .