idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
50,200
private function truncate ( $ hash ) { $ offset = ord ( $ hash [ strlen ( $ hash ) - 1 ] ) & 0xf ; return ( ( ( ord ( $ hash [ $ offset + 0 ] ) & 0x7f ) << 24 ) | ( ( ord ( $ hash [ $ offset + 1 ] ) & 0xff ) << 16 ) | ( ( ord ( $ hash [ $ offset + 2 ] ) & 0xff ) << 8 ) | ( ord ( $ hash [ $ offset + 3 ] ) & 0xff ) ) % pow ( 10 , $ this -> digits ) ; }
Creates the basic number for otp from hash
50,201
public function getArray ( ) { try { $ parsed = TomlParser :: ParseFile ( $ this -> context ) ; } catch ( ParseException $ e ) { throw new InvalidFileException ( $ e -> getMessage ( ) ) ; } return $ parsed ; }
Retrieve the contents of a . toml file and convert it to an array of configuration options .
50,202
public function getArray ( ) { $ contents = include $ this -> context ; if ( gettype ( $ contents ) != 'array' ) { throw new InvalidFileException ( $ this -> context . ' does not return a valid array' ) ; } return $ contents ; }
Retrieve the contents of a . php configuration file and convert it to an array of configuration options .
50,203
public function getArray ( ) { $ parsed = @ parse_ini_file ( $ this -> context , true ) ; if ( ! $ parsed ) { throw new InvalidFileException ( 'Unable to parse invalid INI file at ' . $ this -> context ) ; } return $ parsed ; }
Retrieve the contents of a . ini file and convert it to an array of configuration options .
50,204
private function loadLanguageData ( string $ language = 'de' ) { if ( \ in_array ( $ language , self :: $ availableLanguages , true ) === false ) { throw new StopWordsLanguageNotExists ( 'language not supported: ' . $ language ) ; } $ this -> stopWords [ $ language ] = $ this -> getData ( $ language ) ; }
Load language - data from one language .
50,205
public function getStopWordsFromLanguage ( string $ language = 'de' ) : array { if ( \ in_array ( $ language , self :: $ availableLanguages , true ) === false ) { throw new StopWordsLanguageNotExists ( 'language not supported: ' . $ language ) ; } if ( ! isset ( $ this -> stopWords [ $ language ] ) ) { $ this -> loadLanguageData ( $ language ) ; } return $ this -> stopWords [ $ language ] ; }
Get the stop - words from one language .
50,206
public function prepandRoutes ( IRouter $ router , array $ routes ) : void { if ( empty ( $ routes ) ) { return ; } if ( ! ( $ router instanceof \ Traversable ) || ! ( $ router instanceof \ ArrayAccess ) ) { throw new ApiRouteWrongRouterException ( sprintf ( 'ApiRoutesResolver can not add ApiRoutes to your router. Use for example %s instead' , RouteList :: class ) ) ; } $ user_routes = $ this -> findAndDestroyUserRoutes ( $ router ) ; foreach ( $ routes as $ route ) { $ router [ ] = $ route ; } foreach ( $ user_routes as $ route ) { $ router [ ] = $ route ; } }
Place REST API routes at the beginnig of all routes
50,207
public static function convertSumupObjectToArray ( $ object ) { $ results = [ ] ; foreach ( $ object -> _keys as $ property ) { $ v = $ object -> { $ property } ; if ( $ v instanceof SumupObject ) { $ results [ $ property ] = $ v -> __toArray ( ) ; } elseif ( is_array ( $ v ) ) { $ results [ $ property ] = self :: convertSumupObjectToArray ( $ v ) ; } else { $ results [ $ property ] = $ v ; } } return $ results ; }
Recursively converts the PHP Sumup object to an array .
50,208
public static function authorizeUrl ( $ params = null ) { if ( ! $ params ) { $ params = array ( ) ; } $ params [ 'client_id' ] = self :: _getConnectParam ( 'client_id' , $ params ) ; $ params [ 'redirect_uri' ] = self :: _getConnectParam ( 'redirect_uri' , $ params ) ; if ( ! array_key_exists ( 'response_type' , $ params ) ) { $ params [ 'response_type' ] = 'code' ; } $ query = Util \ Util :: urlEncode ( $ params ) ; return Sumup :: $ connectBase . '/authorize?' . $ query ; }
Generates a URL to Sumup s OAuth form .
50,209
private static function _getConnectParam ( $ paramName , $ params = null ) { $ oauthParam = ( $ params && array_key_exists ( $ paramName , $ params ) ) ? $ params [ $ paramName ] : null ; if ( $ oauthParam === null ) { $ funcName = 'get' . Util \ Util :: toCamelCase ( $ paramName , true ) ; $ oauthParam = Sumup :: { $ funcName } ( ) ; } if ( $ oauthParam === null ) { $ msg = 'No ' . $ paramName . ' provided. You can find your ' . $ paramName . ' in your Sumup dashboard at ' . 'https://me.sumup.com/developers, ' . 'after registering your account as a platform. See ' . 'https://sumupus.desk.com/ for details, ' . 'or email support@sumup.com if you have any questions.' ; throw new Error \ AuthenticationError ( $ msg ) ; } return $ oauthParam ; }
return the Connect param based on the name
50,210
public function getPlacehodlerParameters ( ) : array { if ( ! empty ( $ this -> placeholder_order ) ) { return array_filter ( $ this -> placeholder_order ) ; } $ return = [ ] ; preg_replace_callback ( '/<(\w+)>/' , function ( $ item ) use ( & $ return ) { $ return [ ] = end ( $ item ) ; } , $ this -> path ) ; return $ return ; }
Get all parameters from url mask
50,211
public function getRequiredParams ( ) : array { $ regex = '/\[[^\[]+?\]/' ; $ path = $ this -> getPath ( ) ; while ( preg_match ( $ regex , $ path ) ) { $ path = preg_replace ( $ regex , '' , $ path ) ; } $ required = [ ] ; preg_replace_callback ( '/<(\w+)>/' , function ( $ item ) use ( & $ required ) { $ required [ ] = end ( $ item ) ; } , $ path ) ; return $ required ; }
Get required parameters from url mask
50,212
public function getError ( ) { return ( object ) [ "code" => $ this -> getCode ( ) , "message" => $ this -> getMessage ( ) , "details" => $ this -> getDetails ( ) , "key" => $ this -> getKey ( ) ] ; }
Get client error data
50,213
private function parse ( $ response ) { list ( $ headers , $ response ) = explode ( "\r\n\r\n" , $ response , 2 ) ; $ lines = explode ( "\r\n" , $ headers ) ; if ( preg_match ( '#^HTTP/1.1 100#' , $ lines [ 0 ] ) ) { list ( $ headers , $ response ) = explode ( "\r\n\r\n" , $ response , 2 ) ; $ lines = explode ( "\r\n" , $ headers ) ; } $ first = array_shift ( $ lines ) ; $ pattern = '#^HTTP/1.1 ([0-9]{3})#' ; preg_match ( $ pattern , $ first , $ matches ) ; $ code = $ matches [ 1 ] ; $ headers = array ( ) ; foreach ( $ lines as $ line ) { list ( $ k , $ v ) = explode ( ': ' , $ line , 2 ) ; $ headers [ strtolower ( $ k ) ] = $ v ; } if ( ! $ body = json_decode ( $ response ) ) { $ body = $ response ; } return array ( 'code' => $ code , 'body' => $ body , 'headers' => $ headers ) ; }
Parse a cURL response
50,214
public function encrypt ( $ token ) { $ iv = mcrypt_create_iv ( self :: IV_SIZE , self :: IV_SOURCE ) ; $ cipherText = mcrypt_encrypt ( self :: CIPHER , $ this -> key , $ token , self :: MODE , $ iv ) ; return base64_encode ( $ iv . $ cipherText ) ; }
Encrypt the OAuth token
50,215
public function decrypt ( $ cipherText ) { $ cipherText = base64_decode ( $ cipherText ) ; $ iv = substr ( $ cipherText , 0 , self :: IV_SIZE ) ; $ cipherText = substr ( $ cipherText , self :: IV_SIZE ) ; $ token = mcrypt_decrypt ( self :: CIPHER , $ this -> key , $ cipherText , self :: MODE , $ iv ) ; return $ token ; }
Decrypt the ciphertext
50,216
public function delete ( ) { try { parent :: delete ( ) ; $ query = 'DELETE FROM ' . $ this -> table . ' WHERE userID = ?' ; $ stmt = $ this -> pdo -> prepare ( $ query ) ; $ stmt -> execute ( array ( $ this -> userID ) ) ; return $ stmt -> rowCount ( ) > 0 ; } catch ( \ PDOException $ e ) { return false ; } }
Delete access token for the current user ID from the database
50,217
protected function createTable ( ) { $ template = file_get_contents ( dirname ( __FILE__ ) . '/TableSchema.sql' ) ; $ this -> pdo -> query ( sprintf ( $ template , $ this -> table ) ) ; }
Attempt to create the OAuth token table
50,218
public function get ( $ type ) { if ( $ type != 'request_token' && $ type != 'access_token' ) { throw new \ Dropbox \ Exception ( "Expected a type of either 'request_token' or 'access_token', got '$type'" ) ; } else { if ( isset ( $ _SESSION [ $ this -> namespace ] [ $ this -> userID ] [ $ type ] ) ) { $ token = $ this -> decrypt ( $ _SESSION [ $ this -> namespace ] [ $ this -> userID ] [ $ type ] ) ; return $ token ; } return false ; } }
Get an OAuth token from the session If the encrpytion object is set then decrypt the token before returning
50,219
public function set ( $ token , $ type ) { if ( $ type != 'request_token' && $ type != 'access_token' ) { throw new \ Dropbox \ Exception ( "Expected a type of either 'request_token' or 'access_token', got '$type'" ) ; } else { $ token = $ this -> encrypt ( $ token ) ; $ _SESSION [ $ this -> namespace ] [ $ this -> userID ] [ $ type ] = $ token ; } }
Set an OAuth token in the session by type If the encryption object is set then encrypt the token before storing
50,220
protected function encrypt ( $ token ) { $ token = serialize ( $ token ) ; if ( $ this -> encrypter instanceof Encrypter ) { $ token = $ this -> encrypter -> encrypt ( $ token ) ; } return $ token ; }
Use the Encrypter to encrypt a token and return it If there is not encrypter object return just the serialized token object for storage
50,221
protected function decrypt ( $ token ) { if ( $ this -> encrypter instanceof Encrypter ) { $ token = $ this -> encrypter -> decrypt ( $ token ) ; } return @ unserialize ( $ token ) ; }
Decrypt a token using the Encrypter object and return it If there is no Encrypter object assume the token was stored serialized and return the unserialized token object
50,222
public function delete ( ) { parent :: delete ( ) ; $ file = $ this -> getTokenFilePath ( ) ; return file_exists ( $ file ) && @ unlink ( $ file ) ; }
Delete the access token stored on disk for the current user ID
50,223
private function getTokenFilePath ( ) { if ( $ this -> tokenDirectory === null ) { throw new \ Dropbox \ Exception ( 'OAuth token directory not set. See Filesystem::setDirectory()' ) ; } else { return $ this -> tokenDirectory . '/' . md5 ( $ this -> userID ) . '.token' ; } }
Get the token file path for the specified user ID
50,224
public function putFile ( $ file , $ filename = false , $ path = '' , $ overwrite = true ) { if ( file_exists ( $ file ) ) { if ( filesize ( $ file ) <= 157286400 ) { $ call = 'files/' . $ this -> root . '/' . $ this -> encodePath ( $ path ) ; $ filename = ( is_string ( $ filename ) ) ? $ filename : basename ( $ file ) ; $ params = array ( 'filename' => $ filename , 'file' => '@' . str_replace ( '\\' , '/' , $ file ) . ';filename=' . $ filename , 'overwrite' => ( int ) $ overwrite , ) ; $ response = $ this -> fetch ( 'POST' , self :: CONTENT_URL , $ call , $ params ) ; return $ response ; } throw new Exception ( 'File exceeds 150MB upload limit' ) ; } throw new Exception ( 'Local file ' . $ file . ' does not exist' ) ; }
Uploads a physical file from disk Dropbox impose a 150MB limit to files uploaded via the API . If the file exceeds this limit or does not exist an Exception will be thrown
50,225
public function chunkedUpload ( $ file , $ filename = false , $ path = '' , $ overwrite = true , $ offset = 0 , $ uploadID = null ) { if ( file_exists ( $ file ) ) { if ( $ handle = @ fopen ( $ file , 'r' ) ) { fseek ( $ handle , $ offset ) ; while ( $ data = fread ( $ handle , $ this -> chunkSize ) ) { $ chunkHandle = fopen ( 'php://temp' , 'rw' ) ; fwrite ( $ chunkHandle , $ data ) ; $ this -> OAuth -> setInFile ( $ chunkHandle ) ; $ params = array ( 'upload_id' => $ uploadID , 'offset' => $ offset ) ; try { $ response = $ this -> fetch ( 'PUT' , self :: CONTENT_URL , 'chunked_upload' , $ params ) ; } catch ( Exception $ e ) { $ response = $ this -> OAuth -> getLastResponse ( ) ; if ( $ response [ 'code' ] == 400 ) { $ uploadID = $ response [ 'body' ] -> upload_id ; $ offset = $ response [ 'body' ] -> offset ; return array ( 'uploadID' => $ uploadID , 'offset' => $ offset ) ; } else { throw $ e ; } } if ( isset ( $ response [ 'body' ] -> upload_id ) ) { $ uploadID = $ response [ 'body' ] -> upload_id ; } if ( isset ( $ response [ 'body' ] -> offset ) ) { $ offset = $ response [ 'body' ] -> offset ; } fclose ( $ chunkHandle ) ; } $ filename = ( is_string ( $ filename ) ) ? $ filename : basename ( $ file ) ; $ call = 'commit_chunked_upload/' . $ this -> root . '/' . $ this -> encodePath ( rtrim ( $ path , '/' ) . '/' . $ filename ) ; $ params = array ( 'overwrite' => ( int ) $ overwrite , 'upload_id' => $ uploadID ) ; $ response = $ this -> fetch ( 'POST' , self :: CONTENT_URL , $ call , $ params ) ; return $ response ; } else { throw new Exception ( 'Could not open ' . $ file . ' for reading' ) ; } } throw new Exception ( 'Local file ' . $ file . ' does not exist' ) ; }
Uploads large files to Dropbox in mulitple chunks
50,226
public function getFile ( $ file , $ outFile = false , $ revision = null ) { if ( $ this -> responseFormat !== 'php' ) { throw new Exception ( 'This method only supports the `php` response format' ) ; } $ handle = null ; if ( $ outFile !== false ) { if ( ! $ handle = fopen ( $ outFile , 'w' ) ) { throw new Exception ( "Unable to open file handle for $outFile" ) ; } else { $ this -> OAuth -> setOutFile ( $ handle ) ; } } $ file = $ this -> encodePath ( $ file ) ; $ call = 'files/' . $ this -> root . '/' . $ file ; $ params = array ( 'rev' => $ revision ) ; $ response = $ this -> fetch ( 'GET' , self :: CONTENT_URL , $ call , $ params ) ; if ( $ handle ) fclose ( $ handle ) ; return array ( 'name' => ( $ outFile ) ? $ outFile : basename ( $ file ) , 'mime' => $ this -> getMimeType ( ( $ outFile ) ? : $ response [ 'body' ] , $ outFile ) , 'meta' => json_decode ( $ response [ 'headers' ] [ 'x-dropbox-metadata' ] ) , 'data' => $ response [ 'body' ] , ) ; }
Downloads a file Returns the base filename raw file data and mime type returned by Fileinfo
50,227
public function metaData ( $ path = null , $ rev = null , $ limit = 10000 , $ hash = false , $ list = true , $ deleted = false ) { $ call = 'metadata/' . $ this -> root . '/' . $ this -> encodePath ( $ path ) ; $ params = array ( 'file_limit' => ( $ limit < 1 ) ? 1 : ( ( $ limit > 10000 ) ? 10000 : ( int ) $ limit ) , 'hash' => ( is_string ( $ hash ) ) ? $ hash : 0 , 'list' => ( int ) $ list , 'include_deleted' => ( int ) $ deleted , 'rev' => ( is_string ( $ rev ) ) ? $ rev : null , ) ; $ response = $ this -> fetch ( 'POST' , self :: API_URL , $ call , $ params ) ; return $ response ; }
Retrieves file and folder metadata
50,228
public function revisions ( $ file , $ limit = 10 ) { $ call = 'revisions/' . $ this -> root . '/' . $ this -> encodePath ( $ file ) ; $ params = array ( 'rev_limit' => ( $ limit < 1 ) ? 1 : ( ( $ limit > 1000 ) ? 1000 : ( int ) $ limit ) , ) ; $ response = $ this -> fetch ( 'GET' , self :: API_URL , $ call , $ params ) ; return $ response ; }
Obtains metadata for the previous revisions of a file
50,229
public function restore ( $ file , $ revision ) { $ call = 'restore/' . $ this -> root . '/' . $ this -> encodePath ( $ file ) ; $ params = array ( 'rev' => $ revision ) ; $ response = $ this -> fetch ( 'POST' , self :: API_URL , $ call , $ params ) ; return $ response ; }
Restores a file path to a previous revision
50,230
public function search ( $ query , $ path = '' , $ limit = 1000 , $ deleted = false ) { $ call = 'search/' . $ this -> root . '/' . $ this -> encodePath ( $ path ) ; $ params = array ( 'query' => $ query , 'file_limit' => ( $ limit < 1 ) ? 1 : ( ( $ limit > 1000 ) ? 1000 : ( int ) $ limit ) , 'include_deleted' => ( int ) $ deleted , ) ; $ response = $ this -> fetch ( 'GET' , self :: API_URL , $ call , $ params ) ; return $ response ; }
Returns metadata for all files and folders that match the search query
50,231
public function media ( $ path ) { $ call = 'media/' . $ this -> root . '/' . $ this -> encodePath ( $ path ) ; $ response = $ this -> fetch ( 'POST' , self :: API_URL , $ call ) ; return $ response ; }
Returns a link directly to a file
50,232
public function thumbnails ( $ file , $ format = 'JPEG' , $ size = 'small' ) { if ( $ this -> responseFormat !== 'php' ) { throw new Exception ( 'This method only supports the `php` response format' ) ; } $ format = strtoupper ( $ format ) ; if ( $ format != 'PNG' ) $ format = 'JPEG' ; $ size = strtolower ( $ size ) ; $ sizes = array ( 's' , 'm' , 'l' , 'xl' , 'small' , 'medium' , 'large' ) ; if ( ! in_array ( $ size , $ sizes ) ) $ size = 'small' ; $ call = 'thumbnails/' . $ this -> root . '/' . $ this -> encodePath ( $ file ) ; $ params = array ( 'format' => $ format , 'size' => $ size ) ; $ response = $ this -> fetch ( 'GET' , self :: CONTENT_URL , $ call , $ params ) ; return array ( 'name' => basename ( $ file ) , 'mime' => $ this -> getMimeType ( $ response [ 'body' ] ) , 'meta' => json_decode ( $ response [ 'headers' ] [ 'x-dropbox-metadata' ] ) , 'data' => $ response [ 'body' ] , ) ; }
Gets a thumbnail for an image
50,233
public function copy ( $ from , $ to , $ fromCopyRef = null ) { $ call = 'fileops/copy' ; $ params = array ( 'root' => $ this -> root , 'from_path' => $ this -> normalisePath ( $ from ) , 'to_path' => $ this -> normalisePath ( $ to ) , ) ; if ( $ fromCopyRef ) { $ params [ 'from_path' ] = null ; $ params [ 'from_copy_ref' ] = $ fromCopyRef ; } $ response = $ this -> fetch ( 'POST' , self :: API_URL , $ call , $ params ) ; return $ response ; }
Copies a file or folder to a new location
50,234
public function move ( $ from , $ to ) { $ call = 'fileops/move' ; $ params = array ( 'root' => $ this -> root , 'from_path' => $ this -> normalisePath ( $ from ) , 'to_path' => $ this -> normalisePath ( $ to ) , ) ; $ response = $ this -> fetch ( 'POST' , self :: API_URL , $ call , $ params ) ; return $ response ; }
Moves a file or folder to a new location
50,235
private function fetch ( $ method , $ url , $ call , array $ params = array ( ) ) { $ response = $ this -> OAuth -> fetch ( $ method , $ url , $ call , $ params ) ; switch ( $ this -> responseFormat ) { case 'json' : return json_encode ( $ response ) ; case 'jsonp' : $ response = json_encode ( $ response ) ; return $ this -> callback . '(' . $ response . ')' ; default : return $ response ; } }
Intermediate fetch function
50,236
public function setResponseFormat ( $ format ) { $ format = strtolower ( $ format ) ; if ( ! in_array ( $ format , array ( 'php' , 'json' , 'jsonp' ) ) ) { throw new Exception ( "Expected a format of php, json or jsonp, got '$format'" ) ; } else { $ this -> responseFormat = $ format ; } }
Set the API response format
50,237
private function getMimeType ( $ data , $ isFilename = false ) { if ( extension_loaded ( 'fileinfo' ) ) { $ finfo = new \ finfo ( FILEINFO_MIME ) ; if ( $ isFilename !== false ) { return $ finfo -> file ( $ data ) ; } return $ finfo -> buffer ( $ data ) ; } return false ; }
Get the mime type of downloaded file If the Fileinfo extension is not loaded return false
50,238
private function encodePath ( $ path ) { $ path = $ this -> normalisePath ( $ path ) ; $ path = str_replace ( '%2F' , '/' , rawurlencode ( $ path ) ) ; return $ path ; }
Encode the path then replace encoded slashes with literal forward slash characters
50,239
protected function authenticate ( ) { if ( ( ! $ this -> storage -> get ( 'access_token' ) ) ) { try { $ this -> getAccessToken ( ) ; } catch ( \ Dropbox \ Exception $ e ) { $ this -> getRequestToken ( ) ; $ this -> authorise ( ) ; } } }
Authenticate using 3 - legged OAuth flow firstly checking we don t already have tokens to use
50,240
public function getRequestToken ( ) { $ this -> storage -> set ( null , 'request_token' ) ; $ url = API :: API_URL . self :: REQUEST_TOKEN_METHOD ; $ response = $ this -> fetch ( 'POST' , $ url , '' ) ; $ token = $ this -> parseTokenString ( $ response [ 'body' ] ) ; $ this -> storage -> set ( $ token , 'request_token' ) ; }
Acquire an unauthorised request token
50,241
public function getAuthoriseUrl ( ) { $ token = $ this -> getToken ( ) ; $ params = array ( 'oauth_token' => $ token -> oauth_token , 'oauth_token_secret' => $ token -> oauth_token_secret , 'oauth_callback' => $ this -> callback , ) ; $ query = '?' . http_build_query ( $ params , '' , '&' ) ; $ url = self :: WEB_URL . self :: AUTHORISE_METHOD . $ query ; return $ url ; }
Build the user authorisation URL
50,242
public function getAccessToken ( ) { $ response = $ this -> fetch ( 'POST' , API :: API_URL , self :: ACCESS_TOKEN_METHOD ) ; $ token = $ this -> parseTokenString ( $ response [ 'body' ] ) ; $ this -> storage -> set ( $ token , 'access_token' ) ; }
Acquire an access token Tokens acquired at this point should be stored to prevent having to request new tokens for each API call
50,243
protected function getSignedRequest ( $ method , $ url , $ call , array $ additional = array ( ) ) { $ token = $ this -> getToken ( ) ; $ nonce = md5 ( microtime ( true ) . uniqid ( '' , true ) ) ; $ params = array ( 'oauth_consumer_key' => $ this -> consumerKey , 'oauth_token' => $ token -> oauth_token , 'oauth_signature_method' => $ this -> sigMethod , 'oauth_version' => '1.0' , 'oauth_timestamp' => ( $ this -> sigMethod == 'HMAC-SHA1' ) ? time ( ) : null , 'oauth_nonce' => ( $ this -> sigMethod == 'HMAC-SHA1' ) ? $ nonce : null , ) ; $ params = array_merge ( $ params , $ additional ) ; ksort ( $ params ) ; $ encoded = array ( ) ; foreach ( $ params as $ param => $ value ) { if ( $ value !== null ) { if ( isset ( $ value [ 0 ] ) && $ value [ 0 ] === '@' ) $ value = $ params [ 'filename' ] ; $ encoded [ ] = $ this -> encode ( $ param ) . '=' . $ this -> encode ( $ value ) ; } else { unset ( $ params [ $ param ] ) ; } } $ base = $ method . '&' . $ this -> encode ( $ url . $ call ) . '&' ; $ base .= $ this -> encode ( implode ( '&' , $ encoded ) ) ; $ key = $ this -> consumerSecret . '&' . $ token -> oauth_token_secret ; $ signature = $ this -> getSignature ( $ base , $ key ) ; $ params [ 'oauth_signature' ] = $ signature ; $ query = '?' . http_build_query ( $ params , '' , '&' ) ; return array ( 'url' => $ url . $ call . $ query , 'postfields' => $ params , ) ; }
Generate signed request URL See inline comments for description
50,244
private function getSignature ( $ base , $ key ) { switch ( $ this -> sigMethod ) { case 'PLAINTEXT' : $ signature = $ key ; break ; case 'HMAC-SHA1' : $ signature = base64_encode ( hash_hmac ( 'sha1' , $ base , $ key , true ) ) ; break ; } return $ signature ; }
Generate the oauth_signature for a request
50,245
public function setSignatureMethod ( $ method ) { $ method = strtoupper ( $ method ) ; switch ( $ method ) { case 'PLAINTEXT' : case 'HMAC-SHA1' : $ this -> sigMethod = $ method ; break ; default : throw new \ Dropbox \ Exception ( 'Unsupported signature method ' . $ method ) ; } }
Set the OAuth signature method
50,246
private function parseTokenString ( $ response ) { $ parts = explode ( '&' , $ response ) ; $ token = new \ stdClass ( ) ; foreach ( $ parts as $ part ) { list ( $ k , $ v ) = explode ( '=' , $ part , 2 ) ; $ k = strtolower ( $ k ) ; $ token -> $ k = $ v ; } return $ token ; }
Parse response parameters for a token into an object Dropbox returns tokens in the response parameters and not a JSON encoded object as per other API requests
50,247
public function setBreadcrumbs ( $ breadcrumbs ) { if ( ! is_array ( $ breadcrumbs ) ) { throw new \ InvalidArgumentException ( 'Breadcrumbs::setBreadcrumbs() only accepts arrays, but ' . ( is_object ( $ breadcrumbs ) ? get_class ( $ breadcrumbs ) : gettype ( $ breadcrumbs ) ) . ' given: ' . print_r ( $ breadcrumbs , true ) ) ; } foreach ( $ breadcrumbs as $ key => $ breadcrumb ) { if ( ! static :: isValidCrumb ( $ breadcrumb ) ) { throw new \ InvalidArgumentException ( 'Breadcrumbs::setBreadcrumbs() only accepts correctly formatted arrays, but at least one of the ' . 'values was misformed: $breadcrumbs[' . $ key . '] = ' . print_r ( $ breadcrumb , true ) ) ; } else { $ this -> addCrumb ( $ breadcrumb [ 'name' ] ? : '' , $ breadcrumb [ 'href' ] ? : '' , isset ( $ breadcrumb [ 'hrefIsFullUrl' ] ) ? ( bool ) $ breadcrumb [ 'hrefIsFullUrl' ] : false ) ; } } return $ this ; }
Sets all the breadcrumbs . Useful for quickly configuring the instance .
50,248
public static function isValidCrumb ( $ crumb ) { if ( ! is_array ( $ crumb ) ) { return false ; } if ( ! isset ( $ crumb [ 'name' ] , $ crumb [ 'href' ] ) ) { return false ; } if ( ! is_string ( $ crumb [ 'name' ] ) || ! is_string ( $ crumb [ 'href' ] ) ) { return false ; } if ( empty ( $ crumb [ 'name' ] ) || empty ( $ crumb [ 'href' ] ) ) { return false ; } return true ; }
Checks whether a crumb is valid so that it can safely be added to the internal breadcrumbs array .
50,249
public function setListElement ( $ element ) { if ( ! is_string ( $ element ) ) { throw new \ InvalidArgumentException ( 'Breadcrumbs::setListElement() only accepts strings, but ' . ( is_object ( $ element ) ? get_class ( $ element ) : gettype ( $ element ) ) . ' given: ' . print_r ( $ element , true ) ) ; } $ this -> listElement = $ element ; return $ this ; }
Set the containing list DOM element
50,250
public function setListItemCssClass ( $ class ) { if ( ! is_string ( $ class ) ) { throw new \ InvalidArgumentException ( 'Breadcrumbs::setListItemCssClass() only accepts strings, but ' . ( is_object ( $ class ) ? get_class ( $ class ) : gettype ( $ class ) ) . ' given: ' . print_r ( $ class , true ) ) ; } $ this -> listItemCssClass = $ class ; return $ this ; }
Set the list item CSS class .
50,251
protected function renderCrumb ( $ name , $ href , $ isLast = false , $ position = null ) { if ( $ this -> divider ) { $ divider = " <span class=\"divider\">{$this->divider}</span>" ; } else { $ divider = '' ; } if ( $ position != null ) { $ positionMeta = "<meta itemprop=\"position\" content=\"{$position}\" />" ; } else { $ positionMeta = "" ; } if ( ! $ isLast ) { return '<li itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem" ' . "class=\"{$this->listItemCssClass}\" >" . "<a itemprop=\"item\" href=\"{$href}\"><span itemprop=\"name\">{$name}</span></a>" . "{$positionMeta}{$divider}</li>" ; } else { return '<li itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem" ' . "class=\"{$this->listItemCssClass} active\"><span itemprop=\"name\">{$name}</span>" . "{$positionMeta}</li>" ; } }
Renders a single breadcrumb Twitter Bootstrap - style .
50,252
protected function renderCrumbs ( ) { end ( $ this -> breadcrumbs ) ; $ lastKey = key ( $ this -> breadcrumbs ) ; $ output = '' ; $ hrefSegments = array ( ) ; $ position = 1 ; foreach ( $ this -> breadcrumbs as $ key => $ crumb ) { $ isLast = ( $ lastKey === $ key ) ; if ( $ crumb [ 'hrefIsFullUrl' ] ) { $ hrefSegments = array ( ) ; } if ( $ crumb [ 'href' ] ) { $ hrefSegments [ ] = $ crumb [ 'href' ] ; } $ href = implode ( '/' , $ hrefSegments ) ; if ( ! preg_match ( '#^https?://.*#' , $ href ) ) { $ href = "/{$href}" ; } $ output .= $ this -> renderCrumb ( $ crumb [ 'name' ] , $ href , $ isLast , $ position ) ; $ position ++ ; } return $ output ; }
Renders the crumbs one by one and returns them concatenated .
50,253
public function render ( ) { if ( empty ( $ this -> breadcrumbs ) ) { return '' ; } $ cssClasses = implode ( ' ' , $ this -> breadcrumbsCssClasses ) ; return '<' . $ this -> listElement . ' itemscope itemtype="http://schema.org/BreadcrumbList"' . ' class="' . $ cssClasses . '">' . $ this -> renderCrumbs ( ) . '</' . $ this -> listElement . '>' ; }
Renders the complete breadcrumbs into Twitter Bootstrap - compatible HTML .
50,254
protected function startListening ( ) { foreach ( $ this -> eventsToListenFor as $ event ) { if ( is_callable ( [ $ this , $ event ] ) ) { $ this -> connection -> eventManager ( ) -> bind ( $ event , [ $ this , $ event ] ) ; } } return $ this ; }
Binds the requested events to the event manager .
50,255
public function requestCode ( $ username , $ type = 'sms' , $ debug = false ) { $ registration = new Registration ( $ username , $ debug ) ; switch ( $ type ) { case 'sms' : $ registration -> codeRequest ( 'sms' ) ; break ; case 'voice' : $ registration -> codeRequest ( 'voice' ) ; break ; default : throw new Exception ( 'Invalid registration type' ) ; } return $ registration ; }
When requesting the code you can do it via SMS or voice call in both cases you will receive a code like 123 - 456 that we will use for register the number .
50,256
public function authenticate ( Request $ request , Response $ response ) { if ( ! isset ( $ this -> _registry -> Cookie ) || ! $ this -> _registry -> Cookie instanceof CookieComponent ) { throw new \ RuntimeException ( 'You need to load the CookieComponent.' ) ; } $ cookies = $ this -> _registry -> Cookie -> read ( $ this -> _config [ 'cookie' ] [ 'name' ] ) ; if ( empty ( $ cookies ) ) { return false ; } extract ( $ this -> _config [ 'fields' ] ) ; if ( empty ( $ cookies [ $ username ] ) || empty ( $ cookies [ $ password ] ) ) { return false ; } $ user = $ this -> _findUser ( $ cookies [ $ username ] , $ cookies [ $ password ] ) ; if ( $ user ) { return $ user ; } return false ; }
Authenticate a user based on the cookies information .
50,257
public function getProperties ( ) { $ properties = [ ] ; foreach ( $ this -> audios as $ audio ) { $ properties = array_merge ( $ properties , $ audio -> getProperties ( ) ) ; } if ( $ this -> title !== null ) { $ properties [ ] = new Property ( Property :: TITLE , $ this -> title ) ; } if ( $ this -> description !== null ) { $ properties [ ] = new Property ( Property :: DESCRIPTION , $ this -> description ) ; } if ( $ this -> determiner !== null ) { $ properties [ ] = new Property ( Property :: DETERMINER , $ this -> determiner ) ; } foreach ( $ this -> images as $ image ) { $ properties = array_merge ( $ properties , $ image -> getProperties ( ) ) ; } if ( $ this -> locale !== null ) { $ properties [ ] = new Property ( Property :: LOCALE , $ this -> locale ) ; } foreach ( $ this -> localeAlternate as $ locale ) { $ properties [ ] = new Property ( Property :: LOCALE_ALTERNATE , $ locale ) ; } if ( $ this -> richAttachment !== null ) { $ properties [ ] = new Property ( Property :: RICH_ATTACHMENT , ( int ) $ this -> richAttachment ) ; } foreach ( $ this -> seeAlso as $ seeAlso ) { $ properties [ ] = new Property ( Property :: SEE_ALSO , $ seeAlso ) ; } if ( $ this -> siteName !== null ) { $ properties [ ] = new Property ( Property :: SITE_NAME , $ this -> siteName ) ; } if ( $ this -> type !== null ) { $ properties [ ] = new Property ( Property :: TYPE , $ this -> type ) ; } if ( $ this -> updatedTime !== null ) { $ properties [ ] = new Property ( Property :: UPDATED_TIME , $ this -> updatedTime -> format ( "c" ) ) ; } if ( $ this -> url !== null ) { $ properties [ ] = new Property ( Property :: URL , $ this -> url ) ; } foreach ( $ this -> videos as $ video ) { $ properties = array_merge ( $ properties , $ video -> getProperties ( ) ) ; } return $ properties ; }
Gets all properties set on this object .
50,258
public function loadUrl ( $ url ) { $ response = $ this -> client -> get ( $ url ) ; return $ this -> loadHtml ( $ response -> getBody ( ) -> __toString ( ) , $ url ) ; }
Fetches HTML content from the given URL and then crawls it for Open Graph data .
50,259
public function loadHtml ( $ html , $ fallbackUrl = null ) { $ page = $ this -> extractOpenGraphData ( $ html ) ; if ( $ this -> useFallbackMode && $ page -> url === null ) { $ page -> url = $ fallbackUrl ; } return $ page ; }
Crawls the given HTML string for OpenGraph data .
50,260
protected function formatPdf ( $ response ) { $ mpdf = new \ mPDF ( $ this -> mode , $ this -> format , $ this -> defaultFontSize , $ this -> defaultFont , $ this -> marginLeft , $ this -> marginRight , $ this -> marginTop , $ this -> marginBottom , $ this -> marginHeader , $ this -> marginFooter , $ this -> orientation ) ; foreach ( $ this -> options as $ key => $ option ) { $ mpdf -> $ key = $ option ; } if ( $ this -> beforeRender instanceof \ Closure ) { call_user_func ( $ this -> beforeRender , $ mpdf , $ response -> data ) ; } $ mpdf -> WriteHTML ( $ response -> data ) ; return $ mpdf -> Output ( '' , 'S' ) ; }
Formats response HTML in PDF
50,261
public function render ( ) { $ this -> applyElementBehavior ( ) ; $ elements = [ ] ; if ( $ this -> cloneElement ( ) ) { $ originalArguments = $ this -> arguments ( ) ; $ originalMethods = $ this -> methods ( ) ; $ locales = $ this -> locales ( ) ; if ( $ count = func_num_args ( ) ) { $ args = ( $ count == 1 ? head ( func_get_args ( ) ) : func_get_args ( ) ) ; $ locales = array_intersect ( $ locales , ( array ) $ args ) ; } foreach ( $ locales as $ locale ) { $ this -> arguments ( $ originalArguments ) ; $ this -> methods ( $ originalMethods ) ; $ name = str_contains ( $ originalArguments [ 'name' ] , '%locale' ) ? $ originalArguments [ 'name' ] : '%locale[' . $ originalArguments [ 'name' ] . ']' ; $ this -> overwriteArgument ( 'name' , str_replace ( '%locale' , $ locale , $ name ) ) ; if ( $ this -> translatableIndicator ( ) ) { $ this -> setTranslatableLabelIndicator ( $ locale ) ; } if ( ! empty ( $ this -> config [ 'form-group-class' ] ) ) { $ this -> addMethod ( 'addGroupClass' , str_replace ( '%locale' , $ locale , $ this -> config [ 'form-group-class' ] ) ) ; } if ( ! empty ( $ this -> config [ 'input-locale-attribute' ] ) ) { $ this -> addMethod ( 'attribute' , [ $ this -> config [ 'input-locale-attribute' ] , $ locale ] ) ; } $ elements [ ] = $ this -> createInput ( $ locale ) ; } } else { $ elements [ ] = $ this -> createInput ( ) ; } $ this -> reset ( ) ; return implode ( '' , $ elements ) ; }
Renders the current translatable form element .
50,262
public function findUnitByStart ( Token $ token ) { foreach ( $ this -> collection as $ unit ) { if ( $ unit -> start === $ token ) { return $ unit ; } } return null ; }
Searches for blocks that start with a given token and returns it or null if none is found
50,263
public function generate ( $ path , $ themeName , $ force = false , array $ options = [ ] ) { $ options = $ this -> createOptionsResolver ( ) -> resolve ( $ options ) ; $ this -> checkThemeName ( $ themeName ) ; $ this -> processPath ( $ path , $ force ) ; try { $ this -> createSite ( $ path , $ themeName , $ options [ 'prefer-lock' ] , $ options [ 'prefer-source' ] , $ options [ 'no-scripts' ] ) ; } catch ( \ Exception $ e ) { $ this -> fs -> remove ( $ path ) ; throw $ e ; } }
Scaffold a new site . In case of exception the new - site directory will be removed .
50,264
protected function createSite ( $ path , $ themeName , $ preferLock , $ preferSource , $ noScripts ) { $ this -> checkRequirements ( $ themeName ) ; $ themePair = new PackageNameVersion ( $ themeName ) ; $ this -> createBlankSite ( $ path , $ themePair ) ; if ( $ themeName === self :: BLANK_THEME ) { return ; } if ( $ this -> packageManager -> existPackage ( $ themeName ) === false ) { throw new \ RuntimeException ( sprintf ( 'The theme: "%s" does not exist at registered repositories.' , $ themeName ) ) ; } if ( $ this -> packageManager -> isThemePackage ( $ themeName ) === false ) { throw new \ RuntimeException ( sprintf ( 'The theme: "%s" is not a Spress theme.' , $ themeName ) ) ; } if ( $ this -> packageManager -> isPackageDependOn ( $ themeName , $ this -> spressInstallerPackage ) === false ) { throw new \ RuntimeException ( sprintf ( sprintf ( 'This version of Spress requires a theme with "%s".' , $ this -> spressInstallerPackage ) , $ themeName ) ) ; } $ this -> updateDependencies ( $ preferLock , $ preferSource , $ noScripts ) ; $ relativeThemePath = 'src/themes/' . $ themePair -> getName ( ) ; $ this -> copyContentFromThemeToSite ( $ path , $ relativeThemePath ) ; $ this -> setUpSiteConfigFile ( $ path , $ relativeThemePath , $ themePair -> getName ( ) ) ; }
Create a site .
50,265
protected function updateDependencies ( $ preferLock , $ preferSource , $ noScripts ) { $ pmOptions = [ 'prefer-source' => $ preferSource , 'prefer-dist' => ! $ preferSource , 'no-scripts' => $ noScripts , ] ; if ( $ preferLock === true ) { $ this -> packageManager -> install ( $ pmOptions ) ; } else { $ this -> packageManager -> update ( $ pmOptions ) ; } }
Updates the site dependencies .
50,266
protected function processPath ( $ path , $ force ) { $ existsPath = $ this -> fs -> exists ( $ path ) ; $ isEmpty = $ this -> isEmptyDir ( $ path ) ; if ( $ existsPath === true && $ force === false && $ isEmpty === false ) { throw new \ RuntimeException ( sprintf ( 'Path "%s" exists and is not empty.' , $ path ) ) ; } $ existsPath ? $ this -> clearDir ( $ path ) : $ this -> fs -> mkdir ( $ path ) ; }
Process the path of the future site .
50,267
protected function createBlankSite ( $ path , PackageNameVersion $ themePair ) { $ themeName = '' ; $ packagePairs = $ this -> getInitialPackagePairs ( ) ; if ( $ themePair -> getName ( ) !== self :: BLANK_THEME ) { $ themeName = $ themePair -> getName ( ) ; array_push ( $ packagePairs , $ themePair ) ; } $ orgDir = getcwd ( ) ; chdir ( $ path ) ; $ this -> fs -> mkdir ( [ 'build' , 'src/layouts' , 'src/content' , 'src/content/posts' , 'src/content/assets' , 'src/includes' , 'src/plugins' , ] ) ; $ this -> renderFile ( 'site/config.yml.twig' , 'config.yml' , [ 'theme_name' => $ themeName , ] ) ; $ this -> renderFile ( 'site/composer.json.twig' , 'composer.json' , [ 'requires' => $ this -> generateRequirePackages ( $ packagePairs ) , ] ) ; $ this -> fs -> dumpFile ( 'src/content/index.html' , '' ) ; chdir ( $ orgDir ) ; }
Creates a blank site .
50,268
protected function setUpSiteConfigFile ( $ sitePath , $ relativeThemePath , $ themeName ) { $ source = $ sitePath . '/' . $ relativeThemePath . '/config.yml' ; $ destination = $ sitePath . '/config.yml' ; $ this -> fs -> copy ( $ source , $ destination , true ) ; $ configContent = file_get_contents ( $ destination ) ; $ configValues = Yaml :: parse ( $ configContent ) ; $ configValues [ 'themes' ] = [ 'name' => $ themeName ] ; $ configParsed = Yaml :: dump ( $ configValues ) ; $ this -> fs -> dumpFile ( $ destination , $ configParsed ) ; }
Sets up the configuration file .
50,269
protected function isEmptyDir ( $ path ) { if ( $ this -> fs -> exists ( $ path ) === true ) { $ finder = new Finder ( ) ; $ finder -> in ( $ path ) ; $ iterator = $ finder -> getIterator ( ) ; $ iterator -> next ( ) ; return iterator_count ( $ iterator ) === 0 ; } return true ; }
Is the path empty?
50,270
protected function clearDir ( $ path ) { $ items = [ ] ; $ finder = new Finder ( ) ; $ finder -> in ( $ path ) -> ignoreVCS ( false ) -> ignoreDotFiles ( false ) ; foreach ( $ finder as $ item ) { $ items [ ] = $ item -> getRealpath ( ) ; } if ( count ( $ items ) > 0 ) { $ this -> fs -> remove ( $ items ) ; } }
Clears the directory .
50,271
protected function generateRequirePackages ( array $ packagePairs ) { $ requires = [ ] ; foreach ( $ packagePairs as $ packagePair ) { $ requires [ $ packagePair -> getName ( ) ] = $ packagePair -> getVersion ( ) ; } return $ requires ; }
Generates the list of required packages .
50,272
protected function createOptionsResolver ( ) { $ resolver = new AttributesResolver ( ) ; $ resolver -> setDefault ( 'prefer-lock' , false , 'bool' ) -> setDefault ( 'prefer-source' , false , 'bool' ) -> setDefault ( 'no-scripts' , false , 'bool' ) ; return $ resolver ; }
Returns the resolver for generating options .
50,273
public function add ( ItemInterface $ item ) { if ( $ this -> has ( $ item -> getId ( ) ) === true ) { throw new \ RuntimeException ( sprintf ( 'A previous item exists with the same id: "%s".' , $ item -> getId ( ) ) ) ; } $ this -> set ( $ item ) ; }
Adds an new item .
50,274
public function set ( ItemInterface $ item ) { $ id = $ item -> getId ( ) ; $ collectionName = $ item -> getCollection ( ) ; $ this -> items [ $ id ] = $ item ; if ( isset ( $ this -> idCollections [ $ id ] ) && $ this -> idCollections [ $ id ] !== $ collectionName ) { throw new \ RuntimeException ( sprintf ( 'The item with id: "%s" has been registered previously with another collection.' , $ id ) ) ; } if ( isset ( $ this -> itemCollections [ $ collectionName ] ) === false ) { $ this -> itemCollections [ $ collectionName ] = [ ] ; } $ this -> itemCollections [ $ collectionName ] [ $ id ] = $ item ; $ this -> idCollections [ $ id ] = $ collectionName ; }
Sets an item .
50,275
public function get ( $ id ) { if ( false === $ this -> has ( $ id ) ) { throw new \ RuntimeException ( sprintf ( 'Item with id: "%s" not found.' , $ id ) ) ; } return $ this -> items [ $ id ] ; }
Gets an item .
50,276
public function all ( array $ collections = [ ] , $ groupByCollection = false ) { if ( count ( $ collections ) === 0 ) { if ( $ groupByCollection === false ) { return $ this -> items ; } return $ this -> itemCollections ; } $ result = [ ] ; foreach ( $ collections as $ collection ) { if ( isset ( $ this -> itemCollections [ $ collection ] ) === false ) { continue ; } if ( $ groupByCollection === false ) { $ result = array_merge ( $ result , $ this -> itemCollections [ $ collection ] ) ; continue ; } $ result [ $ collection ] = $ this -> itemCollections [ $ collection ] ; } return $ result ; }
Returns all items in this collection .
50,277
public function remove ( $ id ) { if ( $ this -> has ( $ id ) === false ) { return ; } $ collection = $ this -> idCollections [ $ id ] ; unset ( $ this -> idCollections [ $ id ] ) ; unset ( $ this -> itemCollections [ $ collection ] ) ; unset ( $ this -> items [ $ id ] ) ; }
Removes an item .
50,278
public function generate ( $ path , $ themeName , $ force = false , array $ options = [ ] ) { if ( $ themeName === self :: BLANK_THEME ) { parent :: generate ( $ path , $ themeName , $ force , $ options ) ; return ; } $ options = $ this -> getGenerateOptionsResolver ( ) -> resolve ( $ options ) ; $ this -> checkThemeName ( $ themeName ) ; $ this -> processPath ( $ path , $ force ) ; $ this -> checkRequirements ( $ themeName ) ; $ this -> packageManager -> createThemeProject ( $ path , $ themeName , $ options [ 'repository' ] , $ options [ 'prefer-source' ] ) ; }
Scaffolds a new theme . In case of exception the new - site directory will be removed .
50,279
public function install ( array $ options = [ ] , array $ packageNames = [ ] ) { $ options = $ this -> getInstallResolver ( ) -> resolve ( $ options ) ; $ installer = $ this -> buildInstaller ( $ options ) ; $ installer -> setUpdateWhitelist ( $ packageNames ) ; $ status = $ installer -> run ( ) ; if ( $ status !== 0 ) { throw new \ RuntimeException ( sprintf ( 'An error has been occurred with code: %s while resolving dependencies.' , $ status ) ) ; } }
Installs plugins and themes .
50,280
public function update ( array $ options = [ ] , array $ packageNames = [ ] ) { $ options = $ this -> getInstallResolver ( ) -> resolve ( $ options ) ; $ installer = $ this -> buildInstaller ( $ options ) ; $ installer -> setUpdate ( true ) ; $ installer -> setUpdateWhitelist ( $ packageNames ) ; $ status = $ installer -> run ( ) ; if ( $ status !== 0 ) { throw new \ RuntimeException ( sprintf ( 'An error has been occurred with code: %s while resolving dependencies.' , $ status ) ) ; } }
Update plugins and themes installed previously .
50,281
public function addPackage ( array $ packageNames , $ areDevPackages = false ) { $ fs = new Filesystem ( ) ; $ file = $ this -> embeddedComposer -> getExternalComposerFilename ( ) ; if ( $ fs -> exists ( $ file ) === false ) { $ fs -> dumpFile ( $ file , "{\n}\n" ) ; } if ( filesize ( $ file ) === 0 ) { $ fs -> dumpFile ( $ file , "{\n}\n" ) ; } $ json = new JsonFile ( $ file ) ; $ requirements = $ this -> formatPackageNames ( $ packageNames ) ; $ versionParser = new VersionParser ( ) ; foreach ( $ requirements as $ constraint ) { $ versionParser -> parseConstraints ( $ constraint ) ; } $ composerDefinition = $ json -> read ( ) ; $ requireKey = $ areDevPackages ? 'require-dev' : 'require' ; foreach ( $ requirements as $ package => $ version ) { $ composerDefinition [ $ requireKey ] [ $ package ] = $ version ; } $ json -> write ( $ composerDefinition ) ; return $ composerDefinition [ $ requireKey ] ; }
Adds a new set of packages to the current Composer file .
50,282
public function removePackage ( array $ packageNames , $ areDevPackages = false ) { $ packages = $ this -> formatPackageNames ( $ packageNames ) ; $ file = $ this -> embeddedComposer -> getExternalComposerFilename ( ) ; $ jsonFile = new JsonFile ( $ file ) ; $ json = new JsonConfigSource ( $ jsonFile ) ; $ composerDefinition = $ jsonFile -> read ( ) ; $ type = $ areDevPackages ? 'require-dev' : 'require' ; foreach ( $ packages as $ name => $ version ) { if ( isset ( $ composerDefinition [ $ type ] [ $ name ] ) ) { $ json -> removeLink ( $ type , $ name ) ; unset ( $ composerDefinition [ $ type ] [ $ name ] ) ; continue ; } $ this -> io -> writeError ( sprintf ( 'Package: "%s" is not required and has not been removed.' , $ name ) ) ; } return $ composerDefinition [ $ type ] ; }
Remove a set of packages of the current Composer file .
50,283
public function rewritingSelfVersionDependencies ( ) { $ composer = $ this -> embeddedComposer -> createComposer ( $ this -> io ) ; $ package = $ composer -> getPackage ( ) ; $ configSource = new JsonConfigSource ( new JsonFile ( 'composer.json' ) ) ; foreach ( BasePackage :: $ supportedLinkTypes as $ type => $ meta ) { foreach ( $ package -> { 'get' . $ meta [ 'method' ] } ( ) as $ link ) { if ( $ link -> getPrettyConstraint ( ) === 'self.version' ) { $ configSource -> addLink ( $ type , $ link -> getTarget ( ) , $ package -> getPrettyVersion ( ) ) ; } } } }
Rewriting self . version dependencies with explicit version numbers of the current composer . json file . Useful if the package s vcs metadata is gone .
50,284
public function isThemePackage ( $ packageName ) { $ composerPackage = $ this -> findPackageGlobal ( $ packageName ) ; if ( is_null ( $ composerPackage ) === true ) { throw new \ RuntimeException ( sprintf ( 'The theme: "%s" does not exist.' , $ packageName ) ) ; } return $ composerPackage -> getType ( ) == self :: PACKAGE_TYPE_THEME ; }
Determines if package is a Spress theme .
50,285
public function isPackageDependOn ( $ packageNameA , $ packageNameB ) { $ composerPackageA = $ this -> findPackageGlobal ( $ packageNameA ) ; if ( is_null ( $ composerPackageA ) === true ) { throw new \ RuntimeException ( sprintf ( 'The package: "%s" does not exist.' , $ packageNameA ) ) ; } $ requires = $ composerPackageA -> getRequires ( ) ; $ pairPackageB = new PackageNameVersion ( $ packageNameB ) ; foreach ( $ requires as $ link ) { if ( $ link -> getTarget ( ) == $ pairPackageB -> getName ( ) ) { if ( $ link -> getConstraint ( ) -> matches ( $ pairPackageB -> getComposerVersionConstraint ( ) ) ) { return true ; } return false ; } } return false ; }
Determines if a package A depends on package B . Only scan with first deep level .
50,286
protected function findPackageGlobal ( $ packageName ) { $ packagePair = new PackageNameVersion ( $ packageName ) ; if ( isset ( $ this -> packageCache [ $ packagePair -> getNormalizedNameVersion ( ) ] ) ) { return $ this -> packageCache [ $ packagePair -> getNormalizedNameVersion ( ) ] ; } $ composer = $ this -> embeddedComposer -> createComposer ( $ this -> io ) ; $ repoManager = $ composer -> getRepositoryManager ( ) ; $ name = $ packagePair -> getName ( ) ; $ version = $ packagePair -> getVersion ( ) ; $ composerPackage = $ this -> packageCache [ $ packageName ] = $ repoManager -> findPackage ( $ name , $ version ) ; return $ composerPackage ; }
Recovers the data of a package registered in repositories such as packagist . org .
50,287
protected function formatPackageNames ( array $ packageNames ) { $ requires = [ ] ; foreach ( $ packageNames as $ packageName ) { $ packagePair = new PackageNameVersion ( $ packageName ) ; $ requires [ $ packagePair -> getName ( ) ] = $ packagePair -> getVersion ( ) ; } return $ requires ; }
Formats the packages names .
50,288
public function convert ( $ input ) { if ( is_string ( $ input ) === false ) { throw new \ InvalidArgumentException ( 'Expected a string value at Parsedown converter.' ) ; } $ converter = new \ ParsedownExtra ( ) ; return $ converter -> text ( $ input ) ; }
Convert the input data .
50,289
public function getFilename ( ) { if ( is_null ( $ this -> filename ) === true ) { $ str = new StringWrapper ( parent :: getFilename ( ) ) ; $ this -> filename = $ str -> deleteSufix ( '.' . $ this -> getExtension ( ) ) ; } return $ this -> filename ; }
Gets the filename without extension .
50,290
public function getExtension ( ) { if ( is_null ( $ this -> extension ) === true ) { $ filename = parent :: getFilename ( ) ; $ str = new StringWrapper ( $ filename ) ; $ this -> extension = $ str -> getFirstEndMatch ( $ this -> predefinedExtensions ) ; $ this -> hasPredefinedExt = true ; if ( $ this -> extension === '' ) { $ this -> hasPredefinedExt = false ; $ this -> extension = parent :: getExtension ( ) ; } } return $ this -> extension ; }
Gets the extension of the file .
50,291
protected function buildSpress ( IOInterface $ io , InputInterface $ input ) { $ timezone = $ input -> getOption ( 'timezone' ) ; $ drafts = $ input -> getOption ( 'drafts' ) ; $ safe = $ input -> getOption ( 'safe' ) ; $ env = $ input -> getOption ( 'env' ) ; $ sourceDir = $ input -> getOption ( 'source' ) ; if ( is_null ( $ sourceDir ) === true ) { $ sourceDir = './' ; } if ( ( $ realDir = realpath ( $ sourceDir ) ) === false ) { throw new \ RuntimeException ( sprintf ( 'Invalid source path: "%s".' , $ sourceDir ) ) ; } $ spress = $ this -> getSpress ( $ realDir ) ; $ spress [ 'spress.config.env' ] = $ env ; $ spress [ 'spress.config.safe' ] = $ safe ; $ spress [ 'spress.config.drafts' ] = $ drafts ; $ spress [ 'spress.config.timezone' ] = $ timezone ; $ resolver = $ this -> getConfigResolver ( ) ; $ resolver -> resolve ( $ spress [ 'spress.config.values' ] ) ; if ( $ spress [ 'spress.config.values' ] [ 'parsedown_activated' ] === true ) { $ this -> enableParsedown ( $ spress ) ; $ io -> labelValue ( 'Parsedown converter' , 'enabled' ) ; } $ spress [ 'spress.io' ] = $ io ; return $ spress ; }
Builds a Spress instance .
50,292
protected function reParse ( IOInterface $ io , InputInterface $ input , ResourceWatcher $ rw ) { $ rw -> findChanges ( ) ; if ( $ rw -> hasChanges ( ) === false ) { return ; } $ this -> rebuildingSiteMessage ( $ io , $ rw -> getNewResources ( ) , $ rw -> getUpdatedResources ( ) , $ rw -> getDeletedResources ( ) ) ; $ spress = $ this -> buildSpress ( $ io , $ input ) ; $ resultData = $ spress -> parse ( ) ; $ this -> resultMessage ( $ io , $ resultData ) ; }
Reparses a site .
50,293
protected function buildResourceWatcher ( $ sourceDir , $ destinationDir ) { $ fs = new Filesystem ( ) ; $ relativeDestination = rtrim ( $ fs -> makePathRelative ( $ destinationDir , $ sourceDir ) , '/' ) ; $ finder = new Finder ( ) ; $ finder -> files ( ) -> name ( '*.*' ) -> in ( $ sourceDir ) ; if ( false === strpos ( $ relativeDestination , '..' ) ) { $ finder -> exclude ( $ relativeDestination ) ; } $ rc = new ResourceCacheMemory ( ) ; $ rw = new ResourceWatcher ( $ rc ) ; $ rw -> setFinder ( $ finder ) ; return $ rw ; }
Builds a ResourceWatcher instance .
50,294
protected function getConfigResolver ( ) { if ( is_null ( $ this -> configResolver ) === false ) { return $ this -> configResolver ; } $ resolver = new AttributesResolver ( ) ; $ resolver -> setDefault ( 'host' , '0.0.0.0' , 'string' , true ) -> setDefault ( 'port' , 4000 , 'integer' , true ) -> setValidator ( 'port' , function ( $ value ) { return $ value >= 0 ; } ) -> setDefault ( 'server_watch_ext' , [ 'html' ] , 'array' , true ) -> setDefault ( 'parsedown_activated' , false , 'bool' , true ) ; $ this -> configResolver = $ resolver ; return $ this -> configResolver ; }
Returns the attributes or options resolver for configuration values .
50,295
protected function enableParsedown ( Spress $ spress ) { $ spress -> extend ( 'spress.cms.converterManager.converters' , function ( $ predefinedConverters , $ c ) { unset ( $ predefinedConverters [ 'MichelfMarkdownConverter' ] ) ; $ markdownExts = $ c [ 'spress.config.values' ] [ 'markdown_ext' ] ; $ predefinedConverters [ 'ParsedownConverter' ] = new ParsedownConverter ( $ markdownExts ) ; return $ predefinedConverters ; } ) ; }
Enables Parsedown converter .
50,296
protected function resultMessage ( ConsoleIO $ io , array $ items ) { $ io -> newLine ( ) ; $ io -> labelValue ( 'Total items' , count ( $ items ) ) ; $ io -> newLine ( ) ; $ io -> success ( 'Success!' ) ; }
Writes the result of a parsing a site .
50,297
protected function rebuildingSiteMessage ( ConsoleIO $ io , array $ newResources , array $ updatedResources , array $ deletedResources ) { $ io -> write ( sprintf ( '<comment>Rebuilding site... (%s new, %s updated and %s deleted resources)</comment>' , count ( $ newResources ) , count ( $ updatedResources ) , count ( $ deletedResources ) ) ) ; $ io -> newLine ( ) ; }
Write the result of rebuilding a site .
50,298
public function buildCommands ( ) { $ result = [ ] ; $ pluginsCollection = $ this -> pluginManager -> getPluginCollection ( ) ; foreach ( $ pluginsCollection as $ plugin ) { if ( $ this -> isValidCommandPlugin ( $ plugin ) === true ) { $ result [ ] = $ this -> buildCommand ( $ plugin ) ; } } return $ result ; }
Gets a list of Symfony Console command .
50,299
protected function buildCommand ( CommandPluginInterface $ commandPlugin ) { $ definition = $ commandPlugin -> getCommandDefinition ( ) ; $ argumentsAndOptions = [ ] ; $ consoleComand = new Command ( $ definition -> getName ( ) ) ; $ consoleComand -> setDescription ( $ definition -> getDescription ( ) ) ; $ consoleComand -> setHelp ( $ definition -> getHelp ( ) ) ; foreach ( $ definition -> getArguments ( ) as list ( $ name , $ mode , $ description , $ defaultValue ) ) { $ argumentsAndOptions [ ] = new InputArgument ( $ name , $ mode , $ description , $ defaultValue ) ; } foreach ( $ definition -> getOptions ( ) as list ( $ name , $ shortcut , $ mode , $ description , $ defaultValue ) ) { $ argumentsAndOptions [ ] = new InputOption ( $ name , $ shortcut , $ mode , $ description , $ defaultValue ) ; } $ consoleComand -> setDefinition ( $ argumentsAndOptions ) ; $ consoleComand -> setCode ( function ( InputInterface $ input , OutputInterface $ output ) use ( $ commandPlugin , $ consoleComand ) { $ io = new ConsoleIO ( $ input , $ output ) ; $ arguments = $ input -> getArguments ( ) ; $ options = $ input -> getOptions ( ) ; $ commandPlugin -> setCommandEnvironment ( new SymfonyCommandEnvironment ( $ consoleComand , $ output ) ) ; $ commandPlugin -> executeCommand ( $ io , $ arguments , $ options ) ; } ) ; return $ consoleComand ; }
Build a Symfony Console commands .