idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
23,000
public function isKeepAlive ( ) { $ nKeepAlive = intval ( $ this -> m_cUCProMain -> getXTInstance ( ) -> getTValue ( UCProConst :: CKT_KP_ALIVE ) ) ; return ( 1 === $ nKeepAlive ) ; }
if user set flag to keep the session alive
23,001
protected function configureAliases ( ) { $ file = "{$this->basePath}/aliases.sh" ; if ( file_exists ( $ file ) ) { $ fileContent = file_get_contents ( $ file ) ; $ fileContent = str_replace ( 'alias p=\'cd ~/Code/artestead\'' , 'alias p=\'cd ~/Code/' . $ this -> defaultName . '\'' , $ fileContent ) ; file_put_contents ( $ file , $ fileContent ) ; } }
Updates the aliases file with a shortcut to the project folder .
23,002
public function logEvent ( EventMessage $ message ) : void { $ name = $ message -> payloadType ( ) -> toString ( ) ; $ this -> logger -> info ( sprintf ( 'Event dispatched {%s}' , $ name ) , [ 'message' => $ message -> toString ( ) ] ) ; }
Logs the event message
23,003
private function addChildNode ( string $ name , array $ config , \ XMLWriter $ writer ) : void { $ writer -> startElement ( $ name ) ; foreach ( $ config as $ nodeName => $ nodeData ) { $ nodeName = \ is_numeric ( $ nodeName ) ? 'num__' . $ nodeName : $ nodeName ; if ( \ is_array ( $ nodeData ) ) { $ this -> addChildNode ( $ nodeName , $ nodeData , $ writer ) ; } elseif ( \ is_bool ( $ nodeData ) ) { $ writer -> writeElement ( $ nodeName , $ nodeData === true ? 'true' : 'false' ) ; } else { $ writer -> writeElement ( $ nodeName , ( string ) $ nodeData ) ; } } $ writer -> endElement ( ) ; }
Adds new child node to configuration XML
23,004
public static function get ( ) { $ req = new static ( ) ; $ post = \ file_get_contents ( 'php://input' ) ; if ( $ post !== false ) { $ obj = Json :: deserialise ( $ post ) ; if ( $ obj !== null ) { $ req -> _Obj = $ obj ; } } return $ req ; }
Returns an instance for a request which is JSON - formatted
23,005
protected function registerCommands ( OutputInterface $ output ) { $ container = $ this -> kernel -> getContainer ( ) ; foreach ( $ this -> kernel -> getBundles ( ) as $ bundle ) { if ( $ bundle instanceof Bundle ) { $ bundle -> registerCommands ( $ this ) ; } } if ( $ container -> hasParameter ( 'console.command.ids' ) ) { foreach ( $ container -> getParameter ( 'console.command.ids' ) as $ id ) { $ this -> add ( $ container -> get ( $ id ) ) ; } } $ this -> addComposerCommands ( ) ; $ file = $ container -> get ( 'tenside.composer_json' ) ; if ( $ file -> has ( 'scripts' ) ) { foreach ( array_keys ( $ file -> get ( 'scripts' ) ) as $ script ) { if ( ! defined ( 'Composer\Script\ScriptEvents::' . str_replace ( '-' , '_' , strtoupper ( $ script ) ) ) ) { if ( $ this -> has ( $ script ) ) { $ output -> writeln ( sprintf ( '<warning>' . 'A script named %s would override a native function and has been skipped' . '</warning>' , $ script ) ) ; continue ; } $ this -> add ( new ScriptAliasCommand ( $ script ) ) ; } } } }
Register all commands from the container and bundles in the application .
23,006
protected function addComposerCommands ( ) { $ this -> add ( new ComposerCommand \ AboutCommand ( ) ) ; $ this -> add ( new ComposerCommand \ ConfigCommand ( ) ) ; $ this -> add ( new ComposerCommand \ DependsCommand ( ) ) ; $ this -> add ( new ComposerCommand \ InitCommand ( ) ) ; $ this -> add ( new ComposerCommand \ InstallCommand ( ) ) ; $ this -> add ( new ComposerCommand \ CreateProjectCommand ( ) ) ; $ this -> add ( new ComposerCommand \ UpdateCommand ( ) ) ; $ this -> add ( new ComposerCommand \ SearchCommand ( ) ) ; $ this -> add ( new ComposerCommand \ ValidateCommand ( ) ) ; $ this -> add ( new ComposerCommand \ ShowCommand ( ) ) ; $ this -> add ( new ComposerCommand \ SuggestsCommand ( ) ) ; $ this -> add ( new ComposerCommand \ RequireCommand ( ) ) ; $ this -> add ( new ComposerCommand \ DumpAutoloadCommand ( ) ) ; $ this -> add ( new ComposerCommand \ StatusCommand ( ) ) ; $ this -> add ( new ComposerCommand \ ArchiveCommand ( ) ) ; $ this -> add ( new ComposerCommand \ DiagnoseCommand ( ) ) ; $ this -> add ( new ComposerCommand \ RunScriptCommand ( ) ) ; $ this -> add ( new ComposerCommand \ LicensesCommand ( ) ) ; $ this -> add ( new ComposerCommand \ GlobalCommand ( ) ) ; $ this -> add ( new ComposerCommand \ ClearCacheCommand ( ) ) ; $ this -> add ( new ComposerCommand \ RemoveCommand ( ) ) ; $ this -> add ( new ComposerCommand \ HomeCommand ( ) ) ; }
Add the composer base commands .
23,007
protected function isUpdateNeeded ( InputInterface $ input , OutputInterface $ output ) { if ( '@warning_time@' !== Tenside :: WARNING_TIME ) { $ commandName = '' ; if ( $ name = $ this -> getCommandName ( $ input ) ) { try { $ commandName = $ this -> find ( $ name ) -> getName ( ) ; } catch ( \ InvalidArgumentException $ e ) { } } if ( $ commandName !== 'self-update' && $ commandName !== 'selfupdate' ) { if ( time ( ) > Tenside :: WARNING_TIME ) { $ output -> writeln ( sprintf ( '<warning>Warning: This development build is over 30 days old. ' . 'It is recommended to update it by running "%s self-update" to get the latest version.' . '</warning>' , $ _SERVER [ 'PHP_SELF' ] ) ) ; return true ; } } } return false ; }
Check if updating is needed .
23,008
public static function cut ( $ string = '' , $ length = 120 , $ end_str = ' ...' ) { if ( empty ( $ string ) ) { return '' ; } if ( strlen ( $ string ) >= $ length ) { $ stringint = substr ( $ string , 0 , $ length ) ; $ last_space = strrpos ( $ stringint , " " ) ; $ stringinter = substr ( $ stringint , 0 , $ last_space ) . $ end_str ; if ( strlen ( $ stringinter ) === strlen ( $ end_str ) ) { $ stringcut = $ stringint . $ end_str ; } else { $ stringcut = $ stringinter ; } } else { $ stringcut = $ string ; } return $ stringcut ; }
Truncate a string at a maximum length adding it a suffix like ...
23,009
public static function slugify ( $ string = '' ) { $ string = preg_replace ( '~[^\\pL\d]+~u' , '-' , $ string ) ; if ( function_exists ( 'iconv' ) ) { $ string = iconv ( 'utf-8' , 'us-ascii//TRANSLIT' , $ string ) ; } $ string = preg_replace ( '~[^-\w]+~' , '' , strtolower ( trim ( $ string , '-' ) ) ) ; return $ string ; }
Get a slugified string
23,010
public static function toCamelCase ( $ name = '' , $ replace = '_' , $ capitalize_first_char = true ) { if ( empty ( $ name ) ) { return '' ; } if ( $ capitalize_first_char ) { $ name [ 0 ] = strtoupper ( $ name [ 0 ] ) ; } $ func = create_function ( '$c' , 'return strtoupper($c[1]);' ) ; return trim ( preg_replace_callback ( '#' . $ replace . '([a-z])#' , $ func , $ name ) , $ replace ) ; }
Transform a name in CamelCase
23,011
public static function fromCamelCase ( $ name = '' , $ replace = '_' , $ lowerize_first_char = true ) { if ( empty ( $ name ) ) { return '' ; } if ( $ lowerize_first_char ) { $ name [ 0 ] = strtolower ( $ name [ 0 ] ) ; } $ func = create_function ( '$c' , 'return "' . $ replace . '" . strtolower($c[1]);' ) ; return trim ( preg_replace_callback ( '/([A-Z])/' , $ func , $ name ) , $ replace ) ; }
Transform a name from CamelCase to other
23,012
public function fillValues ( & $ values = array ( ) ) { $ values [ 'Controller' ] = $ this ; $ values [ 'Request' ] = $ this -> getRequest ( ) ; $ values [ 'Route' ] = $ this -> getRoute ( ) ; }
Fill array with default values
23,013
public function add ( EntityAdded $ event ) { $ entity = $ event -> getEntity ( ) ; $ table = $ this -> getParentTableName ( ) ; $ pmk = $ this -> getParentPrimaryKey ( ) ; $ value = $ event -> getCollection ( ) -> parentEntity ( ) -> getId ( ) ; Sql :: createSql ( $ this -> getAdapter ( ) ) -> update ( $ table ) -> set ( [ $ this -> getForeignKey ( ) => $ value ] ) -> where ( [ "{$pmk} = :id" => [ ':id' => $ entity -> getId ( ) ] ] ) -> execute ( ) ; }
Saves the relation foreign key upon entity add
23,014
protected function checkConditions ( Sql \ Select $ query ) { if ( null != $ this -> conditions ) { $ query -> andWhere ( $ this -> conditions ) ; } return $ this ; }
Check custom conditions
23,015
protected function checkOrder ( Sql \ Select $ query ) { $ order = $ this -> getEntityDescriptor ( ) -> getPrimaryKey ( ) -> getField ( ) ; $ order .= " DESC" ; if ( null != $ this -> order ) { $ order = $ this -> order ; } $ query -> order ( $ order ) ; return $ this ; }
Check custom order
23,016
protected function getCommand ( StrategyInterface $ strategy ) { $ command = $ strategy -> get ( ) ; if ( $ command === null ) { throw new Exception ( 'Failed to locate a sensible command' ) ; } return $ command ; }
Execute the strategy and return the command .
23,017
protected function request ( $ method , $ url , $ parameters = array ( ) ) { Logger :: get ( ) -> debug ( 'HTTP: starting request...' ) ; $ headers = $ this -> headers ; $ headers [ ] = 'Content-Type: ' . $ this -> contentType ; $ headers [ ] = 'Accept: ' . $ this -> acceptedContentType ; $ handler = curl_init ( ) ; if ( ! is_null ( $ this -> user ) ) { curl_setopt ( $ handler , CURLOPT_USERPWD , $ this -> user . ':' . $ this -> password ) ; } Logger :: get ( ) -> debug ( 'HTTP: method is ' . $ method ) ; switch ( $ method ) { case self :: METHOD_DELETE : curl_setopt ( $ handler , CURLOPT_URL , $ url . '?' . http_build_query ( $ parameters ) ) ; curl_setopt ( $ handler , CURLOPT_CUSTOMREQUEST , self :: DELETE ) ; break ; case self :: METHOD_POST : curl_setopt ( $ handler , CURLOPT_URL , $ url ) ; curl_setopt ( $ handler , CURLOPT_POST , true ) ; curl_setopt ( $ handler , CURLOPT_POSTFIELDS , $ parameters ) ; break ; case self :: METHOD_GET : curl_setopt ( $ handler , CURLOPT_URL , $ url . '?' . http_build_query ( $ parameters ) ) ; break ; } curl_setopt ( $ handler , CURLOPT_RETURNTRANSFER , true ) ; curl_setopt ( $ handler , CURLOPT_HTTPHEADER , $ headers ) ; Logger :: get ( ) -> debug ( 'HTTP: headers set.' ) ; Logger :: get ( ) -> debug ( "HTTP: requesting $url..." ) ; $ output = curl_exec ( $ handler ) ; $ errNo = curl_errno ( $ handler ) ; $ error = curl_error ( $ handler ) ; Logger :: get ( ) -> debug ( 'HTTP: Done. Getting status...' ) ; $ status = curl_getinfo ( $ handler , CURLINFO_HTTP_CODE ) ; curl_close ( $ handler ) ; Logger :: get ( ) -> debug ( 'HTTP: request finished.' ) ; if ( $ errNo ) { throw new Exception ( 'HTTP: cURL failed: ' . $ error , $ errNo ) ; } switch ( $ status ) { case self :: STATUS_OK : case self :: STATUS_CREATED : case self :: STATUS_ACCEPTED : case self :: STATUS_NO_CONTENT : return $ output ; default : throw new Http \ Exception ( "HTTP {$status}" , $ status ) ; } }
Performs the actual request .
23,018
public function generateKeyFile ( ) { $ this -> output -> outputLine ( ) ; if ( file_exists ( $ this -> createFilePath ( [ $ this -> localBackupTarget , 'key' ] ) ) ) { $ this -> output -> outputLine ( '<b>You have already a keyfile!</b>' ) ; $ this -> output -> outputLine ( 'If you generate a new one, all existing Backups are worthless.' ) ; $ this -> output -> outputLine ( ) ; $ this -> output -> outputLine ( 'Call \'./flow backup:clear --force\' to delete all Backups and the Keyfile.' ) ; $ this -> output -> outputLine ( ) ; return ; } $ this -> output -> outputLine ( '<b>Generate a new Crypto Key</b>' ) ; $ this -> output -> outputLine ( ) ; $ this -> files -> createDirectoryRecursively ( $ this -> localBackupTarget ) ; try { $ key = \ Crypto :: createNewRandomKey ( ) ; file_put_contents ( $ this -> createFilePath ( [ $ this -> localBackupTarget , 'key' ] ) , $ key ) ; } catch ( Ex \ CryptoTestFailedException $ ex ) { die ( 'Cannot safely create a key' ) ; } catch ( Ex \ CannotPerformOperationException $ ex ) { die ( 'Cannot safely create a key' ) ; } $ this -> output -> outputLine ( 'done' ) ; $ this -> output -> outputLine ( ) ; }
Create a new Crypto Key File
23,019
public function removeAllBackups ( ) { $ this -> output -> outputLine ( ) ; $ this -> output -> outputLine ( '<b>Remove Backups</b>' ) ; $ this -> output -> outputLine ( ) ; $ versions = $ this -> getAvailableVersions ( ) ; $ this -> output -> progressStart ( count ( $ versions ) ) ; $ i = 0 ; foreach ( $ versions as $ version ) { $ this -> files -> removeDirectoryRecursively ( $ this -> createDirectoryPath ( [ $ this -> localBackupTarget , $ version ] ) ) ; $ i ++ ; $ this -> output -> progressSet ( $ i ) ; } $ this -> output -> progressFinish ( ) ; $ this -> output -> outputLine ( ) ; }
Remove all Backup Versions
23,020
public function deleteBy ( $ criteria ) { $ criteria = Util :: normalizeCriteria ( $ criteria ) ; $ queryBuilder = $ this -> getQueryBuilder ( $ criteria ) ; $ queryBuilder -> delete ( $ this -> entityName , 'e' ) ; $ queryBuilder -> getQuery ( ) -> execute ( ) ; }
Removes objects by a set of criteria .
23,021
public function findBy ( $ criteria ) { $ criteria = Util :: normalizeCriteria ( $ criteria ) ; $ queryBuilder = $ this -> getQueryBuilder ( $ criteria ) ; return $ queryBuilder -> getQuery ( ) -> getResult ( ) ; }
Tries to find entities by a set of criteria .
23,022
public function findOneBy ( $ criteria ) { $ criteria = Util :: normalizeCriteria ( $ criteria ) ; $ criteria -> setFirstResult ( 0 ) ; $ criteria -> setMaxResults ( 1 ) ; $ queryBuilder = $ this -> getQueryBuilder ( $ criteria ) ; return $ queryBuilder -> getQuery ( ) -> getOneOrNullResult ( ) ; }
Tries to find a single entity by a set of criteria .
23,023
public function getRepository ( ) { if ( $ this -> repository === null ) { $ this -> repository = $ this -> entityManager -> getRepository ( $ this -> entityName ) ; } return $ this -> repository ; }
Returns the doctrine repository .
23,024
public static function app ( $ workingDir , $ file ) { $ workingFile = rtrim ( $ workingDir , '/' ) . '/' . ltrim ( $ file , '/' ) ; return self :: file ( $ workingFile , true , true ) ; }
Special config shortcut for application config
23,025
public function save ( $ force = false ) { if ( ! $ this -> writeable ) { return false ; } if ( ! $ this -> dirty && ! $ force ) { return null ; } $ savetype = $ force ? 'forced ' : '' ; if ( is_null ( $ force ) ) { $ savetype = 'auto ' ; } $ path = dirname ( $ this -> file ) ; if ( ! is_dir ( $ path ) ) { mkdir ( $ path , 0755 , true ) ; } $ data = $ this -> store -> dump ( ) ; $ conf = version_compare ( PHP_VERSION , '5.4' , '>=' ) ? json_encode ( $ data , JSON_PRETTY_PRINT ) : json_encode ( $ data ) ; unset ( $ data ) ; if ( ! $ conf || ! json_decode ( $ conf ) ) { return ; } $ saved = ( bool ) $ this -> writeAtomic ( $ this -> file , $ conf , 0755 ) ; if ( $ saved ) { $ this -> dirty = false ; } return $ saved ; }
Save config back to file
23,026
protected function writeAtomic ( $ filename , $ content , $ mode ) { $ temp = tempnam ( dirname ( $ filename ) , 'atomic' ) ; if ( ! ( $ fp = @ fopen ( $ temp , 'wb' ) ) ) { $ temp = dirname ( $ filename ) . '/' . uniqid ( 'atomic' ) ; if ( ! ( $ fp = @ fopen ( $ temp , 'wb' ) ) ) { trigger_error ( __METHOD__ . " : error writing temporary file '{$temp}'" , E_USER_WARNING ) ; return false ; } } $ br = fwrite ( $ fp , $ content ) ; fclose ( $ fp ) ; if ( ! $ br || $ br != strlen ( $ content ) ) { unlink ( $ temp ) ; return false ; } chmod ( $ temp , $ mode ) ; if ( ! rename ( $ temp , $ filename ) ) { unlink ( $ filename ) ; rename ( $ temp , $ filename ) ; } return true ; }
Write file atomically
23,027
public function getActions ( ) { $ actions = $ this -> actions ; if ( ! empty ( $ this -> unclassifiedProcessors ) ) { $ time = 0 ; foreach ( $ this -> unclassifiedProcessors as $ processor ) { if ( array_key_exists ( 'time' , $ processor ) ) { $ time += $ processor [ 'time' ] ; } } $ actions [ ] = [ 'name' => 'unclassified processors' , 'time' => $ time , 'processors' => $ this -> unclassifiedProcessors ] ; } return $ actions ; }
Gets all executed actions
23,028
public function getApplicableCheckers ( ) { $ applicableCheckers = [ ] ; foreach ( $ this -> applicableCheckers as $ className => $ applicableChecker ) { $ applicableCheckers [ ] = [ 'class' => $ className , 'time' => $ applicableChecker [ 'time' ] , 'count' => $ applicableChecker [ 'count' ] ] ; } return $ applicableCheckers ; }
Gets all executed applicable checkers
23,029
public function startAction ( $ actionName ) { $ startStopwatch = $ this -> stopwatch && empty ( $ this -> actionStack ) ; $ this -> actionStack [ ] = [ 'name' => $ actionName , 'time' => microtime ( true ) , 'subtrahend' => 0 ] ; $ this -> lastActionIndex ++ ; if ( $ startStopwatch ) { $ this -> stopwatch -> start ( $ this -> getStopwatchName ( ) , $ this -> sectionName ) ; } }
Marks an action as started
23,030
public function stopAction ( \ Exception $ exception = null ) { $ action = array_pop ( $ this -> actionStack ) ; $ this -> lastActionIndex -- ; $ action [ 'time' ] = microtime ( true ) - $ action [ 'time' ] - $ action [ 'subtrahend' ] ; if ( null !== $ exception ) { $ action [ 'exception' ] = $ exception -> getMessage ( ) ; } unset ( $ action [ 'subtrahend' ] ) ; $ this -> addSubtrahend ( $ this -> actionStack , $ action [ 'time' ] ) ; $ this -> addSubtrahend ( $ this -> processorStack , $ action [ 'time' ] ) ; $ this -> actions [ ] = $ action ; if ( empty ( $ this -> actionStack ) && $ this -> stopwatch ) { $ this -> stopwatch -> stop ( $ this -> getStopwatchName ( ) ) ; } }
Marks an action as stopped
23,031
public function stopProcessor ( \ Exception $ exception = null ) { $ processor = array_pop ( $ this -> processorStack ) ; $ processor [ 'time' ] = microtime ( true ) - $ processor [ 'time' ] - $ processor [ 'subtrahend' ] ; if ( null !== $ exception ) { $ processor [ 'exception' ] = $ exception -> getMessage ( ) ; } unset ( $ processor [ 'subtrahend' ] ) ; if ( ! empty ( $ this -> actionStack ) ) { if ( ! array_key_exists ( 'processors' , $ this -> actionStack [ $ this -> lastActionIndex ] ) ) { $ this -> actionStack [ $ this -> lastActionIndex ] [ 'processors' ] = [ $ processor ] ; } else { $ this -> actionStack [ $ this -> lastActionIndex ] [ 'processors' ] [ ] = $ processor ; } } else { $ this -> unclassifiedProcessors [ ] = $ processor ; } }
Marks a processor as stopped
23,032
public function startApplicableChecker ( $ className ) { if ( isset ( $ this -> applicableCheckers [ $ className ] ) ) { $ this -> applicableCheckers [ $ className ] [ 'startTime' ] = microtime ( true ) ; } else { $ this -> applicableCheckers [ $ className ] = [ 'startTime' => microtime ( true ) , 'time' => 0 , 'count' => 0 ] ; } $ this -> lastApplicableChecker = $ className ; }
Marks an applicable checker as started
23,033
public function stopApplicableChecker ( ) { $ this -> applicableCheckers [ $ this -> lastApplicableChecker ] [ 'time' ] += microtime ( true ) - $ this -> applicableCheckers [ $ this -> lastApplicableChecker ] [ 'startTime' ] ; $ this -> applicableCheckers [ $ this -> lastApplicableChecker ] [ 'count' ] += 1 ; }
Marks an applicable checker as stopped
23,034
public function push ( array $ results , $ name = false ) { $ this -> event_results = array_merge ( $ this -> event_results , $ results ) ; if ( $ name ) { $ this -> event_names [ ] = $ name ; } return $ this ; }
Push event results to collection
23,035
public function entities ( $ value ) { if ( is_array ( $ value ) ) { $ newValue = array ( ) ; foreach ( $ value as $ key => $ val ) { $ newValue [ $ key ] = htmlentities ( $ val , ENT_QUOTES , 'UTF-8' , false ) ; } return $ newValue ; } return htmlentities ( $ value , ENT_QUOTES , 'UTF-8' , false ) ; }
Convert an HTML string to entities .
23,036
public function decode ( $ value ) { if ( is_array ( $ value ) ) { $ newValue = array ( ) ; foreach ( $ value as $ key => $ val ) { $ newValue [ $ key ] = html_entity_decode ( $ val , ENT_QUOTES , 'UTF-8' ) ; } return $ newValue ; } return html_entity_decode ( $ value , ENT_QUOTES , 'UTF-8' ) ; }
Convert entities to HTML characters .
23,037
public function connect ( $ template , $ name , $ controller = null , $ metadata = array ( ) ) { if ( is_object ( $ template ) ) $ this -> _customRoutes [ $ name ] = $ template ; else $ this -> _routes [ $ name ] = new Route ( $ name , $ template ) ; if ( $ metadata ) $ this -> _metadata [ $ name ] = $ metadata ; if ( $ controller ) $ this -> _controllers [ $ name ] = $ controller ; return $ this ; }
Gives a route template a unique name and a controller to route to
23,038
public function redirect ( $ template , $ name , $ to ) { return $ this -> connect ( $ template , $ name , new RedirectController ( $ to ) ) ; }
Create a redirect from a particular route name to another
23,039
public function alias ( $ template , $ name , $ to ) { $ router = $ this ; return $ this -> connect ( $ template , $ name , function ( $ request ) use ( $ router , $ to ) { return $ router -> controller ( $ to ) -> execute ( $ request ) ; } ) ; }
Register an alias from one route name to another
23,040
public function lookup ( $ path ) { if ( $ match = $ this -> _getRouteMatch ( $ path , $ this -> _routes ) ) return $ match ; if ( $ match = $ this -> _getRouteMatch ( $ path , $ this -> _customRoutes ) ) return $ match ; throw new LookupException ( "No route matches path '$path'" ) ; }
Looks up a route match based on a url path
23,041
public function metadata ( $ routeName ) { return isset ( $ this -> _metadata [ $ routeName ] ) ? array_merge ( $ this -> _defaultMetadata , $ this -> _metadata [ $ routeName ] ) : $ this -> _defaultMetadata ; }
Looks up metadata for a route name
23,042
public function routeByName ( $ name ) { if ( isset ( $ this -> _routes [ $ name ] ) ) return $ this -> _routes [ $ name ] ; if ( isset ( $ this -> _customRoutes [ $ name ] ) ) return $ this -> _customRoutes [ $ name ] ; throw new LookupException ( "No route named '$name'" ) ; }
Looks up a route by name
23,043
public function buildUrl ( $ name , $ parameters = array ( ) , $ baseUrl = null ) { $ url = $ this -> routeByName ( $ name ) -> interpolate ( $ parameters ) ; if ( $ baseUrl ) return ( string ) $ baseUrl -> relative ( $ url ) ; else if ( isset ( $ this -> _baseUrl ) ) return $ this -> _baseUrl -> relative ( $ url ) ; else return $ url ; }
Build a URL path based on a route name and associated parameters .
23,044
public function controller ( $ name ) { if ( isset ( $ this -> _controllers [ $ name ] ) && ( $ controller = $ this -> _controllers [ $ name ] ) ) { $ name = is_callable ( $ controller ) ? new CallbackController ( $ controller ) : $ controller ; if ( is_object ( $ name ) ) return $ name ; } if ( $ this -> _resolver ) return $ this -> _resolver -> resolve ( $ name ) ; throw new LookupException ( "No controller defined for route '$name'" ) ; }
Looks up a controller from a route name
23,045
private function _getRouteMatch ( $ path , $ routes ) { foreach ( $ routes as $ route ) { if ( $ match = $ route -> getMatch ( $ path , $ this -> metadata ( $ route -> getName ( ) ) ) ) return $ match ; } return false ; }
Look for a matching route in provided route list .
23,046
public function addWpEnv ( ) { $ wpp = $ this -> wpProvider ; $ data = [ 'site-url' => $ wpp -> getBlogInfo ( 'url' ) , 'site-wpurl' => $ wpp -> getBlogInfo ( 'wpurl' ) , 'site-description' => $ wpp -> getBlogInfo ( 'description' ) , 'site-rss_url' => $ wpp -> getBlogInfo ( 'rss_url' ) , 'site-rss2_url' => $ wpp -> getBlogInfo ( 'rss2_url' ) , 'site-atom_url' => $ wpp -> getBlogInfo ( 'atom_url' ) , 'site-comments_atom_url' => $ wpp -> getBlogInfo ( 'comments_atom_url' ) , 'site-comments_rss2_url' => $ wpp -> getBlogInfo ( 'comments_rss2_url' ) , 'site-pingback_url' => $ wpp -> getBlogInfo ( 'pingback_url' ) , 'site-stylesheet_url' => $ wpp -> getBlogInfo ( 'stylesheet_url' ) , 'site-stylesheet_directory' => $ wpp -> getBlogInfo ( 'stylesheet_directory' ) , 'site-template_directory' => $ wpp -> getBlogInfo ( 'template_directory' ) , 'site-admin_email' => $ wpp -> getBlogInfo ( 'admin_email' ) , 'site-charset' => $ wpp -> getBlogInfo ( 'charset' ) , 'site-html_type' => $ wpp -> getBlogInfo ( 'html_type' ) , 'site-version' => $ wpp -> getBlogInfo ( 'version' ) , 'site-language' => $ wpp -> getBlogInfo ( 'language' ) , 'site-name' => $ wpp -> getBlogInfo ( 'name' ) , ] ; $ this -> mergeToTheData ( $ data ) ; return $ this ; }
Add wordpress environment to the data
23,047
public function addPostData ( ? callable $ anotherElse = null , bool $ withoutWp = false ) { $ post = Core :: get ( WpPost :: class ) ; $ queryObject = $ this -> wpQuery ( ) ; $ data = [ ] ; if ( $ queryObject -> have_posts ( ) ) { $ queryObject -> the_post ( ) ; $ data [ 'title' ] = $ this -> wpProvider -> getTheTitle ( ) ; ob_start ( ) ; $ this -> wpProvider -> theContent ( ) ; $ data [ 'content' ] = ob_get_clean ( ) ; $ postData [ 'excerpt' ] = $ post -> post_excerpt ; $ data = array_merge ( $ this -> getAcfFromPage ( $ post -> ID ) , $ data ) ; if ( ! is_null ( $ anotherElse ) ) { $ anotherElse ( $ data , $ post ) ; } } if ( ! $ withoutWp ) { ob_start ( ) ; $ this -> wpProvider -> wpHead ( ) ; $ data [ 'wp-head' ] = ob_get_clean ( ) ; ob_start ( ) ; $ this -> wpProvider -> wpFooter ( ) ; $ data [ 'wp-footer' ] = ob_get_clean ( ) ; } $ queryObject -> rewind_posts ( ) ; $ this -> wpProvider -> wpResetPostData ( ) ; $ this -> mergeToTheData ( $ data ) ; return $ this ; }
Add to result current post data
23,048
public function addMenu ( ) { $ menuLocations = $ this -> wpProvider -> getNavMenuLocations ( ) ; $ data = [ ] ; foreach ( $ menuLocations as $ menuLocation => $ menuId ) { $ menu = $ this -> wpProvider -> wpGetNavMenuItems ( $ menuId ) ; foreach ( $ menu as $ menuItem ) { $ item = new stdClass ( ) ; $ item -> item = $ menuItem -> title ; $ item -> link = $ menuItem -> url ; $ item -> active = ( Path :: getCurrentUrl ( ) === $ menuItem -> url ) ? true : false ; $ data [ $ menuLocation ] [ ] = $ item ; } } $ this -> mergeToTheData ( $ data ) ; return $ this ; }
Add menus to template
23,049
public function addHomePageAcf ( ) { $ homePageId = ( int ) $ this -> wpProvider -> getOption ( 'page_on_front' ) ; $ this -> addAcfFromPage ( $ homePageId ) ; return $ this ; }
Try to add homepage ACF data to result
23,050
protected function wpQuery ( ) : WpQuery { $ hashDecoratedObject = spl_object_hash ( $ this -> decoratedWpQuery ) ; $ globalObject = spl_object_hash ( Core :: get ( WpQuery :: class ) ) ; if ( $ hashDecoratedObject === $ globalObject ) { $ this -> wpProvider -> wpResetQuery ( ) ; } return $ this -> decoratedWpQuery ; }
Right way to get current and correct query object
23,051
protected function getAcfFromPage ( int $ pageId ) : array { $ data = [ ] ; try { $ data = $ this -> wpProvider -> getFields ( $ pageId ) ; } catch ( \ Throwable $ e ) { ; } if ( ! is_array ( $ data ) || empty ( $ data ) ) return [ ] ; return $ data ; }
Try to receive the ACF data by page id will return empty array if fail
23,052
public function getKeys ( $ value , int $ limit = 0 ) : array { $ predicate = function ( $ v , $ k ) use ( $ value ) { return ( $ v === $ value ) ; } ; return $ this -> find ( $ predicate , true , $ limit ) ; }
Get all keys of a given value .
23,053
public function findValue ( callable $ predicate , bool $ findFirst = true ) : Option { $ data = $ this -> find ( $ predicate , false , $ findFirst ? 1 : - 1 ) ; return new Option ( $ data [ 0 ] ?? null , isset ( $ data [ 0 ] ) ) ; }
Find a value that matches the given criteria .
23,054
public function findKey ( callable $ predicate , bool $ findFirst = true ) : Option { $ data = $ this -> find ( $ predicate , true , $ findFirst ? 1 : - 1 ) ; return new Option ( $ data [ 0 ] ?? null , isset ( $ data [ 0 ] ) ) ; }
Find the key of a value that matches the given criteria .
23,055
public function find ( callable $ predicate , bool $ findKeys = null , int $ limit = 0 ) : array { $ data = [ ] ; $ found = 0 ; if ( $ limit >= 0 ) { foreach ( $ this -> data as $ key => $ value ) { if ( $ predicate ( $ value , $ key ) === true ) { $ found ++ ; if ( $ findKeys === null ) { $ data [ $ key ] = $ value ; } else { $ data [ ] = $ findKeys ? $ key : $ value ; } if ( $ found === $ limit ) { break ; } } } } else { end ( $ this -> data ) ; for ( $ i = 0 ; $ i < count ( $ this -> data ) ; $ i ++ ) { $ key = $ this -> key ( ) ; $ value = $ this -> current ( ) ; if ( $ predicate ( $ value , $ key ) === true ) { $ found ++ ; if ( $ findKeys === null ) { $ data [ $ key ] = $ value ; } else { $ data [ ] = $ findKeys ? $ key : $ value ; } if ( $ found === - $ limit ) { break ; } } $ this -> prev ( ) ; } $ this -> rewind ( ) ; $ data = array_reverse ( $ data , ( $ findKeys === null ) ) ; } return $ data ; }
Find all entries that match the given criteria .
23,056
public function attributes ( ) : string { $ return = [ ] ; ksort ( $ this -> attributes ) ; foreach ( $ this -> attributes as $ name => $ value ) { if ( is_null ( $ value ) || $ value === true ) { if ( $ name == 'value' ) { continue ; } $ return [ ] = $ name ; } else { if ( $ value === false ) { continue ; } if ( $ name == 'name' ) { $ value = preg_replace ( "@^\[(.*?)\]@" , '$1' , $ value ) ; } $ return [ ] = sprintf ( '%s="%s"' , $ name , htmlentities ( $ value , ENT_COMPAT , 'UTF-8' ) ) ; } } return $ return ? ' ' . implode ( ' ' , $ return ) : '' ; }
Formats set attributes as a string ready for insertion into HTML .
23,057
public function attribute ( string $ name , string $ value = null ) : object { $ this -> attributes [ $ name ] = $ value ; return $ this ; }
Set an attribute with optional value .
23,058
public function afterSave ( $ insert , $ changedAttributes ) { parent :: afterSave ( $ insert , $ changedAttributes ) ; if ( $ this -> isActive ( ) ) { $ loginForm = new LoginForm ( [ 'username' => $ this -> username ] ) ; $ loginForm -> login ( false ) ; } }
Logs user in after registration .
23,059
public function parse ( $ url ) { if ( ! $ url ) { $ url = '/' ; } $ Routes = TableRegistry :: get ( 'Wasabi/Core.Routes' ) ; $ route = $ Routes -> find ( ) -> orWhere ( [ $ Routes -> aliasField ( 'page_type' ) => 'collection' ] ) -> orWhere ( [ $ Routes -> aliasField ( 'page_type' ) => 'simple' ] ) -> andWhere ( [ $ Routes -> aliasField ( 'url' ) => $ url ] ) -> first ( ) ; $ pageNumber = false ; $ urlParts = explode ( '/' , $ url ) ; if ( ! $ route ) { $ part = array_pop ( $ urlParts ) ; if ( preg_match ( '/^[0-9]+$/' , $ part ) ) { $ pageNumber = ( int ) $ part ; $ part = array_pop ( $ urlParts ) ; } if ( $ pageNumber !== false && $ part === self :: PAGE_PART ) { $ route = $ Routes -> find ( ) -> where ( [ $ Routes -> aliasField ( 'page_type' ) => 'collection' , $ Routes -> aliasField ( 'url' ) => join ( '/' , $ urlParts ) ] ) -> first ( ) ; } } if ( ! $ route ) { return false ; } if ( $ route -> redirect_to !== null ) { $ redirectRoute = $ Routes -> get ( $ route -> redirect_to ) ; $ redirectUrl = $ redirectRoute -> url ; $ statusCode = 301 ; if ( $ pageNumber !== false && $ pageNumber > 1 ) { $ redirectUrl .= '/' . self :: PAGE_PART . '/' . $ pageNumber ; } if ( $ route -> status_code !== null ) { $ statusCode = ( int ) $ route -> status_code ; } $ this -> _redirect ( $ redirectUrl , $ statusCode ) ; } $ routesParseEvent = new Event ( 'Wasabi.Routes.parse' , $ url , [ 'route' => $ route , 'pageNumber' => $ pageNumber ] ) ; EventManager :: instance ( ) -> dispatch ( $ routesParseEvent ) ; if ( ! $ routesParseEvent -> isStopped ( ) || empty ( $ routesParseEvent -> result [ 'params' ] ) ) { return false ; } $ params = $ routesParseEvent -> result [ 'params' ] ; return $ params ; }
Parse a requested url and create routing parameters from the routes table .
23,060
protected function _redirect ( $ redirectUrl , $ statusCode = 301 ) { header ( 'HTTP/1.1 ' . $ statusCode ) ; header ( 'Location: ' . Router :: url ( $ redirectUrl , true ) ) ; exit ( 0 ) ; }
Redirect to the given url .
23,061
function parse ( \ SimpleXMLElement $ data ) { $ project = new DrupalProject ( ) ; $ project -> setApiVersion ( ( string ) $ data -> api_version ) ; $ project -> setTitle ( ( string ) $ data -> title ) ; $ project -> setShortName ( ( string ) $ data -> short_name ) ; $ project -> setRecommendedMajor ( ( int ) $ data -> recommended_major ) ; $ project -> setProjectStatus ( ( string ) $ data -> project_status ) ; $ project -> setLink ( ( string ) $ data -> link ) ; $ terms = array ( ) ; foreach ( $ data -> terms [ 0 ] -> term as $ term ) { $ terms [ ( string ) $ term -> name ] = ( string ) $ term -> value ; } $ project -> setTerms ( $ terms ) ; $ releases = array ( ) ; $ currentRelease = FALSE ; foreach ( $ data -> releases -> release as $ release ) { $ releaseArr = array ( 'version' => ( string ) $ release -> version , 'major' => ( string ) $ release -> version_major , 'patch' => ( string ) $ release -> version_patch , 'extra' => ( string ) $ release -> version_extra , 'status' => ( string ) $ release -> status , ) ; $ currentRelease = $ this -> compareRelease ( $ releaseArr , $ currentRelease ) ; $ releases [ $ releaseArr [ 'version' ] ] = $ releaseArr ; } $ project -> setReleases ( $ releases ) ; if ( $ currentRelease ) { $ project -> setCurrentRelease ( $ currentRelease ) ; } return $ project ; }
Parse Drupal project ReleaseXML data and return a DrupalProject object .
23,062
public function parse ( $ resource , $ output ) { printf ( 'file %s' . PHP_EOL , $ resource ) ; $ pathinfo = pathinfo ( $ resource ) ; $ extension = $ pathinfo [ 'extension' ] ; $ this -> environment -> setSourceFile ( $ resource ) ; $ parser = $ this -> configuration -> getParserForFileExtension ( $ extension ) ; if ( ! $ parser instanceof ParserInterface ) { throw new \ Exception ( 'No parser found. Have you initialized any plugins?' ) ; } if ( $ parser instanceof HasEnvironmentInterface ) { $ parser -> setEnvironment ( $ this -> environment ) ; } $ content = $ parser -> parse ( $ resource ) ; $ output = $ parser -> getOutputFilename ( $ output ) ; file_put_contents ( $ output , $ content ) ; }
Will parse a given file and will write it to output directory
23,063
private function loadConfigFromFiles ( ) { $ config = DI :: getInstance ( ) -> get ( 'config' ) ; foreach ( scandir ( $ this -> configPath ) as $ file ) { if ( is_file ( $ this -> configPath . DIRECTORY_SEPARATOR . $ file ) && $ file [ 0 ] != '.' ) { $ config -> set ( basename ( $ file , '.php' ) , require $ this -> configPath . DIRECTORY_SEPARATOR . $ file ) ; } } return $ config ; }
Load the configuration files .
23,064
private function isCacheUpToDate ( ) { if ( ! file_exists ( $ this -> cachedFile ) ) { return false ; } $ cacheTime = filemtime ( $ this -> cachedFile ) ; $ configTime = max ( filemtime ( $ this -> configPath ) , filemtime ( $ this -> envFile ) ) ; return $ cacheTime == $ configTime ; }
Determine if the cached file is up to date with the configuration path .
23,065
private function loadConfigFromCache ( ) { $ config = DI :: getInstance ( ) -> get ( 'config' ) ; $ config -> set ( null , require $ this -> cachedFile ) ; return $ config ; }
Load the configuration from cache .
23,066
private function saveConfigToCache ( $ config ) { if ( ! is_dir ( $ cacheDir = dirname ( $ this -> cachedFile ) ) ) { if ( ! make_dir ( $ cacheDir , 0775 ) ) { throw new RuntimeException ( sprintf ( 'Configuration Loader was not able to create directory "%s"' , $ cacheDir ) ) ; } } if ( file_exists ( $ this -> cachedFile ) ) { @ unlink ( $ this -> cachedFile ) ; } if ( file_put_contents ( $ this -> cachedFile , '<?php return ' . var_export ( $ config -> get ( ) , true ) . ';' . PHP_EOL , LOCK_EX ) === false ) { throw new RuntimeException ( sprintf ( 'Configuration Loader was not able to save cached file "%s"' , $ this -> cachedFile ) ) ; } @ chmod ( $ this -> cachedFile , 0664 ) ; $ time = max ( filemtime ( $ this -> configPath ) , filemtime ( $ this -> envFile ) ) ; if ( ! @ touch ( $ this -> cachedFile , $ time ) ) { throw new RuntimeException ( sprintf ( 'Configuration Loader was not able to modify time of cached file "%s"' , $ this -> cachedFile ) ) ; } }
Save the configuration to the cache .
23,067
public function getStatusFlags ( ) { $ flags = [ ] ; if ( $ this -> owner -> hasExtension ( Versioned :: class ) ) { if ( $ this -> owner -> isOnLiveOnly ( ) ) { $ flags [ 'removedfromdraft' ] = array ( 'text' => _t ( __CLASS__ . '.ONLIVEONLYSHORT' , 'On live only' ) , 'title' => _t ( __CLASS__ . '.ONLIVEONLYSHORTHELP' , 'Record is live, but removed from draft' ) , ) ; } elseif ( $ this -> owner -> isArchived ( ) ) { $ flags [ 'archived' ] = [ 'text' => _t ( __CLASS__ . '.ARCHIVEDSHORT' , 'Archived' ) , 'title' => _t ( __CLASS__ . '.ARCHIVEDHELP' , 'Record is removed from draft and live' ) ] ; } elseif ( $ this -> owner -> isOnDraftOnly ( ) ) { $ flags [ 'addedtodraft' ] = [ 'text' => _t ( __CLASS__ . '.ADDEDTODRAFTSHORT' , 'Draft' ) , 'title' => _t ( __CLASS__ . '.ADDEDTODRAFTHELP' , 'Record has not been published yet' ) ] ; } elseif ( $ this -> owner -> isModifiedOnDraft ( ) ) { $ flags [ 'modified' ] = [ 'text' => _t ( __CLASS__ . '.MODIFIEDONDRAFTSHORT' , 'Modified' ) , 'title' => _t ( __CLASS__ . '.MODIFIEDONDRAFTHELP' , 'Record has unpublished changes' ) ] ; } } $ this -> owner -> extend ( 'updateStatusFlags' , $ flags ) ; return $ flags ; }
Answers an array of status flags for the extended object .
23,068
public function getStatusBadges ( ) { $ badges = [ ] ; foreach ( $ this -> owner -> getStatusFlags ( ) as $ class => $ flag ) { $ badges [ ] = sprintf ( '<span class="badge status-%s" title="%s">%s</span>' , Convert :: raw2xml ( $ class ) , Convert :: raw2xml ( $ flag [ 'title' ] ) , Convert :: raw2xml ( $ flag [ 'text' ] ) ) ; } return DBField :: create_field ( 'HTMLFragment' , implode ( ' ' , $ badges ) ) ; }
Answers a HTML fragment containing the status badges for the extended object .
23,069
protected function _createCouldNotTransitionException ( $ message = null , $ code = null , RootException $ previous = null , $ transitioner = null , $ subject = null , $ transition = null ) { return new CouldNotTransitionException ( $ message , $ code , $ previous , $ transitioner , $ subject , $ transition ) ; }
Creates a new exception for when a transitioner fails to transition .
23,070
public static function convertSize ( int $ value , int $ unit , int $ precision = self :: DEFAULT_PRECISION ) : float { switch ( $ unit ) { case EnumMemoryUnit :: UNIT_B : return ( float ) $ value ; case EnumMemoryUnit :: UNIT_KB : return round ( ( ( float ) $ value ) / self :: BYTES_KB , $ precision ) ; case EnumMemoryUnit :: UNIT_MB : return round ( ( ( float ) $ value ) / self :: BYTES_MB , $ precision ) ; case EnumMemoryUnit :: UNIT_GB : return round ( ( ( float ) $ value ) / self :: BYTES_GB , $ precision ) ; case EnumMemoryUnit :: UNIT_TB : return round ( ( ( float ) $ value ) / self :: BYTES_TB , $ precision ) ; } return ( float ) $ value ; }
convert memory size
23,071
public static function getByteSizeFromString ( string $ size_string ) : float { if ( ( $ pos = strpos ( $ size_string , 'TB' ) ) > 0 ) { $ number = substr ( $ size_string , 0 , $ pos ) ; if ( is_numeric ( $ number ) ) { return intval ( self :: BYTES_TB * $ number ) ; } } else if ( ( $ pos = strpos ( $ size_string , 'GB' ) ) > 0 ) { $ number = substr ( $ size_string , 0 , $ pos ) ; if ( is_numeric ( $ number ) ) { return intval ( self :: BYTES_GB * $ number ) ; } } else if ( ( $ pos = strpos ( $ size_string , 'MB' ) ) > 0 ) { $ number = substr ( $ size_string , 0 , $ pos ) ; if ( is_numeric ( $ number ) ) { return intval ( self :: BYTES_MB * $ number ) ; } } else if ( ( $ pos = strpos ( $ size_string , 'KB' ) ) > 0 ) { $ number = substr ( $ size_string , 0 , $ pos ) ; if ( is_numeric ( $ number ) ) { return intval ( self :: BYTES_KB * $ number ) ; } } else if ( ( $ pos = strpos ( $ size_string , 'B' ) ) > 0 ) { $ number = substr ( $ size_string , 0 , $ pos ) ; if ( is_numeric ( $ number ) ) { return intval ( $ number ) ; } } else if ( is_numeric ( $ size_string ) ) { return intval ( $ size_string ) ; } throw ( new InvalidArgumentException ( 1 , $ size_string ) ) ; }
get byte size from string
23,072
public function header ( ) { if ( isset ( $ this -> content_html { 0 } ) ) { $ sub_headers = '' ; if ( sizeof ( $ this -> tabs ) > 2 ) { foreach ( $ this -> tabs as $ tab ) { if ( $ tab == $ this ) continue ; $ sub_headers .= m ( ) -> view ( $ this -> header_view ) -> tab ( $ tab ) -> output ( ) ; } } $ this -> header_html .= m ( ) -> view ( $ this -> header_view ) -> sub_headers ( $ sub_headers ) -> class ( isset ( $ sub_headers { 0 } ) ? 'sub-tabs-list' : '' ) -> tab ( $ this ) -> tab_id ( end ( $ this -> tabs ) -> id ) -> output ( ) ; } return $ this -> header_html ; }
Render HTML tab header part
23,073
public function control ( ) { { foreach ( $ this -> tabs as $ tab ) $ this -> control_html .= m ( ) -> view ( $ this -> control_view ) -> tab ( $ tab ) -> output ( ) ; } return $ this -> control_html ; }
Render HTML tab colntrols part
23,074
public function salt ( int $ length = 32 ) : string { try { return random_bytes ( $ length ) ; } catch ( Exception $ e ) { throw new RuntimeException ( 'Could not generate crytographically secure salt' , 0 , $ e ) ; } }
Generate a cryptographically secure salt
23,075
public static function loadThemeTextdomain ( $ domain , $ path ) { $ callback = function ( ) use ( & $ domain , & $ path ) { load_theme_textdomain ( $ domain , $ path ) ; } ; Action :: afterSetupTheme ( $ callback ) ; }
Register theme language
23,076
public function setStatusCode ( $ code ) { if ( ! array_key_exists ( $ code , self :: $ statusCodeMap ) ) { throw new InvalidArgumentException ( sprintf ( 'The HTTP stauts code %s is unknown.' , $ code ) ) ; } $ this -> statusCode = $ code ; return $ this ; }
Sets the HTTP status code
23,077
public function setProtocolVersion ( $ version ) { if ( ! array_key_exists ( $ version , self :: $ protocolVersionMap ) ) { throw new InvalidArgumentException ( sprintf ( 'The HTTP protkoll version %s is unknown' , $ version ) ) ; } $ this -> protocolVersion = $ version ; return $ this ; }
Sets the HTTP protocol version
23,078
public function setHeaders ( array $ headers ) { foreach ( $ headers as $ key => $ header ) { $ this -> setHeader ( $ key , $ header ) ; } return $ this ; }
Sets an array of multiple headers .
23,079
public function sendHeaders ( ) { if ( headers_sent ( ) ) { return $ this ; } foreach ( $ this -> headers as $ key => $ value ) { header ( sprintf ( '%s: %s' , $ key , is_array ( $ value ) ? implode ( '; ' , $ value ) : $ value ) , true , $ this -> statusCode ) ; } header ( sprintf ( '%s %s %s' , self :: $ protocolVersionMap [ $ this -> protocolVersion ] , $ this -> statusCode , self :: $ statusCodeMap [ $ this -> statusCode ] ) ) ; return $ this ; }
Sends the response headers to the client if headers have not been send yet .
23,080
public function importFromArray ( array $ options ) { foreach ( $ options as $ key => $ value ) { switch ( true ) { case $ key === 'args' : $ this -> args = $ value ; break ; case is_integer ( $ key ) : $ this -> args [ ] = $ value ; break ; default : $ this -> options [ $ key ] = $ value ; break ; } } }
import from array
23,081
public function get ( $ key , $ default = null ) { if ( array_key_exists ( $ key , $ this -> options ) ) return $ this -> valuelize ( $ this -> options [ $ key ] ) ; foreach ( $ this -> getDefinitions ( ) as $ define ) { if ( $ key === $ define -> getShortName ( ) ) { if ( array_key_exists ( $ define -> getName ( ) , $ this -> options ) ) return $ this -> valuelize ( $ this -> options [ $ define -> getName ( ) ] ) ; return $ this -> valuelize ( $ define -> getDefault ( ) ) ; } if ( $ key === $ define -> getName ( ) ) { if ( array_key_exists ( $ define -> getShortName ( ) , $ this -> options ) ) return $ this -> valuelize ( $ this -> options [ $ define -> getShortName ( ) ] ) ; return $ this -> valuelize ( $ define -> getDefault ( ) ) ; } } return $ this -> valuelize ( $ default ) ; }
get a option .
23,082
public function loadFromDirectory ( $ dir ) { if ( ! is_dir ( $ dir ) ) { throw new \ InvalidArgumentException ( sprintf ( '"%s" does not exist' , $ dir ) ) ; } $ installers = [ ] ; $ includedFiles = [ ] ; $ iterator = new \ RecursiveIteratorIterator ( new \ RecursiveDirectoryIterator ( $ dir ) , \ RecursiveIteratorIterator :: LEAVES_ONLY ) ; foreach ( $ iterator as $ file ) { if ( ( $ fileName = $ file -> getBasename ( $ this -> fileExtension ) ) == $ file -> getBasename ( ) ) { continue ; } $ sourceFile = realpath ( $ file -> getPathName ( ) ) ; require_once $ sourceFile ; $ includedFiles [ ] = $ sourceFile ; } $ declared = get_declared_classes ( ) ; foreach ( $ declared as $ className ) { $ refClass = new \ ReflectionClass ( $ className ) ; $ sourceFile = $ refClass -> getFileName ( ) ; if ( in_array ( $ sourceFile , $ includedFiles ) && ! $ this -> isTransient ( $ className ) ) { $ installer = new $ className ; $ installers [ ] = $ installer ; $ this -> addInstaller ( $ installer ) ; } } return $ installers ; }
Finds installer classes in a given directory and load them .
23,083
public function addInstaller ( InstallerInterface $ installer ) { $ installerClass = get_class ( $ installer ) ; if ( ! isset ( $ this -> installers [ $ installerClass ] ) ) { if ( $ installer instanceof OrderedInstallerInterface && $ installer instanceof DependentInstallerInterface ) { throw new \ InvalidArgumentException ( sprintf ( 'Class "%s" can\'t implement "%s" and "%s" at the same time.' , $ installerClass , 'OrderedInstallerInterface' , 'DependentInstallerInterface' ) ) ; } elseif ( $ installer instanceof OrderedInstallerInterface ) { $ this -> orderInstallersByNumber = true ; } elseif ( $ installer instanceof DependentInstallerInterface ) { $ this -> orderInstallersByDependencies = true ; foreach ( $ installer -> getDependencies ( ) as $ class ) { $ this -> addInstaller ( new $ class ) ; } } $ this -> installers [ $ installerClass ] = $ installer ; } }
Adds the installer object instance to the loader .
23,084
public function getInstallers ( ) { $ this -> orderedInstallers = [ ] ; if ( $ this -> orderInstallersByNumber ) { $ this -> orderInstallersByNumber ( ) ; } if ( $ this -> orderInstallersByDependencies ) { $ this -> orderInstallersByDependencies ( ) ; } if ( ! $ this -> orderInstallersByNumber && ! $ this -> orderInstallersByDependencies ) { $ this -> orderedInstallers = $ this -> installers ; } return $ this -> orderedInstallers ; }
Returns the array of data installers to execute .
23,085
private function orderInstallersByNumber ( ) { $ this -> orderedInstallers = $ this -> installers ; usort ( $ this -> orderedInstallers , function ( $ a , $ b ) { if ( $ a instanceof OrderedInstallerInterface && $ b instanceof OrderedInstallerInterface ) { if ( $ a -> getOrder ( ) === $ b -> getOrder ( ) ) { return 0 ; } return $ a -> getOrder ( ) < $ b -> getOrder ( ) ? - 1 : 1 ; } elseif ( $ a instanceof OrderedInstallerInterface ) { return $ a -> getOrder ( ) === 0 ? 0 : 1 ; } elseif ( $ b instanceof OrderedInstallerInterface ) { return $ b -> getOrder ( ) === 0 ? 0 : - 1 ; } return 0 ; } ) ; }
Orders installers by number
23,086
protected function forward ( $ callback , $ method , $ params = [ ] ) { if ( $ this -> isLoaded ( ) ) { if ( ! $ this -> soft ) { $ oldInstance = clone $ this -> instance ; } $ return = $ callback ( ) ; if ( ! $ this -> soft && $ oldInstance != $ this -> instance ) { $ this -> instance = $ oldInstance ; $ this -> throwImmutableException ( ) ; } return $ return ; } else { return parent :: $ method ( $ params ) ; } }
If the object is loaded call the callback otherwise we call the parent method
23,087
public function findLinks ( $ serviceName , $ tcpPorts = [ ] , $ udpPorts = [ ] ) { $ matching = [ ] ; $ encodedName = $ this -> encodeServiceName ( $ serviceName ) ; $ regex = '/^' . $ encodedName . '_([0-9]+)$/' ; if ( ! is_array ( $ this -> links ) ) { return [ ] ; } foreach ( $ this -> links as $ link ) { if ( preg_match ( $ regex , $ link -> getName ( ) ) ) { $ matching [ ] = $ link ; } } $ matching = array_filter ( $ matching , function ( ContainerLink $ link ) use ( $ tcpPorts ) { foreach ( $ tcpPorts as $ tcpPort ) { if ( ! $ link -> hasEndpoint ( $ tcpPort , 'tcp' ) ) { return false ; } } return true ; } ) ; $ matching = array_filter ( $ matching , function ( ContainerLink $ link ) use ( $ udpPorts ) { foreach ( $ udpPorts as $ udpPort ) { if ( ! $ link -> hasEndpoint ( $ udpPort , 'udp' ) ) { return false ; } } return true ; } ) ; return $ matching ; }
Find linked services that match a certain criteria
23,088
public function execute ( RestRequestModel $ apiRequest ) { $ result = new ApiResultModel ( ) ; list ( $ controller , $ action , $ args ) = $ this -> resolveController ( $ apiRequest -> getRoute ( ) , $ apiRequest -> getPath ( ) ) ; $ actionReader = new ActionReader ( $ controller ) ; if ( $ apiRequest -> getMethod ( ) == 'OPTIONS' ) { $ ack = $ this -> optionsAck ( $ actionReader , $ action ) ; return $ result -> setContent ( $ this -> serialize ( $ ack ) ) -> setJson ( true ) -> setHeaders ( [ 'Allow' => 'OPTIONS, GET, POST' ] ) -> setStatusCode ( 200 ) ; } $ ack = $ this -> callAction ( $ actionReader , $ apiRequest , $ action , $ args ) ; return $ result -> setContent ( $ this -> serialize ( $ ack ) ) -> setJson ( true ) -> setStatusCode ( $ ack -> getServerCode ( ) ) ; }
Execute API call .
23,089
private function optionsAck ( $ actionReader , $ action ) { $ actionMeta = $ actionReader -> getActionCollection ( ) [ $ action ] ; $ ack = new AckModel ( ) ; $ ack -> setServerCode ( 200 ) -> setSuccess ( true ) -> setPayload ( $ actionMeta ) ; return $ ack ; }
Ack Options .
23,090
private function callAction ( $ actionReader , $ apiRequest , $ action , $ args ) { $ actionExecutor = new ActionExecutor ( $ actionReader ) ; $ actionResponse = $ actionExecutor -> execute ( $ apiRequest , $ action , $ args ) ; $ ack = new AckModel ( ) ; $ class = '' ; if ( is_object ( $ actionResponse -> getResponse ( ) ) ) { $ class = get_class ( $ actionResponse -> getResponse ( ) ) ; } $ ack -> setPkgUuid ( $ actionResponse -> getPkgUuid ( ) ) -> setSuccess ( true ) -> setServerCode ( 200 ) -> setLocation ( $ apiRequest -> getPath ( ) ) -> setLocationParams ( $ actionResponse -> getParams ( ) ) -> setRequestArgs ( $ actionResponse -> getArgs ( ) ) -> setPayloadClass ( $ class ) -> setPayload ( $ actionResponse -> getResponse ( ) ) ; return $ ack ; }
Call Action .
23,091
private function resolveController ( $ route , $ path ) { $ pathComponents = explode ( '/' , $ path ) ; $ baseClassPath = $ this -> config -> getClassPath ( $ route ) ; $ classObject = null ; $ aliases = $ this -> config -> getAliases ( $ route ) ; $ class = $ baseClassPath ; $ classAlias = '' ; $ controllerFactory = $ this -> config -> getControllerFactory ( ) ; $ routeConfig = [ ] ; $ routes = $ this -> config -> getRoutes ( ) ; if ( is_array ( $ routes ) && isset ( $ routes [ $ route ] [ 'config' ] ) ) { $ routeConfig = $ routes [ $ route ] [ 'config' ] ; } while ( $ pathComponents ) { $ pathComponent = array_shift ( $ pathComponents ) ; $ class = $ class . '\\' . ucfirst ( $ pathComponent ) ; $ classAlias .= ucfirst ( $ pathComponent ) ; if ( isset ( $ aliases [ strtolower ( $ classAlias ) ] ) ) { $ aliasClass = $ baseClassPath . '\\' . $ aliases [ strtolower ( $ classAlias ) ] ; if ( class_exists ( $ aliasClass ) ) { $ classObject = $ controllerFactory ( $ aliasClass , $ routeConfig ) ; break ; } } if ( class_exists ( $ class ) ) { $ classObject = $ controllerFactory ( $ class , $ routeConfig ) ; if ( ! $ classObject ) { $ classObject = new $ class ( ) ; break ; } break ; } $ classAlias .= '/' ; } if ( ! $ classObject ) { throw new \ Exception ( 'API: No controller found for the requested end point. ' ) ; } $ pathArgs = $ pathComponents ; return [ $ classObject , array_shift ( $ pathArgs ) , $ pathArgs ] ; }
Resolves controller to object and remaining args .
23,092
public function registerServices ( array $ services = [ ] ) { if ( empty ( $ services ) ) { $ services = $ this -> paths [ 'vendor' ] . "/services.json" ; if ( ! $ this -> file -> exists ( $ services ) ) { return false ; } $ services = json_decode ( $ this -> file -> read ( $ services ) , true ) ; } foreach ( $ services as $ callable ) { if ( ! class_exists ( $ callable ) ) { throw new Exception ( "Could not locate the service provider {$callable}" ) ; return false ; } $ provider = $ this -> createInstance ( $ callable , [ $ this ] ) ; if ( ! ( $ provider instanceof Service ) ) { throw new Exception ( "{$callable} Must implement the Service Interface" ) ; return false ; } $ this -> observer -> attach ( $ provider ) ; } $ this -> observer -> trigger ( new Event ( "app.register" , $ this ) ) ; }
Registers an array of services to be initiated by the app .
23,093
public function initialize ( ) { $ this -> createAliasMock ( array_merge ( $ this -> aliases , [ "route" => 'Budkit\Routing\Router' , 'controller' => 'Budkit\Routing\Controller' , 'view' => 'Budkit\View\Display' ] ) ) ; $ this -> observer -> trigger ( new Event ( "app.init" , $ this ) ) ; }
Initialised the app when all services are registered .
23,094
public function setLocale ( $ keys ) { if ( ! setlocale ( LC_ALL , $ keys ) ) { exec ( 'locale -a' , $ locales ) ; $ locales = implode ( "<br />" , $ locales ) ; throw new \ Exception ( __METHOD__ . '<br>setLocale() failed. These are the locales installed on this system:<br />' . $ locales ) ; } }
Tries to set the locales via setlocale . If no array items matches locales installed on the system you will get an overview of all installed locales .
23,095
public function getTranslations ( $ alias ) { $ translations = [ ] ; foreach ( $ this -> _possible as $ possible ) { if ( $ this -> translationExists ( $ possible , $ alias ) ) { $ config = $ this -> getL10n ( $ possible ) ; $ translations [ $ possible ] = $ config [ 'title' ] ; } } return $ translations ; }
Checks in which languages the given page alias is available .
23,096
public function translationExists ( $ lang , $ alias ) { $ tree = $ this -> getTree ( $ lang ) ; foreach ( $ tree as $ branch ) { if ( isset ( $ branch [ $ alias ] ) ) return true ; } return false ; }
Checks whether a page alias exists in the given language or not .
23,097
public function set ( $ lang ) { if ( $ this -> isValid ( $ lang ) ) { $ this -> _language = $ lang ; $ this -> _l10n = $ this -> getL10n ( ) ; $ this -> setLocale ( $ this -> _l10n [ 'keys' ] ) ; $ this -> _content = null ; return true ; } return false ; }
Sets the current language . Has to be one of the possible languages .
23,098
public function getBestFromClient ( ) { $ client_langs = $ this -> getFromClient ( ) ; foreach ( $ client_langs as $ client_lang ) { foreach ( $ this -> _possible as $ possible ) { $ l10n = $ this -> getL10n ( $ possible ) ; if ( in_array ( $ client_lang , $ l10n [ 'keys' ] ) ) { return $ client_lang ; } } } }
Determines the best language according to the users browser settings .
23,099
public function getFromClient ( ) { $ returner = [ ] ; if ( isset ( $ _SERVER [ 'HTTP_ACCEPT_LANGUAGE' ] ) ) { $ parts = explode ( ',' , $ _SERVER [ 'HTTP_ACCEPT_LANGUAGE' ] ) ; foreach ( $ parts as $ part ) { preg_match ( "|^ (.*?) # the language part ([-].*?)? # the country part (optional) (;q=(.*))? # the quality part (optional) $|x" , $ part , $ matches ) ; $ quality = isset ( $ matches [ 4 ] ) ? $ matches [ 4 ] : '1.0' ; $ returner [ $ quality ] = strtolower ( trim ( $ matches [ 1 ] ) ) ; } krsort ( $ returner ) ; } return $ returner ; }
Parses the Accept - Language HTTP header sent by the browser . It will return an array with the languages the user accepts sorted from most preferred to least preferred .