idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
52,100
private function adaptArgument ( Argument $ argument ) { $ mode = null ; if ( $ argument -> isMultiValued ( ) ) { $ mode |= InputArgument :: IS_ARRAY ; } if ( $ argument -> isOptional ( ) ) { $ mode |= InputArgument :: OPTIONAL ; } if ( $ argument -> isRequired ( ) ) { $ mode |= InputArgument :: REQUIRED ; } return new InputArgument ( $ argument -> getName ( ) , $ mode , $ argument -> getDescription ( ) , $ argument -> getDefaultValue ( ) ) ; }
Creates an input argument for the given argument .
52,101
public static function existsAlready ( $ name , Exception $ cause = null ) { return new static ( sprintf ( 'An option named "%s%s" exists already.' , strlen ( $ name ) > 1 ? '--' : '-' , $ name ) , 0 , $ cause ) ; }
Creates an exception for a duplicate option .
52,102
protected function resolve ( string $ handler ) { $ handler = $ this -> split ( $ handler ) ; if ( is_string ( $ handler ) ) { return function_exists ( $ handler ) ? $ handler : $ this -> createClass ( $ handler ) ; } list ( $ class , $ method ) = $ handler ; if ( ( new ReflectionMethod ( $ class , $ method ) ) -> isStatic ( ) ) { return $ handler ; } return [ $ this -> createClass ( $ class ) , $ method ] ; }
Resolves a handler
52,103
protected function createClass ( string $ className ) { if ( ! class_exists ( $ className ) ) { throw new class ( "The class $className does not exists" ) extends Exception implements NotFoundExceptionInterface { } ; } $ reflection = new ReflectionClass ( $ className ) ; if ( $ reflection -> hasMethod ( '__construct' ) ) { return $ reflection -> newInstanceArgs ( $ this -> arguments ) ; } return $ reflection -> newInstance ( ) ; }
Returns the instance of a class .
52,104
public function getHandlerToRun ( Args $ args , IO $ io , Command $ command ) { $ rawArgs = $ args -> getRawArgs ( ) ; if ( ! $ rawArgs ) { return 'text' ; } if ( $ rawArgs -> hasToken ( '-h' ) ) { return 'text' ; } foreach ( $ this -> getRegisteredNames ( ) as $ handlerName ) { if ( $ rawArgs -> hasToken ( '--' . $ handlerName ) ) { return $ handlerName ; } } if ( $ rawArgs -> hasToken ( '--help' ) ) { $ manPage = $ this -> getManPage ( $ command -> getApplication ( ) , $ args ) ; if ( file_exists ( $ manPage ) && $ this -> processLauncher -> isSupported ( ) ) { if ( ! $ this -> manBinary ) { $ this -> manBinary = $ this -> executableFinder -> find ( 'man' ) ; } if ( $ this -> manBinary ) { return 'man' ; } } $ asciiDocPage = $ this -> getAsciiDocPage ( $ command -> getApplication ( ) , $ args ) ; if ( file_exists ( $ asciiDocPage ) ) { return 'ascii-doc' ; } } return 'text' ; }
Callback for selecting the handler that should be run .
52,105
public function setManBinary ( $ manBinary ) { if ( null !== $ manBinary ) { Assert :: string ( $ manBinary , 'The man binary must be a string or null. Got: %s' ) ; Assert :: notEmpty ( $ manBinary , 'The man binary must not be empty.' ) ; } $ this -> manBinary = $ manBinary ; }
Sets the man binary used to display the AsciiDoc pages .
52,106
public function findIn ( $ haystack ) : array { $ matches = [ ] ; call_user_func_array ( $ this -> _method , [ sprintf ( "/%s/%s" , $ this -> _expr , $ this -> _flags ) , $ haystack , & $ matches , $ this -> _pregMatchFlags ? : null , ] ) ; if ( ! isset ( $ matches [ 1 ] ) && isset ( $ matches [ 0 ] ) && is_array ( $ matches [ 0 ] ) ) { return $ matches [ 0 ] ; } return $ matches ; }
execute preg_match return matches
52,107
public function limit ( $ count , $ offset = 0 ) { $ this -> limit = array ( ( int ) $ count , ( int ) $ offset ) ; return $ this ; }
Set a limit on the number of documents returned . An offset from 0 can also be specified .
52,108
public function andWhere ( $ field , $ operator = null , $ value = null ) { $ this -> predicate -> andWhere ( $ field , $ operator , $ value ) ; return $ this ; }
Adds a boolean AND predicate for this query
52,109
public function orWhere ( $ field , $ operator = null , $ value = null ) { $ this -> predicate -> orWhere ( $ field , $ operator , $ value ) ; return $ this ; }
Adds a boolean OR predicate for this query
52,110
public function last ( ) { return ! empty ( $ this -> documents ) ? $ this -> documents [ count ( $ this -> documents ) - 1 ] : false ; }
Gets the last document from the results .
52,111
public function pick ( $ field ) { $ result = array ( ) ; foreach ( $ this -> documents as $ document ) { if ( isset ( $ document -> { $ field } ) ) { $ result [ ] = $ document -> { $ field } ; } } return $ result ; }
Returns an array where each value is a single property from each document . If the property doesnt exist on the document then it won t be in the returned array .
52,112
public function execute ( ) { static $ apcPrefix = null ; if ( $ apcPrefix === null ) { $ apcPrefix = function_exists ( 'apcu_fetch' ) ? 'apcu' : 'apc' ; } $ key = $ this -> getParameterHash ( ) . $ this -> getFileHash ( ) ; $ funcName = $ apcPrefix . '_fetch' ; $ success = false ; $ result = $ funcName ( $ key , $ success ) ; if ( ! $ success ) { $ result = parent :: execute ( ) ; $ funcName = $ apcPrefix . '_store' ; $ funcName ( $ key , $ result ) ; } return $ result ; }
Checks the cache to see if this query exists and returns it . If it s not in the cache then the query is run stored and then returned .
52,113
protected function getParameterHash ( ) { $ parts = array ( $ this -> repo -> getName ( ) , serialize ( ( array ) $ this -> limit ) , serialize ( ( array ) $ this -> orderBy ) , serialize ( ( array ) $ this -> predicate ) , ) ; return md5 ( implode ( '|' , $ parts ) ) ; }
Generates a hash based on the parameters set in the query .
52,114
public function setId ( $ id ) { $ id = ( string ) $ id ; if ( ! isset ( $ this -> __flywheelInitialId ) ) { $ this -> __flywheelInitialId = $ id ; } $ this -> __flywheelDocId = $ id ; return $ id ; }
Set the document ID .
52,115
protected function sort ( array $ array , array $ args ) { $ c = count ( $ args ) ; $ self = $ this ; usort ( $ array , function ( $ a , $ b ) use ( $ self , $ args , $ c ) { $ i = 0 ; $ cmp = 0 ; while ( $ cmp == 0 && $ i < $ c ) { $ keyName = $ args [ $ i ] [ 0 ] ; if ( $ keyName == 'id' || $ keyName == '__id' ) { $ valueA = $ a -> getId ( ) ; $ valueB = $ b -> getId ( ) ; } else { $ valueA = $ self -> getFieldValue ( $ a , $ keyName , $ found ) ; if ( $ found === false ) { $ valueA = null ; } $ valueB = $ self -> getFieldValue ( $ b , $ keyName , $ found ) ; if ( $ found === false ) { $ valueB = null ; } } if ( is_string ( $ valueA ) ) { $ cmp = strcmp ( $ valueA , $ valueB ) ; } elseif ( is_bool ( $ valueA ) ) { $ cmp = $ valueA - $ valueB ; } else { $ cmp = ( $ valueA == $ valueB ) ? 0 : ( ( $ valueA < $ valueB ) ? - 1 : 1 ) ; } if ( $ args [ $ i ] [ 1 ] === SORT_DESC ) { $ cmp *= - 1 ; } $ i ++ ; } return $ cmp ; } ) ; return $ array ; }
Sorts an array of documents by multiple fields if needed .
52,116
public function findAll ( ) { $ ext = $ this -> formatter -> getFileExtension ( ) ; $ files = $ this -> getAllFiles ( ) ; $ documents = array ( ) ; foreach ( $ files as $ file ) { $ fp = fopen ( $ file , 'r' ) ; $ contents = fread ( $ fp , filesize ( $ file ) ) ; fclose ( $ fp ) ; $ data = $ this -> formatter -> decode ( $ contents ) ; if ( null !== $ data ) { $ doc = new $ this -> documentClass ( ( array ) $ data ) ; $ doc -> setId ( $ this -> getIdFromPath ( $ file , $ ext ) ) ; $ documents [ ] = $ doc ; } } return $ documents ; }
Returns all the documents within this repo .
52,117
public function findById ( $ id ) { if ( ! file_exists ( $ path = $ this -> getPathForDocument ( $ id ) ) ) { return false ; } $ fp = fopen ( $ path , 'r' ) ; $ contents = fread ( $ fp , filesize ( $ path ) ) ; fclose ( $ fp ) ; $ data = $ this -> formatter -> decode ( $ contents ) ; if ( $ data === null ) { return false ; } $ ext = $ this -> formatter -> getFileExtension ( ) ; $ doc = new $ this -> documentClass ( ( array ) $ data ) ; $ doc -> setId ( $ this -> getIdFromPath ( $ path , $ ext ) ) ; return $ doc ; }
Returns a single document based on it s ID
52,118
public function store ( DocumentInterface $ document ) { $ id = $ document -> getId ( ) ; if ( is_null ( $ id ) ) { $ id = $ document -> setId ( $ this -> generateId ( ) ) ; } if ( ! $ this -> validateId ( $ id ) ) { throw new \ Exception ( sprintf ( '`%s` is not a valid document ID.' , $ id ) ) ; } $ path = $ this -> getPathForDocument ( $ id ) ; $ data = get_object_vars ( $ document ) ; $ data = $ this -> formatter -> encode ( $ data ) ; if ( ! $ this -> write ( $ path , $ data ) ) { return false ; } return $ id ; }
Store a Document in the repository .
52,119
public function update ( DocumentInterface $ document ) { if ( ! $ document -> getId ( ) ) { return false ; } $ oldPath = $ this -> getPathForDocument ( $ document -> getInitialId ( ) ) ; if ( ! file_exists ( $ oldPath ) ) { return false ; } if ( $ document -> getId ( ) !== $ document -> getInitialId ( ) ) { if ( file_exists ( $ oldPath ) ) { unlink ( $ oldPath ) ; } } return $ this -> store ( $ document ) ; }
Store a Document in the repository but only if it already exists . The document must have an ID .
52,120
public function delete ( $ id ) { if ( $ id instanceof DocumentInterface ) { $ id = $ id -> getId ( ) ; } $ path = $ this -> getPathForDocument ( $ id ) ; return unlink ( $ path ) ; }
Delete a document from the repository using its ID .
52,121
protected function write ( $ path , $ contents ) { $ fp = fopen ( $ path , 'w' ) ; if ( ! flock ( $ fp , LOCK_EX ) ) { return false ; } $ result = fwrite ( $ fp , $ contents ) ; flock ( $ fp , LOCK_UN ) ; fclose ( $ fp ) ; return $ result !== false ; }
Writes data to the filesystem .
52,122
protected function generateId ( ) { static $ choices = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ; $ id = '' ; while ( strlen ( $ id ) < 9 ) { $ id .= $ choices [ mt_rand ( 0 , strlen ( $ choices ) - 1 ) ] ; } return $ id ; }
Generates a random unique ID for a document . The result is returned in base62 . This keeps it shorted but still human readable if shared in URLs .
52,123
public function getUserValue ( $ val ) { if ( '' == $ val ) { return '' ; } if ( $ val instanceof PhpDateTime ) { $ date = $ val ; $ date -> setTimezone ( new DateTimeZone ( $ this -> getSourceTimezone ( ) ) ) ; $ date -> setTimezone ( new DateTimeZone ( $ this -> getOutputTimezone ( ) ) ) ; } else { $ date = PhpDateTime :: createFromFormat ( $ this -> getSourceDateTimeFormat ( ) , $ val , new DateTimeZone ( $ this -> getSourceTimezone ( ) ) ) ; if ( false === $ date ) { return '' ; } $ date -> setTimezone ( new DateTimeZone ( $ this -> getOutputTimezone ( ) ) ) ; } $ formatter = new IntlDateFormatter ( $ this -> getLocale ( ) , $ this -> getOutputDateType ( ) , $ this -> getOutputTimeType ( ) , $ this -> getOutputTimezone ( ) , IntlDateFormatter :: GREGORIAN , $ this -> getOutputPattern ( ) ) ; return $ formatter -> format ( $ date -> getTimestamp ( ) ) ; }
Convert the value from the source to the value which the user will see in the column .
52,124
public function execute ( ) { $ data = $ this -> getData ( ) ; if ( ! empty ( $ this -> getSortConditions ( ) ) ) { $ data = $ this -> sortArrayMultiple ( $ data , $ this -> getSortConditions ( ) ) ; } foreach ( $ this -> getFilters ( ) as $ filter ) { if ( $ filter -> isColumnFilter ( ) === true ) { $ data = array_filter ( $ data , [ new PhpArray \ Filter ( $ filter ) , 'applyFilter' , ] ) ; } } $ selectedColumns = [ ] ; foreach ( $ this -> getColumns ( ) as $ col ) { if ( ! $ col instanceof Column \ Select ) { continue ; } $ colString = $ col -> getSelectPart1 ( ) ; if ( $ col -> getSelectPart2 ( ) != '' ) { $ colString = $ col -> getSelectPart1 ( ) . '_' . $ col -> getSelectPart2 ( ) ; } $ selectedColumns [ ] = $ colString ; } foreach ( $ data as & $ row ) { foreach ( $ row as $ keyRowCol => $ rowCol ) { if ( ! in_array ( $ keyRowCol , $ selectedColumns ) ) { unset ( $ row [ $ keyRowCol ] ) ; } } } $ this -> setPaginatorAdapter ( new PaginatorAdapter ( $ data ) ) ; }
Execute the query and set the paginator - with sort statements - with filters statements .
52,125
private function applyMultiSort ( array $ data , array $ sortArguments ) { $ args = [ ] ; foreach ( $ sortArguments as $ values ) { $ remain = count ( $ values ) % 3 ; if ( $ remain != 0 ) { throw new \ InvalidArgumentException ( 'The parameter count for each sortArgument has to be three. Given count of: ' . count ( $ values ) ) ; } $ args [ ] = $ values [ 0 ] ; $ args [ ] = $ values [ 1 ] ; $ args [ ] = $ values [ 2 ] ; } $ args [ ] = $ data ; $ sortArgs = [ ] ; foreach ( $ args as $ key => & $ value ) { $ sortArgs [ $ key ] = & $ value ; } call_user_func_array ( 'array_multisort' , $ sortArgs ) ; return end ( $ args ) ; }
Multisort an array .
52,126
public function getUserValue ( $ val ) { $ formatter = $ this -> getFormatter ( ) ; $ formattedValue = $ formatter -> format ( $ val , $ this -> getFormatType ( ) ) ; return ( string ) $ this -> getPrefix ( ) . $ formattedValue . $ this -> getSuffix ( ) ; }
Convert the value from the source to the value which the user will see .
52,127
public function createService ( ServiceLocatorInterface $ serviceLocator ) { $ plugins = parent :: createService ( $ serviceLocator ) ; $ plugins -> addPeeringServiceManager ( $ serviceLocator ) ; $ plugins -> setRetrieveFromPeeringManagerFirst ( true ) ; return $ plugins ; }
Create and return the MVC controller plugin manager .
52,128
public function init ( ) { if ( $ this -> getCache ( ) === null ) { $ options = $ this -> getOptions ( ) ; $ this -> setCache ( Cache \ StorageFactory :: factory ( $ options [ 'cache' ] ) ) ; } $ this -> isInit = true ; }
Init method is called automatically with the service creation .
52,129
public function setId ( $ id = null ) { if ( $ id !== null ) { $ id = preg_replace ( "/[^a-z0-9_\\\d]/i" , '_' , $ id ) ; $ this -> id = ( string ) $ id ; } }
Set the grid id .
52,130
public function getSession ( ) { if ( null === $ this -> session ) { $ this -> session = new SessionContainer ( $ this -> getId ( ) ) ; } return $ this -> session ; }
Get session container .
52,131
public function getCacheId ( ) { if ( null === $ this -> cacheId ) { $ this -> cacheId = md5 ( $ this -> getSession ( ) -> getManager ( ) -> getId ( ) . '_' . $ this -> getId ( ) ) ; } return $ this -> cacheId ; }
Get the cache id .
52,132
public function setDataSource ( $ data ) { if ( $ data instanceof DataSource \ DataSourceInterface ) { $ this -> dataSource = $ data ; } elseif ( is_array ( $ data ) ) { $ this -> dataSource = new DataSource \ PhpArray ( $ data ) ; } elseif ( $ data instanceof QueryBuilder ) { $ this -> dataSource = new DataSource \ Doctrine2 ( $ data ) ; } elseif ( $ data instanceof ZendSelect ) { $ args = func_get_args ( ) ; if ( count ( $ args ) === 1 || ( ! $ args [ 1 ] instanceof \ Zend \ Db \ Adapter \ Adapter && ! $ args [ 1 ] instanceof \ Zend \ Db \ Sql \ Sql ) ) { throw new \ InvalidArgumentException ( 'For "Zend\Db\Sql\Select" also a "Zend\Db\Adapter\Sql" or "Zend\Db\Sql\Sql" is needed.' ) ; } $ this -> dataSource = new DataSource \ ZendSelect ( $ data ) ; $ this -> dataSource -> setAdapter ( $ args [ 1 ] ) ; } elseif ( $ data instanceof Collection ) { $ args = func_get_args ( ) ; if ( count ( $ args ) === 1 || ! $ args [ 1 ] instanceof \ Doctrine \ ORM \ EntityManager ) { throw new \ InvalidArgumentException ( 'If providing a Collection, also the Doctrine\ORM\EntityManager is needed as a second parameter' ) ; } $ this -> dataSource = new DataSource \ Doctrine2Collection ( $ data ) ; $ this -> dataSource -> setEntityManager ( $ args [ 1 ] ) ; } else { throw new \ InvalidArgumentException ( '$data must implement the interface ZfcDatagrid\DataSource\DataSourceInterface' ) ; } }
Set the data source .
52,133
public function getExportRenderers ( ) { if ( null === $ this -> exportRenderers ) { $ options = $ this -> getOptions ( ) ; $ this -> exportRenderers = $ options [ 'settings' ] [ 'export' ] [ 'formats' ] ; } return $ this -> exportRenderers ; }
Get the export renderers .
52,134
private function createColumn ( array $ config ) { $ colType = isset ( $ config [ 'colType' ] ) ? $ config [ 'colType' ] : 'Select' ; if ( class_exists ( $ colType , true ) ) { $ class = $ colType ; } elseif ( class_exists ( 'ZfcDatagrid\\Column\\' . $ colType , true ) ) { $ class = 'ZfcDatagrid\\Column\\' . $ colType ; } else { throw new \ InvalidArgumentException ( sprintf ( 'Column type: "%s" not found!' , $ colType ) ) ; } if ( 'ZfcDatagrid\\Column\\Select' == $ class ) { if ( ! isset ( $ config [ 'select' ] [ 'column' ] ) ) { throw new \ InvalidArgumentException ( 'For "ZfcDatagrid\Column\Select" the option select[column] must be defined!' ) ; } $ table = isset ( $ config [ 'select' ] [ 'table' ] ) ? $ config [ 'select' ] [ 'table' ] : null ; $ instance = new $ class ( $ config [ 'select' ] [ 'column' ] , $ table ) ; } else { $ instance = new $ class ( ) ; } foreach ( $ config as $ key => $ value ) { $ method = 'set' . ucfirst ( $ key ) ; if ( method_exists ( $ instance , $ method ) ) { if ( in_array ( $ key , $ this -> specialMethods ) ) { if ( ! is_array ( $ value ) ) { $ value = [ $ value , ] ; } call_user_func_array ( [ $ instance , $ method , ] , $ value ) ; } else { call_user_func ( [ $ instance , $ method , ] , $ value ) ; } } } return $ instance ; }
Create a column from array instanceof .
52,135
public function getRendererName ( ) { $ options = $ this -> getOptions ( ) ; $ parameterName = $ options [ 'generalParameterNames' ] [ 'rendererType' ] ; if ( $ this -> forceRenderer !== null ) { $ rendererName = $ this -> forceRenderer ; } else { if ( $ this -> getRequest ( ) instanceof ConsoleRequest ) { $ rendererName = $ options [ 'settings' ] [ 'default' ] [ 'renderer' ] [ 'console' ] ; } else { $ rendererName = $ options [ 'settings' ] [ 'default' ] [ 'renderer' ] [ 'http' ] ; } } if ( $ this -> getRequest ( ) instanceof HttpRequest && $ this -> getRequest ( ) -> getQuery ( $ parameterName ) != '' ) { $ rendererName = $ this -> getRequest ( ) -> getQuery ( $ parameterName ) ; } return $ rendererName ; }
Get the current renderer name .
52,136
public function getRenderer ( ) { if ( null === $ this -> renderer ) { if ( isset ( $ this -> rendererService ) ) { $ renderer = $ this -> rendererService ; if ( ! $ renderer instanceof Renderer \ AbstractRenderer ) { throw new \ Exception ( 'Renderer service must implement "ZfcDatagrid\Renderer\AbstractRenderer"' ) ; } $ renderer -> setOptions ( $ this -> getOptions ( ) ) ; $ renderer -> setMvcEvent ( $ this -> getMvcEvent ( ) ) ; if ( $ this -> getToolbarTemplate ( ) !== null ) { $ renderer -> setToolbarTemplate ( $ this -> getToolbarTemplate ( ) ) ; } $ renderer -> setToolbarTemplateVariables ( $ this -> getToolbarTemplateVariables ( ) ) ; $ renderer -> setViewModel ( $ this -> getViewModel ( ) ) ; if ( $ this -> hasTranslator ( ) ) { $ renderer -> setTranslator ( $ this -> getTranslator ( ) ) ; } $ renderer -> setTitle ( $ this -> getTitle ( ) ) ; $ renderer -> setColumns ( $ this -> getColumns ( ) ) ; $ renderer -> setRowStyles ( $ this -> getRowStyles ( ) ) ; $ renderer -> setCache ( $ this -> getCache ( ) ) ; $ renderer -> setCacheId ( $ this -> getCacheId ( ) ) ; $ this -> renderer = $ renderer ; } else { throw new \ Exception ( sprintf ( 'Renderer service was not found, please register it: "zfcDatagrid.renderer.%s"' , $ this -> getRendererName ( ) ) ) ; } } return $ this -> renderer ; }
Return the current renderer .
52,137
public function render ( ) { if ( $ this -> isDataLoaded ( ) === false ) { $ this -> loadData ( ) ; } $ renderer = $ this -> getRenderer ( ) ; $ renderer -> setTitle ( $ this -> getTitle ( ) ) ; $ renderer -> setPaginator ( $ this -> getPaginator ( ) ) ; $ renderer -> setData ( $ this -> getPreparedData ( ) ) ; $ renderer -> prepareViewModel ( $ this ) ; $ this -> response = $ renderer -> execute ( ) ; $ this -> isRendered = true ; }
Render the grid .
52,138
public function setViewModel ( ViewModel $ viewModel ) { if ( $ this -> viewModel !== null ) { throw new \ Exception ( 'A viewModel is already set. Did you already called ' . '$grid->render() or $grid->getViewModel() before?' ) ; } $ this -> viewModel = $ viewModel ; }
Set a custom ViewModel ... generally NOT necessary!
52,139
public function setIdentity ( $ mode = true ) { $ this -> isIdentity = ( bool ) $ mode ; $ this -> setHidden ( $ mode ) ; }
Set this column as primaryKey column .
52,140
public function setType ( Type \ AbstractType $ type ) { if ( $ type instanceof Type \ Image && $ this -> hasFormatters ( ) === false ) { $ this -> addFormatter ( new Formatter \ Image ( ) ) ; $ this -> setRowClickDisabled ( true ) ; } $ this -> type = $ type ; }
Set the column type .
52,141
public function setStyles ( array $ styles ) { $ this -> styles = [ ] ; foreach ( $ styles as $ style ) { $ this -> addStyle ( $ style ) ; } }
Set styles .
52,142
public function setReplaceValues ( array $ values , $ notReplacedGetEmpty = true ) { $ this -> replaceValues = $ values ; $ this -> notReplacedGetEmpty = ( bool ) $ notReplacedGetEmpty ; $ this -> setFilterDefaultOperation ( Filter :: EQUAL ) ; $ this -> setFilterSelectOptions ( $ values ) ; }
Replace the column values with the applied values .
52,143
public function getFormattedValue ( AbstractColumn $ column ) { $ row = $ this -> getRowData ( ) ; $ value = $ row [ $ column -> getUniqueId ( ) ] ; if ( '' == $ value ) { return $ value ; } $ index = 0 ; while ( $ value >= 1024 && $ index < count ( self :: $ prefixes ) ) { $ value = $ value / 1024 ; ++ $ index ; } return sprintf ( '%1.2f %sB' , $ value , self :: $ prefixes [ $ index ] ) ; }
The value should be in bytes .
52,144
public function applyFilter ( array $ row ) { $ wasTrueOneTime = false ; $ isApply = false ; foreach ( $ this -> getFilter ( ) -> getValues ( ) as $ filterValue ) { $ filter = $ this -> getFilter ( ) ; $ col = $ filter -> getColumn ( ) ; $ value = $ row [ $ col -> getUniqueId ( ) ] ; $ value = $ col -> getType ( ) -> getFilterValue ( $ value ) ; if ( $ filter -> getOperator ( ) == DatagridFilter :: BETWEEN ) { $ isApply = DatagridFilter :: isApply ( $ value , $ this -> getFilter ( ) -> getValues ( ) , $ filter -> getOperator ( ) ) ; return $ isApply ; } else { $ isApply = DatagridFilter :: isApply ( $ value , $ filterValue , $ filter -> getOperator ( ) ) ; } if ( true === $ isApply ) { $ wasTrueOneTime = true ; } switch ( $ filter -> getOperator ( ) ) { case DatagridFilter :: NOT_LIKE : case DatagridFilter :: NOT_LIKE_LEFT : case DatagridFilter :: NOT_LIKE_RIGHT : case DatagridFilter :: NOT_EQUAL : case DatagridFilter :: NOT_IN : if ( false === $ isApply ) { return false ; } break ; } } if ( false === $ isApply && true === $ wasTrueOneTime ) { return true ; } return $ isApply ; }
Does the value get filtered?
52,145
public function addByValue ( AbstractColumn $ column , $ value , $ operator = Filter :: EQUAL ) { $ this -> byValues [ ] = [ 'column' => $ column , 'value' => $ value , 'operator' => $ operator , ] ; }
Set the style value based and not general .
52,146
public function get ( $ name , $ options = [ ] , $ usePeeringServiceManagers = true ) { $ instance = new $ name ( ) ; $ instance -> createService ( $ this -> getServiceLocator ( ) ) ; return $ instance ; }
Retrieve a service from the manager by name .
52,147
public function getUserValue ( $ value ) { if ( ! is_array ( $ value ) ) { if ( '' == $ value ) { $ value = [ ] ; } else { $ value = explode ( $ this -> getSeparator ( ) , $ value ) ; } } return $ value ; }
Convert a value into an array .
52,148
public function setRgb ( $ red , $ green , $ blue ) { $ this -> red = ( int ) $ red ; $ this -> green = ( int ) $ green ; $ this -> blue = ( int ) $ blue ; }
Set the RGB .
52,149
public function getRgbHexString ( ) { $ red = dechex ( $ this -> getRed ( ) ) ; if ( strlen ( $ red ) === 1 ) { $ red = '0' . $ red ; } $ green = dechex ( $ this -> getGreen ( ) ) ; if ( strlen ( $ green ) === 1 ) { $ green = '0' . $ green ; } $ blue = dechex ( $ this -> getBlue ( ) ) ; if ( strlen ( $ blue ) === 1 ) { $ blue = '0' . $ blue ; } return $ red . $ green . $ blue ; }
Convert RGB dec to hex as a string .
52,150
public function getLinkReplaced ( array $ row ) { $ link = $ this -> getLink ( ) ; if ( strpos ( $ this -> getLink ( ) , self :: ROW_ID_PLACEHOLDER ) !== false ) { $ id = '' ; if ( isset ( $ row [ 'idConcated' ] ) ) { $ id = $ row [ 'idConcated' ] ; } $ link = str_replace ( self :: ROW_ID_PLACEHOLDER , $ id , $ link ) ; } foreach ( $ this -> getLinkColumnPlaceholders ( ) as $ col ) { $ link = str_replace ( ':' . $ col -> getUniqueId ( ) . ':' , $ row [ $ col -> getUniqueId ( ) ] , $ link ) ; } return $ link ; }
This is needed public for rowClickAction ...
52,151
public function addClass ( $ className ) { $ attr = $ this -> getAttribute ( 'class' ) ; if ( $ attr != '' ) { $ attr .= ' ' ; } $ attr .= ( string ) $ className ; $ this -> setAttribute ( 'class' , $ attr ) ; }
Add a css class .
52,152
public function addShowOnValue ( Column \ AbstractColumn $ col , $ value = null , $ comparison = Filter :: EQUAL ) { $ this -> showOnValues [ ] = [ 'column' => $ col , 'value' => $ value , 'comparison' => $ comparison , ] ; }
Show this action only on the values defined .
52,153
public function isDisplayed ( array $ row ) { if ( $ this -> hasShowOnValues ( ) === false ) { return true ; } $ isDisplayed = false ; foreach ( $ this -> getShowOnValues ( ) as $ rule ) { $ value = '' ; if ( isset ( $ row [ $ rule [ 'column' ] -> getUniqueId ( ) ] ) ) { $ value = $ row [ $ rule [ 'column' ] -> getUniqueId ( ) ] ; } if ( $ rule [ 'value' ] instanceof AbstractColumn ) { if ( isset ( $ row [ $ rule [ 'value' ] -> getUniqueId ( ) ] ) ) { $ ruleValue = $ row [ $ rule [ 'value' ] -> getUniqueId ( ) ] ; } else { $ ruleValue = '' ; } } else { $ ruleValue = $ rule [ 'value' ] ; } $ isDisplayedMatch = Filter :: isApply ( $ value , $ ruleValue , $ rule [ 'comparison' ] ) ; if ( $ this -> getShowOnValueOperator ( ) == 'OR' && true === $ isDisplayedMatch ) { return true ; } elseif ( $ this -> getShowOnValueOperator ( ) == 'AND' && false === $ isDisplayedMatch ) { return false ; } else { $ isDisplayed = $ isDisplayedMatch ; } } return $ isDisplayed ; }
Display this action on this row?
52,154
private function useCustomPaginator ( ) { $ qb = $ this -> getQueryBuilder ( ) ; $ parts = $ qb -> getDQLParts ( ) ; if ( $ parts [ 'having' ] !== null || true === $ parts [ 'distinct' ] ) { return false ; } return true ; }
Test which pagination solution to use .
52,155
public function setFromColumn ( Column \ AbstractColumn $ column , $ inputFilterValue ) { $ this -> column = $ column ; $ this -> setColumnOperator ( $ inputFilterValue , $ column -> getFilterDefaultOperation ( ) ) ; }
Apply a filter based on a column .
52,156
protected function setPrinting ( PHPExcel $ phpExcel ) { $ optionsRenderer = $ this -> getOptionsRenderer ( ) ; $ phpExcel -> getProperties ( ) -> setCreator ( 'https://github.com/zfc-datagrid/zfc-datagrid' ) -> setTitle ( $ this -> getTitle ( ) ) ; $ papersize = $ optionsRenderer [ 'papersize' ] ; $ orientation = $ optionsRenderer [ 'orientation' ] ; foreach ( $ phpExcel -> getAllSheets ( ) as $ sheet ) { if ( 'landscape' == $ orientation ) { $ sheet -> getPageSetup ( ) -> setOrientation ( PHPExcel_Worksheet_PageSetup :: ORIENTATION_LANDSCAPE ) ; } else { $ sheet -> getPageSetup ( ) -> setOrientation ( PHPExcel_Worksheet_PageSetup :: ORIENTATION_PORTRAIT ) ; } switch ( $ papersize ) { case 'A5' : $ sheet -> getPageSetup ( ) -> setPaperSize ( PHPExcel_Worksheet_PageSetup :: PAPERSIZE_A5 ) ; break ; case 'A4' : $ sheet -> getPageSetup ( ) -> setPaperSize ( PHPExcel_Worksheet_PageSetup :: PAPERSIZE_A4 ) ; break ; case 'A3' : $ sheet -> getPageSetup ( ) -> setPaperSize ( PHPExcel_Worksheet_PageSetup :: PAPERSIZE_A3 ) ; break ; case 'A2' : $ sheet -> getPageSetup ( ) -> setPaperSize ( PHPExcel_Worksheet_PageSetup :: PAPERSIZE_A2_PAPER ) ; break ; } $ sheet -> getPageMargins ( ) -> setTop ( 0.8 ) ; $ sheet -> getPageMargins ( ) -> setBottom ( 0.5 ) ; $ sheet -> getPageMargins ( ) -> setLeft ( 0.5 ) ; $ sheet -> getPageMargins ( ) -> setRight ( 0.5 ) ; $ this -> setHeaderFooter ( $ sheet ) ; } $ phpExcel -> setActiveSheetIndex ( 0 ) ; }
Set the printing options .
52,157
public function getTemplate ( ) { if ( null === $ this -> template ) { $ this -> template = $ this -> getTemplatePathDefault ( 'layout' ) ; } return $ this -> template ; }
Get the view template name .
52,158
protected function calculateColumnWidthPercent ( array $ columns ) { $ widthAllColumn = 0 ; foreach ( $ columns as $ column ) { $ widthAllColumn += $ column -> getWidth ( ) ; } $ widthSum = 0 ; $ relativeOnePercent = $ widthAllColumn / 100 ; foreach ( $ columns as $ column ) { $ widthSum += ( ( $ column -> getWidth ( ) / $ relativeOnePercent ) ) ; $ column -> setWidth ( ( $ column -> getWidth ( ) / $ relativeOnePercent ) ) ; } }
Calculate the sum of the displayed column width to 100% .
52,159
public function getSortConditionsDefault ( ) { $ sortConditions = [ ] ; foreach ( $ this -> getColumns ( ) as $ column ) { if ( $ column -> hasSortDefault ( ) === true ) { $ sortDefaults = $ column -> getSortDefault ( ) ; $ sortConditions [ $ sortDefaults [ 'priority' ] ] = [ 'column' => $ column , 'sortDirection' => $ sortDefaults [ 'sortDirection' ] , ] ; $ column -> setSortActive ( $ sortDefaults [ 'sortDirection' ] ) ; } } ksort ( $ sortConditions ) ; return $ sortConditions ; }
Get the default sort conditions defined for the columns .
52,160
public function getFiltersDefault ( ) { $ filters = [ ] ; foreach ( $ this -> getColumns ( ) as $ column ) { if ( $ column -> hasFilterDefaultValue ( ) === true ) { $ filter = new Filter ( ) ; $ filter -> setFromColumn ( $ column , $ column -> getFilterDefaultValue ( ) ) ; $ filters [ ] = $ filter ; $ column -> setFilterActive ( $ filter -> getDisplayColumnValue ( ) ) ; } } return $ filters ; }
Get the default filter conditions defined for the columns .
52,161
public function prepareViewModel ( Datagrid $ grid ) { $ viewModel = $ this -> getViewModel ( ) ; $ viewModel -> setVariable ( 'gridId' , $ grid -> getId ( ) ) ; $ viewModel -> setVariable ( 'title' , $ this -> getTitle ( ) ) ; $ viewModel -> setVariable ( 'parameters' , $ grid -> getParameters ( ) ) ; $ viewModel -> setVariable ( 'overwriteUrl' , $ grid -> getUrl ( ) ) ; $ viewModel -> setVariable ( 'templateToolbar' , $ this -> getToolbarTemplate ( ) ) ; foreach ( $ this -> getToolbarTemplateVariables ( ) as $ key => $ value ) { $ viewModel -> setVariable ( $ key , $ value ) ; } $ viewModel -> setVariable ( 'rendererName' , $ this -> getName ( ) ) ; $ options = $ this -> getOptions ( ) ; $ generalParameterNames = $ options [ 'generalParameterNames' ] ; $ viewModel -> setVariable ( 'generalParameterNames' , $ generalParameterNames ) ; $ viewModel -> setVariable ( 'columns' , $ this -> getColumns ( ) ) ; $ viewModel -> setVariable ( 'rowStyles' , $ grid -> getRowStyles ( ) ) ; $ viewModel -> setVariable ( 'paginator' , $ this -> getPaginator ( ) ) ; $ viewModel -> setVariable ( 'data' , $ this -> getData ( ) ) ; $ viewModel -> setVariable ( 'filters' , $ this -> getFilters ( ) ) ; $ viewModel -> setVariable ( 'rowClickAction' , $ grid -> getRowClickAction ( ) ) ; $ viewModel -> setVariable ( 'massActions' , $ grid -> getMassActions ( ) ) ; $ viewModel -> setVariable ( 'isUserFilterEnabled' , $ grid -> isUserFilterEnabled ( ) ) ; $ optionsRenderer = $ this -> getOptionsRenderer ( ) ; $ viewModel -> setVariable ( 'optionsRenderer' , $ optionsRenderer ) ; if ( $ this -> isExport ( ) === false ) { $ parameterNames = $ optionsRenderer [ 'parameterNames' ] ; $ viewModel -> setVariable ( 'parameterNames' , $ parameterNames ) ; $ activeParameters = [ ] ; $ activeParameters [ $ parameterNames [ 'currentPage' ] ] = $ this -> getCurrentPageNumber ( ) ; { $ sortColumns = [ ] ; $ sortDirections = [ ] ; foreach ( $ this -> getSortConditions ( ) as $ sortCondition ) { $ sortColumns [ ] = $ sortCondition [ 'column' ] -> getUniqueId ( ) ; $ sortDirections [ ] = $ sortCondition [ 'sortDirection' ] ; } $ activeParameters [ $ parameterNames [ 'sortColumns' ] ] = implode ( ',' , $ sortColumns ) ; $ activeParameters [ $ parameterNames [ 'sortDirections' ] ] = implode ( ',' , $ sortDirections ) ; } $ viewModel -> setVariable ( 'activeParameters' , $ activeParameters ) ; } $ viewModel -> setVariable ( 'exportRenderers' , $ grid -> getExportRenderers ( ) ) ; }
VERY UGLY DEPENDECY ...
52,162
public function getAllRouteRules ( string $ format = 'Craft' , $ siteId = null ) : array { return RouteMap :: $ plugin -> routes -> getAllRouteRules ( $ format , $ siteId ) ; }
Return all of the section and category route rules
52,163
public function getCategoryUrls ( string $ category , array $ criteria = [ ] , $ siteId = null ) : array { return RouteMap :: $ plugin -> routes -> getCategoryUrls ( $ category , $ criteria , $ siteId ) ; }
Return the public URLs for a category group
52,164
public function actionGetRouteRules ( $ siteId = null , $ includeGlobal = true ) : Response { return $ this -> asJson ( RouteMap :: $ plugin -> routes -> getRouteRules ( $ siteId , $ includeGlobal ) ) ; }
Return the Craft Control Panel and routes . php rules
52,165
public function invalidateCache ( ) { $ cache = Craft :: $ app -> getCache ( ) ; TagDependency :: invalidate ( $ cache , self :: ROUTEMAP_CACHE_TAG ) ; Craft :: info ( 'Route Map cache cleared' , __METHOD__ ) ; }
Invalidate the RouteMap caches
52,166
protected function getDbRoutes ( $ siteId = null ) : array { if ( $ siteId === null ) { $ siteId = Craft :: $ app -> getSites ( ) -> currentSite -> id ; } if ( $ siteId === 'global' ) { $ siteId = null ; } if ( RouteMap :: $ craft31 ) { return Craft :: $ app -> getRoutes ( ) -> getProjectConfigRoutes ( ) ; } $ results = ( new Query ( ) ) -> select ( [ 'uriPattern' , 'template' ] ) -> from ( [ '{{%routes}}' ] ) -> where ( [ 'or' , [ 'siteId' => $ siteId ] , ] ) -> orderBy ( [ 'sortOrder' => SORT_ASC ] ) -> all ( ) ; return ArrayHelper :: map ( $ results , 'uriPattern' , function ( $ results ) { return [ 'template' => $ results [ 'template' ] ] ; } ) ; }
Query the database for db routes
52,167
protected function normalizeFormat ( $ format , $ route ) : array { $ route [ 'url' ] = $ this -> normalizeUri ( $ route [ 'url' ] ) ; switch ( $ format ) { case $ this :: ROUTE_FORMAT_REACT : case $ this :: ROUTE_FORMAT_VUE : $ matchRegEx = '`{(.*?)}`i' ; $ replaceRegEx = ':$1' ; $ route [ 'url' ] = preg_replace ( $ matchRegEx , $ replaceRegEx , $ route [ 'url' ] ) ; $ route [ 'url' ] = '/' . ltrim ( $ route [ 'url' ] , '/' ) ; break ; case $ this :: ROUTE_FORMAT_CRAFT : default : break ; } return $ route ; }
Normalize the routes based on the format
52,168
public function initConfig ( ) { if ( empty ( Yii :: $ app -> params [ 'domain' ] ) ) { throw new InvalidConfigException ( "param `domain` must set." , 1 ) ; } $ this -> _config = $ this -> mergeConfig ( ) ; $ config = Json :: htmlEncode ( $ this -> _config ) ; $ js = <<<JS var {$this->_hashVar} = {$config}; $('#{$this->_hashVar}').webupload_fileinput({$this->_hashVar});JS ; $ this -> _view -> registerJs ( $ js ) ; }
register base js config
52,169
protected function hashClientOptions ( $ name ) { $ this -> _encOptions = empty ( $ this -> clientOptions ) ? '' : Json :: htmlEncode ( $ this -> clientOptions ) ; $ this -> _hashVar = $ name . '_' . hash ( 'crc32' , $ this -> _encOptions ) ; }
generate hash var by plugin options
52,170
public function handle ( Request $ request , $ type = self :: MASTER_REQUEST , $ catch = true ) { $ this -> getContainer ( ) -> add ( 'Symfony\Component\HttpFoundation\Request' , $ request ) ; try { $ this -> emit ( 'request.received' , $ request ) ; $ dispatcher = $ this -> getRouter ( ) -> getDispatcher ( ) ; $ response = $ dispatcher -> dispatch ( $ request -> getMethod ( ) , $ request -> getPathInfo ( ) ) ; $ this -> emit ( 'response.created' , $ request , $ response ) ; return $ response ; } catch ( \ Exception $ e ) { if ( ! $ catch ) { throw $ e ; } $ response = call_user_func ( $ this -> exceptionDecorator , $ e ) ; if ( ! $ response instanceof Response ) { throw new \ LogicException ( 'Exception decorator did not return an instance of Symfony\Component\HttpFoundation\Response' ) ; } $ this -> emit ( 'response.created' , $ request , $ response ) ; return $ response ; } }
Handle the request .
52,171
public function fetchUrl ( $ url , $ parameters = [ ] , $ json_formatted = true , $ verb = 'get' ) { $ full_url = $ this -> buildUrl ( $ url , $ parameters ) ; $ response = $ this -> client -> { $ verb } ( $ full_url ) ; return ( $ json_formatted ) ? $ response -> json ( ) : $ response ; }
build the URI from the provided data do the actual call to the API through the Http Client parse the data to return the shorten URL .
52,172
private function buildUrl ( $ url , $ parameters ) { $ prams_former = '?' ; foreach ( $ parameters as $ key => $ value ) { $ prams_former = $ prams_former . $ key . '=' . $ value . '&' ; } return $ url . substr ( $ prams_former , 0 , - 1 ) ; }
build the final URI to be called by the client .
52,173
private function setParameters ( $ parameters ) { $ this -> domain = $ this -> validateConfiguration ( $ parameters [ 'domain' ] ) ; $ this -> endpoint = $ this -> validateConfiguration ( $ parameters [ 'endpoint' ] ) ; $ this -> access_token = $ this -> validateConfiguration ( $ parameters [ 'token' ] ) ; }
set the attributes on the class after validating them .
52,174
public static function make ( $ name , $ parameters , $ httpClient = null ) { if ( ! $ name ) { throw new MissingConfigurationException ( 'The config file is missing the (Default Driver Name)' ) ; } $ driver_class = self :: DRIVERS_NAMESPACE . ucwords ( $ name ) ; if ( ! class_exists ( $ driver_class ) ) { throw new UnsupportedDriverException ( "The driver ($name) is not supported." ) ; } $ driver_object = new $ driver_class ( $ parameters , $ httpClient ) ; return $ driver_object ; }
initialize the driver instance and return it .
52,175
public static function getValue ( array $ config , string $ configPath , $ default = null ) { if ( $ configPath === '' ) { throw new InvalidArgumentException ( 'Path must be not be empty string' , 1496758719 ) ; } $ path = str_getcsv ( $ configPath , '.' ) ; $ value = $ config ; foreach ( $ path as $ segment ) { if ( array_key_exists ( $ segment , $ value ) ) { $ value = $ value [ $ segment ] ; } else { if ( \ count ( \ func_get_args ( ) ) !== 2 ) { return $ default ; } throw new PathDoesNotExistException ( sprintf ( 'Path "%s" does not exist in array (tried reading)' , $ configPath ) , 1496758722 ) ; } } return $ value ; }
Getting a value to an array in a given path
52,176
public static function setValue ( array $ array , string $ configPath , $ value ) : array { if ( ! is_string ( $ configPath ) || $ configPath === '' ) { throw new InvalidArgumentException ( 'Path must be not be empty string' , 1496472912 ) ; } $ path = str_getcsv ( $ configPath , '.' ) ; $ pointer = & $ array ; foreach ( $ path as $ segment ) { if ( $ segment === '' ) { throw new InvalidArgumentException ( 'Invalid path segment specified' , 1496472917 ) ; } if ( ! array_key_exists ( $ segment , $ pointer ) ) { $ pointer [ $ segment ] = [ ] ; } $ pointer = & $ pointer [ $ segment ] ; } $ pointer = $ value ; return $ array ; }
Setting a value to an array in a given path
52,177
public static function removeValue ( array $ config , string $ configPath ) : array { if ( ! is_string ( $ configPath ) || $ configPath === '' ) { throw new InvalidArgumentException ( 'Path must be not be empty string' , 1496759385 ) ; } $ path = str_getcsv ( $ configPath , '.' ) ; $ pathDepth = count ( $ path ) ; $ currentDepth = 0 ; $ pointer = & $ config ; foreach ( $ path as $ segment ) { $ currentDepth ++ ; if ( $ segment === '' ) { throw new InvalidArgumentException ( 'Invalid path segment specified' , 1496759389 ) ; } if ( ! array_key_exists ( $ segment , $ pointer ) ) { throw new PathDoesNotExistException ( sprintf ( 'Path "%s" does not exist in array (tried removing)' , $ configPath ) , 1496759405 ) ; } if ( $ currentDepth === $ pathDepth ) { unset ( $ pointer [ $ segment ] ) ; } else { $ pointer = & $ pointer [ $ segment ] ; } } return $ config ; }
Removing a path of an array
52,178
private function getConfigurationFiles ( ) { $ path = $ this -> configPath ; if ( ! is_dir ( $ path ) ) { return [ ] ; } $ files = [ ] ; $ phpFiles = Finder :: create ( ) -> files ( ) -> name ( '*.php' ) -> in ( $ path ) -> depth ( 0 ) ; foreach ( $ phpFiles as $ file ) { $ files [ basename ( $ file -> getRealPath ( ) , '.php' ) ] = $ file -> getRealPath ( ) ; } return $ files ; }
Get the configuration files for the selected environment .
52,179
public function max_children_set ( $ value , $ bucket = self :: DEFAULT_BUCKET ) { if ( $ value < 1 ) { $ value = 0 ; $ this -> log ( ( $ bucket === self :: DEFAULT_BUCKET ? 'default' : $ bucket ) . ' bucket max_children set to 0, bucket will be disabled' , self :: LOG_LEVEL_WARN ) ; } $ old = $ this -> max_children [ $ bucket ] ; $ this -> max_children [ $ bucket ] = $ value ; if ( $ this -> child_persistent_mode [ $ bucket ] && $ old > $ this -> max_children [ $ bucket ] ) { $ difference = $ old - $ this -> max_children [ $ bucket ] ; $ killed = 0 ; foreach ( $ this -> forked_children as $ pid => $ child ) { if ( $ child [ 'bucket' ] == $ bucket && $ child [ 'status' ] == self :: WORKER ) { $ this -> safe_kill ( $ pid , SIGINT , "max_children lowered for bucket $bucket, killing pid $pid" ) ; $ killed ++ ; if ( $ killed == $ difference ) { break ; } } } } }
Allows the app to set the max_children value
52,180
public function max_work_per_child_set ( $ value , $ bucket = self :: DEFAULT_BUCKET ) { if ( $ this -> child_single_work_item [ $ bucket ] ) { $ value = 1 ; } if ( $ value < 1 ) { $ value = 0 ; $ this -> log ( ( $ bucket === self :: DEFAULT_BUCKET ? 'default' : $ bucket ) . ' bucket max_work_per_child set to 0, bucket will be disabled' , self :: LOG_LEVEL_WARN ) ; } $ this -> max_work_per_child [ $ bucket ] = $ value ; }
Allows the app to set the max_work_per_child value
52,181
public function child_max_run_time_set ( $ value , $ bucket = self :: DEFAULT_BUCKET ) { if ( $ value == 0 ) { $ this -> log ( ( $ bucket === self :: DEFAULT_BUCKET ? 'default' : $ bucket ) . ' bucket child_max_run_time set to 0' , self :: LOG_LEVEL_WARN ) ; } elseif ( $ value < 0 ) { $ value = - 1 ; $ this -> log ( ( $ bucket === self :: DEFAULT_BUCKET ? 'default' : $ bucket ) . ' bucket child_max_run_time set to unlimited' , self :: LOG_LEVEL_WARN ) ; } $ this -> child_max_run_time [ $ bucket ] = $ value ; }
Allows the app to set the child_max_run_time value
52,182
public function child_single_work_item_set ( $ value , $ bucket = self :: DEFAULT_BUCKET ) { if ( $ value < 1 ) { $ value = 0 ; $ this -> log ( ( $ bucket === self :: DEFAULT_BUCKET ? 'default' : $ bucket ) . ' bucket child_single_work_item set to 0' , self :: LOG_LEVEL_WARN ) ; } $ this -> child_single_work_item [ $ bucket ] = $ value ; }
Allows the app to set the child_single_work_item value
52,183
public function add_bucket ( $ bucket ) { $ this -> max_children [ $ bucket ] = $ this -> max_children [ self :: DEFAULT_BUCKET ] ; $ this -> child_single_work_item [ $ bucket ] = $ this -> child_single_work_item [ self :: DEFAULT_BUCKET ] ; $ this -> max_work_per_child [ $ bucket ] = $ this -> max_work_per_child [ self :: DEFAULT_BUCKET ] ; $ this -> child_max_run_time [ $ bucket ] = $ this -> child_max_run_time [ self :: DEFAULT_BUCKET ] ; $ this -> child_single_work_item [ $ bucket ] = $ this -> child_single_work_item [ self :: DEFAULT_BUCKET ] ; $ this -> child_function_run [ $ bucket ] = $ this -> child_function_run [ self :: DEFAULT_BUCKET ] ; $ this -> parent_function_fork [ $ bucket ] = $ this -> parent_function_fork [ self :: DEFAULT_BUCKET ] ; $ this -> child_function_sighup [ $ bucket ] = $ this -> child_function_sighup [ self :: DEFAULT_BUCKET ] ; $ this -> child_function_exit [ $ bucket ] = $ this -> child_function_exit [ self :: DEFAULT_BUCKET ] ; $ this -> child_function_timeout [ $ bucket ] = $ this -> child_function_timeout [ self :: DEFAULT_BUCKET ] ; $ this -> parent_function_child_exited [ $ bucket ] = $ this -> parent_function_child_exited [ self :: DEFAULT_BUCKET ] ; $ this -> child_persistent_mode [ $ bucket ] = $ this -> child_persistent_mode [ self :: DEFAULT_BUCKET ] ; $ this -> child_persistent_mode_data [ $ bucket ] = $ this -> child_persistent_mode_data [ self :: DEFAULT_BUCKET ] ; $ this -> work_units [ $ bucket ] = array ( ) ; $ this -> buckets [ $ bucket ] = $ bucket ; $ this -> results [ $ bucket ] = array ( ) ; }
Creates a new bucket to house forking operations
52,184
public function register_child_run ( $ function_name , $ bucket = self :: DEFAULT_BUCKET ) { if ( is_callable ( $ function_name ) || ( is_array ( $ function_name ) && method_exists ( $ function_name [ 0 ] , $ function_name [ 1 ] ) ) || method_exists ( $ this , $ function_name ) || function_exists ( $ function_name ) ) { $ this -> child_function_run [ $ bucket ] = $ function_name ; return true ; } return false ; }
Allows the app to set the call back function for child processes
52,185
public function register_parent_fork ( $ function_name , $ bucket = self :: DEFAULT_BUCKET ) { if ( is_callable ( $ function_name ) || ( is_array ( $ function_name ) && method_exists ( $ function_name [ 0 ] , $ function_name [ 1 ] ) ) || method_exists ( $ this , $ function_name ) || function_exists ( $ function_name ) ) { $ this -> parent_function_fork [ $ bucket ] = $ function_name ; return true ; } return false ; }
Allows the app to set the call back function for when a child process is spawned
52,186
public function register_parent_sighup ( $ function_name , $ cascade_signal = true ) { if ( is_callable ( $ function_name ) || ( is_array ( $ function_name ) && method_exists ( $ function_name [ 0 ] , $ function_name [ 1 ] ) ) || method_exists ( $ this , $ function_name ) || function_exists ( $ function_name ) ) { $ this -> parent_function_sighup = $ function_name ; $ this -> parent_function_sighup_cascade = $ cascade_signal ; return true ; } return false ; }
Allows the app to set the call back function for when a parent process receives a SIGHUP
52,187
public function register_child_sighup ( $ function_name , $ bucket = self :: DEFAULT_BUCKET ) { if ( is_callable ( $ function_name ) || ( is_array ( $ function_name ) && method_exists ( $ function_name [ 0 ] , $ function_name [ 1 ] ) ) || method_exists ( $ this , $ function_name ) || function_exists ( $ function_name ) ) { $ this -> child_function_sighup [ $ bucket ] = $ function_name ; return true ; } return false ; }
Allows the app to set the call back function for when a child process receives a SIGHUP
52,188
public function register_child_exit ( $ function_name , $ bucket = self :: DEFAULT_BUCKET ) { if ( is_callable ( $ function_name ) || ( is_array ( $ function_name ) && method_exists ( $ function_name [ 0 ] , $ function_name [ 1 ] ) ) || method_exists ( $ this , $ function_name ) || function_exists ( $ function_name ) ) { $ this -> child_function_exit [ $ bucket ] = $ function_name ; return true ; } return false ; }
Allows the app to set the call back function for when a child process exits
52,189
public function register_child_timeout ( $ function_name , $ bucket = self :: DEFAULT_BUCKET ) { if ( is_callable ( $ function_name ) || ( is_array ( $ function_name ) && method_exists ( $ function_name [ 0 ] , $ function_name [ 1 ] ) ) || method_exists ( $ this , $ function_name ) || function_exists ( $ function_name ) ) { $ this -> child_function_timeout [ $ bucket ] = $ function_name ; return true ; } return false ; }
Allows the app to set the call back function for when a child process is killed to exceeding its max runtime
52,190
public function register_parent_exit ( $ function_name ) { if ( is_callable ( $ function_name ) || ( is_array ( $ function_name ) && method_exists ( $ function_name [ 0 ] , $ function_name [ 1 ] ) ) || method_exists ( $ this , $ function_name ) || function_exists ( $ function_name ) ) { $ this -> parent_function_exit = $ function_name ; return true ; } return false ; }
Allows the app to set the call back function for when the parent process exits
52,191
public function register_parent_child_exit ( $ function_name , $ bucket = self :: DEFAULT_BUCKET ) { if ( is_callable ( $ function_name ) || ( is_array ( $ function_name ) && method_exists ( $ function_name [ 0 ] , $ function_name [ 1 ] ) ) || method_exists ( $ this , $ function_name ) || function_exists ( $ function_name ) ) { $ this -> parent_function_child_exited [ $ bucket ] = $ function_name ; return true ; } return false ; }
Allows the app to set the call back function for when a child exits in the parent
52,192
public function register_parent_results ( $ function_name , $ bucket = self :: DEFAULT_BUCKET ) { if ( is_callable ( $ function_name ) || ( is_array ( $ function_name ) && method_exists ( $ function_name [ 0 ] , $ function_name [ 1 ] ) ) || method_exists ( $ this , $ function_name ) || function_exists ( $ function_name ) ) { $ this -> parent_function_results [ $ bucket ] = $ function_name ; return true ; } return false ; }
Allows the app to set the call back function for when the a child has results
52,193
public function register_logging ( $ function_name , $ severity ) { if ( is_callable ( $ function_name ) || ( is_array ( $ function_name ) && method_exists ( $ function_name [ 0 ] , $ function_name [ 1 ] ) ) || method_exists ( $ this , $ function_name ) || function_exists ( $ function_name ) ) { $ this -> log_function [ $ severity ] = $ function_name ; return true ; } return false ; }
Allows the app to set the call back function for logging
52,194
public function signal_handler_sighup ( $ signal_number ) { if ( self :: $ parent_pid == getmypid ( ) ) { $ this -> log ( 'parent process [' . getmypid ( ) . '] received sighup' , self :: LOG_LEVEL_DEBUG ) ; $ this -> invoke_callback ( $ this -> parent_function_sighup , array ( ) , true ) ; if ( $ this -> parent_function_sighup_cascade === true ) { foreach ( $ this -> forked_children as $ pid => $ pid_info ) { if ( $ pid_info [ 'status' ] == self :: STOPPED ) { continue ; } $ this -> safe_kill ( $ pid , SIGHUP , 'parent process [' . getmypid ( ) . '] sending sighup to child ' . $ pid , self :: LOG_LEVEL_DEBUG ) ; } } } else { if ( isset ( $ this -> child_bucket ) && isset ( $ this -> child_function_sighup [ $ this -> child_bucket ] ) ) { $ this -> log ( 'child process [' . getmypid ( ) . '] received sighup with bucket type [' . $ this -> child_bucket . ']' , self :: LOG_LEVEL_DEBUG ) ; $ this -> invoke_callback ( $ this -> child_function_sighup [ $ this -> child_bucket ] , array ( $ this -> child_bucket ) , true ) ; } } }
Handle both parent and child registered sighup callbacks .
52,195
public function signal_handler_sigchild ( $ signal_number ) { pcntl_async_signals ( false ) ; { if ( self :: $ parent_pid == getmypid ( ) ) { $ status = '' ; do { $ child_pid = pcntl_waitpid ( 0 , $ status , WNOHANG ) ; if ( $ child_pid > 0 ) { $ identifier = false ; if ( ! isset ( $ this -> forked_children [ $ child_pid ] ) ) { $ this -> log ( "Cannot find $child_pid in array! (This may be a subprocess not in our fork)" , self :: LOG_LEVEL_INFO ) ; continue ; } $ child = $ this -> forked_children [ $ child_pid ] ; $ identifier = $ child [ 'identifier' ] ; if ( $ child [ 'status' ] == self :: WORKER ) { $ this -> invoke_callback ( $ this -> parent_function_child_exited [ $ this -> forked_children [ $ child_pid ] [ 'bucket' ] ] , array ( $ child_pid , $ this -> forked_children [ $ child_pid ] [ 'identifier' ] ) , true ) ; } $ this -> forked_children [ $ child_pid ] [ 'status' ] = self :: STOPPED ; $ this -> forked_children_count -- ; if ( $ child [ 'status' ] == self :: HELPER && $ child [ 'respawn' ] === true ) { $ this -> log ( 'Helper process ' . $ child_pid . ' died, respawning' , self :: LOG_LEVEL_INFO ) ; $ this -> helper_process_spawn ( $ child [ 'function' ] , $ child [ 'arguments' ] , $ child [ 'identifier' ] , true ) ; } $ this -> post_results ( $ child [ 'bucket' ] ) ; } elseif ( $ child_pid < 0 ) { if ( pcntl_get_last_error ( ) == 10 ) { continue ; } $ this -> log ( 'pcntl_waitpid failed with error ' . pcntl_get_last_error ( ) . ':' . pcntl_strerror ( ( pcntl_get_last_error ( ) ) ) , self :: LOG_LEVEL_DEBUG ) ; } } while ( $ child_pid > 0 ) ; } } }
Handle parent registered sigchild callbacks .
52,196
public function signal_handler_sigint ( $ signal_number ) { $ this -> received_exit_request ( true ) ; if ( self :: $ parent_pid == getmypid ( ) ) { foreach ( $ this -> forked_children as $ pid => & $ pid_info ) { if ( $ pid_info [ 'status' ] == self :: STOPPED ) { continue ; } if ( $ pid_info [ 'status' ] == self :: HELPER ) { $ pid_info [ 'respawn' ] = false ; } $ this -> safe_kill ( $ pid , SIGINT , 'requesting child exit for pid: ' . $ pid , self :: LOG_LEVEL_INFO ) ; } sleep ( 1 ) ; $ this -> signal_handler_sigchild ( SIGCHLD ) ; $ start_time = time ( ) ; while ( $ this -> forked_children_count > 0 ) { if ( time ( ) > ( $ start_time + $ this -> children_max_timeout ) ) { foreach ( $ this -> forked_children as $ pid => $ child ) { if ( $ child [ 'status' ] == self :: STOPPED ) { continue ; } $ this -> safe_kill ( $ pid , SIGKILL , 'force killing child pid: ' . $ pid , self :: LOG_LEVEL_INFO ) ; $ this -> forked_children [ $ pid ] [ 'status' ] = self :: STOPPED ; $ this -> forked_children_count -- ; } } else { $ this -> log ( 'waiting ' . ( $ start_time + $ this -> children_max_timeout - time ( ) ) . ' seconds for ' . $ this -> forked_children_count . ' children to clean up' , self :: LOG_LEVEL_INFO ) ; sleep ( 1 ) ; $ this -> housekeeping_check ( ) ; } } $ this -> invoke_callback ( $ this -> parent_function_exit , $ parameters = array ( self :: $ parent_pid , $ signal_number ) , true ) ; } else { if ( isset ( $ this -> child_bucket ) ) { $ this -> invoke_callback ( $ this -> child_function_exit [ $ this -> child_bucket ] , $ parameters = array ( $ this -> child_bucket ) , true ) ; } } exit ( - 1 ) ; }
Handle both parent and child registered sigint callbacks
52,197
public function received_exit_request ( $ requested = null ) { if ( $ requested === null ) { return $ this -> exit_request_status ; } if ( ! is_bool ( $ requested ) ) { $ requested = false ; } return ( $ this -> exit_request_status = $ requested ) ; }
Check or set if we have recieved an exit request
52,198
public function addwork ( array $ new_work_units , $ identifier = '' , $ bucket = self :: DEFAULT_BUCKET , $ sort_queue = false ) { if ( ! array_key_exists ( $ bucket , $ this -> work_units ) ) { $ this -> add_bucket ( $ bucket ) ; } if ( $ this -> child_single_work_item [ $ bucket ] ) { $ this -> work_units [ $ bucket ] [ 'id-' . $ identifier ] = $ new_work_units ; } elseif ( $ new_work_units === null || sizeof ( $ new_work_units ) === 0 ) { } else { $ this -> work_units [ $ bucket ] = array_merge ( $ this -> work_units [ $ bucket ] , $ new_work_units ) ; } if ( $ sort_queue ) { ksort ( $ this -> work_units [ $ bucket ] ) ; } return ; }
Add work to the group of work to be processed
52,199
public function is_work_running ( $ identifier , $ bucket = self :: DEFAULT_BUCKET ) { foreach ( $ this -> forked_children as $ info ) { if ( ( $ info [ 'status' ] != self :: STOPPED ) && ( $ info [ 'identifier' ] == $ identifier ) && ( $ info [ 'bucket' ] == $ bucket ) ) { return true ; } } return false ; }
Based on identifier and bucket is a child working on the work