idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
21,000
private function generateModel ( $ model ) { if ( is_object ( $ model ) ) Session :: set ( md5 ( Request :: getArea ( ) . Request :: getController ( ) . Request :: getAction ( ) ) , base64_encode ( get_class ( $ model ) ) ) ; }
Gera um gid para gravar a tipagem da model por action
21,001
public static function getTypeModel ( ) { $ type = base64_decode ( Session :: get ( md5 ( Request :: getArea ( ) . Request :: getController ( ) . Request :: getAction ( ) ) ) ) ; if ( $ type == null ) return 'stdClass' ; return $ type ; }
Resgata o tipo da model
21,002
private function convert ( array $ config ) { foreach ( $ config as $ index => $ data ) { if ( is_array ( $ data ) ) { $ config [ $ index ] = new Config ( $ data ) ; } } return $ config ; }
Convert each sub array in an own config instance .
21,003
public function merge ( Config $ config ) { $ this -> data = array_replace_recursive ( $ this -> data , $ config -> toArray ( ) ) ; return $ this ; }
Merge another config instance in this config instance .
21,004
public function addCommentOnTable ( $ table , $ comment ) { $ table = $ this -> db -> quoteTableName ( $ table ) ; $ comment = $ this -> db -> quoteValue ( $ comment ) ; $ this -> execute ( "COMMENT ON TABLE $table IS $comment;" ) ; }
Adds comment for a table .
21,005
public function addCommentOnColumn ( $ table , $ column , $ comment ) { $ table = $ this -> db -> quoteTableName ( $ table ) ; $ column = $ this -> db -> quoteColumnName ( $ column ) ; $ comment = $ this -> db -> quoteValue ( $ comment ) ; $ this -> execute ( "COMMENT ON COLUMN $table.$column IS $comment;" ) ; }
Adds comment for a table s column .
21,006
public function actionView ( $ id , $ renderPartial = false ) { $ modelNews = $ this -> module -> model ( 'News' ) ; $ model = $ modelNews :: findOne ( $ id ) ; $ modelI18n = false ; if ( ! empty ( $ model ) ) { $ modelsI18n = $ modelNews :: prepareI18nModels ( $ model ) ; $ modelI18n = $ modelsI18n [ $ this -> langCodeMain ] ; } $ searchModel = $ this -> module -> model ( 'NewsSearchFront' ) ; if ( $ renderPartial ) { $ model = $ searchModel :: canShow ( $ model , $ modelI18n , $ ignoreVisibility = true ) ; } else { $ model = $ searchModel :: canShow ( $ model , $ modelI18n ) ; } if ( ! $ model ) { $ modelI18n = false ; } if ( $ renderPartial ) { return $ this -> renderPartial ( 'view' , compact ( 'model' , 'modelI18n' ) ) ; } else { return $ this -> render ( 'view' , compact ( 'model' , 'modelI18n' ) ) ; } }
Render article s body .
21,007
private static function logObject ( $ obj ) { $ path = config ( 'system.errors.save_dir' ) ; if ( $ path != null ) { if ( ! is_dir ( $ path ) ) { @ mkdir ( $ path , 0755 ) ; } $ name = strftime ( config ( 'system.errors.file_name' ) ) ; if ( $ name != '' && @ touch ( $ path . DIRECTORY_SEPARATOR . $ name ) ) { @ error_log ( PHP_EOL . $ obj . PHP_EOL , 3 , $ path . DIRECTORY_SEPARATOR . $ name ) ; } else { @ error_log ( PHP_EOL . $ obj . PHP_EOL , 0 ) ; } } }
Efetua o log do erro nos registros
21,008
public function create ( $ languageCode ) { $ mappings = $ this -> getMappings ( ) ; if ( ! isset ( $ mappings [ $ languageCode ] ) ) { throw new \ InvalidArgumentException ( 'The language code is not part of the supported list. Please see GoogleSupportedLanguages\LanguageFactory::getMappings() for reference.' ) ; } return new $ mappings [ $ languageCode ] ( ) ; }
Create a language object from the language code .
21,009
public function init ( ) : void { if ( $ this -> initialized ) { return ; } if ( ! $ this -> view ) { $ containerGetter = 'get' . ucfirst ( $ this -> viewName ) ; $ this -> setView ( Container :: $ containerGetter ( ) ) ; } if ( method_exists ( $ this , 'getAvailableHelpers' ) ) { $ this -> registerHelpers ( $ this -> getAvailableHelpers ( ) ) ; } $ this -> initialized = true ; }
Lazy loading process
21,010
public function get ( $ key , $ alternateContent = '' ) { $ this -> init ( ) ; return isset ( $ this -> view -> getValues ( ) [ $ key ] ) ? $ this -> view -> getValues ( ) [ $ key ] : $ alternateContent ; }
Get a value from action controller
21,011
function recursiveRemoveDir ( $ dir ) { if ( is_link ( $ dir ) ) { @ unlink ( $ dir ) ; } else if ( is_dir ( $ dir ) ) { $ files = array_diff ( @ scandir ( $ dir ) , array ( '.' , '..' ) ) ; foreach ( $ files as $ file ) { ( is_dir ( "$dir/$file" ) ) ? $ this -> recursiveRemoveDir ( "$dir/$file" ) : @ unlink ( "$dir/$file" ) ; } } return @ rmdir ( $ dir ) ; }
Recursive Remove Dir
21,012
public function addPromise ( ClientRequestInterface $ request , callable $ startingSuccessCallback = null , callable $ startingFailCallback = null ) : ApiResponseInterface { $ return = $ this -> promises [ $ request -> getIdentifier ( ) ] = $ this -> createStartingPromise ( $ request , $ startingSuccessCallback , $ startingFailCallback ) ; return $ return ; }
Adds a promise to this pool .
21,013
private function createStartingPromise ( ClientRequestInterface $ request , callable $ startingSuccessCallback = null , callable $ startingFailCallback = null ) : ApiResponseInterface { if ( ! $ startingSuccessCallback ) { $ startingSuccessCallback = function ( ResponseInterface $ response ) use ( $ request ) { return $ request -> mapFromResponse ( $ request -> buildResponse ( $ response ) ) ; } ; } if ( ! $ startingFailCallback ) { $ startingFailCallback = function ( RequestException $ exception ) { return ApiException :: create ( $ exception -> getRequest ( ) , $ exception -> getResponse ( ) , $ exception ) ; } ; } return $ this -> getClient ( ) -> executeAsync ( $ request ) -> then ( $ startingSuccessCallback , $ startingFailCallback ) ; }
Makes a ctp response out of the default async response and returns the promise for the next chaining level .
21,014
public function flush ( ) { $ promises = $ this -> getPromises ( ) ; $ this -> setPromises ( [ ] ) ; Promise \ settle ( $ promises ) -> wait ( ) ; }
Flushes the collected pull of promises .
21,015
private function findNodes ( ) { $ nodes = array ( ) ; $ container = $ this -> cloneContainer ( ) ; foreach ( $ container -> getDefinitions ( ) as $ id => $ definition ) { $ class = $ definition -> getClass ( ) ; if ( '\\' === substr ( $ class , 0 , 1 ) ) { $ class = substr ( $ class , 1 ) ; } try { $ class = $ this -> container -> getParameterBag ( ) -> resolveValue ( $ class ) ; } catch ( ParameterNotFoundException $ e ) { } $ nodes [ $ id ] = array ( 'class' => str_replace ( '\\' , '\\\\' , $ class ) , 'attributes' => array_merge ( $ this -> options [ 'node.definition' ] , array ( 'style' => $ definition -> isShared ( ) ? 'filled' : 'dotted' ) ) ) ; $ container -> setDefinition ( $ id , new Definition ( 'stdClass' ) ) ; } foreach ( $ container -> getServiceIds ( ) as $ id ) { if ( array_key_exists ( $ id , $ container -> getAliases ( ) ) ) { continue ; } if ( ! $ container -> hasDefinition ( $ id ) ) { $ class = get_class ( 'service_container' === $ id ? $ this -> container : $ container -> get ( $ id ) ) ; $ nodes [ $ id ] = array ( 'class' => str_replace ( '\\' , '\\\\' , $ class ) , 'attributes' => $ this -> options [ 'node.instance' ] ) ; } } return $ nodes ; }
Finds all nodes .
21,016
public function to ( $ url = '' , $ time = 0 , array $ headers = [ ] ) { $ this -> redirector -> setTarget ( $ url ) -> setTime ( $ time ) -> setHeaders ( $ headers ) ; return $ this ; }
redirect user to somewhere else
21,017
public function withError ( $ message ) { if ( is_array ( $ message ) ) { $ this -> errorBag -> setErrors ( $ message ) ; } else { $ this -> errorBag -> add ( $ message ) ; } return $ this ; }
add or set error messages
21,018
public function withInput ( $ name , $ message = null ) { if ( ! is_array ( $ name ) ) { $ name = [ $ name , $ message ] ; } foreach ( $ name as $ key => $ message ) { Session :: set ( $ key , $ message ) ; } return $ this ; }
redirect with input
21,019
public function withCookie ( $ name , $ message = null , $ time = 3600 ) { if ( ! is_array ( $ name ) ) { $ name = [ $ name , $ message ] ; } foreach ( $ name as $ key => $ message ) { $ this -> redirector -> getCookieBase ( ) -> set ( $ key , $ message , $ time ) ; } return $ this ; }
redirect with single or multipile cookies
21,020
public function back ( $ time = 0 ) { $ this -> redirector -> setTarget ( Request :: back ( ) ) ; $ this -> redirector -> setTime ( $ time ) ; return $ this ; }
redirect user to it referer url
21,021
protected function getCreateRoute ( Request $ req , Response $ res ) { $ route = new CreateModelRoute ( $ req , $ res ) ; $ route -> setApp ( $ this -> app ) -> setSerializer ( $ this -> getSerializer ( $ req ) ) ; return $ route ; }
Builds a create route object .
21,022
protected function getListRoute ( Request $ req , Response $ res ) { $ route = new ListModelsRoute ( $ req , $ res ) ; $ route -> setApp ( $ this -> app ) -> setSerializer ( $ this -> getSerializer ( $ req ) ) ; return $ route ; }
Builds a list route object .
21,023
protected function getRetrieveRoute ( Request $ req , Response $ res ) { $ route = new RetrieveModelRoute ( $ req , $ res ) ; $ route -> setApp ( $ this -> app ) -> setSerializer ( $ this -> getSerializer ( $ req ) ) ; return $ route ; }
Builds a retrieve route object .
21,024
protected function getEditRoute ( Request $ req , Response $ res ) { $ route = new EditModelRoute ( $ req , $ res ) ; $ route -> setApp ( $ this -> app ) -> setSerializer ( $ this -> getSerializer ( $ req ) ) ; return $ route ; }
Builds an edit route object .
21,025
protected function getDeleteRoute ( Request $ req , Response $ res ) { $ route = new DeleteModelRoute ( $ req , $ res ) ; $ route -> setApp ( $ this -> app ) -> setSerializer ( $ this -> getSerializer ( $ req ) ) ; return $ route ; }
Builds a delete route object .
21,026
public function getSerializer ( Request $ req ) { $ modelSerializer = new ModelSerializer ( $ req ) ; $ jsonSerializer = new JsonSerializer ( $ req ) ; $ serializer = new ChainedSerializer ( ) ; $ serializer -> add ( $ modelSerializer ) -> add ( $ jsonSerializer ) ; return $ serializer ; }
Builds a serializer object .
21,027
public static function createClosure ( string $ methodStr , string $ methodName , string $ data = '' ) : string { if ( empty ( $ data ) ) { return '$fun = ' . preg_replace ( '/public|static|protected|private|public static|protected static|private static/' , '' , str_replace ( $ methodName , '' , $ methodStr ) . "\n\n//exec\n" . '$fun' . self :: getMethodParamStr ( $ methodStr ) ) ; } else { return '$fun = ' . preg_replace ( '/public|static|protected|private|public static|protected static|private static/' , '' , str_replace ( $ methodName , '' , $ methodStr ) . "\n\n//exec\n" . sprintf ( $ data , '$fun' . self :: getMethodParamStr ( $ methodStr ) ) ) ; } }
create a closure by old method str
21,028
public static function replaceClassInfoStr ( string $ className , string $ data , string $ input ) { return preg_replace ( sprintf ( '/class\s*%s/' , $ className ) , $ data , $ input ) ; }
replace class info
21,029
public function add ( $ records ) { if ( ! $ this -> owner -> isPersisted ( ) ) { throw new Exception \ RuntimeException ( "Owner record must be persisted before adding children" ) ; } $ this -> load ( ) ; if ( ! is_array ( $ records ) ) { $ records = func_get_args ( ) ; } if ( ! $ records ) { return true ; } $ className = get_class ( reset ( $ records ) ) ; return $ className :: transaction ( function ( ) use ( $ records , $ className ) { $ idsForUpdate = [ ] ; foreach ( $ records as $ record ) { if ( $ record -> hasChanged ( ) ) { if ( ! $ record -> updateAttribute ( $ this -> foreignKey , $ this -> owner -> id ( ) ) ) { return false ; } } else { $ idsForUpdate [ ] = $ record -> id ( ) ; } } if ( $ idsForUpdate ) { $ className :: connection ( ) -> table ( $ className :: tableName ( ) ) -> where ( [ $ className :: primaryKey ( ) => $ idsForUpdate ] ) -> update ( [ $ this -> foreignKey => $ this -> owner -> id ( ) ] ) ; } $ this -> records -> merge ( $ records ) ; } ) ; }
Add records to the association . The owner record must be persisted before adding records . Pass an array or records or many records .
21,030
public function run ( $ paths = [ ] , array $ options = [ ] ) { $ this -> notes = [ ] ; $ files = $ this -> getDeployFiles ( $ paths ) ; $ this -> requireFiles ( $ files ) ; $ this -> runDeployies ( $ files , $ options ) ; $ this -> runClearDatabaseCollections ( ) ; return $ files ; }
Run the pending deployies at a given path .
21,031
protected function runDeployies ( array $ deployies , array $ options = [ ] ) { if ( count ( $ deployies ) == 0 ) { $ this -> note ( '<info>Nothing to deploy.</info>' ) ; return ; } foreach ( $ deployies as $ file ) { $ this -> runDeploy ( $ file ) ; } }
Run an array of deployies .
21,032
protected function runDeploy ( $ file ) { $ deploy = $ this -> resolve ( $ name = $ this -> getDeployName ( $ file ) ) ; $ this -> note ( "<comment>Deploying:</comment> {$name}" ) ; $ deploy -> run ( ) ; $ this -> note ( "<info>Deployed:</info> {$name}" ) ; }
Run run a deploy instance .
21,033
protected function runClearDatabaseCollections ( ) { $ collections = db ( ) -> getCollections ( ) ; $ activated = array_keys ( $ this -> collections ) ; $ diff = Arr :: where ( $ collections , function ( $ item ) use ( $ activated ) { return ! in_array ( $ item , $ activated ) ; } ) ; foreach ( $ diff as $ diffColl ) { $ this -> note ( "<comment>Collection droping:</comment> {$diffColl}" ) ; db ( ) -> dropCollection ( $ diffColl ) ; $ this -> note ( "<comment>Collection droped:</comment> {$diffColl}" ) ; } $ this -> runClearDatabaseIndexs ( ) ; }
Run clear database collections .
21,034
protected function runClearDatabaseIndexs ( ) { foreach ( $ this -> collections as $ coll => $ activated ) { $ indexs = db ( ) -> getIndexs ( $ coll ) ; $ diff = Arr :: where ( $ indexs , function ( $ item ) use ( $ activated ) { return ( ( ! in_array ( $ item , $ activated ) ) && ( $ item != '_id_' ) ) ; } ) ; foreach ( $ diff as $ diffIndex ) { $ this -> note ( "<comment>Index droping:</comment> {$coll}.{$diffIndex}" ) ; db ( ) -> dropIndex ( $ coll , $ diffIndex ) ; $ this -> note ( "<comment>Index droped:</comment> {$coll}.{$diffIndex}" ) ; } } }
Run clear database indexs .
21,035
public function getDeployFiles ( $ paths ) { return Collection :: make ( $ paths ) -> flatMap ( function ( $ path ) { return $ this -> files -> glob ( $ path . '/*.php' ) ; } ) -> filter ( ) -> sortBy ( function ( $ file ) { return $ this -> getDeployName ( $ file ) ; } ) -> values ( ) -> keyBy ( function ( $ file ) { return $ this -> getDeployName ( $ file ) ; } ) -> all ( ) ; }
Get all of the deploy files in a given path .
21,036
public function collection ( $ name ) { if ( ! array_key_exists ( $ name , $ this -> collections ) ) { $ this -> collections [ $ name ] = [ ] ; } if ( db ( ) -> hasCollection ( $ name ) ) { return true ; } db ( ) -> createCollection ( $ name ) ; return true ; }
Create collection .
21,037
public function index ( $ collection , $ columns , $ unique ) { $ name = strtolower ( sprintf ( 'ax_%s_%s' , implode ( '_' , array_keys ( $ columns ) ) , $ unique ? 'unique' : "normal" ) ) ; if ( ! array_key_exists ( $ collection , $ this -> collections ) ) { $ this -> collections [ $ collection ] = [ ] ; } if ( ! in_array ( $ name , $ this -> collections [ $ collection ] ) ) { $ this -> collections [ $ collection ] [ ] = $ name ; } if ( db ( ) -> hasIndex ( $ collection , $ name ) ) { return true ; } db ( ) -> createIndex ( $ collection , $ columns , [ 'name' => $ name , 'unique' => $ unique ] ) ; return true ; }
Create index .
21,038
private function loadSettings ( ) { $ settings = $ this -> manage_settings -> getSetting ( $ this ) ; if ( isset ( $ settings [ 'extensions' ] ) ) { try { $ this -> loadExtensions ( $ settings [ 'extensions' ] ) ; } catch ( \ Exception $ ex ) { throw new \ OWeb \ Exception ( 'Failed to load all Extensions in' . OWEB_CONFIG , 0 , $ ex ) ; } } }
Will load the settings from the Default config file . And will after loads the extensions
21,039
public function setRoot ( $ route , array $ args = null , $ label = null ) { array_unshift ( $ this -> hierarchy , [ 'label' => $ label ? : static :: titleIze ( $ route ) , 'route' => $ route , 'args' => ( array ) $ args ] ) ; $ this -> lastKey = null ; return $ this ; }
Set breadcrumb root
21,040
public function add ( $ route , array $ args = null , $ label = null ) { $ this -> hierarchy [ ] = [ 'label' => $ label ? : static :: titleIze ( $ route ) , 'route' => $ route , 'args' => ( array ) $ args ] ; $ this -> lastKey = null ; return $ this ; }
Append to breadcrumb
21,041
public function addCurrentRoute ( $ label = null ) { $ base = Base :: instance ( ) ; $ args = ( $ base [ 'PARAMS' ] ? : [ ] ) + ( $ base [ 'GET' ] ? : [ ] ) ; unset ( $ args [ 0 ] ) ; return $ this -> add ( $ base [ 'ALIAS' ] , $ args , $ label ) ; }
Add current route to breadcrumb
21,042
public function addGroup ( GroupChecker $ groupChecker , $ firstLabel = null , $ route = null , array $ routeArgs = null ) { $ routeArgs = ( array ) $ routeArgs ; if ( empty ( $ route ) ) { $ base = Base :: instance ( ) ; $ routeArgs = ( $ base [ 'PARAMS' ] ? : [ ] ) + ( $ base [ 'GET' ] ? : [ ] ) ; $ route = $ base [ 'ALIAS' ] ; unset ( $ routeArgs [ 0 ] ) ; } $ i = 0 ; foreach ( $ groupChecker -> getGroups ( ) as $ label => $ group ) { if ( $ i === 0 && $ firstLabel ) { $ label = $ firstLabel ; } $ this -> add ( $ route , [ 'group' => $ group ] + $ routeArgs , $ label ) ; $ i ++ ; if ( $ groupChecker -> isEqual ( $ group ) ) { break ; } } return $ this ; }
Add Group to breadcrumb
21,043
public function isLast ( $ key ) { if ( null === $ this -> lastKey ) { end ( $ this -> hierarchy ) ; $ this -> lastKey = key ( $ this -> hierarchy ) ; } return $ key === $ this -> lastKey ; }
Check if key is las key
21,044
public function reset ( ) : ApiClient { $ this -> internalRequest = new InternalRequest ( $ this -> baseUrl , 'GET' ) ; $ this -> request = null ; $ this -> response = null ; $ this -> profiler = false ; $ this -> hasPerformedRequest = false ; $ this -> kernel -> shutdown ( ) ; $ this -> kernel -> boot ( ) ; return $ this ; }
Reset the internal state of the API client
21,045
static function stateResortCompare ( $ a , $ b ) { $ n = $ b -> nNtAct - $ a -> nNtAct ; if ( $ n === 0 ) { $ n = $ b -> nTknAct - $ a -> nTknAct ; } return $ n ; }
Compare two states for sorting purposes . The smaller state is the one with the most non - terminal actions . If they have the same number of non - terminal actions then the smaller is the one with the most token actions .
21,046
static function statecmp ( $ a , $ b ) { for ( $ rc = 0 ; $ rc == 0 && $ a && $ b ; $ a = $ a -> bp , $ b = $ b -> bp ) { $ rc = $ a -> rp -> index - $ b -> rp -> index ; if ( $ rc === 0 ) { $ rc = $ a -> dot - $ b -> dot ; } } if ( $ rc == 0 ) { if ( $ a ) { $ rc = 1 ; } if ( $ b ) { $ rc = - 1 ; } } return $ rc ; }
Compare two states based on their configurations
21,047
private static function statehash ( PHP_ParserGenerator_Config $ a ) { $ h = 0 ; while ( $ a ) { $ h = $ h * 571 + $ a -> rp -> index * 37 + $ a -> dot ; $ a = $ a -> bp ; } return ( int ) $ h ; }
Hash a state based on its configuration
21,048
private function extractArguments ( string $ argumentList ) : array { $ arguments = [ ] ; foreach ( array_map ( 'trim' , explode ( ',' , $ argumentList ) ) as $ rawArgument ) { if ( $ rawArgument === '' ) { continue ; } list ( $ argumentName , $ argumentValue ) = array_map ( 'trim' , explode ( '=' , $ rawArgument , 2 ) + [ null , null ] ) ; $ arguments [ $ argumentName ] = $ argumentValue ; } return $ arguments ; }
Extracts the arguments for a raw argument list .
21,049
public function wrap ( $ text , $ options = array ( ) ) { if ( is_numeric ( $ options ) ) { $ options = array ( 'width' => $ options ) ; } $ options += array ( 'width' => 72 , 'wordWrap' => true , 'indent' => null , 'indentAt' => 0 ) ; if ( $ options [ 'wordWrap' ] ) { $ wrapped = $ this -> wordWrap ( $ text , $ options [ 'width' ] , "\n" ) ; } else { $ wrapped = trim ( chunk_split ( $ text , $ options [ 'width' ] - 1 , "\n" ) ) ; } if ( ! empty ( $ options [ 'indent' ] ) ) { $ chunks = explode ( "\n" , $ wrapped ) ; for ( $ i = $ options [ 'indentAt' ] , $ len = count ( $ chunks ) ; $ i < $ len ; $ i ++ ) { $ chunks [ $ i ] = $ options [ 'indent' ] . $ chunks [ $ i ] ; } $ wrapped = implode ( "\n" , $ chunks ) ; } return $ wrapped ; }
Wraps text to a specific width can optionally wrap at word breaks .
21,050
public function wordWrap ( $ text , $ width = 72 , $ break = "\n" , $ cut = false ) { if ( $ cut ) { $ parts = array ( ) ; while ( mb_strlen ( $ text ) > 0 ) { $ part = mb_substr ( $ text , 0 , $ width ) ; $ parts [ ] = trim ( $ part ) ; $ text = trim ( mb_substr ( $ text , mb_strlen ( $ part ) ) ) ; } return implode ( $ break , $ parts ) ; } $ parts = array ( ) ; while ( mb_strlen ( $ text ) > 0 ) { if ( $ width >= mb_strlen ( $ text ) ) { $ parts [ ] = trim ( $ text ) ; break ; } $ part = mb_substr ( $ text , 0 , $ width ) ; $ nextChar = mb_substr ( $ text , $ width , 1 ) ; if ( $ nextChar !== ' ' ) { $ breakAt = mb_strrpos ( $ part , ' ' ) ; if ( $ breakAt === false ) { $ breakAt = mb_strpos ( $ text , ' ' , $ width ) ; } if ( $ breakAt === false ) { $ parts [ ] = trim ( $ text ) ; break ; } $ part = mb_substr ( $ text , 0 , $ breakAt ) ; } $ part = trim ( $ part ) ; $ parts [ ] = $ part ; $ text = trim ( mb_substr ( $ text , mb_strlen ( $ part ) ) ) ; } return implode ( $ break , $ parts ) ; }
Unicode aware version of wordwrap .
21,051
public function ascii ( $ array ) { $ ascii = '' ; foreach ( $ array as $ utf8 ) { if ( $ utf8 < 128 ) { $ ascii .= chr ( $ utf8 ) ; } elseif ( $ utf8 < 2048 ) { $ ascii .= chr ( 192 + ( ( $ utf8 - ( $ utf8 % 64 ) ) / 64 ) ) ; $ ascii .= chr ( 128 + ( $ utf8 % 64 ) ) ; } else { $ ascii .= chr ( 224 + ( ( $ utf8 - ( $ utf8 % 4096 ) ) / 4096 ) ) ; $ ascii .= chr ( 128 + ( ( ( $ utf8 % 4096 ) - ( $ utf8 % 64 ) ) / 64 ) ) ; $ ascii .= chr ( 128 + ( $ utf8 % 64 ) ) ; } } return $ ascii ; }
Converts the decimal value of a multibyte character string to a string
21,052
public function setPath ( File $ path ) { $ this -> path = $ path ; if ( $ this -> isCreateIfNotExists ( ) && ! $ path -> isFile ( ) ) { $ path -> getParent ( ) -> mkdir ( ) ; $ path -> write ( "" ) ; $ this -> setCreateDefault ( true ) ; if ( ! $ path -> isFile ( ) ) { throw new FileNotFoundException ( $ path ) ; } } $ this -> content = $ path -> getContent ( ) ; }
sets file path
21,053
protected function createRequestFromGlobals ( ) { $ _ATTRIBUTES = array_merge ( [ ] , isset ( $ _SESSION ) ? $ _SESSION : [ ] ) ; $ SERVER = $ _SERVER ; if ( isset ( $ _POST [ "_method" ] ) ) { $ SERVER [ 'REQUEST_METHOD' ] = $ _POST [ "_method" ] ; } return new Http \ Request ( $ _GET , $ _POST , $ _ATTRIBUTES , $ _COOKIE , $ _FILES , $ SERVER ) ; }
Creates an Http \ Request object
21,054
public function execute ( Request $ request = null ) { $ request = $ request ? : $ this -> request ; $ this -> dispatcher -> dispatch ( $ request , $ this -> response ) ; }
Dispatches the request to the router ;
21,055
public function suggest ( $ zipcode , $ number , $ addition = null ) { $ url = self :: API_URL . '/suggest?q=' . $ zipcode . '-' . $ number . ( ! empty ( $ addition ) ? '-' . $ addition : '' ) ; $ request = new \ LibX \ Net \ Rest \ Request ( $ url , \ LibX \ Net \ Rest \ Request :: REQUEST_METHOD_GET ) ; $ response = new \ LibX \ Net \ Rest \ Response ( ) ; $ data = $ this -> call ( $ request , $ response ) ; if ( $ data -> response -> numFound > 1 ) throw new Exception ( 'More then one document found' ) ; $ document = array_pop ( $ data -> response -> docs ) ; if ( $ document -> type !== 'adres' ) throw new Exception ( 'Invalid document type found (' . $ doc -> type . ')' ) ; $ id = $ document -> id ; return $ id ; }
Suggest an address id
21,056
public function lookup ( $ id ) { $ url = self :: API_URL . '/lookup?id=' . $ id ; $ request = new \ LibX \ Net \ Rest \ Request ( $ url , \ LibX \ Net \ Rest \ Request :: REQUEST_METHOD_GET ) ; $ response = new \ LibX \ Net \ Rest \ Response ( ) ; $ data = $ this -> call ( $ request , $ response ) ; if ( $ data -> response -> numFound > 1 ) throw new Exception ( 'More then one document found' ) ; $ document = array_pop ( $ data -> response -> docs ) ; if ( $ document -> type !== 'adres' ) throw new Exception ( 'Invalid document type found (' . $ doc -> type . ')' ) ; $ state = $ document -> provincienaam ; $ municipality = $ document -> gemeentenaam ; $ city = $ document -> woonplaatsnaam ; $ area = $ document -> wijknaam ; $ neighbourhood = $ document -> buurtnaam ; $ street = $ document -> straatnaam ; $ number = $ document -> huisnummer ; if ( isset ( $ document -> huisnummertoevoeging ) && isset ( $ document -> huisletter ) ) $ addition = $ document -> huisnummertoevoeging . $ document -> huisletter ; elseif ( isset ( $ document -> huisnummertoevoeging ) ) $ addition = $ document -> huisnummertoevoeging ; elseif ( isset ( $ document -> huisletter ) ) $ addition = $ document -> huisletter ; else $ addition = null ; $ zipcode = $ document -> postcode ; if ( $ document -> bron === 'BAG' ) { $ address = new \ LibX \ External \ Bag \ Address ( ) ; $ address -> setId ( $ document -> id ) ; $ address -> setStateCode ( $ document -> provinciecode ) ; $ address -> setMunicipalityCode ( $ document -> gemeentecode ) ; $ address -> setCityCode ( $ document -> woonplaatscode ) ; $ address -> setDistrictCode ( $ document -> wijkcode ) ; $ address -> setNeighbourhoodCode ( $ document -> buurtcode ) ; $ address -> setPublicSpaceId ( $ document -> openbareruimte_id ) ; $ address -> setNumberIndicationId ( $ document -> nummeraanduiding_id ) ; $ address -> setAddressableObjectId ( $ document -> adresseerbaarobject_id ) ; } else { $ address = new \ LibX \ Util \ Address ( ) ; } $ address -> setCountry ( 'Nederland' ) ; $ address -> setState ( $ state ) ; $ address -> setMunicipality ( $ municipality ) ; $ address -> setCity ( $ city ) ; $ address -> setDistrict ( $ area ) ; $ address -> setNeighbourhood ( $ neighbourhood ) ; $ address -> setStreet ( $ street ) ; $ address -> setNumber ( $ number ) ; $ address -> setAddition ( $ addition ) ; $ address -> setZipcode ( $ zipcode ) ; return $ address ; }
Lookup an address id
21,057
protected function _setTranslator ( $ translator ) { if ( ! ( is_null ( $ translator ) || $ translator instanceof StringTranslatorInterface ) ) { throw new InvalidArgumentException ( 'Invalid translator' ) ; } $ this -> translator = $ translator ; return $ this ; }
Assigns the translator to be used by this instance .
21,058
protected function readConfig ( ) { if ( $ this -> loaded == false ) { $ this -> config = $ this -> loader -> getDatas ( ) ; $ this -> loaded = true ; } return $ this ; }
Lecture de la configuration
21,059
public static function getFactory ( $ p_name , $ p_file = null ) { if ( self :: $ factory === null ) { self :: $ factory = array ( ) ; } if ( ! array_key_exists ( $ p_name , self :: $ factory ) ) { self :: $ factory [ $ p_name ] = new self ( $ p_file ) ; } return self :: $ factory [ $ p_name ] ; }
Retourne l instance
21,060
public static function _init ( ) { \ Lang :: load ( 'byte_units' , true ) ; static :: $ config = \ Config :: load ( 'num' , true ) ; static :: $ byte_units = \ Lang :: get ( 'byte_units' ) ; }
Class initialization callback
21,061
protected function _setToken ( $ token ) { if ( $ token !== null && ! ( $ token instanceof TokenInterface ) ) { throw $ this -> _createInvalidArgumentException ( $ this -> __ ( 'Invalid token' ) , null , null , $ token ) ; } $ this -> token = $ token ; }
Assigns a token to this instance .
21,062
public function adm_login ( $ args ) { $ this -> init ( ) ; $ logger = $ this -> logger ; if ( $ this -> store_is_logged_in ( ) ) return [ AdminStoreError :: USER_ALREADY_LOGGED_IN ] ; if ( ! isset ( $ args [ 'post' ] ) ) return [ AdminStoreError :: DATA_INCOMPLETE ] ; if ( ! Common :: check_idict ( $ args [ 'post' ] , [ 'uname' , 'upass' ] ) ) return [ AdminStoreError :: DATA_INCOMPLETE ] ; extract ( $ args [ 'post' ] ) ; $ usalt = $ this -> store -> query ( "SELECT usalt FROM udata WHERE uname=? LIMIT 1" , [ $ uname ] ) ; if ( ! $ usalt ) return [ AdminStoreError :: USER_NOT_FOUND ] ; $ usalt = $ usalt [ 'usalt' ] ; $ udata = $ this -> store_match_password ( $ uname , $ upass , $ usalt ) ; if ( ! $ udata ) { $ logger -> warning ( "Zapmin: login: wrong password: '$uname'." ) ; return [ AdminStoreError :: WRONG_PASSWORD ] ; } $ token = $ this -> generate_secret ( $ upass . $ usalt . time ( ) , $ usalt ) ; $ sid = $ this -> store -> insert ( 'usess' , [ 'uid' => $ udata [ 'uid' ] , 'token' => $ token , ] , 'sid' ) ; if ( $ this -> dbtype == 'mysql' ) { $ expire_at = $ this -> store -> stmt_fragment ( 'datetime' , [ 'delta' => $ this -> expiration , ] ) ; $ this -> store -> query_raw ( sprintf ( "UPDATE usess SET expire=(%s) WHERE sid='%s'" , $ expire_at , $ sid ) ) ; } $ logger -> info ( "Zapmin: login: OK: '$uname'." ) ; return [ 0 , [ 'uid' => $ udata [ 'uid' ] , 'uname' => $ udata [ 'uname' ] , 'token' => $ token , ] ] ; }
Sign in .
21,063
public function adm_logout ( ) { if ( ! $ this -> store_is_logged_in ( ) ) return [ AdminStoreError :: USER_NOT_LOGGED_IN ] ; $ this -> store_close_session ( $ this -> user_data [ 'sid' ] ) ; $ this -> store_reset_status ( ) ; $ this -> logger -> info ( sprintf ( "Zapmin: logout: OK: '%s'." , $ this -> user_data [ 'uname' ] ) ) ; return [ 0 ] ; }
Sign out .
21,064
public function adm_change_bio ( $ args ) { if ( ! $ this -> store_is_logged_in ( ) ) return [ AdminStoreError :: USER_NOT_LOGGED_IN ] ; if ( ! isset ( $ args [ 'post' ] ) ) return [ AdminStoreError :: DATA_INCOMPLETE ] ; $ post = $ args [ 'post' ] ; $ vars = [ ] ; foreach ( [ 'fname' , 'site' ] as $ key ) { if ( ! isset ( $ post [ $ key ] ) ) continue ; $ val = trim ( $ post [ $ key ] ) ; if ( ! $ val ) continue ; $ vars [ $ key ] = $ val ; } if ( ! $ vars ) return [ 0 ] ; extract ( $ vars ) ; if ( isset ( $ site ) && ! self :: verify_site_url ( $ site ) ) { $ this -> logger -> warning ( "Zapmin: chbio: site URL invalid: '$site'." ) ; return [ AdminStoreError :: SITEURL_INVALID ] ; } $ this -> store -> update ( 'udata' , $ vars , [ 'uid' => $ this -> user_data [ 'uid' ] ] ) ; $ expire = $ this -> store -> stmt_fragment ( 'datetime' ) ; $ session = $ this -> store -> query ( sprintf ( "SELECT * FROM v_usess " . "WHERE token=? AND expire>%s " . "LIMIT 1" , $ expire ) , [ $ this -> user_token ] ) ; $ updated_data = array_merge ( $ this -> user_data , $ vars ) ; if ( $ session ) $ this -> store_redis_cache_write ( $ this -> user_token , $ updated_data , $ session [ 'expire' ] ) ; $ this -> user_data = null ; $ this -> adm_status ( ) ; $ this -> logger -> info ( sprintf ( "Zapmin: chbio: OK: '%s'." , $ this -> user_data [ 'uname' ] ) ) ; return [ 0 ] ; }
Change user info .
21,065
private function _add_user_verify_name ( $ addname ) { $ logger = $ this -> logger ; if ( strlen ( $ addname ) > 64 ) { $ logger -> warning ( "Zapmin: usradd: name invalid: '$addname'." ) ; return AdminStoreError :: USERNAME_TOO_LONG ; } foreach ( [ " " , "\n" , "\r" , "\t" ] as $ white ) { if ( strpos ( $ addname , $ white ) !== false ) { $ logger -> warning ( "Zapmin: usradd: name invalid: '$addname'." ) ; return AdminStoreError :: USERNAME_HAS_WHITESPACE ; } } if ( $ addname [ 0 ] == '+' ) { $ logger -> warning ( "Zapmin: usradd: name invalid: '$addname'." ) ; return AdminStoreError :: USERNAME_LEADING_PLUS ; } return 0 ; }
Verify username of new user .
21,066
private function _add_user_verify_email ( $ email , $ addname ) { $ logger = $ this -> logger ; if ( ! self :: verify_email_address ( $ email ) ) { $ logger -> warning ( sprintf ( "Zapmin: usradd: email invalid: '%s' <- '%s'." , $ addname , $ email ) ) ; return AdminStoreError :: EMAIL_INVALID ; } if ( $ this -> store -> query ( "SELECT uid FROM udata WHERE email=? LIMIT 1" , [ $ email ] ) ) { $ logger -> warning ( sprintf ( "Zapmin: usradd: email exists: '%s' <- '%s'." , $ addname , $ email ) ) ; return AdminStoreError :: EMAIL_EXISTS ; } return 0 ; }
Verify email of new user .
21,067
public function adm_self_add_user ( $ args , $ pass_twice = null , $ email_required = null ) { if ( $ this -> store_is_logged_in ( ) ) return [ AdminStoreError :: USER_ALREADY_LOGGED_IN ] ; return $ this -> adm_add_user ( $ args , $ pass_twice , true , $ email_required ) ; }
Self - register .
21,068
public function adm_self_add_user_passwordless ( $ args ) { if ( $ this -> store_is_logged_in ( ) ) return [ AdminStoreError :: USER_ALREADY_LOGGED_IN ] ; if ( ! isset ( $ args [ 'service' ] ) ) return [ AdminStoreError :: DATA_INCOMPLETE ] ; $ uname = $ uservice = null ; $ service = Common :: check_idict ( $ args [ 'service' ] , [ 'uname' , 'uservice' ] ) ; if ( ! $ service ) return [ AdminStoreError :: DATA_INCOMPLETE ] ; extract ( $ service ) ; $ dbuname = '+' . $ uname . ':' . $ uservice ; $ check = $ this -> store -> query ( "SELECT uid FROM udata WHERE uname=? LIMIT 1" , [ $ dbuname ] ) ; $ uid = $ check ? $ check [ 'uid' ] : $ this -> store -> insert ( "udata" , [ 'uname' => $ dbuname , ] , 'uid' ) ; $ token = $ this -> generate_secret ( $ dbuname . uniqid ( ) , $ uname ) ; $ date_expire = $ this -> store -> query ( sprintf ( "SELECT %s AS date_expire" , $ this -> store -> stmt_fragment ( 'datetime' , [ 'delta' => $ this -> byway_expiration ] ) ) ) [ 'date_expire' ] ; $ sid = $ this -> store -> insert ( 'usess' , [ 'uid' => $ uid , 'token' => $ token , 'expire' => $ date_expire , ] , 'sid' ) ; $ this -> logger -> info ( "Zapmin: usradd: OK: $uid:'$dbuname'." ) ; return [ 0 , [ 'uid' => $ uid , 'uname' => $ dbuname , 'token' => $ token , 'sid' => $ sid , ] ] ; }
Passwordless self - registration .
21,069
public function authz_delete_user ( $ uid ) { $ udata = $ this -> user_data ; if ( $ udata [ 'uid' ] == 1 && $ uid != 1 ) return true ; if ( $ udata [ 'uid' ] == $ uid ) return true ; return false ; }
Default method to decide if user deletion is allowed .
21,070
public function adm_list_user ( $ args ) { $ this -> init ( ) ; if ( ! $ this -> store_is_logged_in ( ) ) return [ AdminStoreError :: USER_NOT_LOGGED_IN ] ; if ( ! $ this -> authz_list_user ( ) ) return [ AdminStoreError :: USER_NOT_AUTHORIZED ] ; extract ( $ args [ 'post' ] ) ; $ page = isset ( $ page ) ? ( int ) $ page : 0 ; if ( $ page < 0 ) $ page = 0 ; $ limit = isset ( $ limit ) ? ( int ) $ limit : 10 ; if ( $ limit <= 0 || $ limit >= 40 ) $ limit = 10 ; $ offset = $ page * $ limit ; if ( ! isset ( $ order ) || ! in_array ( $ order , [ 'ASC' , 'DESC' ] ) ) $ order = '' ; $ stmt = sprintf ( "SELECT uid, uname, fname, site, since " . "FROM udata ORDER BY uid %s LIMIT %s OFFSET %s" , $ order , $ limit , $ offset ) ; return [ 0 , $ this -> store -> query ( $ stmt , [ ] , true ) ] ; }
List all users .
21,071
function urlFor ( $ internalUri , $ locale = NULL ) { $ internalUri = ltrim ( $ internalUri , '/' ) ; if ( $ locale == NULL ) return $ this -> request -> realBaseUrl . $ internalUri ; else return $ this -> request -> realBaseUrl . $ locale . '/' . $ internalUri ; }
Arma una url para una URI interna
21,072
function i18n ( $ file , $ locale = NULL ) { $ this -> fileName = $ file ; $ this -> i18nContent = NULL ; if ( $ locale != NULL ) { if ( file_exists ( PATHAPP . 'src/content/' . $ file . "_$locale" . '.txt' ) ) { $ this -> i18nContent = \ E_fn \ load_application_file ( 'src/content/' . $ file . "_$locale" . '.txt' ) ; $ this -> i18nContent = \ E_fn \ parse_properties ( $ this -> i18nContent ) ; $ this -> locale = $ locale ; } } if ( $ this -> i18nContent == NULL ) { $ this -> i18nContent = \ E_fn \ load_application_file ( 'src/content/' . $ file . '.txt' ) ; $ this -> i18nContent = \ E_fn \ parse_properties ( $ this -> i18nContent ) ; $ this -> locale = 'Default' ; } }
Carga un archivo de internacionalizacion . Si no se especifica el locale carga el archivo por defecto si no le agrega el locale pasado como parametro
21,073
function i18n_change_locale ( $ locale ) { if ( isset ( $ this -> fileName ) ) { i18n ( $ this -> fileName , $ locale ) ; } else { \ Enola \ Error :: general_error ( 'I18n Error' , 'Before call i18n_change_locale is necesary call i18n' ) ; } }
Cambia el archivo de internacionalizacion cargado . Lo cambia segun el locale pasado
21,074
function i18n_value ( $ val_key , $ params = NULL ) { if ( isset ( $ this -> i18nContent ) ) { if ( isset ( $ this -> i18nContent [ $ val_key ] ) ) { $ mensaje = $ this -> i18nContent [ $ val_key ] ; if ( $ params != NULL ) { foreach ( $ params as $ key => $ valor ) { $ mensaje = str_replace ( ":$key" , $ valor , $ mensaje ) ; } } return $ mensaje ; } } else { \ Enola \ Error :: general_error ( 'I18n Error' , 'Not specified any I18n file to make it run the i18n function' ) ; } }
Devuelve el valor segun el archivo de internacionalizacion que se encuentre cargado
21,075
public static function openTag ( $ script , $ openTag , $ phpOpenTag , $ endOpenTag , $ phpEndOpenTag ) { $ data = Strings :: splite ( $ script , $ openTag ) ; $ output = $ data [ 0 ] ; for ( $ i = 1 ; $ i < Collection :: count ( $ data ) ; $ i ++ ) { $ output .= $ phpOpenTag ; $ next = Strings :: splite ( $ data [ $ i ] , $ endOpenTag ) ; $ output .= $ next [ 0 ] . $ phpEndOpenTag ; for ( $ j = 1 ; $ j < Collection :: count ( $ next ) ; $ j ++ ) { if ( $ j == ( Collection :: count ( $ next ) - 1 ) ) { $ output .= $ next [ $ j ] ; } else { $ output .= $ next [ $ j ] . $ endOpenTag ; } } } return $ output ; }
To replace open tag end it s end with PHP tag .
21,076
public static function hasKeys ( array $ haystack ) { $ fails = false ; $ keys = func_get_args ( ) ; array_shift ( $ keys ) ; foreach ( $ keys as $ key ) { if ( ! array_key_exists ( $ key , $ haystack ) ) { $ fails = true ; break ; } } return ! $ fails ; }
Ensures that specified keys exists in the array
21,077
private static function checkCallable ( $ classInstance , callable $ callable , $ method = null ) { if ( $ method && self :: $ checkCallableParameters ) { $ originalMethodReflection = new \ ReflectionMethod ( $ classInstance , $ method ) ; if ( $ originalMethodReflection -> getNumberOfParameters ( ) === 0 ) { return ; } $ originalMethodReflectionParameters = $ originalMethodReflection -> getParameters ( ) ; if ( is_array ( $ callable ) ) { $ callableReflection = new \ ReflectionMethod ( $ callable [ 0 ] , $ callable [ 1 ] ) ; $ callableReflectionParameters = $ callableReflection -> getParameters ( ) ; } elseif ( $ callable instanceof \ Closure ) { $ callableReflection = new \ ReflectionFunction ( $ callable ) ; $ callableReflectionParameters = $ callableReflection -> getParameters ( ) ; } $ originalParameters = self :: getReflectionParameters ( $ originalMethodReflectionParameters ) ; $ callableParameters = self :: getReflectionParameters ( $ callableReflectionParameters ) ; $ parameterOffset = 0 ; if ( $ method && $ callableParameters && $ callable instanceof \ Closure === false ) { $ callableParameters = array_slice ( $ callableParameters , 1 ) ; $ parameterOffset = 1 ; } $ parameterMeta = array_map ( function ( $ originalParameter , $ callableParameter ) { return [ 'original' => $ originalParameter , 'callable' => $ callableParameter ] ; } , $ originalParameters , $ callableParameters ) ; $ parameterDiff = array_filter ( $ parameterMeta , function ( $ item ) { return $ item [ 'original' ] !== $ item [ 'callable' ] ; } ) ; if ( $ parameterDiff ) { self :: findParameterIssues ( $ method , $ callableParameters , $ parameterDiff , $ parameterOffset ) ; } } }
Currently checks for mismatching parameters
21,078
public function clearCss ( ) : void { foreach ( $ this -> webLoaderDir as $ dir ) { if ( file_exists ( $ dir ) ) { foreach ( Finder :: findFiles ( '*.css' ) -> exclude ( '.htaccess' , 'web.config' ) -> in ( $ dir ) as $ file ) { unlink ( ( string ) $ file ) ; } } } }
Smaze CSS cache
21,079
public function current ( ) { if ( $ this -> current instanceof TerminalBucket ) { return null ; } $ current = $ this -> current ; return $ current -> item ( ) ; }
Retrieves the item from the current bucket
21,080
protected function locate ( $ item ) : ? ItemBucket { for ( $ this -> rewind ( ) ; $ this -> valid ( ) ; $ this -> next ( ) ) { $ current = $ this -> current ; if ( Validate :: areEqual ( $ item , $ current -> item ( ) ) ) { return $ current ; } } return null ; }
Locates a bucket by item
21,081
protected function insertBetween ( $ item , Bucket $ prev , Bucket $ next ) : void { $ bucket = new ItemBucket ( $ item ) ; $ prev -> setNext ( $ bucket ) ; $ next -> setPrev ( $ bucket ) ; $ bucket -> setPrev ( $ prev ) ; $ bucket -> setNext ( $ next ) ; $ this -> current = $ bucket ; $ this -> count ++ ; }
Inserts an item between two nodes
21,082
public function addWidget ( $ widget , $ service , $ priority = null ) { if ( ! isset ( $ this -> widgets [ $ widget ] ) ) { $ this -> widgets [ $ widget ] = new PriorityQueue ; } if ( ! is_a ( $ service , static :: WIDGET_INTERFACE , true ) ) { throw new \ InvalidArgumentException ( sprintf ( '%s: $service must implement "%s"' , __METHOD__ , static :: WIDGET_INTERFACE ) ) ; } $ this -> widgets [ $ widget ] -> insert ( $ service , null === $ priority ? 1 : ( int ) $ priority ) ; return $ this ; }
Add a widget
21,083
public function getAnswers ( \ SplFileInfo $ file ) : array { if ( $ file -> isReadable ( ) ) { return unserialize ( $ file -> openFile ( ) -> fread ( $ file -> getSize ( ) ) ) ; } throw new \ InvalidArgumentException ( sprintf ( 'Given file does not exist or is not readable: "%s"' , $ file -> getPathname ( ) ) ) ; }
Checks if the given file is readable . If so the file is read an unserialized . No further checking of the content is performed!
21,084
public function addResourcePath ( $ domain , $ path ) { $ code = $ this -> getCode ( ) ; $ this -> getLocaleBundle ( ) -> addPath ( $ domain , sprintf ( '%s/locales/%s' , $ path , $ code ) ) ; $ this -> getMessageBundle ( ) -> addPaths ( $ domain , [ sprintf ( '%s/messages/%s' , $ path , $ code ) , sprintf ( '%s/messages/%s/LC_MESSAGES' , $ path , $ code ) ] ) ; return $ this ; }
Add resource path lookups for locales and messages .
21,085
public function initialize ( ) { if ( $ data = $ this -> getLocaleBundle ( ) -> loadResource ( null , 'locale' ) ) { $ data = \ Locale :: parseLocale ( $ data [ 'code' ] ) + $ data ; $ config = $ this -> allConfig ( ) ; unset ( $ config [ 'code' ] , $ config [ 'initialize' ] ) ; $ this -> addConfig ( $ config + $ data ) ; } $ this -> getParentLocale ( ) ; return $ this ; }
Instantiate the locale and message bundles using the resource paths .
21,086
public function getParentLocale ( ) { if ( $ this -> _parent ) { return $ this -> _parent ; } if ( ! $ this -> hasConfig ( 'parent' ) ) { return null ; } $ parent = new Locale ( $ this -> getConfig ( 'parent' ) ) ; $ parent -> initialize ( ) ; $ this -> addConfig ( $ this -> allConfig ( ) + $ parent -> allConfig ( ) ) ; $ this -> _parent = $ parent ; return $ parent ; }
Return the parent locale if it exists .
21,087
protected function _loadResource ( $ resource ) { return $ this -> cache ( [ __METHOD__ , $ resource ] , function ( ) use ( $ resource ) { $ data = $ this -> getLocaleBundle ( ) -> loadResource ( null , $ resource ) ; if ( $ parent = $ this -> getParentLocale ( ) ) { $ data = array_merge ( $ parent -> getLocaleBundle ( ) -> loadResource ( null , $ resource ) , $ data ) ; } return $ data ; } ) ; }
Load a resource from the locale bundle and merge with the parent if possible .
21,088
public function convertErrorsToExceptions ( $ level = null , $ exceptionClass = null ) { $ this -> isHandledLocal = true ; if ( is_null ( $ level ) ) { $ level = E_ALL ; } if ( is_null ( $ exceptionClass ) ) { $ exceptionClass = static :: EXCEPTION_THROW_CLASS ; } set_error_handler ( function ( $ errorNumber , $ errorMessage , $ errorFile , $ errorLine ) use ( $ exceptionClass ) { throw new $ exceptionClass ( sprintf ( "%s in %s on line %s!" , $ errorMessage , $ errorFile , $ errorLine ) , $ errorNumber ) ; } , $ level ) ; }
Converts errors to exceptions
21,089
public function set ( $ path , $ value ) { $ configValue = $ this -> getRepository ( ) -> findOneByPath ( $ path ) ; if ( $ configValue ) { $ configValue -> setValue ( $ value ) ; $ this -> update ( $ configValue ) ; } }
Set the value of config value
21,090
public function synchronize ( $ locale ) { $ existingSystemZones = $ this -> manager -> findSystemSlugs ( ) ; $ newZones = array ( ) ; foreach ( $ this -> registry -> getConfigs ( ) as $ config ) { if ( false === in_array ( $ config -> getSlug ( ) , $ existingSystemZones ) ) { $ newZones [ ] = $ this -> createZone ( $ config ) ; } } if ( 0 < count ( $ newZones ) ) { $ this -> manager -> save ( ) ; foreach ( $ newZones as $ zone ) { $ this -> eventDispatcher -> dispatch ( BannerZoneEvents :: CREATE , new BannerZoneEvent ( $ zone , $ locale ) ) ; } } }
Synchronize system banner zones .
21,091
private function createZone ( BannerZoneConfig $ config ) { list ( $ width , $ height ) = $ config -> getSize ( ) ; $ zone = $ this -> manager -> create ( ) ; $ name = $ config -> getName ( ) ; if ( $ config -> getTranslationDomain ( ) ) { $ name = $ this -> translator -> trans ( $ name , array ( ) , $ config -> getTranslationDomain ( ) ) ; } $ zone -> setName ( $ name ) ; $ zone -> setCode ( $ config -> getSlug ( ) ) ; $ zone -> setSlug ( $ config -> getSlug ( ) ) ; $ zone -> setWidth ( $ width ) ; $ zone -> setHeight ( $ height ) ; $ zone -> setSystem ( true ) ; $ this -> manager -> add ( $ zone ) ; return $ zone ; }
Create banner zone .
21,092
protected function createLogger ( string $ loggerName ) { $ this -> logger = new \ Nofuzz \ Log \ Logger ( $ loggerName ) ; $ logLevel = $ this -> getConfig ( ) -> get ( 'log.level' , 'error' ) ; $ logDriver = $ this -> getConfig ( ) -> get ( 'log.driver' , 'file' ) ; $ logDateFormat = $ this -> getConfig ( ) -> get ( 'log.drivers.' . $ logDriver . '.line_datetime' , 'Y-m-d H:i:s' ) ; $ logLineFormat = $ this -> getConfig ( ) -> get ( 'log.drivers.' . $ logDriver . '.line_format' , '%datetime% > %level_name% > %message% %context% %extra%' ) ; if ( strcasecmp ( $ logDriver , "file" ) == 0 ) { $ logFilePath = $ this -> getConfig ( ) -> get ( 'log.drivers.' . $ logDriver . '.file_path' , 'storage/log' ) ; $ logFileFormat = $ this -> getConfig ( ) -> get ( 'log.drivers.' . $ logDriver . '.file_format' , 'Y-m-d' ) ; $ handler = new \ Monolog \ Handler \ StreamHandler ( realpath ( $ this -> basePath . '/' . $ logFilePath ) . '/' . date ( $ logFileFormat ) . '.log' , $ this -> getLogger ( ) -> toMonologLevel ( $ logLevel ) ) ; } else if ( strcasecmp ( $ logDriver , "php" ) == 0 ) { $ handler = new \ Monolog \ Handler \ ErrorLogHandler ( \ Monolog \ Handler \ ErrorLogHandler :: OPERATING_SYSTEM , $ this -> getLogger ( ) -> toMonologLevel ( $ logLevel ) ) ; } $ formatter = new \ Monolog \ Formatter \ LineFormatter ( $ logLineFormat , $ logDateFormat ) ; $ handler -> setFormatter ( $ formatter ) ; $ this -> logger -> pushHandler ( $ handler ) ; $ this -> setErrorHandlers ( ) ; return $ this ; }
Creates and Initializes the Logger
21,093
protected function loadRoutes ( string $ filename ) { $ filename = realpath ( $ filename ) ; if ( file_exists ( $ filename ) ) { $ routesFile = json_decode ( file_get_contents ( $ filename ) , true ) ; if ( $ routesFile ) { $ routeGroups = $ routesFile [ 'groups' ] ?? [ ] ; foreach ( $ routeGroups as $ routeGroupDef ) { $ routeGroup = new \ Nofuzz \ Route \ Group ( $ routeGroupDef ) ; $ this -> routeGroups [ ] = $ routeGroup ; } $ this -> beforeMiddleware = ( $ routesFile [ 'common' ] [ 'before' ] ?? [ ] ) ; $ this -> afterMiddleware = ( $ routesFile [ 'common' ] [ 'after' ] ?? [ ] ) ; } else { throw new \ RunTimeException ( 'Invalid JSON file "' . $ filename . '"' ) ; } $ this -> getLogger ( ) -> debug ( 'Loaded routes' , [ 'file' => $ filename ] ) ; return true ; } return false ; }
Load the routes . json and create all RouteGroups
21,094
public function existsRouteGroup ( string $ groupName ) : bool { foreach ( $ this -> routeGroups as $ routeGroup ) { if ( strcasecmp ( $ routeGroup -> getName ( ) , $ groupName ) == 0 ) { return true ; } } return false ; }
Checks if a RouteGroup exists
21,095
public function gettext ( $ message ) { $ args = func_get_args ( ) ; $ methodArgsNumber = 1 ; $ message = $ this -> callMethodAndSprintf ( __FUNCTION__ , $ args , $ methodArgsNumber ) ; return $ message ; }
Call sprintf on the translation result .
21,096
public function getAnnotationArray ( ) { if ( empty ( $ this -> annotations ) ) { if ( self :: $ parser ) { $ parser = new self :: $ parser ( $ this -> docs ) ; $ this -> annotations = $ parser -> getAnnotationArray ( ) ; } else $ this -> parse ( ) ; } return $ this -> annotations ; }
Returns an array of the parsed annotations
21,097
public static function getMenu ( $ alias , $ ordered = false ) { if ( ! isset ( self :: $ _menus [ $ alias ] ) ) { throw new Exception ( __d ( 'wasabi_core' , 'No menu with alias "{0}" does exist.' , $ alias ) ) ; } if ( ! $ ordered ) { return self :: $ _menus [ $ alias ] ; } return self :: $ _menus [ $ alias ] -> getOrderedArray ( ) ; }
Get a Menu instance or an ordered array of menu items of a menu .
21,098
public function queue ( Operations $ operations ) { foreach ( $ operations -> getOperations ( ) as $ operation ) { if ( $ operation instanceof AddDocumentOperation ) { $ identity = $ operation -> getDocument ( ) -> getIdentity ( ) ; $ job = new Job ( 'indexer:add' , array ( ( string ) $ identity ) ) ; } elseif ( $ operation instanceof AddIdentityOperation ) { $ identity = $ operation -> getIdentity ( ) ; $ job = new Job ( 'indexer:add' , array ( ( string ) $ identity ) ) ; } elseif ( $ operation instanceof UpdateDocumentOperation ) { $ identity = $ operation -> getDocument ( ) -> getIdentity ( ) ; $ job = new Job ( 'indexer:add' , array ( '--update' , ( string ) $ identity ) ) ; } elseif ( $ operation instanceof UpdateIdentityOperation ) { $ identity = $ operation -> getIdentity ( ) ; $ job = new Job ( 'indexer:add' , array ( '--update' , ( string ) $ identity ) ) ; } elseif ( $ operation instanceof DeleteDocumentOperation ) { $ identity = $ operation -> getDocument ( ) -> getIdentity ( ) ; $ job = new Job ( 'indexer:delete' , array ( '--identifier' , ( string ) $ identity ) ) ; } elseif ( $ operation instanceof DeleteIdentityOperation ) { $ identity = $ operation -> getIdentity ( ) ; $ job = new Job ( 'indexer:delete' , array ( '--identifier' , ( string ) $ identity ) ) ; } elseif ( $ operation instanceof DeleteTypeOperation ) { $ job = new Job ( 'indexer:delete' , array ( '--type' , $ operation -> getType ( ) ) ) ; } elseif ( $ operation instanceof DeleteAllOperation ) { $ job = new Job ( 'indexer:delete' , array ( '--all' ) ) ; } elseif ( $ operation instanceof FlushOperation ) { $ job = new Job ( 'indexer:index' , array ( '--flush' ) ) ; } elseif ( $ operation instanceof OptimizeOperation ) { $ job = new Job ( 'indexer:index' , array ( '--optimize' ) ) ; } elseif ( $ operation instanceof CommitOperation ) { $ job = new Job ( 'indexer:index' , array ( '--commit' ) ) ; } elseif ( $ operation instanceof RollbackOperation ) { $ job = new Job ( 'indexer:index' , array ( '--rollback' ) ) ; } else { continue ; } $ this -> jobManager -> addJob ( $ job ) ; } return true ; }
Queue operations .
21,099
public function execute ( StorageInterface $ storage , Operations $ operations ) { foreach ( $ operations -> getOperations ( ) as $ operation ) { if ( $ operation instanceof AddDocumentOperation ) { $ document = $ operation -> getDocument ( ) ; $ event = new DocumentEvent ( $ document ) ; if ( $ this -> eventDispatcher -> dispatch ( IndexerEvents :: BEFORE_STORAGE_ADD_DOCUMENT , $ event ) -> isPropagationStopped ( ) ) { continue ; } $ storage -> addDocument ( $ document ) ; $ event = new DocumentEvent ( $ document ) ; $ this -> eventDispatcher -> dispatch ( IndexerEvents :: STORAGE_ADD_DOCUMENT , $ event ) ; } elseif ( $ operation instanceof AddIdentityOperation ) { throw new InvalidArgumentException ( 'Add identity command not supported by run().' ) ; } elseif ( $ operation instanceof UpdateDocumentOperation ) { $ document = $ operation -> getDocument ( ) ; $ event = new DocumentEvent ( $ document ) ; if ( $ this -> eventDispatcher -> dispatch ( IndexerEvents :: BEFORE_STORAGE_UPDATE_DOCUMENT , $ event ) -> isPropagationStopped ( ) ) { continue ; } $ storage -> updateDocument ( $ document ) ; $ event = new DocumentEvent ( $ document ) ; $ this -> eventDispatcher -> dispatch ( IndexerEvents :: STORAGE_UPDATE_DOCUMENT , $ event ) ; } elseif ( $ operation instanceof UpdateIdentityOperation ) { throw new InvalidArgumentException ( 'Update identity command not supported by run().' ) ; } elseif ( $ operation instanceof DeleteDocumentOperation ) { $ storage -> deleteDocument ( $ operation -> getDocument ( ) ) ; } elseif ( $ operation instanceof DeleteIdentityOperation ) { $ storage -> delete ( $ operation -> getIdentity ( ) ) ; } elseif ( $ operation instanceof DeleteTypeOperation ) { $ storage -> deleteType ( $ operation -> getType ( ) ) ; } elseif ( $ operation instanceof DeleteAllOperation ) { $ storage -> deleteAll ( ) ; } elseif ( $ operation instanceof FlushOperation ) { if ( $ storage instanceof Flushable ) { $ storage -> flush ( ) ; } } elseif ( $ operation instanceof OptimizeOperation ) { if ( $ storage instanceof Optimizable ) { $ storage -> optimize ( ) ; } } elseif ( $ operation instanceof CommitOperation ) { if ( $ storage instanceof Commitable ) { $ storage -> commit ( ) ; } } elseif ( $ operation instanceof RollbackOperation ) { if ( $ storage instanceof Rollbackable ) { $ storage -> rollback ( ) ; } } } return true ; }
Execute operations .