idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
4,600
private function getTemplates ( DataSourceViewInterface $ dataSource ) { $ templates = [ ] ; if ( isset ( $ this -> themes [ $ dataSource -> getName ( ) ] ) ) { $ templates [ ] = $ this -> themes [ $ dataSource -> getName ( ) ] ; } $ templates [ ] = $ this -> themes [ self :: DEFAULT_THEME ] ; return $ templates ; }
Return list of templates that might be useful to render DataSourceView . Always the last template will be default one .
4,601
private function getVars ( DataSourceViewInterface $ dataSource ) { return isset ( $ this -> themesVars [ $ dataSource -> getName ( ) ] ) ? $ this -> themesVars [ $ dataSource -> getName ( ) ] : [ ] ; }
Return vars passed to theme . Those vars will be added to block context .
4,602
private function getUrl ( DataSourceViewInterface $ dataSource , array $ options = [ ] , array $ parameters = [ ] ) { $ router = $ this -> container -> get ( 'router' ) ; return $ router -> generate ( $ options [ 'route' ] , array_merge ( isset ( $ this -> additional_parameters [ $ dataSource -> getName ( ) ] ) ? $ this -> additional_parameters [ $ dataSource -> getName ( ) ] : [ ] , isset ( $ options [ 'additional_parameters' ] ) ? $ options [ 'additional_parameters' ] : [ ] , $ parameters ) ) ; }
Return additional parameters that should be passed to the URL generation for specified datasource .
4,603
public static function snakeCase ( $ value ) { if ( ! ctype_lower ( $ value ) ) { $ value = preg_replace ( '/\s+/u' , '' , ucwords ( $ value ) ) ; $ value = preg_replace ( '/-/u' , '_' , $ value ) ; $ value = mb_strtolower ( preg_replace ( '/(.)(?=[A-Z])/u' , '$1_' , $ value ) , 'UTF-8' ) ; } return $ value ; }
Convert given input into snake case .
4,604
protected function notFound ( ServerRequestInterface $ request , ResponseInterface $ response ) { $ finalResponse = $ response -> withProtocolVersion ( $ request -> getProtocolVersion ( ) ) -> withStatus ( 404 ) -> withHeader ( 'Content-Type' , 'text/plain' ) ; $ finalResponse -> getBody ( ) -> write ( "Not found" ) ; return $ finalResponse ; }
Return with a 404 not found response
4,605
public function initiateLogin ( ) { if ( ! $ this -> canInitiateLogin ( ) ) { throw new \ RuntimeException ( 'Unable to initiate login' ) ; } $ uri = $ this -> getAuthenticationUri ( ) ; return $ this -> redirector -> redirect ( $ uri ) ; }
initiate the login process
4,606
public function getAuthenticationUri ( ) { if ( ! $ this -> canBuildAuthenticationUri ( ) ) { throw new \ RuntimeException ( 'Cannot build authentication uri, dependencies are missing' ) ; } $ uriParams = array ( 'client_id' => $ this -> clientId , 'response_type' => 'code' , 'redirect_uri' => $ this -> redirectUri , ) ; return $ this -> authorizeUri . '?' . http_build_query ( $ uriParams ) ; }
build the foursquare authentication uri that users are forwarded to for authentication
4,607
public function authenticateUser ( $ code ) { if ( ! $ this -> canAuthenticateUser ( ) ) { throw new \ RuntimeException ( 'Cannot authenticate user, dependencies are missing' ) ; } if ( ! $ this -> codeIsValid ( $ code ) ) { throw new \ InvalidArgumentException ( 'Foursquare code is invalid' ) ; } $ response = json_decode ( $ this -> httpClient -> get ( $ this -> accessTokenUri , array ( 'client_id' => $ this -> clientId , 'client_secret' => $ this -> clientSecret , 'grant_type' => 'authorization_code' , 'redirect_uri' => $ this -> redirectUri , 'code' => $ code , ) ) ) ; $ this -> token = isset ( $ response -> access_token ) ? $ response -> access_token : null ; return $ this -> token ; }
authenticate the user with the response code
4,608
protected function cleanManagerSet ( ) { foreach ( $ this -> managerSet as $ managerKey => $ manager ) { if ( ! $ manager -> isRunning ( ) ) { $ this -> getLogger ( ) -> debug ( "Daemon clean old manager : {$managerKey}" , [ __NAMESPACE__ ] ) ; unset ( $ this -> managerSet [ $ managerKey ] ) ; } } return $ this ; }
Clean Manager SET
4,609
protected function updateManagerSet ( ) { $ queueStatsServer = $ this -> getQueue ( ) -> getStats ( ) ; if ( ! isset ( $ queueStatsServer [ Queue :: STATS_QUEUES ] ) || count ( $ queueStatsServer [ Queue :: STATS_QUEUES ] ) == 0 ) { return $ this ; } $ managerOptionsSet = [ ] ; foreach ( $ queueStatsServer [ Queue :: STATS_QUEUES ] as $ workerClass => $ queueStats ) { if ( in_array ( $ workerClass , $ this -> managerIgnoreSet ) ) { continue ; } if ( ! class_exists ( $ workerClass ) ) { $ this -> managerIgnoreSet [ ] = $ workerClass ; continue ; } if ( $ queueStats [ Queue :: STATS_QUEUE_STOP ] ) { continue ; } if ( $ queueStats [ Queue :: STATS_JOBS_READY ] == 0 ) { continue ; } try { $ workerConfig = $ workerClass :: getConfig ( ) ; $ managerCount = $ this -> calcManagerSize ( $ queueStats [ Queue :: STATS_JOBS_READY ] , $ workerConfig [ AbstractWorker :: CONFIG_P_MANAGER_POOL_SIZE ] , $ workerConfig [ AbstractWorker :: CONFIG_P_MANAGERS_LIMIT ] ) ; $ managerOptionsSet [ $ workerClass ] = $ managerCount ; } catch ( WorkerException $ ex ) { $ this -> managerIgnoreSet [ ] = $ workerClass ; $ this -> getLogger ( ) -> warning ( $ ex -> getMessage ( ) , [ __NAMESPACE__ ] ) ; $ this -> getLogger ( ) -> warning ( "Daemon {$this->getAppId()} will ignore worker class {$workerClass}" , [ __NAMESPACE__ ] ) ; continue ; } catch ( \ Exception $ ex ) { $ this -> getLogger ( ) -> warning ( $ ex -> getMessage ( ) , [ __NAMESPACE__ ] ) ; continue ; } } if ( count ( $ managerOptionsSet ) == 0 ) { return $ this ; } $ appId = $ this -> getAppId ( ) ; $ bootstrapFile = $ this -> getConfig ( self :: CONFIG_BOOTSTRAP_FILE ) ; foreach ( $ managerOptionsSet as $ workerClass => $ managerCount ) { while ( $ managerCount -- ) { $ managerId = $ this -> buildManagerId ( $ workerClass , $ managerCount ) ; if ( array_key_exists ( $ managerId , $ this -> managerSet ) ) { continue ; } $ this -> getLogger ( ) -> debug ( "Daemon create manager : {$managerId}" , [ __NAMESPACE__ ] ) ; $ this -> managerSet [ $ managerId ] = new Manager ( $ managerId , $ appId , $ workerClass , $ bootstrapFile ) ; } } return $ this ; }
Update Manager SET
4,610
protected function getClassMetadata ( string $ class ) : ClassMetadata { $ factory = $ this -> getDoctrineHelper ( ) -> getMetadataFactory ( ) ; if ( ! $ factory -> hasMetadataFor ( $ class ) ) { throw new \ InvalidArgumentException ( sprintf ( 'No metadata found for class "%s"' , $ class ) ) ; } return $ factory -> getMetadataFor ( $ class ) ; }
Returns mapping information for class
4,611
private function protect ( ) { if ( ! in_array ( $ this -> type , self :: allAsString ( ) , true ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Invalid token type "%s"' , $ this -> type ) ) ; } }
Check if the tokenType exists in our list
4,612
public function add ( $ constant ) { if ( ! $ constant instanceof ConstantInterface ) { throw new \ InvalidArgumentException ( 'This Constant must be a instance of \ClassGeneration\ConstantInterface' ) ; } if ( $ constant -> getName ( ) === null ) { $ constant -> setName ( 'constant' . ( $ this -> count ( ) + 1 ) ) ; } return parent :: add ( $ constant ) ; }
Adds a new Constant at ConstantCollection .
4,613
public function toString ( ) { $ string = '' ; $ constants = $ this -> getIterator ( ) ; foreach ( $ constants as $ constant ) { $ string .= $ constant -> toString ( ) ; } return $ string ; }
Parse the Constant Collection to string .
4,614
public function setSelectOptions ( $ attr , $ options = null ) { $ optionsList = is_array ( $ attr ) ? $ attr : [ $ attr => $ options ] ; foreach ( $ optionsList as $ key => $ value ) $ this -> selectOptions [ $ key ] = $ value ; return $ this ; }
Sets the Select options .
4,615
public function ingest ( $ data_set ) { if ( strlen ( $ this -> _source_id ) == 0 ) { throw new DataSift_Exception_InvalidData ( 'Cannot make request without a source ID' ) ; } if ( empty ( $ data_set ) ) { throw new DataSift_Exception_InvalidData ( 'Cannot make request without a valid data set' ) ; } return $ this -> _user -> post ( $ this -> getSourceId ( ) , $ data_set , array ( ) , true ) ; }
Generates a curl request to the Ingestion Endpoint
4,616
public function addObject ( $ object , $ state , $ repository ) { $ data = $ repository -> getHydrator ( ) -> unhydrate ( $ object ) ; $ oid = spl_object_hash ( $ object ) ; $ id = isset ( $ data [ '_id' ] ) ? serialize ( $ data [ '_id' ] ) . $ repository -> getCollection ( ) : $ oid ; if ( ! isset ( $ this -> objectStates [ $ id ] ) ) { $ this -> objectStates [ $ id ] = $ state ; } $ this -> objects [ $ id ] = $ object ; $ this -> objectsRepository [ $ oid ] = $ repository ; }
Add an object
4,617
public function setObjectState ( $ object , $ state ) { if ( is_object ( $ object ) ) { $ oid = spl_object_hash ( $ object ) ; $ repository = $ this -> objectsRepository [ $ oid ] ; $ data = $ repository -> getHydrator ( ) -> unhydrate ( $ object ) ; $ id = isset ( $ data [ '_id' ] ) ? serialize ( $ data [ '_id' ] ) . $ repository -> getCollection ( ) : $ oid ; } else { return false ; } if ( ! isset ( $ this -> objectStates [ $ id ] ) && ! isset ( $ this -> objectStates [ $ oid ] ) ) { throw new Exception \ StateException ( ) ; } if ( ! in_array ( $ state , [ self :: OBJ_MANAGED , self :: OBJ_NEW , self :: OBJ_REMOVED ] ) ) { throw new Exception \ StateException ( "Invalid state '$state'" ) ; } if ( $ state == self :: OBJ_REMOVED && isset ( $ this -> objectStates [ $ oid ] ) && $ this -> objectStates [ $ oid ] == self :: OBJ_NEW ) { throw new Exception \ StateException ( "Can't change state to removed because object is not managed. Insert it in database before" ) ; } if ( isset ( $ this -> objectStates [ $ oid ] ) ) { unset ( $ this -> objectStates [ $ oid ] ) ; unset ( $ this -> objects [ $ oid ] ) ; } $ this -> objectStates [ $ id ] = $ state ; $ this -> objects [ $ id ] = $ object ; return true ; }
Update object state
4,618
public function getObjectState ( $ object ) { $ oid = spl_object_hash ( $ object ) ; if ( isset ( $ this -> objectsRepository [ $ oid ] ) ) { $ repository = $ this -> objectsRepository [ $ oid ] ; $ data = $ repository -> getHydrator ( ) -> unhydrate ( $ object ) ; $ id = isset ( $ data [ '_id' ] ) ? serialize ( $ data [ '_id' ] ) . $ repository -> getCollection ( ) : $ oid ; if ( isset ( $ this -> objectStates [ $ id ] ) ) { return $ this -> objectStates [ $ id ] ; } } return null ; }
Get object state
4,619
public function getObjects ( $ state = null ) { if ( ! isset ( $ state ) ) { return $ this -> objects ; } $ objectList = [ ] ; foreach ( $ this -> objects as $ id => $ object ) { if ( $ this -> objectStates [ $ id ] == $ state ) { $ objectList [ $ id ] = $ object ; } } return $ objectList ; }
Get object with specified state
4,620
public function hasObject ( $ object ) { $ oid = spl_object_hash ( $ object ) ; if ( ! isset ( $ this -> objectsRepository [ $ oid ] ) ) { return false ; } $ repository = $ this -> objectsRepository [ $ oid ] ; $ data = $ repository -> getHydrator ( ) -> unhydrate ( $ object ) ; $ id = isset ( $ data [ '_id' ] ) ? serialize ( $ data [ '_id' ] ) . $ repository -> getCollection ( ) : $ oid ; return isset ( $ this -> objects [ $ oid ] ) || isset ( $ this -> objects [ $ id ] ) ; }
Check if object is managed
4,621
public function filterByRole ( $ role , $ comparison = Criteria :: EQUAL ) { return $ this -> useUserRoleQuery ( ) -> filterByRole ( $ role , $ comparison ) -> endUse ( ) ; }
Filter the query by a related Role object using the user_role table as cross reference
4,622
protected function fetchDocumentData ( $ options ) { $ documents = $ this -> dependencyManager -> getDocuments ( $ options [ 'orderId' ] , $ options [ 'locale' ] ) ; if ( ! empty ( $ documents ) ) { foreach ( $ documents as $ document ) { $ data = $ document -> getSalesDocumentData ( ) ; parent :: addEntry ( $ data [ 'id' ] , $ data [ 'number' ] , $ data [ 'type' ] , $ data [ 'date' ] , parent :: getRoute ( $ data [ 'id' ] , $ data [ 'type' ] , 'details' ) , $ data [ 'pdfBaseUrl' ] ) ; } } }
Retrieves document data for a specific order and adds it to the entries
4,623
static function getInstance ( $ name = null ) { if ( empty ( $ name ) ) { $ name = get_called_class ( ) ; } if ( ! empty ( static :: $ plugins [ $ name ] ) ) { return static :: $ plugins [ $ name ] ; } return false ; }
Get the existing instance of this Plugin .
4,624
protected function registerRequestBindings ( ) { $ this -> singleton ( 'Illuminate\Http\Request' , function ( ) { $ request = Request :: capture ( ) ; $ this -> response = new Response ; $ manager = $ this [ 'session' ] ; $ middleware = new StartSession ( $ manager ) ; $ middleware -> handle ( $ request , function ( ) { return $ this -> response ; } ) ; foreach ( $ this -> response -> headers -> getCookies ( ) as $ cookie ) { @ header ( 'Set-Cookie: ' . $ cookie ) ; } return $ request ; } ) ; }
Register container bindings for the plugin .
4,625
static function bootstrap ( $ bootstrap ) { $ basepath = realpath ( dirname ( $ bootstrap ) ) ; $ fs = new Filesystem ; $ pluginSrcFile = $ basepath . '/src/plugin.php' ; require_once $ pluginSrcFile ; $ source = $ fs -> get ( $ pluginSrcFile ) ; $ pluginClass = static :: getFirstPluginClassName ( $ source ) ; if ( ! empty ( static :: $ plugins [ $ pluginClass ] ) ) { return static :: $ plugins [ $ pluginClass ] ; } if ( ! file_exists ( $ composer = $ basepath . '/vendor/autoload.php' ) ) { spl_autoload_register ( function ( $ name ) use ( $ fs , $ basepath ) { $ src = $ basepath . '/src' ; $ files = $ fs -> glob ( $ src . '/**/*.php' ) ; static $ classmap ; if ( $ classmap === null ) { $ classmap = [ ] ; foreach ( $ files as $ file ) { $ contents = $ fs -> get ( $ file ) ; $ namespace = '' ; if ( preg_match ( '/namespace\s+(.*?);/i' , $ contents , $ matches ) ) { $ namespace = $ matches [ 1 ] ; } if ( preg_match_all ( '/class\s+([\w\_]+).*?{/i' , $ contents , $ matches ) ) { foreach ( $ matches [ 1 ] as $ className ) { $ classmap [ "{$namespace}\\{$className}" ] = $ file ; } } } } if ( ! empty ( $ classmap [ $ name ] ) ) { require_once $ classmap [ $ name ] ; } } ) ; } $ plugin = new $ pluginClass ( $ bootstrap ) ; static :: $ plugins [ $ pluginClass ] = $ plugin ; static :: $ plugins [ $ plugin -> getSlug ( ) ] = $ plugin ; return static :: $ plugins [ $ pluginClass ] ; }
Bootstrap a plugin found in the given bootstrap file .
4,626
protected function getDefaultDatabaseConnectionConfig ( ) { global $ table_prefix ; $ default = [ 'driver' => 'mysql' , 'host' => getenv ( 'DB_HOST' ) , 'port' => getenv ( 'DB_PORT' ) , 'database' => getenv ( 'DB_NAME' ) , 'username' => getenv ( 'DB_USER' ) , 'password' => getenv ( 'DB_PASSWORD' ) , 'charset' => getenv ( 'DB_CHARSET' ) , 'collation' => getenv ( 'DB_COLLATE' ) , 'prefix' => getenv ( 'DB_PREFIX' ) ? : $ table_prefix , 'timezone' => getenv ( 'DB_TIMEZONE' ) ? : '+00:00' , 'strict' => getenv ( 'DB_STRICT_MODE' ) ? : false , ] ; if ( empty ( $ default [ 'database' ] ) && defined ( 'DB_NAME' ) ) { $ default [ 'database' ] = DB_NAME ; } if ( empty ( $ default [ 'username' ] ) && defined ( 'DB_USER' ) ) { $ default [ 'username' ] = DB_USER ; } if ( empty ( $ default [ 'password' ] ) && defined ( 'DB_PASSWORD' ) ) { $ default [ 'password' ] = DB_PASSWORD ; } if ( empty ( $ default [ 'host' ] ) && defined ( 'DB_HOST' ) ) { $ default [ 'host' ] = DB_HOST ; } if ( empty ( $ default [ 'charset' ] ) && defined ( 'DB_CHARSET' ) ) { $ default [ 'charset' ] = DB_CHARSET ; } if ( empty ( $ default [ 'collation' ] ) ) { if ( defined ( 'DB_COLLATE' ) && DB_COLLATE ) { $ default [ 'collation' ] = DB_COLLATE ; } else { $ default [ 'collation' ] = 'utf8_unicode_ci' ; } } return $ default ; }
Try to load the database configuration from the environment first using getenv ; finding none look to the traditional constants typically defined in wp - config . php
4,627
protected function bootstrapContainer ( ) { $ this -> instance ( 'app' , $ this ) ; $ this -> instance ( 'Illuminate\Container\Container' , $ this ) ; $ this -> instance ( 'path' , $ this -> path ( ) ) ; $ this -> configure ( 'app' ) ; $ this -> configure ( 'scout' ) ; $ this -> configure ( 'services' ) ; $ this -> configure ( 'session' ) ; $ this -> configure ( 'mail' ) ; $ this -> registerContainerAliases ( ) ; $ this -> bindActionsAndFilters ( ) ; $ this -> register ( \ Illuminate \ Session \ SessionServiceProvider :: class ) ; $ this -> register ( \ FatPanda \ Illuminate \ WordPress \ Providers \ Mail \ MailServiceProvider :: class ) ; $ this -> register ( Providers \ Session \ WordPressSessionServiceProvider :: class ) ; $ this -> register ( Providers \ Scout \ ScoutServiceProvider :: class ) ; $ this -> singleton ( \ Illuminate \ Contracts \ Console \ Kernel :: class , WordPressConsoleKernel :: class ) ; $ this -> singleton ( \ Illuminate \ Contracts \ Debug \ ExceptionHandler :: class , WordPressExceptionHandler :: class ) ; }
Bootstrap the plugin container .
4,628
public function storagePath ( $ path = null ) { return WP_CONTENT_DIR . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . Str :: slug ( $ this -> getNamespaceName ( ) ) . DIRECTORY_SEPARATOR . ( $ path ? DIRECTORY_SEPARATOR . $ path : $ path ) ; }
Get the storage path for the plugin
4,629
public function register ( $ provider , $ options = [ ] , $ force = false ) { if ( is_string ( $ provider ) || is_class ( $ provider ) ) { $ implements = class_implements ( $ provider ) ; if ( isset ( $ implements [ 'FatPanda\Illuminate\WordPress\Concerns\CustomSchema' ] ) ) { $ this -> customSchema [ ] = $ provider ; return $ this ; } if ( isset ( $ implements [ 'FatPanda\Illuminate\WordPress\Concerns\CanShortcode' ] ) ) { call_user_func_array ( $ provider . '::register' , [ $ this ] ) ; return $ this ; } } if ( ! $ provider instanceof ServiceProvider ) { $ provider = new $ provider ( $ this ) ; } if ( array_key_exists ( $ providerName = get_class ( $ provider ) , $ this -> loadedProviders ) ) { return $ this ; } $ this -> loadedProviders [ $ providerName ] = true ; if ( method_exists ( $ provider , 'register' ) ) { $ provider -> register ( ) ; } if ( method_exists ( $ provider , 'boot' ) ) { return $ this -> call ( [ $ provider , 'boot' ] ) ; } return $ this ; }
Register a service provider or a CustomSchema with the plugin .
4,630
protected function registerArtisanCommand ( ) { if ( ! class_exists ( 'WP_CLI' ) ) { return false ; } \ WP_CLI :: add_command ( $ this -> getCLICommandName ( ) , function ( ) { $ args = [ ] ; if ( ! empty ( $ _SERVER [ 'argv' ] ) ) { $ args = array_slice ( $ _SERVER [ 'argv' ] , 2 ) ; array_unshift ( $ args , $ _SERVER [ 'argv' ] [ 0 ] ) ; } $ this -> artisan -> handle ( new \ Symfony \ Component \ Console \ Input \ ArgvInput ( $ args ) , new \ Symfony \ Component \ Console \ Output \ ConsoleOutput ) ; } ) ; }
Create a WP - CLI command for running Artisan .
4,631
protected function registerRestRouter ( ) { $ this -> singleton ( 'FatPanda\Illuminate\WordPress\Http\Router' , function ( ) { $ router = new Router ( $ this ) ; $ router -> setNamespace ( $ this -> getRestNamespace ( ) ) ; $ router -> setVersion ( $ this -> getRestVersion ( ) ) ; $ router -> setControllerClasspath ( $ this -> getNamespaceName ( ) . '\\Http\\Controllers' ) ; $ plugin = $ this ; require $ this -> basePath ( 'src/routes.php' ) ; return $ router ; } ) ; }
Create router instance and load routes
4,632
public function toCsv ( $ filename = null ) { if ( ! is_null ( $ filename ) ) { $ this -> setFilename ( $ filename ) ; } if ( ! $ this -> hasFilename ( ) ) { $ this -> setFilename ( $ this -> filenameDefault ) ; } $ renderer = $ this -> getRenderer ( ) ; $ this -> setRenderer ( new Csv ( ) ) ; if ( $ this -> hasExport ( ) ) { call_user_func ( $ this -> export , $ this ) ; } $ this -> render ( ) ; $ this -> setRenderer ( $ renderer ) ; return $ this ; }
Export dans un fichier CSV
4,633
public function getSEOFields ( ) { $ config = SiteConfig :: current_site_config ( ) ; $ SEO = [ ] ; if ( $ config -> CanonicalEnabled ( ) ) { $ SEO [ ] = ReadonlyField :: create ( 'ReadonlyMetaCanonical' , 'link rel="canonical"' , $ this -> owner -> AbsoluteLink ( ) ) ; } if ( $ config -> TitleEnabled ( ) ) { $ SEO [ ] = TextField :: create ( 'MetaTitle' , 'meta title' ) -> setAttribute ( 'placeholder' , $ this -> owner -> GenerateTitle ( ) ) ; } $ SEO [ ] = TextareaField :: create ( 'MetaDescription' , 'meta description' ) -> setAttribute ( 'placeholder' , $ this -> owner -> GenerateDescriptionFromContent ( ) ) ; if ( $ config -> ExtraMetaEnabled ( ) ) { $ SEO [ ] = TextareaField :: create ( 'ExtraMeta' , 'Custom Metadata' ) ; } return $ SEO ; }
Gets SEO fields .
4,634
public function getFullOutput ( ) { return array ( LiteralField :: create ( 'HeaderMetadata' , '<pre class="bold">$Metadata()</pre>' ) , LiteralField :: create ( 'LiteralMetadata' , '<pre>' . nl2br ( htmlentities ( trim ( $ this -> owner -> Metadata ( ) ) , ENT_QUOTES ) ) . '</pre>' ) ) ; }
Gets the full output .
4,635
public function Metadata ( ) { $ config = SiteConfig :: current_site_config ( ) ; $ metadata = PHP_EOL . $ this -> owner -> MarkupComment ( 'SEO' ) ; $ this -> owner -> extend ( 'updateMetadata' , $ config , $ this -> owner , $ metadata ) ; $ metadata .= $ this -> owner -> MarkupComment ( 'END SEO' ) ; return $ metadata ; }
Main function to format & output metadata as an HTML string .
4,636
public function updateMetadata ( SiteConfig $ config , SiteTree $ owner , & $ metadata ) { $ metadata .= $ owner -> MarkupComment ( 'Metadata' ) ; if ( $ config -> CharsetEnabled ( ) ) { $ metadata .= '<meta charset="' . $ config -> Charset ( ) . '" />' . PHP_EOL ; } if ( $ config -> CanonicalEnabled ( ) ) { $ metadata .= $ owner -> MarkupLink ( 'canonical' , $ owner -> AbsoluteLink ( ) ) ; } if ( $ config -> TitleEnabled ( ) ) { $ metadata .= '<title>' . $ owner -> encodeContent ( $ owner -> GenerateTitle ( ) , $ config -> Charset ( ) ) . '</title>' . PHP_EOL ; } if ( $ description = $ owner -> GenerateDescription ( ) ) { $ metadata .= $ owner -> MarkupMeta ( 'description' , $ description , $ config -> Charset ( ) ) ; } if ( $ config -> ExtraMetaEnabled ( ) ) { $ metadata .= $ owner -> MarkupComment ( 'Extra Metadata' ) ; $ metadata .= $ owner -> GenerateExtraMeta ( ) ; } }
Updates metadata fields .
4,637
public function MarkupMeta ( $ name , $ content , $ encode = null ) { if ( $ encode !== null ) { return '<meta name="' . $ name . '" content="' . $ this -> encodeContent ( $ content , $ encode ) . '" />' . PHP_EOL ; } else { return '<meta name="' . $ name . '" content="' . $ content . '" />' . PHP_EOL ; } }
Returns markup for a HTML meta element . Can be flagged for encoding .
4,638
public function MarkupLink ( $ rel , $ href , $ type = null , $ sizes = null ) { $ return = '<link rel="' . $ rel . '" href="' . $ href . '"' ; if ( $ type !== null ) { $ return .= ' type="' . $ type . '"' ; } if ( $ sizes !== null ) { $ return .= ' sizes="' . $ sizes . '"' ; } $ return .= ' />' . PHP_EOL ; return $ return ; }
Returns markup for a HTML link element .
4,639
public function GenerateDescription ( ) { if ( $ this -> owner -> MetaDescription ) { return $ this -> owner -> MetaDescription ; } else { return $ this -> owner -> GenerateDescriptionFromContent ( ) ; } }
Generates description from the page MetaDescription or the first paragraph of the Content attribute .
4,640
public function GenerateDescriptionFromContent ( ) { if ( $ content = trim ( $ this -> owner -> Content ) ) { if ( preg_match ( '/<p>(.*?)<\/p>/i' , $ content , $ match ) ) { $ content = $ match [ 0 ] ; } else { $ content = explode ( PHP_EOL , $ content ) ; $ content = $ content [ 0 ] ; } return trim ( html_entity_decode ( strip_tags ( $ content ) ) ) ; } else { return null ; } }
Generates description from the first paragraph of the Content attribute .
4,641
public function GenerateExtraMeta ( ) { if ( $ this -> owner -> ExtraMeta ) { return $ this -> owner -> ExtraMeta . PHP_EOL ; } else { return $ this -> owner -> MarkupComment ( 'none' ) ; } }
Generates extra metadata .
4,642
public function isCurrent ( ) { $ link = $ this -> getLink ( ) ; if ( $ link { 0 } == '/' ) { $ link = substr ( $ link , 1 ) ; } return request ( ) -> is ( $ link ) ; }
Return TRUE if the current page is this page
4,643
private function queryArray ( $ query , $ options , $ fetcher ) { $ statement = $ this -> _runQuery ( $ query , $ options ) ; $ result = call_user_func ( $ fetcher , $ statement ) ; return is_array ( $ result ) ? $ result : [ ] ; }
executes SELECT or SHOW query and returns result array
4,644
public function queryValue ( $ query , $ options = array ( ) ) { $ statement = $ this -> _runQuery ( $ query , $ options ) ; return $ statement -> fetch ( \ PDO :: FETCH_COLUMN ) ; }
executes SELECT or SHOW query and returns 1st returned element
4,645
public function queryAssoc ( $ query , $ options = array ( ) ) { $ statement = $ this -> _runQuery ( $ query , $ options ) ; return $ statement -> fetch ( \ PDO :: FETCH_ASSOC ) ; }
executes SELECT or SHOW query and returns 1st row as assoc array
4,646
public function queryList ( $ query , $ options = array ( ) ) { $ statement = $ this -> _runQuery ( $ query , $ options ) ; return $ statement -> fetch ( \ PDO :: FETCH_NUM ) ; }
executes SELECT or SHOW query and returns as array
4,647
public function queryVector ( $ query , $ options = array ( ) ) { return $ this -> queryArray ( $ query , $ options , function ( \ PDOStatement $ statement ) { return $ statement -> fetchAll ( \ PDO :: FETCH_COLUMN , 0 ) ; } ) ; }
executes SELECT or SHOW query and returns result as array
4,648
public function queryTable ( $ query , $ options = array ( ) ) { return $ this -> queryArray ( $ query , $ options , function ( \ PDOStatement $ statement ) { return $ statement -> fetchAll ( \ PDO :: FETCH_ASSOC ) ; } ) ; }
executes SELECT or SHOW query and returns result as assoc array
4,649
public function queryObjArray ( $ query , $ className , $ options = array ( ) , $ classConstructorArguments = NULL ) { if ( ! class_exists ( $ className ) ) { $ this -> _error ( FQDBException :: CLASS_NOT_EXIST , FQDBException :: FQDB_CODE ) ; } return $ this -> queryArray ( $ query , $ options , function ( \ PDOStatement $ statement ) use ( $ className , $ classConstructorArguments ) { return $ statement -> fetchAll ( \ PDO :: FETCH_CLASS | \ PDO :: FETCH_PROPS_LATE , $ className , $ classConstructorArguments ) ; } ) ; }
executes SELECT or SHOW query and returns result as array of objects of given class
4,650
public function queryObj ( $ query , $ className , $ options = array ( ) , $ classConstructorArguments = NULL ) { if ( ! class_exists ( $ className ) ) { $ this -> _error ( FQDBException :: CLASS_NOT_EXIST , FQDBException :: FQDB_CODE ) ; } $ statement = $ this -> _runQuery ( $ query , $ options ) ; $ statement -> setFetchMode ( \ PDO :: FETCH_CLASS | \ PDO :: FETCH_PROPS_LATE , $ className , $ classConstructorArguments ) ; return $ statement -> fetch ( ) ; }
executes SELECT or SHOW query and returns object of given class
4,651
public function queryTableCallback ( $ query , $ options = [ ] , $ callback ) { if ( ! is_callable ( $ callback ) ) { $ this -> _error ( FQDBException :: NOT_CALLABLE_ERROR , FQDBException :: FQDB_CODE ) ; } $ statement = $ this -> _runQuery ( $ query , $ options ) ; while ( $ row = $ statement -> fetch ( \ PDO :: FETCH_ASSOC ) ) { call_user_func ( $ callback , $ row ) ; } return true ; }
Execute query and apply a callback function to each row
4,652
public function queryTableGenerator ( $ query , $ options = [ ] ) { $ statement = $ this -> _runQuery ( $ query , $ options ) ; while ( $ row = $ statement -> fetch ( \ PDO :: FETCH_ASSOC ) ) { yield $ row ; } }
Execute a query and makes generator from the result
4,653
public function queryHash ( $ query , $ options = array ( ) ) { return $ this -> queryArray ( $ query , $ options , function ( \ PDOStatement $ statement ) { return $ statement -> fetchAll ( \ PDO :: FETCH_KEY_PAIR ) ; } ) ; }
executes SELECT or SHOW query and returns an assoc array made of two - columns where the first column is a key and the second column is the value
4,654
public function read ( $ folders = array ( ) , Route $ value = null , $ regex = '' ) { if ( is_null ( $ value ) ) { $ value = new Route ( ) ; } while ( ! empty ( $ folders ) && empty ( $ folders [ 0 ] ) ) { array_shift ( $ folders ) ; } if ( empty ( $ folders ) ) { return '^' . $ regex . '[\/]?$' ; } else { $ folder = array_shift ( $ folders ) ; $ decoded = json_decode ( $ folder , true ) ; if ( ! is_null ( $ decoded ) && is_array ( $ decoded ) ) { $ param_regex = '' ; $ param_required = false ; foreach ( $ decoded as $ key => $ string ) { $ this -> logger -> debug ( "Route parser - parameter key: $key" ) ; $ this -> logger -> debug ( "Route parser - parameter string: $string" ) ; $ param_regex .= $ this -> param ( $ key , $ string , $ value ) ; if ( $ value -> isQueryRequired ( $ key ) ) { $ param_required = true ; } $ this -> logger -> debug ( "Route parser - parameter regex: $param_regex" ) ; } return $ this -> read ( $ folders , $ value , $ regex . '(?:\/' . $ param_regex . ')' . ( ( $ param_required ) ? '{1}' : '?' ) ) ; } else { $ value -> addService ( $ folder ) ; return $ this -> read ( $ folders , $ value , $ regex . '\/' . $ folder ) ; } } }
the global regular expression against which all the request URI will be compared
4,655
private function param ( $ key , $ string , $ value ) { $ field_required = false ; if ( preg_match ( '/^(.+)\*$/' , $ key , $ bits ) ) { $ key = $ bits [ 1 ] ; $ field_required = true ; } $ value -> setQuery ( $ key , $ string , $ field_required ) ; $ string = preg_replace ( "/(?<!\\\\)\\((?!\\?)/" , '(?:' , $ string ) ; $ string = preg_replace ( "/\\.([\\*\\+])(?!\\?)/" , '.${1}?' , $ string ) ; $ string = preg_replace ( "/^[\\^]/" , '' , $ string ) ; $ string = preg_replace ( "/[\\$]$/" , '' , $ string ) ; return '(?P<' . $ key . '>' . $ string . ')' . ( ( $ field_required ) ? '{1}' : '?' ) ; }
This method read a single parameter and build the regular expression
4,656
public static function reset ( ) { $ _SERVER [ 'REQUEST_URI' ] = '/' ; $ _SERVER [ 'REQUEST_METHOD' ] = 'GET' ; $ _GET = $ _POST = $ _FILES = $ _REQUEST = [ ] ; self :: $ code = 200 ; self :: $ head = [ ] ; self :: $ body_raw = null ; self :: $ body = null ; self :: $ errno = 0 ; self :: $ data = [ ] ; }
Reset fake HTTP variables and properties .
4,657
public function override_callback_args ( array $ args = [ ] ) { foreach ( $ args as $ key => $ val ) { if ( ! in_array ( $ key , [ 'get' , 'post' , 'files' , 'put' , 'patch' , 'delete' , ] ) ) continue ; self :: $ override_args [ $ key ] = $ val ; } }
Overrides callback args .
4,658
public function abort_custom ( int $ code ) { self :: $ code = $ code ; static :: $ body_raw = "ERROR: $code" ; self :: $ body = "ERROR: $code" ; self :: $ errno = $ code ; self :: $ data = [ ] ; }
Custom abort for testing .
4,659
public function redirect_custom ( string $ url ) { self :: $ code = 301 ; self :: $ head = [ "Location: $url" ] ; self :: $ body_raw = self :: $ body = "Location: $url" ; self :: $ errno = 0 ; self :: $ data = [ $ url ] ; }
Custom redirect for testing .
4,660
public function static_file_custom ( string $ path , int $ cache = 0 , $ disposition = null ) { self :: reset ( ) ; if ( file_exists ( $ path ) ) { self :: $ code = 200 ; self :: $ body_raw = file_get_contents ( $ path ) ; self :: $ body = "Path: $path" ; self :: $ errno = 0 ; self :: $ data = [ $ path ] ; } else { self :: $ code = 404 ; } }
Custom static file serving for testing .
4,661
private function registerRoute ( $ folders , $ type , $ class = null , array $ parameters = [ ] ) { $ route = new Route ( ) ; $ this -> updateRoute ( $ route , $ type , $ class , $ parameters ) ; $ this -> logger -> debug ( "Route table - route: " . implode ( "/" , $ folders ) ) ; $ regex = $ this -> parser -> read ( $ folders , $ route ) ; $ this -> logger -> debug ( "Route table - route regex: $regex" ) ; $ this -> routes = array_merge ( $ this -> routes , [ $ regex => $ route ] ) ; }
This method add a route to the supported list
4,662
protected function mailConfigCheck ( ) { if ( ! $ this -> app [ 'config' ] -> get ( 'general/mailoptions' ) && $ this -> app [ 'users' ] -> getCurrentuser ( ) && $ this -> app [ 'users' ] -> isAllowed ( 'files:config' ) ) { $ notice = json_encode ( [ 'severity' => 1 , 'notice' => 'The <strong>mail configuration parameters</strong> have not been set up. This may interfere with password resets, and extension functionality. Please set up the <code>mailoptions</code> in <code>config.yml</code>.' , ] ) ; $ this -> app [ 'logger.flash' ] -> configuration ( $ notice ) ; } }
No mail transport has been set . We should gently nudge the user to set the mail configuration .
4,663
protected function liveCheck ( Request $ request ) { if ( ! $ this -> app [ 'debug' ] ) { return ; } $ host = parse_url ( $ request -> getSchemeAndHttpHost ( ) ) ; if ( filter_var ( $ host [ 'host' ] , FILTER_VALIDATE_IP ) !== false ) { return ; } $ domainPartials = ( array ) $ this -> app [ 'config' ] -> get ( 'general/debug_local_domains' , [ ] ) ; $ domainPartials = array_unique ( array_merge ( ( array ) $ domainPartials , $ this -> defaultDomainPartials ) ) ; foreach ( $ domainPartials as $ partial ) { if ( strpos ( $ host [ 'host' ] , $ partial ) !== false ) { return ; } } $ notice = json_encode ( [ 'severity' => 2 , 'notice' => "It seems like this website is running on a <strong>non-development environment</strong>, while 'debug' is enabled. Make sure debug is disabled in production environments. If you don't do this, it will result in an extremely large <code>app/cache</code> folder and a measurable reduced performance across all pages." , 'info' => "If you wish to hide this message, add a key to your <code>config.yml</code> with a (partial) domain name in it, that should be seen as a development environment: <code>debug_local_domains: [ '.foo' ]</code>." , ] ) ; $ this -> app [ 'logger.flash' ] -> configuration ( $ notice ) ; }
Check whether the site is live or not .
4,664
protected function writableFolderCheck ( ) { $ fileName = '/configtester_' . date ( 'Y-m-d-h-i-s' ) . '.txt' ; $ fileSystems = [ [ 'name' => 'files' , 'folder' => '' , 'label' => '<code>files/</code> in the webroot' ] , [ 'name' => 'extensions' , 'folder' => '' , 'label' => '<code>extensions/</code> in the webroot' ] , [ 'name' => 'config' , 'folder' => '' ] , [ 'name' => 'cache' , 'folder' => '' ] , ] ; if ( $ this -> app [ 'config' ] -> get ( 'general/database/driver' ) === 'pdo_sqlite' ) { $ fileSystems [ ] = [ 'name' => 'app' , 'folder' => 'database' ] ; } $ fileSystems = Bag :: fromRecursive ( $ fileSystems ) ; foreach ( $ fileSystems as $ fileSystem ) { $ contents = $ this -> isWritable ( $ fileSystem , $ fileName ) ; if ( $ contents != 'ok' ) { $ folderName = $ this -> getFoldername ( $ fileSystem ) ; $ notice = json_encode ( [ 'severity' => 1 , 'notice' => 'Bolt needs to be able to <strong>write files to</strong> the folder <code>' . $ folderName . "</code>, but it doesn't seem to be writable." , 'info' => 'Make sure the folder exists, and is writable to the webserver.' , ] ) ; $ this -> app [ 'logger.flash' ] -> configuration ( $ notice ) ; } } }
Check if some common file locations are writable .
4,665
protected function canonicalCheck ( Request $ request ) { $ hostname = strtok ( $ request -> getUri ( ) , '?' ) ; $ canonical = strtok ( $ this -> app [ 'canonical' ] -> getUrl ( ) ) ; if ( ! empty ( $ canonical ) && ( $ hostname != $ canonical ) ) { $ notice = json_encode ( [ 'severity' => 1 , 'notice' => "The <code>canonical hostname</code> is set to <code>$canonical</code> in <code>config.yml</code>, but you are currently logged in using another hostname. This might cause issues with uploaded files, or links inserted in the content." , 'info' => sprintf ( "Log in on Bolt using the proper URL: <code><a href='%s'>%s</a></code>." , $ this -> app [ 'canonical' ] -> getUrl ( ) , $ this -> app [ 'canonical' ] -> getUrl ( ) ) , ] ) ; $ this -> app [ 'logger.flash' ] -> configuration ( $ notice ) ; } }
Check if the current url matches the canonical .
4,666
protected function maintenanceCheck ( ) { if ( $ this -> app [ 'config' ] -> get ( 'general/maintenance_mode' , false ) ) { $ notice = json_encode ( [ 'severity' => 1 , 'notice' => "Bolt's <strong>maintenance mode</strong> is enabled. This means that non-authenticated users will not be able to see the website." , 'info' => 'To make the site available to the general public again, set <code>maintenance_mode: false</code> in your <code>config.yml</code> file.' , ] ) ; $ this -> app [ 'logger.flash' ] -> configuration ( $ notice ) ; } }
If the site is in maintenance mode show this on the dashboard .
4,667
protected function changelogCheck ( ) { if ( ! $ this -> app [ 'config' ] -> get ( 'general/changelog/enabled' , false ) ) { return ; } $ count = $ this -> app [ 'storage' ] -> getRepository ( LogChange :: class ) -> count ( ) ; if ( $ count > $ this -> logThreshold ) { $ message = sprintf ( "Bolt's <strong>changelog</strong> is enabled, and there are more than %s rows in the table." , $ this -> logThreshold ) ; $ info = sprintf ( "Be sure to clean it up periodically, using a Cron job or on the <a href='%s'>Changelog page</a>." , $ this -> app [ 'url_generator' ] -> generate ( 'changelog' ) ) ; $ notice = json_encode ( [ 'severity' => 1 , 'notice' => $ message , 'info' => $ info , ] ) ; $ this -> app [ 'logger.flash' ] -> configuration ( $ notice ) ; } }
Check if Changelog is enabled and if doesn t contain too many rows .
4,668
protected function systemlogCheck ( ) { $ count = $ this -> app [ 'storage' ] -> getRepository ( LogSystem :: class ) -> count ( ) ; if ( $ count > $ this -> logThreshold ) { $ message = sprintf ( "Bolt's <strong>systemlog</strong> is enabled, and there are more than %s rows in the table." , $ this -> logThreshold ) ; $ info = sprintf ( "Be sure to clean it up periodically, using a Cron job or on the <a href='%s'>Systemlog page</a>." , $ this -> app [ 'url_generator' ] -> generate ( 'systemlog' ) ) ; $ notice = json_encode ( [ 'severity' => 1 , 'notice' => $ message , 'info' => $ info , ] ) ; $ this -> app [ 'logger.flash' ] -> configuration ( $ notice ) ; } }
Check if systemlog doesn t contain too many rows .
4,669
protected function thumbnailConfigCheck ( ) { $ thumbConfig = $ this -> app [ 'config' ] -> get ( 'general/thumbnails' ) ; if ( ( strpos ( $ thumbConfig [ 'notfound_image' ] . $ thumbConfig [ 'error_image' ] , '://' ) === false ) ) { $ notice = json_encode ( [ 'severity' => 1 , 'notice' => 'Your configuration settings for <code>thumbnails/notfound_image</code> or <code>thumbnails/error_image</code> contain a value that needs to be updated.' , 'info' => 'Update the value with a namespace, for example: <code>bolt_assets://img/default_notfound.png</code>.' , ] ) ; $ this -> app [ 'logger.flash' ] -> configuration ( $ notice ) ; } }
Check if the thumbnail config has been updated for 3 . 3 + .
4,670
public function setValue ( $ value ) { if ( isset ( $ this -> element ) ) { $ this -> element -> setValue ( $ value ) ; } return $ this ; }
Set value to strainer element
4,671
public function loadFromDirectory ( $ dir ) { if ( ! is_dir ( $ dir ) ) { throw new \ InvalidArgumentException ( sprintf ( '"%s" does not exist' , $ dir ) ) ; } $ iterator = new \ RecursiveIteratorIterator ( new \ RecursiveDirectoryIterator ( $ dir , \ RecursiveDirectoryIterator :: SKIP_DOTS ) , \ RecursiveIteratorIterator :: LEAVES_ONLY ) ; return $ this -> loadFromIterator ( $ iterator ) ; }
Find fixtures classes in a given directory and load them .
4,672
public function isTransient ( $ className ) { $ rc = new \ ReflectionClass ( $ className ) ; if ( $ rc -> isAbstract ( ) ) { return true ; } $ interfaces = class_implements ( $ className ) ; return ! in_array ( 'PandawanTechnology\Neo4jDataFixtures\Neo4jFixtureInterface' , $ interfaces ) ; }
Check if a given fixture is transient and should not be considered a data fixtures class .
4,673
private function loadFromIterator ( \ Iterator $ iterator ) { $ includedFiles = [ ] ; foreach ( $ iterator as $ file ) { if ( ( $ fileName = $ file -> getBasename ( $ this -> fileExtension ) ) == $ file -> getBasename ( ) ) { continue ; } $ sourceFile = realpath ( $ file -> getPathName ( ) ) ; require_once $ sourceFile ; $ includedFiles [ ] = $ sourceFile ; } $ fixtures = [ ] ; $ declared = get_declared_classes ( ) ; foreach ( $ declared as $ className ) { $ reflClass = new \ ReflectionClass ( $ className ) ; $ sourceFile = $ reflClass -> getFileName ( ) ; if ( in_array ( $ sourceFile , $ includedFiles ) && ! $ this -> isTransient ( $ className ) ) { $ fixture = new $ className ( ) ; $ fixtures [ ] = $ fixture ; $ this -> addFixture ( $ fixture ) ; } } return $ fixtures ; }
Load fixtures from files contained in iterator .
4,674
public function toUpperCamelCase ( $ string ) { $ string = str_replace ( array ( '-' , '_' ) , ' ' , $ string ) ; $ string = ucwords ( strtolower ( $ string ) ) ; $ string = str_replace ( ' ' , '' , $ string ) ; return $ string ; }
Converts a string to upper camel case .
4,675
public function getMagicVariableValue ( $ variable ) { $ base_path_name = basename ( realpath ( "." ) ) ; switch ( $ variable ) { case self :: MAGIC_VAR_BASENAME : return $ base_path_name ; break ; case self :: MAGIC_VAR_UCFIRST_BASENAME : return ucfirst ( $ base_path_name ) ; break ; case self :: MAGIC_VAR_UPPER_CAMEL_CASE_BASENAME : return $ this -> toUpperCamelCase ( $ base_path_name ) ; break ; case self :: MAGIC_VAR_LOWER_CAMEL_CASE_BASENAME : return $ this -> toLowerCamelCase ( $ base_path_name ) ; break ; } return null ; }
Returns the magic value of a magic variable .
4,676
public function getReplaceValuesFromArgument ( $ argValues ) { $ replaceValues = array ( ) ; $ argValues = explode ( ',' , $ argValues ) ; foreach ( $ argValues as $ argValue ) { $ argValue = explode ( ':' , $ argValue ) ; if ( count ( $ argValue ) != 2 ) { $ msg = 'Command argument "--replace" must follow the format: --replace="{SEARCH}:{REPLACE},..."' ; throw new \ ErrorException ( $ msg ) ; } $ search = trim ( $ argValue [ 0 ] ) ; $ replace = trim ( $ argValue [ 1 ] ) ; if ( $ this -> isMagicVariable ( $ replace ) ) { $ replace = $ this -> getMagicVariableValue ( $ replace ) ; } $ replaceValues [ $ search ] = $ replace ; } return $ replaceValues ; }
Returns an array containing the replace values from command argument .
4,677
public function getArguments ( ) { $ cmdArguments = $ this -> event -> getArguments ( ) ; if ( ! $ cmdArguments ) { throw new \ ErrorException ( 'Hydrate command expects arguments.' ) ; } $ returnArguments = array ( ) ; foreach ( $ cmdArguments as $ cmdArgument ) { $ cmdArgument = explode ( '=' , $ cmdArgument ) ; $ argument = $ cmdArgument [ 0 ] ; if ( ! $ this -> cmdArgumentExist ( $ argument ) ) { throw new \ ErrorException ( "Command argument '$argument' do not exist." ) ; } if ( $ argument == self :: REPLACE_ARG ) { $ replaceValues = ! empty ( $ cmdArgument [ 1 ] ) ? $ cmdArgument [ 1 ] : null ; if ( ! $ replaceValues ) { $ msg = 'Command argument "--replace" must contain values, like: --replace="{SEARCH}:{REPLACE},.."' ; throw new \ ErrorException ( $ msg ) ; } $ returnArguments [ self :: REPLACE_ARG ] = $ this -> getReplaceValuesFromArgument ( $ replaceValues ) ; } } return $ returnArguments ; }
Returns an array containing the command arguments values .
4,678
public function hydrateFileContents ( $ replaceMap ) { $ io = $ this -> event -> getIO ( ) ; $ finder = new Finder ( ) ; $ finder -> in ( $ this -> basePath ) ; $ finder -> ignoreDotFiles ( false ) ; $ finder -> notPath ( 'vendor' ) ; $ finder -> notName ( 'composer.json' ) ; foreach ( $ replaceMap as $ search => $ replace ) { $ finder -> contains ( $ search ) ; } $ count = iterator_count ( $ finder ) ; if ( ! $ count ) { $ io -> write ( "[Hydration][OK] Skipping, no file contents to be replaced." ) ; return ; } $ io -> write ( "[Hydration][INFO] Hydrating $count file(s)." ) ; foreach ( $ finder as $ file ) { $ filePath = $ file -> getRelativePathname ( ) ; $ fileContent = str_replace ( array_keys ( $ replaceMap ) , array_values ( $ replaceMap ) , $ file -> getContents ( ) ) ; if ( ! file_put_contents ( $ filePath , $ fileContent ) ) { $ msg = "Unable to Hydrate the file, check the file permissions and try again: $filePath" ; throw new \ ErrorException ( $ msg ) ; } $ io -> write ( "[Hydration][OK] File Hydrated: $filePath" ) ; } }
Process hydration to File contents .
4,679
public function hydrateRenameFilesAndFolders ( $ replaceMap ) { $ io = $ this -> event -> getIO ( ) ; $ finder = new Finder ( ) ; $ finder -> in ( $ this -> basePath ) ; $ finder -> ignoreDotFiles ( false ) ; $ finder -> exclude ( 'vendor' ) ; foreach ( $ replaceMap as $ search => $ replace ) { $ finder -> name ( ".*$search*" ) ; $ finder -> name ( "*$search*" ) ; } $ count = iterator_count ( $ finder ) ; if ( ! $ count ) { $ io -> write ( "[Hydration][OK] Skipping, no folders and files to be renamed." ) ; return ; } $ io -> write ( "[Hydration][INFO] Renaming $count file(s)/folder(s)." ) ; $ finder = array_keys ( iterator_to_array ( $ finder , true ) ) ; foreach ( $ finder as $ currentName ) { $ newName = str_replace ( array_keys ( $ replaceMap ) , array_values ( $ replaceMap ) , $ currentName ) ; $ renamed = rename ( $ currentName , $ newName ) ; if ( ! $ renamed ) { throw new \ ErrorException ( "Unable to rename file/folder: $currentName" ) ; } $ io -> write ( "[Hydration][OK] Renamed $currentName - ) ; } }
Process hydration renaming files and folders .
4,680
public function hydrate ( ) { $ arguments = $ this -> getArguments ( ) ; $ replaceMap = $ arguments [ self :: REPLACE_ARG ] ; $ this -> hydrateRenameFilesAndFolders ( $ replaceMap ) ; $ this -> hydrateFileContents ( $ replaceMap ) ; }
Performs Hydration process .
4,681
private function buildRepository ( $ wurflInfoIterator , $ deviceIterator , $ patchDeviceIterators = null ) { $ this -> persistWurflInfo ( $ wurflInfoIterator ) ; $ patchingDevices = $ this -> toListOfPatchingDevices ( $ patchDeviceIterators ) ; try { $ this -> process ( $ deviceIterator , $ patchingDevices ) ; } catch ( Exception $ exception ) { $ this -> clean ( ) ; throw new Exception ( "Problem Building WURFL Repository: " . $ exception -> getMessage ( ) , 0 , $ exception ) ; } }
Iterates over XML files and pulls relevent data
4,682
public function getReducedTree ( ) { $ parseTree = function ( Node $ node , Node $ target ) use ( & $ parseTree ) { if ( substr ( $ target -> getPath ( ) , 0 , strlen ( $ node -> getPath ( ) ) ) != $ node -> getPath ( ) ) { return array ( ) ; } $ tree = array ( ) ; foreach ( $ node -> getNodes ( ) as $ child ) { $ tree [ ] = array ( 'name' => $ child -> getName ( ) , 'path' => $ child -> getPath ( ) , 'hasChildren' => $ child -> hasNodes ( ) , 'children' => $ parseTree ( $ child , $ target ) ) ; } return $ tree ; } ; $ treeFactory = function ( $ parent , $ node ) use ( $ parseTree ) { return [ '/' => [ 'name' => '/' , 'path' => '/' , 'hasChildren' => $ parent -> hasNodes ( ) , 'children' => $ parseTree ( $ parent , $ node ) ] ] ; } ; if ( $ this -> getPath ( ) == '/' ) { return $ treeFactory ( $ this , $ this ) ; } $ parent = $ this ; do { $ parent = $ parent -> getParent ( ) ; } while ( $ parent -> getPath ( ) != '/' ) ; return $ treeFactory ( $ parent , $ this ) ; }
Return a the minimum tree to display for a node
4,683
public function getPropertiesAsArray ( ) { $ array = array ( ) ; foreach ( $ this -> getProperties ( ) as $ property ) { $ array [ $ property -> getName ( ) ] = [ 'value' => $ property -> getValue ( ) , 'type' => $ property -> getType ( ) ] ; } return $ array ; }
Convert node s properties to array
4,684
public function setFilters ( $ filters ) { if ( ! is_array ( $ filters ) ) $ filters = [ $ filters ] ; $ this -> filters = array_unique ( array_merge ( $ this -> filters , $ filters ) ) ; return $ this ; }
Sets the Filters .
4,685
public function setFields ( $ values ) { foreach ( $ values as $ field => $ value ) { $ this -> setField ( $ field , $ value ) ; } }
Sets values of multiple fields at once . Fields not present in the array will not be changed in any way .
4,686
protected function exists ( int $ id = 0 ) : bool { return ( bool ) @ shmop_open ( $ id ? $ id : $ this -> id , 'a' , 0 , 0 ) ; }
Whether there is a system s id
4,687
protected function pack ( $ data , int $ seconds = 0 ) : string { return serialize ( array ( 'data' => $ this -> toPack ( $ data ) , 'timeout' => $ seconds ? $ this -> microtime ( $ seconds * 1000 ) : 0 , ) ) ; }
Package to an array and serialize to a string
4,688
protected function unpack ( string $ data ) { if ( $ data ) { $ data = unserialize ( $ data ) ; if ( is_array ( $ data ) && isset ( $ data [ 'data' ] ) && isset ( $ data [ 'timeout' ] ) ) { $ timeout = intval ( $ data [ 'timeout' ] ) ; if ( ! $ timeout || $ timeout >= $ this -> microtime ( ) ) { return $ this -> toUnpack ( $ data [ 'data' ] ) ; } } } return false ; }
Unpacking a string and parse no timeout data from array
4,689
protected function write ( $ data , int $ seconds = 0 ) : bool { if ( ! $ data ) { return false ; } $ this -> clean ( ) ; $ data = $ this -> pack ( $ data , $ seconds ) ; $ id = shmop_open ( $ this -> id , "n" , $ this -> mode , strlen ( $ data ) ) ; if ( ! $ id ) { return false ; } $ size = shmop_write ( $ id , $ data , 0 ) ; return ! empty ( $ size ) ; }
Write data into shared memory block
4,690
protected function read ( ) { if ( $ this -> exists ( ) ) { $ id = shmop_open ( $ this -> id , "a" , 0 , 0 ) ; if ( ! $ id ) { return false ; } $ data = shmop_read ( $ id , 0 , shmop_size ( $ id ) ) ; if ( ! $ data ) { return false ; } $ data = $ this -> unpack ( $ data ) ; shmop_close ( $ id ) ; return $ data ; } return false ; }
Read data from shared memory block
4,691
protected function clean ( ) { if ( $ this -> exists ( ) ) { $ id = shmop_open ( $ this -> id , "a" , 0 , 0 ) ; shmop_delete ( $ id ) ; shmop_close ( $ id ) ; } }
Clean data from shared memory block
4,692
public function findMatch ( AcceptHeader $ acceptedMimeTypes ) { if ( count ( $ this -> mimeTypes ) === 0 ) { return 'text/html' ; } if ( count ( $ acceptedMimeTypes ) === 0 ) { reset ( $ this -> mimeTypes ) ; return current ( $ this -> mimeTypes ) ; } return $ acceptedMimeTypes -> findMatchWithGreatestPriority ( $ this -> mimeTypes ) ; }
finds best matching mime type based on accept header
4,693
public static function removeDefaultMimeTypeClass ( string $ mimeType ) { if ( isset ( self :: $ supported [ $ mimeType ] ) ) { unset ( self :: $ supported [ $ mimeType ] ) ; } }
removes default mime type class for given mime type
4,694
public static function provideDefaultClassFor ( string $ mimeType ) : bool { if ( in_array ( $ mimeType , array_keys ( self :: $ supported ) ) ) { return true ; } if ( class_exists ( 'stubbles\xml\serializer\XmlSerializerFacade' ) && in_array ( $ mimeType , array_keys ( self :: $ xml ) ) ) { return true ; } if ( class_exists ( 'stubbles\img\Image' ) && in_array ( $ mimeType , array_keys ( self :: $ image ) ) ) { return true ; } return false ; }
checks if a default class is known for the given mime type
4,695
public function classFor ( string $ mimeType ) { if ( $ this -> provideClass ( $ mimeType ) ) { return $ this -> mimeTypeClasses [ $ mimeType ] ; } return null ; }
returns special class which was defined for given mime type or null if none defined
4,696
public function getColumnsMetadata ( string $ sql ) : ColumnsMetadata { if ( $ this -> cache_active ) { $ cache_key = md5 ( $ sql ) ; if ( ! array_key_exists ( $ cache_key , static :: $ metadata_cache ) ) { $ md = $ this -> readColumnsMetadata ( $ sql ) ; static :: $ metadata_cache [ $ cache_key ] = $ md ; } return static :: $ metadata_cache [ $ cache_key ] ; } return $ this -> readColumnsMetadata ( $ sql ) ; }
Return columns metadata from query .
4,697
public function getTableMetadata ( string $ table ) : ColumnsMetadata { try { $ metadata = $ this -> getColumnsMetadata ( sprintf ( 'select * from %s' , $ table ) ) ; } catch ( Exception \ InvalidQueryException $ e ) { throw new Exception \ TableNotFoundException ( sprintf ( 'Table "%s" does not exists (%s).' , $ table , $ e -> getMessage ( ) ) ) ; } return $ metadata ; }
Return columns metadata from a table .
4,698
protected function getEmptiedQuery ( string $ sql ) : string { $ sql = preg_replace ( '/(\r\n|\r|\n|\t)+/' , ' ' , strtolower ( $ sql ) ) ; $ sql = trim ( $ sql ? : '' ) ; $ sql = preg_replace ( '/\s+/' , ' ' , $ sql ) ? : '' ; $ replace_regexp = "LIMIT[\s]+[\d]+((\s*,\s*\d+)|(\s+OFFSET\s+\d+)){0,1}" ; $ search_regexp = "$replace_regexp" ; if ( preg_match ( "/$search_regexp/i" , $ sql ) < 1 ) { $ sql .= ' LIMIT 0' ; } else { $ sql = preg_replace ( "/($replace_regexp)/i" , 'LIMIT 0' , $ sql ) ? : '' ; } return $ sql ; }
Optimization will add false condition to the query so the metadata loading will be faster .
4,699
protected function processFieldsCollection ( $ fieldCollection , $ data , FormHandler $ formHandler ) { $ fields = array ( ) ; foreach ( $ fieldCollection as $ field ) { if ( $ field [ 'name' ] === null ) { if ( ! isset ( $ i ) ) $ i = 0 ; $ field [ 'name' ] = $ i ; $ field = $ this -> typeHandler -> makeView ( $ field , $ data , $ formHandler ) ; $ fields [ ] = $ field ; $ i ++ ; } else { $ fieldName = $ field [ 'name' ] ; $ field = $ this -> typeHandler -> makeView ( $ field , $ data , $ formHandler ) ; $ field [ 'has_error' ] = false ; if ( $ formHandler -> fieldHasError ( $ field [ 'name' ] ) ) { $ field [ 'has_error' ] = true ; } $ fields [ $ fieldName ] = $ field ; } } return $ fields ; }
Process a collection of fields