idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
5,100
public function get ( $ key ) { $ setting = SettingModel :: where ( 'key' , $ key ) -> first ( ) ; return $ setting ? $ setting -> value : false ; }
Get value by a key .
5,101
protected function deleteObjectByType ( $ name , $ id ) { $ this -> db -> delete ( $ this -> config [ $ name ] . '-' . $ id , "" , 1 ) ; }
Helper function to delete couchbase item by type wait for persist to at least 1 node
5,102
public function handleAuthorizeRequest ( RequestInterface $ request , ResponseInterface $ response , $ is_authorized , $ user_id = null ) { $ this -> response = $ response ; $ this -> getAuthorizeController ( ) -> handleAuthorizeRequest ( $ request , $ this -> response , $ is_authorized , $ user_id ) ; return $ this -> response ; }
Redirect the user appropriately after approval .
5,103
public function addStorage ( $ storage , $ key = null ) { if ( isset ( $ this -> storageMap [ $ key ] ) ) { if ( ! is_null ( $ storage ) && ! $ storage instanceof $ this -> storageMap [ $ key ] ) { throw new \ InvalidArgumentException ( sprintf ( 'storage of type "%s" must implement interface "%s"' , $ key , $ this -> storageMap [ $ key ] ) ) ; } $ this -> storages [ $ key ] = $ storage ; if ( $ key === 'client' && ! isset ( $ this -> storages [ 'client_credentials' ] ) ) { if ( $ storage instanceof ClientCredentialsInterface ) { $ this -> storages [ 'client_credentials' ] = $ storage ; } } elseif ( $ key === 'client_credentials' && ! isset ( $ this -> storages [ 'client' ] ) ) { if ( $ storage instanceof ClientInterface ) { $ this -> storages [ 'client' ] = $ storage ; } } } elseif ( ! is_null ( $ key ) && ! is_numeric ( $ key ) ) { throw new \ InvalidArgumentException ( sprintf ( 'unknown storage key "%s", must be one of [%s]' , $ key , implode ( ', ' , array_keys ( $ this -> storageMap ) ) ) ) ; } else { $ set = false ; foreach ( $ this -> storageMap as $ type => $ interface ) { if ( $ storage instanceof $ interface ) { $ this -> storages [ $ type ] = $ storage ; $ set = true ; } } if ( ! $ set ) { throw new \ InvalidArgumentException ( sprintf ( 'storage of class "%s" must implement one of [%s]' , get_class ( $ storage ) , implode ( ', ' , $ this -> storageMap ) ) ) ; } } }
Set a storage object for the server
5,104
protected function createDefaultJwtAccessTokenStorage ( ) { if ( ! isset ( $ this -> storages [ 'public_key' ] ) ) { throw new \ LogicException ( 'You must supply a storage object implementing OAuth2\Storage\PublicKeyInterface to use crypto tokens' ) ; } $ tokenStorage = null ; if ( ! empty ( $ this -> config [ 'store_encrypted_token_string' ] ) && isset ( $ this -> storages [ 'access_token' ] ) ) { $ tokenStorage = $ this -> storages [ 'access_token' ] ; } return new JwtAccessTokenStorage ( $ this -> storages [ 'public_key' ] , $ tokenStorage ) ; }
For Resource Controller
5,105
protected function createDefaultJwtAccessTokenResponseType ( ) { if ( ! isset ( $ this -> storages [ 'public_key' ] ) ) { throw new \ LogicException ( 'You must supply a storage object implementing OAuth2\Storage\PublicKeyInterface to use crypto tokens' ) ; } $ tokenStorage = null ; if ( isset ( $ this -> storages [ 'access_token' ] ) ) { $ tokenStorage = $ this -> storages [ 'access_token' ] ; } $ refreshStorage = null ; if ( isset ( $ this -> storages [ 'refresh_token' ] ) ) { $ refreshStorage = $ this -> storages [ 'refresh_token' ] ; } $ config = array_intersect_key ( $ this -> config , array_flip ( explode ( ' ' , 'store_encrypted_token_string issuer access_lifetime refresh_token_lifetime jwt_extra_payload_callable' ) ) ) ; return new JwtAccessToken ( $ this -> storages [ 'public_key' ] , $ tokenStorage , $ refreshStorage , $ config ) ; }
For Authorize and Token Controllers
5,106
private function dynamo2array ( $ dynamodbResult ) { $ result = array ( ) ; foreach ( $ dynamodbResult [ "Item" ] as $ key => $ val ) { $ result [ $ key ] = $ val [ "S" ] ; $ result [ ] = $ val [ "S" ] ; } return $ result ; }
Transform dynamodb resultset to an array .
5,107
public function getClientCredentials ( RequestInterface $ request , ResponseInterface $ response = null ) { if ( ! is_null ( $ request -> headers ( 'PHP_AUTH_USER' ) ) && ! is_null ( $ request -> headers ( 'PHP_AUTH_PW' ) ) ) { return array ( 'client_id' => $ request -> headers ( 'PHP_AUTH_USER' ) , 'client_secret' => $ request -> headers ( 'PHP_AUTH_PW' ) ) ; } if ( $ this -> config [ 'allow_credentials_in_request_body' ] ) { if ( ! is_null ( $ request -> request ( 'client_id' ) ) ) { return array ( 'client_id' => $ request -> request ( 'client_id' ) , 'client_secret' => $ request -> request ( 'client_secret' ) ) ; } } if ( $ response ) { $ message = $ this -> config [ 'allow_credentials_in_request_body' ] ? ' or body' : '' ; $ response -> setError ( 400 , 'invalid_client' , 'Client credentials were not found in the headers' . $ message ) ; } return null ; }
Internal function used to get the client credentials from HTTP basic auth or POST data .
5,108
public function getAuthorizeResponse ( $ params , $ user_id = null ) { $ result = array ( 'query' => array ( ) ) ; $ params += array ( 'scope' => null , 'state' => null ) ; $ includeRefreshToken = false ; $ result [ "fragment" ] = $ this -> createAccessToken ( $ params [ 'client_id' ] , $ user_id , $ params [ 'scope' ] , $ includeRefreshToken ) ; if ( isset ( $ params [ 'state' ] ) ) { $ result [ "fragment" ] [ "state" ] = $ params [ 'state' ] ; } return array ( $ params [ 'redirect_uri' ] , $ result ) ; }
Get authorize response
5,109
protected function convertJwtToOAuth2 ( $ tokenData ) { $ keyMapping = array ( 'aud' => 'client_id' , 'exp' => 'expires' , 'sub' => 'user_id' ) ; foreach ( $ keyMapping as $ jwtKey => $ oauth2Key ) { if ( isset ( $ tokenData [ $ jwtKey ] ) ) { $ tokenData [ $ oauth2Key ] = $ tokenData [ $ jwtKey ] ; unset ( $ tokenData [ $ jwtKey ] ) ; } } return $ tokenData ; }
converts a JWT access token into an OAuth2 - friendly format
5,110
protected function getValidResponseTypes ( ) { return array ( self :: RESPONSE_TYPE_ACCESS_TOKEN , self :: RESPONSE_TYPE_AUTHORIZATION_CODE , self :: RESPONSE_TYPE_ID_TOKEN , self :: RESPONSE_TYPE_ID_TOKEN_TOKEN , self :: RESPONSE_TYPE_CODE_ID_TOKEN , ) ; }
Array of valid response types
5,111
protected function createPayload ( $ client_id , $ user_id , $ scope = null ) { $ expires = time ( ) + $ this -> config [ 'access_lifetime' ] ; $ id = $ this -> generateAccessToken ( ) ; $ payload = array ( 'id' => $ id , 'jti' => $ id , 'iss' => $ this -> config [ 'issuer' ] , 'aud' => $ client_id , 'sub' => $ user_id , 'exp' => $ expires , 'iat' => time ( ) , 'token_type' => $ this -> config [ 'token_type' ] , 'scope' => $ scope ) ; if ( isset ( $ this -> config [ 'jwt_extra_payload_callable' ] ) ) { if ( ! is_callable ( $ this -> config [ 'jwt_extra_payload_callable' ] ) ) { throw new \ InvalidArgumentException ( 'jwt_extra_payload_callable is not callable' ) ; } $ extra = call_user_func ( $ this -> config [ 'jwt_extra_payload_callable' ] , $ client_id , $ user_id , $ scope ) ; if ( ! is_array ( $ extra ) ) { throw new \ InvalidArgumentException ( 'jwt_extra_payload_callable must return array' ) ; } $ payload = array_merge ( $ extra , $ payload ) ; } return $ payload ; }
This function can be used to create custom JWT payloads
5,112
public function handleUserInfoRequest ( RequestInterface $ request , ResponseInterface $ response ) { if ( ! $ this -> verifyResourceRequest ( $ request , $ response , 'openid' ) ) { return ; } $ token = $ this -> getToken ( ) ; $ claims = $ this -> userClaimsStorage -> getUserClaims ( $ token [ 'user_id' ] , $ token [ 'scope' ] ) ; $ claims += array ( 'sub' => $ token [ 'user_id' ] , ) ; $ response -> addParameters ( $ claims ) ; }
Handle the user info request
5,113
public function handleAuthorizeRequest ( RequestInterface $ request , ResponseInterface $ response , $ is_authorized , $ user_id = null ) { if ( ! is_bool ( $ is_authorized ) ) { throw new InvalidArgumentException ( 'Argument "is_authorized" must be a boolean. This method must know if the user has granted access to the client.' ) ; } if ( ! $ this -> validateAuthorizeRequest ( $ request , $ response ) ) { return ; } if ( empty ( $ this -> redirect_uri ) ) { $ clientData = $ this -> clientStorage -> getClientDetails ( $ this -> client_id ) ; $ registered_redirect_uri = $ clientData [ 'redirect_uri' ] ; } if ( $ is_authorized === false ) { $ redirect_uri = $ this -> redirect_uri ? : $ registered_redirect_uri ; $ this -> setNotAuthorizedResponse ( $ request , $ response , $ redirect_uri , $ user_id ) ; return ; } if ( ! $ params = $ this -> buildAuthorizeParameters ( $ request , $ response , $ user_id ) ) { return ; } $ authResult = $ this -> responseTypes [ $ this -> response_type ] -> getAuthorizeResponse ( $ params , $ user_id ) ; list ( $ redirect_uri , $ uri_params ) = $ authResult ; if ( empty ( $ redirect_uri ) && ! empty ( $ registered_redirect_uri ) ) { $ redirect_uri = $ registered_redirect_uri ; } $ uri = $ this -> buildUri ( $ redirect_uri , $ uri_params ) ; $ response -> setRedirect ( $ this -> config [ 'redirect_status_code' ] , $ uri ) ; }
Handle the authorization request
5,114
public function verifyResourceRequest ( RequestInterface $ request , ResponseInterface $ response , $ scope = null ) { $ token = $ this -> getAccessTokenData ( $ request , $ response ) ; if ( is_null ( $ token ) ) { return false ; } if ( $ scope && ( ! isset ( $ token [ "scope" ] ) || ! $ token [ "scope" ] || ! $ this -> scopeUtil -> checkScope ( $ scope , $ token [ "scope" ] ) ) ) { $ response -> setError ( 403 , 'insufficient_scope' , 'The request requires higher privileges than provided by the access token' ) ; $ response -> addHttpHeaders ( array ( 'WWW-Authenticate' => sprintf ( '%s realm="%s", scope="%s", error="%s", error_description="%s"' , $ this -> tokenType -> getTokenType ( ) , $ this -> config [ 'www_realm' ] , $ scope , $ response -> getParameter ( 'error' ) , $ response -> getParameter ( 'error_description' ) ) ) ) ; return false ; } $ this -> token = $ token ; return ( bool ) $ token ; }
Verify the resource request
5,115
public function getAccessTokenData ( RequestInterface $ request , ResponseInterface $ response ) { if ( $ token_param = $ this -> tokenType -> getAccessTokenParameter ( $ request , $ response ) ) { if ( ! $ token = $ this -> tokenStorage -> getAccessToken ( $ token_param ) ) { $ response -> setError ( 401 , 'invalid_token' , 'The access token provided is invalid' ) ; } elseif ( ! isset ( $ token [ "expires" ] ) || ! isset ( $ token [ "client_id" ] ) ) { $ response -> setError ( 401 , 'malformed_token' , 'Malformed token (missing "expires")' ) ; } elseif ( time ( ) > $ token [ "expires" ] ) { $ response -> setError ( 401 , 'invalid_token' , 'The access token provided has expired' ) ; } else { return $ token ; } } $ authHeader = sprintf ( '%s realm="%s"' , $ this -> tokenType -> getTokenType ( ) , $ this -> config [ 'www_realm' ] ) ; if ( $ error = $ response -> getParameter ( 'error' ) ) { $ authHeader = sprintf ( '%s, error="%s"' , $ authHeader , $ error ) ; if ( $ error_description = $ response -> getParameter ( 'error_description' ) ) { $ authHeader = sprintf ( '%s, error_description="%s"' , $ authHeader , $ error_description ) ; } } $ response -> addHttpHeaders ( array ( 'WWW-Authenticate' => $ authHeader ) ) ; return null ; }
Get access token data .
5,116
public function addGrantType ( GrantTypeInterface $ grantType , $ identifier = null ) { if ( is_null ( $ identifier ) || is_numeric ( $ identifier ) ) { $ identifier = $ grantType -> getQueryStringIdentifier ( ) ; } $ this -> grantTypes [ $ identifier ] = $ grantType ; }
Add grant type
5,117
public function revokeToken ( RequestInterface $ request , ResponseInterface $ response ) { if ( strtolower ( $ request -> server ( 'REQUEST_METHOD' ) ) === 'options' ) { $ response -> addHttpHeaders ( array ( 'Allow' => 'POST, OPTIONS' ) ) ; return null ; } if ( strtolower ( $ request -> server ( 'REQUEST_METHOD' ) ) !== 'post' ) { $ response -> setError ( 405 , 'invalid_request' , 'The request method must be POST when revoking an access token' , '#section-3.2' ) ; $ response -> addHttpHeaders ( array ( 'Allow' => 'POST, OPTIONS' ) ) ; return null ; } $ token_type_hint = $ request -> request ( 'token_type_hint' ) ; if ( ! in_array ( $ token_type_hint , array ( null , 'access_token' , 'refresh_token' ) , true ) ) { $ response -> setError ( 400 , 'invalid_request' , 'Token type hint must be either \'access_token\' or \'refresh_token\'' ) ; return null ; } $ token = $ request -> request ( 'token' ) ; if ( $ token === null ) { $ response -> setError ( 400 , 'invalid_request' , 'Missing token parameter to revoke' ) ; return null ; } if ( ! method_exists ( $ this -> accessToken , 'revokeToken' ) ) { $ class = get_class ( $ this -> accessToken ) ; throw new RuntimeException ( "AccessToken {$class} does not implement required revokeToken method" ) ; } $ this -> accessToken -> revokeToken ( $ token , $ token_type_hint ) ; return true ; }
Revoke a refresh or access token . Returns true on success and when tokens are invalid
5,118
private function getHttpHeadersAsString ( $ headers ) { if ( count ( $ headers ) == 0 ) { return '' ; } $ max = max ( array_map ( 'strlen' , array_keys ( $ headers ) ) ) + 1 ; $ content = '' ; ksort ( $ headers ) ; foreach ( $ headers as $ name => $ values ) { foreach ( $ values as $ value ) { $ content .= sprintf ( "%-{$max}s %s\r\n" , $ this -> beautifyHeaderName ( $ name ) . ':' , $ value ) ; } } return $ content ; }
Function from Symfony2 HttpFoundation - output pretty header
5,119
public function checkScope ( $ required_scope , $ available_scope ) { $ required_scope = explode ( ' ' , trim ( $ required_scope ) ) ; $ available_scope = explode ( ' ' , trim ( $ available_scope ) ) ; return ( count ( array_diff ( $ required_scope , $ available_scope ) ) == 0 ) ; }
Check if everything in required scope is contained in available scope .
5,120
public function scopeExists ( $ scope ) { $ scope = explode ( ' ' , trim ( $ scope ) ) ; $ reservedScope = $ this -> getReservedScopes ( ) ; $ nonReservedScopes = array_diff ( $ scope , $ reservedScope ) ; if ( count ( $ nonReservedScopes ) == 0 ) { return true ; } else { $ nonReservedScopes = implode ( ' ' , $ nonReservedScopes ) ; return $ this -> storage -> scopeExists ( $ nonReservedScopes ) ; } }
Check if the provided scope exists in storage .
5,121
public function createAuthorizationCode ( $ client_id , $ user_id , $ redirect_uri , $ scope = null ) { $ code = $ this -> generateAuthorizationCode ( ) ; $ this -> storage -> setAuthorizationCode ( $ code , $ client_id , $ user_id , $ redirect_uri , time ( ) + $ this -> config [ 'auth_code_lifetime' ] , $ scope ) ; return $ code ; }
Handle the creation of the authorization code .
5,122
protected function generateAuthorizationCode ( ) { $ tokenLen = 40 ; if ( function_exists ( 'random_bytes' ) ) { $ randomData = random_bytes ( 100 ) ; } elseif ( function_exists ( 'openssl_random_pseudo_bytes' ) ) { $ randomData = openssl_random_pseudo_bytes ( 100 ) ; } elseif ( function_exists ( 'mcrypt_create_iv' ) ) { $ randomData = mcrypt_create_iv ( 100 , MCRYPT_DEV_URANDOM ) ; } elseif ( @ file_exists ( '/dev/urandom' ) ) { $ randomData = file_get_contents ( '/dev/urandom' , false , null , 0 , 100 ) . uniqid ( mt_rand ( ) , true ) ; } else { $ randomData = mt_rand ( ) . mt_rand ( ) . mt_rand ( ) . mt_rand ( ) . microtime ( true ) . uniqid ( mt_rand ( ) , true ) ; } return substr ( hash ( 'sha512' , $ randomData ) , 0 , $ tokenLen ) ; }
Generates an unique auth code .
5,123
public function createIdToken ( $ client_id , $ userInfo , $ nonce = null , $ userClaims = null , $ access_token = null ) { list ( $ user_id , $ auth_time ) = $ this -> getUserIdAndAuthTime ( $ userInfo ) ; $ token = array ( 'iss' => $ this -> config [ 'issuer' ] , 'sub' => $ user_id , 'aud' => $ client_id , 'iat' => time ( ) , 'exp' => time ( ) + $ this -> config [ 'id_lifetime' ] , 'auth_time' => $ auth_time , ) ; if ( $ nonce ) { $ token [ 'nonce' ] = $ nonce ; } if ( $ userClaims ) { $ token += $ userClaims ; } if ( $ access_token ) { $ token [ 'at_hash' ] = $ this -> createAtHash ( $ access_token , $ client_id ) ; } return $ this -> encodeToken ( $ token , $ client_id ) ; }
Create id token
5,124
public function requestHasToken ( RequestInterface $ request ) { $ headers = $ request -> headers ( 'AUTHORIZATION' ) ; return ! empty ( $ headers ) || ( bool ) ( $ request -> request ( $ this -> config [ 'token_param_name' ] ) ) || ( bool ) ( $ request -> query ( $ this -> config [ 'token_param_name' ] ) ) ; }
Check if the request has supplied token
5,125
public function getIndex ( $ version ) { return $ this -> cache -> remember ( function ( ) use ( $ version ) { $ path = base_path ( config ( 'larecipe.docs.path' ) . '/' . $ version . '/index.md' ) ; if ( $ this -> files -> exists ( $ path ) ) { $ parsedContent = $ this -> parse ( $ this -> files -> get ( $ path ) ) ; return $ this -> replaceLinks ( $ version , $ parsedContent ) ; } return null ; } , 'larecipe.docs.' . $ version . '.index' ) ; }
Get the documentation index page .
5,126
public function get ( $ version , $ page , $ data = [ ] ) { return $ this -> cache -> remember ( function ( ) use ( $ version , $ page , $ data ) { $ path = base_path ( config ( 'larecipe.docs.path' ) . '/' . $ version . '/' . $ page . '.md' ) ; if ( $ this -> files -> exists ( $ path ) ) { $ parsedContent = $ this -> parse ( $ this -> files -> get ( $ path ) ) ; $ parsedContent = $ this -> replaceLinks ( $ version , $ parsedContent ) ; return $ this -> renderBlade ( $ parsedContent , $ data ) ; } return null ; } , 'larecipe.docs.' . $ version . '.' . $ page ) ; }
Get the given documentation page .
5,127
public static function replaceLinks ( $ version , $ content ) { $ content = str_replace ( '{{version}}' , $ version , $ content ) ; $ content = str_replace ( '{{route}}' , trim ( config ( 'larecipe.docs.route' ) , '/' ) , $ content ) ; return $ content ; }
Replace the version and route placeholders .
5,128
public function sectionExists ( $ version , $ page ) { return $ this -> files -> exists ( base_path ( config ( 'larecipe.docs.path' ) . '/' . $ version . '/' . $ page . '.md' ) ) ; }
Check if the given section exists .
5,129
protected function runCommand ( $ command , $ path ) { $ process = ( new Process ( $ command , $ path ) ) -> setTimeout ( null ) ; if ( '\\' !== DIRECTORY_SEPARATOR && file_exists ( '/dev/tty' ) && is_readable ( '/dev/tty' ) ) { $ process -> setTty ( true ) ; } $ process -> run ( function ( $ type , $ line ) { $ this -> output -> write ( $ line ) ; } ) ; }
Run the given command as a process .
5,130
public function hasValidNameArgument ( ) { $ name = $ this -> argument ( 'name' ) ; if ( ! Str :: contains ( $ name , '/' ) ) { $ this -> error ( "The name argument expects a vendor and name in 'Composer' format. Here's an example: `vendor/name`." ) ; return false ; } return true ; }
Determine if the name argument is valid .
5,131
protected function renameStubs ( ) { foreach ( $ this -> stubsToRename ( ) as $ stub ) { ( new Filesystem ) -> move ( $ stub , str_replace ( '.stub' , '.php' , $ stub ) ) ; } }
Rename the stubs with PHP file extensions .
5,132
protected function registerConsoleCommands ( ) { $ this -> commands ( AssetCommand :: class ) ; $ this -> commands ( ThemeCommand :: class ) ; $ this -> commands ( InstallCommand :: class ) ; $ this -> commands ( GenerateDocumentationCommand :: class ) ; }
Register the commands accessible from the Console .
5,133
protected function prepareNotFound ( ) { $ this -> title = 'Page not found' ; $ this -> content = view ( 'larecipe::partials.404' ) ; $ this -> currentSection = '' ; $ this -> canonical = '' ; $ this -> statusCode = 404 ; return $ this ; }
If the docs content is empty then show 404 page .
5,134
protected function prepareTitle ( ) { $ this -> title = ( new Crawler ( $ this -> content ) ) -> filterXPath ( '//h1' ) ; $ this -> title = count ( $ this -> title ) ? $ this -> title -> text ( ) : null ; return $ this ; }
Prepare the page title from the first h1 found .
5,135
protected function prepareSection ( $ version , $ page ) { if ( $ this -> documentation -> sectionExists ( $ version , $ page ) ) { $ this -> currentSection = '/' . $ page ; } return $ this ; }
Prepare the current section page .
5,136
protected function prepareCanonical ( ) { if ( $ this -> documentation -> sectionExists ( $ this -> defaultVersion , $ this -> sectionPage ) ) { $ this -> canonical = $ this -> docsRoute . '/' . $ this -> defaultVersion . '/' . $ this -> sectionPage ; } return $ this ; }
Prepare the canonical link .
5,137
protected function createVersionDirectory ( $ versionDirectory ) { if ( ! $ this -> filesystem -> isDirectory ( $ versionDirectory ) ) { $ this -> filesystem -> makeDirectory ( $ versionDirectory , 0755 , true ) ; return true ; } return false ; }
Create a new directory for the given version if not exists .
5,138
protected function createVersionIndex ( $ versionDirectory ) { $ indexPath = $ versionDirectory . '/index.md' ; if ( ! $ this -> filesystem -> exists ( $ indexPath ) ) { $ content = $ this -> generateIndexContent ( $ this -> getStub ( 'index' ) ) ; $ this -> filesystem -> put ( $ indexPath , $ content ) ; return true ; } return false ; }
Create index . md for the given version if it s not exists .
5,139
protected function generateIndexContent ( $ stub ) { $ content = str_replace ( '{{LANDING}}' , ucwords ( config ( 'larecipe.docs.landing' ) ) , $ stub ) ; $ content = str_replace ( '{{ROOT}}' , config ( 'larecipe.docs.route' ) , $ content ) ; $ content = str_replace ( '{{LANDINGSMALL}}' , trim ( config ( 'larecipe.docs.landing' ) , '/' ) , $ content ) ; return $ content ; }
replace stub placeholders .
5,140
public function checkTtlNeedsChanged ( $ ttl ) { $ app_version = explode ( '.' , app ( ) -> version ( ) ) ; if ( ( ( int ) $ app_version [ 0 ] == 5 && ( int ) $ app_version [ 1 ] >= 8 ) || $ app_version [ 0 ] > 5 ) { return config ( 'larecipe.cache.period' ) * 60 ; } return $ ttl ; }
Checks if minutes need to be changed to seconds
5,141
public function renderBlade ( $ content , $ data = [ ] ) { $ content = $ this -> compileBlade ( $ content ) ; $ obLevel = ob_get_level ( ) ; ob_start ( ) ; extract ( $ data , EXTR_SKIP ) ; try { eval ( '?' . '>' . $ content ) ; } catch ( \ Exception $ e ) { while ( ob_get_level ( ) > $ obLevel ) { ob_end_clean ( ) ; } throw $ e ; } catch ( \ Throwable $ e ) { while ( ob_get_level ( ) > $ obLevel ) { ob_end_clean ( ) ; } throw new \ Exception ( $ e ) ; } $ contents = ob_get_clean ( ) ; return $ contents ; }
Render markdown contain blade syntax .
5,142
protected function addThemeRepositoryToRootComposer ( ) { $ composer = json_decode ( file_get_contents ( base_path ( 'composer.json' ) ) , true ) ; $ composer [ 'repositories' ] [ ] = [ 'type' => 'path' , 'url' => './' . $ this -> relativeThemePath ( ) , ] ; file_put_contents ( base_path ( 'composer.json' ) , json_encode ( $ composer , JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) ) ; }
Add a path repository for the theme to the application s composer . json file .
5,143
protected function addThemePackageToRootComposer ( ) { $ composer = json_decode ( file_get_contents ( base_path ( 'composer.json' ) ) , true ) ; $ composer [ 'require' ] [ $ this -> argument ( 'name' ) ] = '*' ; file_put_contents ( base_path ( 'composer.json' ) , json_encode ( $ composer , JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) ) ; }
Add a package entry for the theme to the application s composer . json file .
5,144
public function show ( $ version , $ page = null ) { $ documentation = $ this -> documentationRepository -> get ( $ version , $ page ) ; if ( Gate :: has ( 'viewLarecipe' ) ) { $ this -> authorize ( 'viewLarecipe' , $ documentation ) ; } if ( $ this -> documentationRepository -> isNotPublishedVersion ( $ version ) ) { return redirect ( ) -> route ( 'larecipe.show' , [ 'version' => config ( 'larecipe.versions.default' ) , 'page' => config ( 'larecipe.docs.landing' ) ] ) ; } return response ( ) -> view ( 'larecipe::docs' , [ 'title' => $ documentation -> title , 'index' => $ documentation -> index , 'content' => $ documentation -> content , 'currentVersion' => $ version , 'versions' => $ documentation -> publishedVersions , 'currentSection' => $ documentation -> currentSection , 'canonical' => $ documentation -> canonical , ] , $ documentation -> statusCode ) ; }
Show a documentation page .
5,145
public function performQuery ( string $ viewId , DateTime $ startDate , DateTime $ endDate , string $ metrics , array $ others = [ ] ) { $ cacheName = $ this -> determineCacheName ( func_get_args ( ) ) ; if ( $ this -> cacheLifeTimeInMinutes == 0 ) { $ this -> cache -> forget ( $ cacheName ) ; } return $ this -> cache -> remember ( $ cacheName , $ this -> cacheLifeTimeInMinutes , function ( ) use ( $ viewId , $ startDate , $ endDate , $ metrics , $ others ) { $ result = $ this -> service -> data_ga -> get ( "ga:{$viewId}" , $ startDate -> format ( 'Y-m-d' ) , $ endDate -> format ( 'Y-m-d' ) , $ metrics , $ others ) ; while ( $ nextLink = $ result -> getNextLink ( ) ) { if ( isset ( $ others [ 'max-results' ] ) && count ( $ result -> rows ) >= $ others [ 'max-results' ] ) { break ; } $ options = [ ] ; parse_str ( substr ( $ nextLink , strpos ( $ nextLink , '?' ) + 1 ) , $ options ) ; $ response = $ this -> service -> data_ga -> call ( 'get' , [ $ options ] , 'Google_Service_Analytics_GaData' ) ; if ( $ response -> rows ) { $ result -> rows = array_merge ( $ result -> rows , $ response -> rows ) ; } $ result -> nextLink = $ response -> nextLink ; } return $ result ; } ) ; }
Query the Google Analytics Service with given parameters .
5,146
public function performQuery ( Period $ period , string $ metrics , array $ others = [ ] ) { return $ this -> client -> performQuery ( $ this -> viewId , $ period -> startDate , $ period -> endDate , $ metrics , $ others ) ; }
Call the query method on the authenticated client .
5,147
public function getElements ( ) { foreach ( $ this -> elements as $ name => $ element ) { $ this -> resolveXRef ( $ name ) ; } return $ this -> elements ; }
Returns all elements .
5,148
public function getElementTypes ( ) { $ types = array ( ) ; foreach ( $ this -> elements as $ key => $ element ) { $ types [ $ key ] = get_class ( $ element ) ; } return $ types ; }
Used only for debug .
5,149
protected function resolveXRef ( $ name ) { if ( ( $ obj = $ this -> elements [ $ name ] ) instanceof ElementXRef && ! is_null ( $ this -> document ) ) { $ object = $ this -> document -> getObjectById ( $ obj -> getId ( ) ) ; if ( is_null ( $ object ) ) { return new ElementMissing ( null , null ) ; } $ this -> elements [ $ name ] = $ object ; } return $ this -> elements [ $ name ] ; }
Resolve XRef to object .
5,150
public function getXObjects ( ) { if ( ! is_null ( $ this -> xobjects ) ) { return $ this -> xobjects ; } $ resources = $ this -> get ( 'Resources' ) ; if ( method_exists ( $ resources , 'has' ) && $ resources -> has ( 'XObject' ) ) { if ( $ resources -> get ( 'XObject' ) instanceof Header ) { $ xobjects = $ resources -> get ( 'XObject' ) -> getElements ( ) ; } else { $ xobjects = $ resources -> get ( 'XObject' ) -> getHeader ( ) -> getElements ( ) ; } $ table = array ( ) ; foreach ( $ xobjects as $ id => $ xobject ) { $ table [ $ id ] = $ xobject ; $ id = preg_replace ( '/[^0-9\.\-_]/' , '' , $ id ) ; if ( $ id != '' ) { $ table [ $ id ] = $ xobject ; } } return ( $ this -> xobjects = $ table ) ; } else { return array ( ) ; } }
Support for XObject
5,151
protected function buildDictionary ( ) { $ this -> dictionary = array ( ) ; foreach ( $ this -> objects as $ id => $ object ) { $ type = $ object -> getHeader ( ) -> get ( 'Type' ) -> getContent ( ) ; if ( ! empty ( $ type ) ) { $ this -> dictionary [ $ type ] [ $ id ] = $ id ; } } }
Build dictionary based on type header field .
5,152
protected function buildDetails ( ) { $ details = array ( ) ; if ( $ this -> trailer -> has ( 'Info' ) ) { $ info = $ this -> trailer -> get ( 'Info' ) ; if ( $ info !== null && method_exists ( $ info , 'getHeader' ) ) { $ details = $ info -> getHeader ( ) -> getDetails ( ) ; } } try { $ pages = $ this -> getPages ( ) ; $ details [ 'Pages' ] = count ( $ pages ) ; } catch ( \ Exception $ e ) { $ details [ 'Pages' ] = 0 ; } $ this -> details = $ details ; }
Build details array .
5,153
protected function positions ( $ value ) { mt_srand ( crc32 ( $ value ) ) ; $ positions = new SplFixedArray ( $ this -> k ) ; for ( $ i = 0 ; $ i < $ this -> k ; $ i ++ ) { $ positions [ $ i ] = mt_rand ( 1 , $ this -> m ) ; } return $ positions ; }
Calculates the positions a value hashes to in the bitfield .
5,154
public function add ( $ value ) { foreach ( $ this -> positions ( $ value ) as $ position ) { $ this -> setBitAtPosition ( $ position ) ; } }
Add a value into the set .
5,155
public function maybeInSet ( $ value ) { foreach ( $ this -> positions ( $ value ) as $ position ) { if ( ! $ this -> getBitAtPosition ( $ position ) ) { return false ; } } return true ; }
Checks if the value may have been added to the set before . False positives are possible false negatives are not .
5,156
public function showBitField ( ) { return join ( array_map ( function ( $ chr ) { return str_pad ( base_convert ( bin2hex ( $ chr ) , 16 , 2 ) , 8 , '0' , STR_PAD_LEFT ) ; } , str_split ( $ this -> bitField ) ) ) ; }
Returns an ASCII representation of the current bit field .
5,157
protected function getConnection ( $ key ) { $ offset = crc32 ( $ key ) % count ( $ this -> _globalServers ) ; if ( $ offset < 0 ) { $ offset = - $ offset ; } if ( ! isset ( $ this -> _globalConnections [ $ offset ] ) || feof ( $ this -> _globalConnections [ $ offset ] ) ) { $ connection = stream_socket_client ( "tcp://{$this->_globalServers[$offset]}" , $ code , $ msg , $ this -> timeout ) ; if ( ! $ connection ) { throw new \ Exception ( $ msg ) ; } stream_set_timeout ( $ connection , $ this -> timeout ) ; if ( class_exists ( '\Workerman\Lib\Timer' ) && php_sapi_name ( ) === 'cli' ) { $ timer_id = \ Workerman \ Lib \ Timer :: add ( $ this -> pingInterval , function ( $ connection ) use ( & $ timer_id ) { $ buffer = pack ( 'N' , 8 ) . "ping" ; if ( strlen ( $ buffer ) !== @ fwrite ( $ connection , $ buffer ) ) { @ fclose ( $ connection ) ; \ Workerman \ Lib \ Timer :: del ( $ timer_id ) ; } } , array ( $ connection ) ) ; } $ this -> _globalConnections [ $ offset ] = $ connection ; } return $ this -> _globalConnections [ $ offset ] ; }
Connect to global server .
5,158
protected function writeToRemote ( $ data , $ connection ) { $ buffer = serialize ( $ data ) ; $ buffer = pack ( 'N' , 4 + strlen ( $ buffer ) ) . $ buffer ; $ len = fwrite ( $ connection , $ buffer ) ; if ( $ len !== strlen ( $ buffer ) ) { throw new \ Exception ( 'writeToRemote fail' ) ; } }
Write data to global server .
5,159
protected function readFromRemote ( $ connection ) { $ all_buffer = '' ; $ total_len = 4 ; $ head_read = false ; while ( 1 ) { $ buffer = fread ( $ connection , 8192 ) ; if ( $ buffer === '' || $ buffer === false ) { throw new \ Exception ( 'readFromRemote fail' ) ; } $ all_buffer .= $ buffer ; $ recv_len = strlen ( $ all_buffer ) ; if ( $ recv_len >= $ total_len ) { if ( $ head_read ) { break ; } $ unpack_data = unpack ( 'Ntotal_length' , $ all_buffer ) ; $ total_len = $ unpack_data [ 'total_length' ] ; if ( $ recv_len >= $ total_len ) { break ; } $ head_read = true ; } } return unserialize ( substr ( $ all_buffer , 4 ) ) ; }
Read data from global server .
5,160
public function requirePackage ( $ package_name , $ package_version , $ options = [ 'dev' => FALSE ] ) { $ task = $ this -> taskComposerRequire ( ) -> printOutput ( TRUE ) -> printMetadata ( TRUE ) -> dir ( $ this -> getConfigValue ( 'repo.root' ) ) -> interactive ( $ this -> input ( ) -> isInteractive ( ) ) -> setVerbosityThreshold ( VerbosityThresholdInterface :: VERBOSITY_VERBOSE ) ; if ( $ options [ 'dev' ] ) { $ task -> dev ( TRUE ) ; } if ( $ package_version ) { $ task -> dependency ( $ package_name , $ package_version ) ; } else { $ task -> dependency ( $ package_name ) ; } $ result = $ task -> run ( ) ; if ( ! $ result -> wasSuccessful ( ) ) { $ this -> logger -> error ( "An error occurred while requiring {$package_name}." ) ; $ this -> say ( "This is likely due to an incompatibility with your existing packages or memory exhaustion. See full error output above." ) ; $ confirm = $ this -> confirm ( "Should BLT attempt to update all of your Composer packages in order to find a compatible version?" ) ; if ( $ confirm ) { $ command = "composer require '{$package_name}:{$package_version}' --no-update " ; if ( $ options [ 'dev' ] ) { $ command .= "--dev " ; } $ command .= "&& composer update" ; $ task = $ this -> taskExec ( $ command ) -> printOutput ( TRUE ) -> printMetadata ( TRUE ) -> dir ( $ this -> getConfigValue ( 'repo.root' ) ) -> interactive ( $ this -> input ( ) -> isInteractive ( ) ) -> setVerbosityThreshold ( VerbosityThresholdInterface :: VERBOSITY_VERBOSE ) ; ; $ result = $ task -> run ( ) ; if ( ! $ result -> wasSuccessful ( ) ) { throw new BltException ( "Unable to install {$package_name} package." ) ; } } else { throw new BltException ( "Unable to install {$package_name} package." ) ; } } return $ result ; }
Requires a composer package .
5,161
public function interactGenerateSettingsFiles ( InputInterface $ input , OutputInterface $ output , AnnotationData $ annotationData ) { $ setup_wizard = $ this -> getContainer ( ) -> get ( SetupWizard :: class ) ; $ setup_wizard -> wizardGenerateSettingsFiles ( ) ; }
Runs wizard for generating settings files .
5,162
public function interactInstallDrupal ( InputInterface $ input , OutputInterface $ output , AnnotationData $ annotationData ) { $ setup_wizard = $ this -> getContainer ( ) -> get ( SetupWizard :: class ) ; $ setup_wizard -> wizardInstallDrupal ( ) ; }
Runs wizard for installing Drupal .
5,163
public function interactConfigureBehat ( InputInterface $ input , OutputInterface $ output , AnnotationData $ annotationData ) { $ tests_wizard = $ this -> getContainer ( ) -> get ( TestsWizard :: class ) ; $ tests_wizard -> wizardConfigureBehat ( ) ; }
Runs wizard for configuring Behat .
5,164
public function interactExecuteUpdates ( InputInterface $ input , OutputInterface $ output , AnnotationData $ annotationData ) { if ( $ this -> invokeDepth == 0 && $ input -> getFirstArgument ( ) != 'blt:update' && $ input -> getFirstArgument ( ) != 'update' && ! $ this -> getInspector ( ) -> isSchemaVersionUpToDate ( ) ) { $ this -> logger -> warning ( "Your BLT schema is out of date." ) ; if ( ! $ input -> isInteractive ( ) ) { $ this -> logger -> warning ( "Run `blt blt:update` to update it." ) ; } $ confirm = $ this -> confirm ( "Would you like to run outstanding updates?" ) ; if ( $ confirm ) { $ this -> invokeCommand ( 'blt:update' ) ; } } }
Executes outstanding updates .
5,165
public function interactConfigIdentical ( InputInterface $ input , OutputInterface $ output , AnnotationData $ annotationData ) { $ cm_strategies = [ 'config-split' , 'core-only' , ] ; if ( in_array ( $ this -> getConfigValue ( 'cm.strategy' ) , $ cm_strategies ) && $ this -> getInspector ( ) -> isDrupalInstalled ( ) ) { if ( ! $ this -> getInspector ( ) -> isActiveConfigIdentical ( ) ) { $ this -> logger -> warning ( "The active configuration is not identical to the configuration in the export directory." ) ; $ this -> logger -> warning ( "This means that you have not exported all of your active configuration." ) ; $ this -> logger -> warning ( "Run <comment>drush cex</comment> to export the active config to the sync directory." ) ; if ( $ this -> input ( ) -> isInteractive ( ) ) { $ this -> logger -> warning ( "Continuing will overwrite the active configuration." ) ; $ confirm = $ this -> confirm ( "Continue?" ) ; if ( ! $ confirm ) { throw new BltException ( "The active configuration is not identical to the configuration in the export directory." ) ; } } } } }
Prompts user to confirm overwrite of active config on blt setup .
5,166
protected function checkNodeVersionFileExists ( ) { if ( file_exists ( $ this -> getConfigValue ( 'repo.root' ) . '/.nvmrc' ) ) { $ this -> logProblem ( __FUNCTION__ , ".nvmrc file exists" , 'info' ) ; } elseif ( file_exists ( $ this -> getConfigValue ( 'repo.root' ) . '/.node-version' ) ) { $ this -> logProblem ( __FUNCTION__ , ".node-version file exists" , 'info' ) ; } else { $ this -> logProblem ( __FUNCTION__ , "Neither .nvmrc nor .node-version file found in repo root." , 'comment' ) ; } }
Checks that one of . nvmrc or . node - version exists in repo root .
5,167
public function import ( ) { $ task = $ this -> taskDrush ( ) -> drush ( 'sql-drop' ) -> drush ( 'sql-cli < ' . $ this -> getConfigValue ( 'setup.dump-file' ) ) ; $ result = $ task -> run ( ) ; $ exit_code = $ result -> getExitCode ( ) ; if ( $ exit_code ) { throw new BltException ( "Unable to import setup.dump-file." ) ; } }
Imports a . sql file into the Drupal database .
5,168
public function generate ( $ options = [ 'site-dir' => InputOption :: VALUE_REQUIRED , 'site-uri' => InputOption :: VALUE_REQUIRED , 'remote-alias' => InputOption :: VALUE_REQUIRED , ] ) { $ this -> say ( "This will generate a new site in the docroot/sites directory." ) ; $ site_name = $ this -> getNewSiteName ( $ options ) ; $ new_site_dir = $ this -> getConfigValue ( 'docroot' ) . '/sites/' . $ site_name ; if ( file_exists ( $ new_site_dir ) ) { throw new BltException ( "Cannot generate new multisite, $new_site_dir already exists!" ) ; } $ domain = $ this -> getNewSiteDoman ( $ options , $ site_name ) ; $ url = parse_url ( $ domain ) ; $ newDBSettings = $ this -> setLocalDbConfig ( ) ; if ( $ this -> getInspector ( ) -> isDrupalVmConfigPresent ( ) ) { $ this -> configureDrupalVm ( $ url , $ site_name , $ newDBSettings ) ; } $ default_site_dir = $ this -> getConfigValue ( 'docroot' ) . '/sites/default' ; $ this -> createDefaultBltSiteYml ( $ default_site_dir ) ; $ this -> createSiteDrushAlias ( 'default' ) ; $ this -> createNewSiteDir ( $ default_site_dir , $ new_site_dir ) ; $ remote_alias = $ this -> getNewSiteRemoteAlias ( $ site_name , $ options ) ; $ this -> createNewBltSiteYml ( $ new_site_dir , $ site_name , $ url , $ remote_alias ) ; $ this -> createNewSiteConfigDir ( $ site_name ) ; $ this -> createSiteDrushAlias ( $ site_name ) ; $ this -> resetMultisiteConfig ( ) ; $ this -> invokeCommand ( 'blt:init:settings' ) ; $ this -> say ( "New site generated at <comment>$new_site_dir</comment>" ) ; $ this -> say ( "Drush aliases generated:" ) ; if ( ! file_exists ( $ default_site_dir . "/blt.yml" ) ) { $ this -> say ( " * @default.local" ) ; } $ this -> say ( " * @$remote_alias" ) ; $ this -> say ( "Config directory created for new site at <comment>config/$site_name</comment>" ) ; }
Generates a new multisite .
5,169
protected function setLocalDbConfig ( ) { $ config_local_db = $ this -> confirm ( "Would you like to configure the local database credentials?" ) ; $ db = [ ] ; if ( $ config_local_db ) { $ default_db = $ this -> getConfigValue ( 'drupal.db' ) ; $ db [ 'database' ] = $ this -> askDefault ( "Local database name" , $ default_db [ 'database' ] ) ; $ db [ 'username' ] = $ this -> askDefault ( "Local database user" , $ default_db [ 'username' ] ) ; $ db [ 'password' ] = $ this -> askDefault ( "Local database password" , $ default_db [ 'password' ] ) ; $ db [ 'host' ] = $ this -> askDefault ( "Local database host" , $ default_db [ 'host' ] ) ; $ db [ 'port' ] = $ this -> askDefault ( "Local database port" , $ default_db [ 'port' ] ) ; $ this -> getConfig ( ) -> set ( 'drupal.db' , $ db ) ; } return $ db ; }
Prompts for and sets config for new database .
5,170
public function setRepoRoot ( $ repoRoot ) { if ( ! $ this -> fs -> exists ( $ repoRoot ) ) { throw new FileNotFoundException ( ) ; } $ this -> repoRoot = $ repoRoot ; }
The filepath of the repository root directory .
5,171
public function executeUpdates ( $ updates ) { $ updates_object = new $ this -> updateClassName ( $ this ) ; $ this -> output -> writeln ( "Executing updates..." ) ; foreach ( $ updates as $ method_name => $ update ) { $ this -> output -> writeln ( "-> $method_name: {$update->description}" ) ; call_user_func ( [ $ updates_object , $ method_name ] ) ; } }
Executes an array of updates .
5,172
public function printUpdates ( $ updates ) { foreach ( $ updates as $ method_name => $ update ) { $ this -> output -> writeln ( " - $method_name: {$update->description}" ) ; } $ this -> output -> writeln ( '' ) ; }
Prints a human - readable list of update methods to the screen .
5,173
public function getUpdates ( $ starting_version , $ ending_version = NULL ) { if ( ! $ ending_version ) { $ ending_version = $ this -> getLatestUpdateMethodVersion ( ) ; } $ updates = [ ] ; $ update_methods = $ this -> getAllUpdateMethods ( ) ; foreach ( $ update_methods as $ method_name => $ metadata ) { $ version = $ metadata -> version ; if ( ( $ version > $ starting_version ) && $ version <= $ ending_version ) { $ updates [ $ method_name ] = $ metadata ; } } return $ updates ; }
Gets all applicable updates for a given version delta .
5,174
public function getAllUpdateMethods ( ) { $ update_methods = [ ] ; $ methods = get_class_methods ( $ this -> updateClassName ) ; foreach ( $ methods as $ method_name ) { $ reflectionMethod = new \ ReflectionMethod ( $ this -> updateClassName , $ method_name ) ; $ annotations = $ this -> annotationsReader -> getMethodAnnotation ( $ reflectionMethod , 'Acquia\Blt\Annotations\Update' ) ; if ( $ annotations ) { $ update_methods [ $ method_name ] = $ annotations ; } } return $ update_methods ; }
Gather an array of all available update methods .
5,175
public function removeComposerPatch ( $ package , $ url ) { $ composer_json = $ this -> getComposerJson ( ) ; if ( ! empty ( $ composer_json [ 'extra' ] [ 'patches' ] [ $ package ] ) ) { foreach ( $ composer_json [ 'extra' ] [ 'patches' ] [ $ package ] as $ key => $ patch_url ) { if ( $ patch_url == $ url ) { unset ( $ composer_json [ 'extra' ] [ 'patches' ] [ $ package ] [ $ key ] ) ; if ( empty ( $ composer_json [ 'extra' ] [ 'patches' ] [ $ package ] ) ) { unset ( $ composer_json [ 'extra' ] [ 'patches' ] [ $ package ] ) ; } $ this -> writeComposerJson ( $ composer_json ) ; return TRUE ; } } } return FALSE ; }
Removes a patch from repo s root composer . json file .
5,176
public function writeComposerJson ( $ contents ) { if ( array_key_exists ( 'require' , $ contents ) && is_array ( $ contents [ 'require' ] ) ) { ksort ( $ contents [ 'require' ] ) ; $ contents [ 'require' ] = ( object ) $ contents [ 'require' ] ; } if ( array_key_exists ( 'require-dev' , $ contents ) && is_array ( $ contents [ 'require-dev' ] ) ) { ksort ( $ contents [ 'require-dev' ] ) ; $ contents [ 'require-dev' ] = ( object ) $ contents [ 'require-dev' ] ; } file_put_contents ( $ this -> composerJsonFilepath , json_encode ( $ contents , JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) ) ; }
Writes an array to composer . json .
5,177
public function moveFile ( $ source , $ target , $ overwrite = FALSE ) { $ source_path = $ this -> getRepoRoot ( ) . '/' . $ source ; $ target_path = $ this -> getRepoRoot ( ) . '/' . $ target ; if ( $ this -> getFileSystem ( ) -> exists ( $ source ) ) { if ( $ overwrite ) { $ this -> getFileSystem ( ) -> rename ( $ source_path , $ target_path , TRUE ) ; } elseif ( ! $ this -> getFileSystem ( ) -> exists ( $ target_path ) ) { $ this -> getFileSystem ( ) -> rename ( $ source_path , $ target_path ) ; } } return FALSE ; }
Moves a file from one location to another relative to repo root .
5,178
public function syncWithTemplate ( $ filePath , $ overwrite = FALSE ) { $ sourcePath = $ this -> getBltRoot ( ) . '/template/' . $ filePath ; $ targetPath = $ this -> getRepoRoot ( ) . '/' . $ filePath ; if ( $ this -> getFileSystem ( ) -> exists ( $ sourcePath ) ) { try { $ this -> getFileSystem ( ) -> copy ( $ sourcePath , $ targetPath , $ overwrite ) ; } catch ( IOException $ e ) { throw $ e ; } } }
Copies a file from the BLT template to the repository .
5,179
public function replaceInFile ( $ source , $ original , $ replacement ) { $ source_path = $ this -> getRepoRoot ( ) . '/' . $ source ; if ( $ this -> getFileSystem ( ) -> exists ( $ source ) ) { $ contents = file_get_contents ( $ source_path ) ; $ new_contents = str_replace ( $ original , $ replacement , $ contents ) ; file_put_contents ( $ source_path , $ new_contents ) ; } }
Performs a find and replace in a text file .
5,180
public function regenerateCloudHooks ( ) { if ( file_exists ( $ this -> getRepoRoot ( ) . '/hooks' ) && ! $ this -> cloudHooksAlreadyUpdated ) { self :: executeCommand ( "./vendor/bin/blt recipes:cloud-hooks:init" , NULL , FALSE ) ; $ this -> cloudHooksAlreadyUpdated = TRUE ; return TRUE ; } return FALSE ; }
Regenerate Cloud Hooks but only once .
5,181
public function runCommand ( Command $ command , InputInterface $ input , OutputInterface $ output ) { return $ this -> doRunCommand ( $ command , $ input , $ output ) ; }
This command is identical to its parent but public rather than protected .
5,182
protected function getPhpFilesetFinder ( ) { $ finder = new Finder ( ) ; $ finder -> files ( ) -> name ( "*.inc" ) -> name ( "*.install" ) -> name ( "*.module" ) -> name ( "*.php" ) -> name ( "*.profile" ) -> name ( "*.test" ) -> name ( "*.theme" ) -> notPath ( 'behat' ) -> notPath ( 'node_modules' ) -> notPath ( 'vendor' ) ; return $ finder ; }
Adds Drupalistic PHP patterns to a Symfony finder object .
5,183
protected function getFrontendFilesetFinder ( ) { $ finder = new Finder ( ) ; $ finder -> files ( ) -> path ( "*/js/*" ) -> name ( "*.js" ) -> notName ( '*.min.js' ) -> notPath ( 'bower_components' ) -> notPath ( 'node_modules' ) -> notPath ( 'vendor' ) ; return $ finder ; }
Adds Drupalistic JS patterns to a Symfony finder object .
5,184
protected function getYamlFilesetFinder ( ) { $ finder = new Finder ( ) ; $ finder -> files ( ) -> name ( "*.yml" ) -> name ( "*.yaml" ) -> notPath ( 'bower_components' ) -> notPath ( 'node_modules' ) -> notPath ( 'vendor' ) ; return $ finder ; }
Adds Drupalistic YAML patterns to a Symfony finder object .
5,185
protected function getTwigFilesetFinder ( ) { $ finder = new Finder ( ) ; $ finder -> files ( ) -> name ( "*.twig" ) -> notPath ( 'bower_components' ) -> notPath ( 'node_modules' ) -> notPath ( 'vendor' ) ; return $ finder ; }
Adds Drupalistic Twig patterns to a Symfony finder object .
5,186
protected function formatMessage ( $ label , $ message , $ context , $ taskNameStyle , $ messageStyle = '' ) { $ message = parent :: formatMessage ( $ label , $ message , $ context , $ taskNameStyle , $ messageStyle ) ; $ message = trim ( $ message ) ; return $ message ; }
Log style customization for Robo .
5,187
public function dbScrub ( $ site , $ target_env , $ db_name , $ source_env ) { if ( ! EnvironmentDetector :: isAcsfEnv ( $ site , $ target_env ) ) { $ password = RandomString :: string ( 10 , FALSE , function ( $ string ) { return ! preg_match ( '/[^\x{80}-\x{F7} a-z0-9@+_.\'-]/i' , $ string ) ; } , 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!#%^&*()_?/.,+=><' ) ; $ this -> say ( "Scrubbing database in $target_env" ) ; $ result = $ this -> taskDrush ( ) -> drush ( "sql-sanitize --sanitize-password=\"$password\" --yes" ) -> run ( ) ; if ( ! $ result -> wasSuccessful ( ) ) { throw new BltException ( "Failed to sanitize database!" ) ; } $ this -> taskDrush ( ) -> drush ( "cr" ) -> run ( ) ; } }
Execute sql - sanitize against a database hosted in AC Cloud .
5,188
protected function sendPostCodeUpdateNotifications ( $ site , $ target_env , $ source_branch , $ deployed_tag , $ success ) { $ is_tag = $ source_branch != $ deployed_tag ; if ( $ success ) { if ( $ is_tag ) { $ message = "An updated deployment has been made to *$site.$target_env* using tag *$deployed_tag*." ; } else { $ message = "An updated deployment has been made to *$site.$target_env* using branch *$source_branch* as *$deployed_tag*." ; } } else { $ message = "Deployment has FAILED for environment *$site.$target_env*." ; } $ this -> notifySlack ( $ success , $ message ) ; }
Sends updates to notification endpoints .
5,189
protected function getSlackWebhookUrl ( ) { if ( $ this -> getConfig ( ) -> has ( 'slack.webhook-url' ) ) { return $ this -> getConfigValue ( 'slack.webhook-url' ) ; } elseif ( getenv ( 'SLACK_WEBHOOK_URL' ) ) { return getenv ( 'SLACK_WEBHOOK_URL' ) ; } $ this -> say ( "Slack webhook url not found. To enable Slack notifications, set <comment>slack.webhook-url</comment>." ) ; return FALSE ; }
Gets slack web url .
5,190
protected function sendSlackNotification ( $ url , $ payload ) { $ this -> say ( "Sending slack notification..." ) ; $ data = "payload=" . json_encode ( $ payload ) ; $ ch = curl_init ( $ url ) ; curl_setopt ( $ ch , CURLOPT_CUSTOMREQUEST , "POST" ) ; curl_setopt ( $ ch , CURLOPT_POSTFIELDS , $ data ) ; curl_setopt ( $ ch , CURLOPT_RETURNTRANSFER , TRUE ) ; $ result = curl_exec ( $ ch ) ; curl_close ( $ ch ) ; }
Sends a message to a slack channel .
5,191
protected function updateSites ( $ site , $ target_env ) { if ( EnvironmentDetector :: isAhOdeEnv ( $ target_env ) ) { $ this -> updateOdeSites ( ) ; } else { $ this -> updateAceSites ( $ target_env ) ; } }
Executes updates against all sites .
5,192
public function onPostPackageEvent ( PackageEvent $ event ) { $ package = $ this -> getBltPackage ( $ event -> getOperation ( ) ) ; if ( $ package ) { $ this -> bltPackage = $ package ; } }
Marks blt to be processed after an install or update command .
5,193
protected function isNewProject ( ) { $ composer_json = json_decode ( file_get_contents ( $ this -> getRepoRoot ( ) . '/composer.json' ) , TRUE ) ; if ( isset ( $ composer_json [ 'name' ] ) && in_array ( $ composer_json [ 'name' ] , [ 'acquia/blt-project' , 'acquia/blted8' ] ) ) { return TRUE ; } return FALSE ; }
Determine if this is a project being newly created .
5,194
public function getVendorPath ( ) { $ config = $ this -> composer -> getConfig ( ) ; $ filesystem = new Filesystem ( ) ; $ filesystem -> ensureDirectoryExists ( $ config -> get ( 'vendor-dir' ) ) ; $ vendorPath = $ filesystem -> normalizePath ( realpath ( $ config -> get ( 'vendor-dir' ) ) ) ; return $ vendorPath ; }
Get the path to the vendor directory .
5,195
protected function getOptions ( ) { $ defaults = [ 'update' => TRUE , ] ; $ extra = $ this -> composer -> getPackage ( ) -> getExtra ( ) + [ 'blt' => [ ] ] ; $ extra [ 'blt' ] = $ extra [ 'blt' ] + $ defaults ; return $ extra ; }
Retrieve extra configuration .
5,196
public function install ( ) { if ( $ this -> getConfigValue ( 'drupal.account.name' ) !== NULL ) { $ username = $ this -> getConfigValue ( 'drupal.account.name' ) ; } else { $ username = RandomString :: string ( 10 , FALSE , function ( $ string ) { return ! preg_match ( '/[^\x{80}-\x{F7} a-z0-9@+_.\'-]/i' , $ string ) ; } , 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!#%^&*()_?/.,+=><' ) ; } $ task = $ this -> taskDrush ( ) -> drush ( "site-install" ) -> arg ( $ this -> getConfigValue ( 'project.profile.name' ) ) -> rawArg ( "install_configure_form.enable_update_status_module=NULL" ) -> option ( 'sites-subdir' , $ this -> getConfigValue ( 'site' ) ) -> option ( 'site-name' , $ this -> getConfigValue ( 'project.human_name' ) ) -> option ( 'site-mail' , $ this -> getConfigValue ( 'drupal.account.mail' ) ) -> option ( 'account-name' , $ username , '=' ) -> option ( 'account-mail' , $ this -> getConfigValue ( 'drupal.account.mail' ) ) -> option ( 'locale' , $ this -> getConfigValue ( 'drupal.locale' ) ) -> verbose ( TRUE ) -> printOutput ( TRUE ) ; $ strategy = $ this -> getConfigValue ( 'cm.strategy' ) ; $ cm_core_key = $ this -> getConfigValue ( 'cm.core.key' ) ; $ install_from_config = $ this -> getConfigValue ( 'cm.core.install_from_config' ) ; if ( in_array ( $ strategy , [ 'core-only' , 'config-split' ] ) && $ cm_core_key == 'sync' && $ install_from_config ) { $ core_config_file = $ this -> getConfigValue ( 'docroot' ) . '/' . $ this -> getConfigValue ( "cm.core.dirs.$cm_core_key.path" ) . '/core.extension.yml' ; if ( file_exists ( $ core_config_file ) ) { $ task -> option ( 'existing-config' ) ; } } $ result = $ task -> interactive ( $ this -> input ( ) -> isInteractive ( ) ) -> run ( ) ; if ( ! $ result -> wasSuccessful ( ) ) { throw new BltException ( "Failed to install Drupal!" ) ; } return $ result ; }
Installs Drupal and imports configuration .
5,197
protected function checkBehat ( ) { $ this -> checkLocalConfig ( ) ; if ( $ this -> behatLocalYmlExists ( ) ) { $ behatDefaultLocalConfig = $ this -> getInspector ( ) -> getLocalBehatConfig ( ) -> export ( ) ; $ this -> checkDrupalVm ( $ behatDefaultLocalConfig ) ; $ this -> checkBaseUrl ( $ behatDefaultLocalConfig ) ; } }
Checks Behat configuration in local . yml .
5,198
public function drush ( $ command ) { $ bin = $ this -> getConfigValue ( 'composer.bin' ) ; $ drush_alias = $ this -> getConfigValue ( 'drush.alias' ) ; $ command_string = "'$bin/drush' @$drush_alias $command" ; if ( $ drush_alias != 'self' ) { $ command_string .= ' --uri=' . $ this -> getConfigValue ( 'site' ) ; } $ process_executor = Robo :: process ( new Process ( $ command_string ) ) ; return $ process_executor -> dir ( $ this -> getConfigValue ( 'docroot' ) ) -> interactive ( FALSE ) -> printOutput ( TRUE ) -> printMetadata ( TRUE ) -> setVerbosityThreshold ( VerbosityThresholdInterface :: VERBOSITY_VERY_VERBOSE ) ; }
Executes a drush command .
5,199
public function wait ( callable $ callable , array $ args , $ message = '' ) { $ maxWait = 60 * 1000 ; $ checkEvery = 1 * 1000 ; $ start = microtime ( TRUE ) * 1000 ; $ end = $ start + $ maxWait ; if ( ! $ message ) { $ method_name = is_array ( $ callable ) ? $ callable [ 1 ] : $ callable ; $ message = "Waiting for $method_name() to return true." ; } while ( microtime ( TRUE ) * 1000 < $ end ) { $ this -> logger -> info ( $ message ) ; try { if ( call_user_func_array ( $ callable , $ args ) ) { return TRUE ; } } catch ( \ Exception $ e ) { $ this -> logger -> error ( $ e -> getMessage ( ) ) ; } usleep ( $ checkEvery * 1000 ) ; } throw new BltException ( "Timed out." ) ; }
Waits until a given callable returns TRUE .