idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
7,800
public static function secureCompare ( $ a , $ b ) { if ( self :: $ isHashEqualsAvailable === null ) { self :: $ isHashEqualsAvailable = function_exists ( 'hash_equals' ) ; } if ( self :: $ isHashEqualsAvailable ) { return hash_equals ( $ a , $ b ) ; } else { if ( strlen ( $ a ) != strlen ( $ b ) ) { return false ; } $ result = 0 ; for ( $ i = 0 ; $ i < strlen ( $ a ) ; $ i ++ ) { $ result |= ord ( $ a [ $ i ] ) ^ ord ( $ b [ $ i ] ) ; } return ( $ result == 0 ) ; } }
Compares two strings for equality . The time taken is independent of the number of characters that match .
7,801
public static function objectsToIds ( $ h ) { if ( $ h instanceof \ Stripe \ ApiResource ) { return $ h -> id ; } elseif ( static :: isList ( $ h ) ) { $ results = [ ] ; foreach ( $ h as $ v ) { array_push ( $ results , static :: objectsToIds ( $ v ) ) ; } return $ results ; } elseif ( is_array ( $ h ) ) { $ results = [ ] ; foreach ( $ h as $ k => $ v ) { if ( is_null ( $ v ) ) { continue ; } $ results [ $ k ] = static :: objectsToIds ( $ v ) ; } return $ results ; } else { return $ h ; } }
Recursively goes through an array of parameters . If a parameter is an instance of ApiResource then it is replaced by the resource s ID . Also clears out null values .
7,802
public static function authorizeUrl ( $ params = null , $ opts = null ) { $ params = $ params ? : [ ] ; $ base = ( $ opts && array_key_exists ( 'connect_base' , $ opts ) ) ? $ opts [ 'connect_base' ] : Stripe :: $ connectBase ; $ params [ 'client_id' ] = self :: _getClientId ( $ params ) ; if ( ! array_key_exists ( 'response_type' , $ params ) ) { $ params [ 'response_type' ] = 'code' ; } $ query = Util \ Util :: encodeParameters ( $ params ) ; return $ base . '/oauth/authorize?' . $ query ; }
Generates a URL to Stripe s OAuth form .
7,803
public function discardNonPersistentHeaders ( ) { foreach ( $ this -> headers as $ k => $ v ) { if ( ! in_array ( $ k , self :: $ HEADERS_TO_PERSIST ) ) { unset ( $ this -> headers [ $ k ] ) ; } } }
Discards all headers that we don t want to persist across requests .
7,804
public function uuid ( ) { $ arr = array_values ( unpack ( 'N1a/n4b/N1c' , openssl_random_pseudo_bytes ( 16 ) ) ) ; $ arr [ 2 ] = ( $ arr [ 2 ] & 0x0fff ) | 0x4000 ; $ arr [ 3 ] = ( $ arr [ 3 ] & 0x3fff ) | 0x8000 ; return vsprintf ( '%08x-%04x-%04x-%04x-%04x%08x' , $ arr ) ; }
Returns a v4 UUID .
7,805
public function scopeSearch ( Builder $ q , $ search , $ threshold = null , $ entireText = false , $ entireTextOnly = false ) { return $ this -> scopeSearchRestricted ( $ q , $ search , null , $ threshold , $ entireText , $ entireTextOnly ) ; }
Creates the search scope .
7,806
protected function getColumns ( ) { if ( array_key_exists ( 'columns' , $ this -> searchable ) ) { $ driver = $ this -> getDatabaseDriver ( ) ; $ prefix = Config :: get ( "database.connections.$driver.prefix" ) ; $ columns = [ ] ; foreach ( $ this -> searchable [ 'columns' ] as $ column => $ priority ) { $ columns [ $ prefix . $ column ] = $ priority ; } return $ columns ; } else { return DB :: connection ( ) -> getSchemaBuilder ( ) -> getColumnListing ( $ this -> table ) ; } }
Returns the search columns .
7,807
protected function makeJoins ( Builder $ query ) { foreach ( $ this -> getJoins ( ) as $ table => $ keys ) { $ query -> leftJoin ( $ table , function ( $ join ) use ( $ keys ) { $ join -> on ( $ keys [ 0 ] , '=' , $ keys [ 1 ] ) ; if ( array_key_exists ( 2 , $ keys ) && array_key_exists ( 3 , $ keys ) ) { $ join -> whereRaw ( $ keys [ 2 ] . ' = "' . $ keys [ 3 ] . '"' ) ; } } ) ; } }
Adds the sql joins to the query .
7,808
protected function makeGroupBy ( Builder $ query ) { if ( $ groupBy = $ this -> getGroupBy ( ) ) { $ query -> groupBy ( $ groupBy ) ; } else { $ driver = $ this -> getDatabaseDriver ( ) ; if ( $ driver == 'sqlsrv' ) { $ columns = $ this -> getTableColumns ( ) ; } else { $ columns = $ this -> getTable ( ) . '.' . $ this -> primaryKey ; } $ query -> groupBy ( $ columns ) ; $ joins = array_keys ( ( $ this -> getJoins ( ) ) ) ; foreach ( $ this -> getColumns ( ) as $ column => $ relevance ) { array_map ( function ( $ join ) use ( $ column , $ query ) { if ( Str :: contains ( $ column , $ join ) ) { $ query -> groupBy ( $ column ) ; } } , $ joins ) ; } } }
Makes the query not repeat the results .
7,809
protected function getSearchQueriesForColumn ( Builder $ query , $ column , $ relevance , array $ words ) { $ queries = [ ] ; $ queries [ ] = $ this -> getSearchQuery ( $ query , $ column , $ relevance , $ words , 15 ) ; $ queries [ ] = $ this -> getSearchQuery ( $ query , $ column , $ relevance , $ words , 5 , '' , '%' ) ; $ queries [ ] = $ this -> getSearchQuery ( $ query , $ column , $ relevance , $ words , 1 , '%' , '%' ) ; return $ queries ; }
Returns the search queries for the specified column .
7,810
protected function getSearchQuery ( Builder $ query , $ column , $ relevance , array $ words , $ relevance_multiplier , $ pre_word = '' , $ post_word = '' ) { $ like_comparator = $ this -> getDatabaseDriver ( ) == 'pgsql' ? 'ILIKE' : 'LIKE' ; $ cases = [ ] ; foreach ( $ words as $ word ) { $ cases [ ] = $ this -> getCaseCompare ( $ column , $ like_comparator , $ relevance * $ relevance_multiplier ) ; $ this -> search_bindings [ ] = $ pre_word . $ word . $ post_word ; } return implode ( ' + ' , $ cases ) ; }
Returns the sql string for the given parameters .
7,811
protected function getCaseCompare ( $ column , $ compare , $ relevance ) { if ( $ this -> getDatabaseDriver ( ) == 'pgsql' ) { $ field = "LOWER(" . $ column . ") " . $ compare . " ?" ; return '(case when ' . $ field . ' then ' . $ relevance . ' else 0 end)' ; } $ column = str_replace ( '.' , '`.`' , $ column ) ; $ field = "LOWER(`" . $ column . "`) " . $ compare . " ?" ; return '(case when ' . $ field . ' then ' . $ relevance . ' else 0 end)' ; }
Returns the comparison string .
7,812
protected function mergeQueries ( Builder $ clone , Builder $ original ) { $ tableName = DB :: connection ( $ this -> connection ) -> getTablePrefix ( ) . $ this -> getTable ( ) ; if ( $ this -> getDatabaseDriver ( ) == 'pgsql' ) { $ original -> from ( DB :: connection ( $ this -> connection ) -> raw ( "({$clone->toSql()}) as {$tableName}" ) ) ; } else { $ original -> from ( DB :: connection ( $ this -> connection ) -> raw ( "({$clone->toSql()}) as `{$tableName}`" ) ) ; } $ mergedBindings = array_merge_recursive ( $ clone -> getBindings ( ) , $ original -> getBindings ( ) ) ; $ original -> withoutGlobalScopes ( ) -> setBindings ( $ mergedBindings ) ; }
Merge our cloned query builder with the original one .
7,813
public function setWebhook ( $ url , $ certificate = '' ) { if ( $ certificate == '' ) { $ requestBody = [ 'url' => $ url ] ; } else { $ requestBody = [ 'url' => $ url , 'certificate' => "@$certificate" ] ; } return $ this -> endpoint ( 'setWebhook' , $ requestBody , true ) ; }
Use this method to specify a url and receive incoming updates via an outgoing webhook . Whenever there is an update for the bot we will send an HTTPS POST request to the specified url containing a JSON - serialized Update . In case of an unsuccessful request we will give up after a reasonable amount of attempts .
7,814
public function ChatID ( ) { $ type = $ this -> getUpdateType ( ) ; if ( $ type == self :: CALLBACK_QUERY ) { return @ $ this -> data [ 'callback_query' ] [ 'message' ] [ 'chat' ] [ 'id' ] ; } if ( $ type == self :: CHANNEL_POST ) { return @ $ this -> data [ 'channel_post' ] [ 'chat' ] [ 'id' ] ; } if ( $ type == self :: EDITED_MESSAGE ) { return @ $ this -> data [ 'edited_message' ] [ 'chat' ] [ 'id' ] ; } if ( $ type == self :: INLINE_QUERY ) { return @ $ this -> data [ 'inline_query' ] [ 'from' ] [ 'id' ] ; } return $ this -> data [ 'message' ] [ 'chat' ] [ 'id' ] ; }
\ return the String users s chat_id .
7,815
public function getUpdateType ( ) { $ update = $ this -> data ; if ( isset ( $ update [ 'inline_query' ] ) ) { return self :: INLINE_QUERY ; } if ( isset ( $ update [ 'callback_query' ] ) ) { return self :: CALLBACK_QUERY ; } if ( isset ( $ update [ 'edited_message' ] ) ) { return self :: EDITED_MESSAGE ; } if ( isset ( $ update [ 'message' ] [ 'text' ] ) ) { return self :: MESSAGE ; } if ( isset ( $ update [ 'message' ] [ 'photo' ] ) ) { return self :: PHOTO ; } if ( isset ( $ update [ 'message' ] [ 'video' ] ) ) { return self :: VIDEO ; } if ( isset ( $ update [ 'message' ] [ 'audio' ] ) ) { return self :: AUDIO ; } if ( isset ( $ update [ 'message' ] [ 'voice' ] ) ) { return self :: VOICE ; } if ( isset ( $ update [ 'message' ] [ 'contact' ] ) ) { return self :: CONTACT ; } if ( isset ( $ update [ 'message' ] [ 'location' ] ) ) { return self :: LOCATION ; } if ( isset ( $ update [ 'message' ] [ 'reply_to_message' ] ) ) { return self :: REPLY ; } if ( isset ( $ update [ 'message' ] [ 'animation' ] ) ) { return self :: ANIMATION ; } if ( isset ( $ update [ 'message' ] [ 'document' ] ) ) { return self :: DOCUMENT ; } if ( isset ( $ update [ 'channel_post' ] ) ) { return self :: CHANNEL_POST ; } return false ; }
Return current update type False on failure .
7,816
private static function getPool ( $ type = 'alnum' ) { switch ( $ type ) { case 'alnum' : $ pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ; break ; case 'alpha' : $ pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ; break ; case 'hexdec' : $ pool = '0123456789abcdef' ; break ; case 'numeric' : $ pool = '0123456789' ; break ; case 'nozero' : $ pool = '123456789' ; break ; case 'distinct' : $ pool = '2345679ACDEFHJKLMNPRSTUVWXYZ' ; break ; default : $ pool = ( string ) $ type ; break ; } return $ pool ; }
Get the pool to use based on the type of prefix hash
7,817
public static function getHashedToken ( $ length = 25 ) { $ token = "" ; $ max = strlen ( static :: getPool ( ) ) ; for ( $ i = 0 ; $ i < $ length ; $ i ++ ) { $ token .= static :: getPool ( ) [ static :: secureCrypt ( 0 , $ max ) ] ; } return $ token ; }
Finally generate a hashed token
7,818
private function setRequestOptions ( ) { $ authBearer = 'Bearer ' . $ this -> secretKey ; $ this -> client = new Client ( [ 'base_uri' => $ this -> baseUrl , 'headers' => [ 'Authorization' => $ authBearer , 'Content-Type' => 'application/json' , 'Accept' => 'application/json' ] ] ) ; }
Set options for making the Client request
7,819
public function getAuthorizationResponse ( $ data ) { $ this -> makePaymentRequest ( $ data ) ; $ this -> url = $ this -> getResponse ( ) [ 'data' ] [ 'authorization_url' ] ; return $ this -> getResponse ( ) ; }
Get the authorization callback response In situations where Laravel serves as an backend for a detached UI the api cannot redirect and might need to take different actions based on the success or not of the transaction
7,820
private function verifyTransactionAtGateway ( ) { $ transactionRef = request ( ) -> query ( 'trxref' ) ; $ relativeUrl = "/transaction/verify/{$transactionRef}" ; $ this -> response = $ this -> client -> get ( $ this -> baseUrl . $ relativeUrl , [ ] ) ; }
Hit Paystack Gateway to Verify that the transaction is valid
7,821
public function isTransactionVerificationValid ( ) { $ this -> verifyTransactionAtGateway ( ) ; $ result = $ this -> getResponse ( ) [ 'message' ] ; switch ( $ result ) { case self :: VS : $ validate = true ; break ; case self :: ITF : $ validate = false ; break ; default : $ validate = false ; break ; } return $ validate ; }
True or false condition whether the transaction is verified
7,822
public function createPlan ( ) { $ data = [ "name" => request ( ) -> name , "description" => request ( ) -> desc , "amount" => intval ( request ( ) -> amount ) , "interval" => request ( ) -> interval , "send_invoices" => request ( ) -> send_invoices , "send_sms" => request ( ) -> send_sms , "currency" => request ( ) -> currency , ] ; $ this -> setRequestOptions ( ) ; $ this -> setHttpResponse ( "/plan" , 'POST' , $ data ) ; }
Create a plan
7,823
public function updatePlan ( $ plan_code ) { $ data = [ "name" => request ( ) -> name , "description" => request ( ) -> desc , "amount" => intval ( request ( ) -> amount ) , "interval" => request ( ) -> interval , "send_invoices" => request ( ) -> send_invoices , "send_sms" => request ( ) -> send_sms , "currency" => request ( ) -> currency , ] ; $ this -> setRequestOptions ( ) ; return $ this -> setHttpResponse ( '/plan/' . $ plan_code , 'PUT' , $ data ) -> getResponse ( ) ; }
Update any plan s details based on its id or code
7,824
public function updateCustomer ( $ customer_id ) { $ data = [ "email" => request ( ) -> email , "first_name" => request ( ) -> fname , "last_name" => request ( ) -> lname , "phone" => request ( ) -> phone , "metadata" => request ( ) -> additional_info ] ; $ this -> setRequestOptions ( ) ; return $ this -> setHttpResponse ( '/customer/' . $ customer_id , 'PUT' , $ data ) -> getResponse ( ) ; }
Update a customer s details based on their id or code
7,825
public function exportTransactions ( ) { $ data = [ "from" => request ( ) -> from , "to" => request ( ) -> to , 'settled' => request ( ) -> settled ] ; $ this -> setRequestOptions ( ) ; return $ this -> setHttpResponse ( '/transaction/export' , 'GET' , $ data ) -> getResponse ( ) ; }
Export transactions in . CSV
7,826
public function createSubscription ( ) { $ data = [ "customer" => request ( ) -> customer , "plan" => request ( ) -> plan , "authorization" => request ( ) -> authorization_code ] ; $ this -> setRequestOptions ( ) ; $ this -> setHttpResponse ( '/subscription' , 'POST' , $ data ) ; }
Create a subscription to a plan from a customer .
7,827
public function enableSubscription ( ) { $ data = [ "code" => request ( ) -> code , "token" => request ( ) -> token , ] ; $ this -> setRequestOptions ( ) ; return $ this -> setHttpResponse ( '/subscription/enable' , 'POST' , $ data ) -> getResponse ( ) ; }
Enable a subscription using the subscription code and token
7,828
public function createPage ( ) { $ data = [ "name" => request ( ) -> name , "description" => request ( ) -> description , "amount" => request ( ) -> amount ] ; $ this -> setRequestOptions ( ) ; $ this -> setHttpResponse ( '/page' , 'POST' , $ data ) ; }
Create pages you can share with users using the returned slug
7,829
public function updatePage ( $ page_id ) { $ data = [ "name" => request ( ) -> name , "description" => request ( ) -> description , "amount" => request ( ) -> amount ] ; $ this -> setRequestOptions ( ) ; return $ this -> setHttpResponse ( '/page/' . $ page_id , 'PUT' , $ data ) -> getResponse ( ) ; }
Update the details about a particular page
7,830
public function listSubAccounts ( $ per_page , $ page ) { $ this -> setRequestOptions ( ) ; return $ this -> setHttpResponse ( "/subaccount/?perPage=" . ( int ) $ per_page . "&page=" . ( int ) $ page , "GET" ) -> getResponse ( ) ; }
Lists all the subaccounts associated with the account
7,831
public function updateSubAccount ( $ subaccount_code ) { $ data = [ "business_name" => request ( ) -> business_name , "settlement_bank" => request ( ) -> settlement_bank , "account_number" => request ( ) -> account_number , "percentage_charge" => request ( ) -> percentage_charge , "description" => request ( ) -> description , "primary_contact_email" => request ( ) -> primary_contact_email , "primary_contact_name" => request ( ) -> primary_contact_name , "primary_contact_phone" => request ( ) -> primary_contact_phone , "metadata" => request ( ) -> metadata , 'settlement_schedule' => request ( ) -> settlement_schedule ] ; $ this -> setRequestOptions ( ) ; return $ this -> setHttpResponse ( "/subaccount/{$subaccount_code}" , "PUT" , array_filter ( $ data ) ) -> getResponse ( ) ; }
Updates a subaccount to be used for split payments . Required params are business_name settlement_bank account_number percentage_charge
7,832
public function getAsciiContent ( string $ resource ) : string { $ file = $ this -> config -> getAsciiContentPath ( $ resource ) ; if ( null === $ file ) { return '' ; } if ( $ this -> fileSystem -> exists ( $ file ) ) { return $ this -> fileSystem -> readFromFileInfo ( new SplFileInfo ( $ file ) ) ; } $ embeddedFile = $ this -> getAsciiPath ( ) . $ file ; if ( $ this -> fileSystem -> exists ( $ embeddedFile ) ) { return $ this -> fileSystem -> readFromFileInfo ( new SplFileInfo ( $ embeddedFile ) ) ; } return sprintf ( 'ASCII file %s could not be found.' , $ file ) ; }
Load an ascii image .
7,833
public function getGitDir ( ) : string { $ gitDir = $ this -> config -> getGitDir ( ) ; if ( ! $ this -> fileSystem -> exists ( $ gitDir ) ) { throw new RuntimeException ( 'The configured GIT directory could not be found.' ) ; } return $ this -> getRelativePath ( $ gitDir ) ; }
Find the relative git directory .
7,834
public function getGitHookExecutionPath ( ) : string { $ gitPath = $ this -> getGitDir ( ) ; return $ this -> fileSystem -> makePathRelative ( $ this -> getWorkingDir ( ) , $ this -> getAbsolutePath ( $ gitPath ) ) ; }
Gets the path from where the command needs to be executed in the GIT hook .
7,835
public function getGitHooksDir ( ) : string { $ gitPath = $ this -> getGitDir ( ) ; $ absoluteGitPath = $ this -> getAbsolutePath ( $ gitPath ) ; $ gitRepoPath = $ absoluteGitPath . '/.git' ; if ( is_file ( $ gitRepoPath ) ) { $ fileContent = $ this -> fileSystem -> readFromFileInfo ( new SplFileInfo ( $ gitRepoPath ) ) ; if ( preg_match ( '/gitdir:\s+(\S+)/' , $ fileContent , $ matches ) ) { $ relativePath = $ this -> getRelativePath ( $ matches [ 1 ] ) ; return $ this -> getRelativePath ( $ gitPath . $ relativePath . '/hooks/' ) ; } } return $ gitPath . '.git/hooks/' ; }
Returns the directory where the git hooks are installed .
7,836
public function getBinDir ( ) : string { $ binDir = $ this -> config -> getBinDir ( ) ; if ( ! $ this -> fileSystem -> exists ( $ binDir ) ) { throw new RuntimeException ( 'The configured BIN directory could not be found.' ) ; } return $ this -> getRelativePath ( $ binDir ) ; }
Find the relative bin directory .
7,837
public function getRelativeProjectPath ( string $ path ) : string { $ realPath = $ this -> getAbsolutePath ( $ path ) ; $ gitPath = $ this -> getAbsolutePath ( $ this -> getGitDir ( ) ) ; if ( 0 !== strpos ( $ realPath , $ gitPath ) ) { return $ realPath ; } return rtrim ( $ this -> getRelativePath ( $ realPath ) , '\\/' ) ; }
This method will return a relative path to a file of directory if it lives in the current project . When the file is not located in the current project the absolute path to the file is returned .
7,838
public static function containsOneOf ( $ haystack , array $ needles ) { foreach ( $ needles as $ needle ) { if ( $ needle !== '' && mb_strpos ( $ haystack , $ needle ) !== false ) { return true ; } } return false ; }
String contains one of the provided needles
7,839
public function addArgumentArrayWithSeparatedValue ( string $ argument , array $ values ) { foreach ( $ values as $ value ) { $ this -> add ( sprintf ( $ argument , $ value ) ) ; $ this -> add ( $ value ) ; } }
Some CLI tools prefer to split the argument and the value .
7,840
public function process ( ContainerBuilder $ container ) { $ traverserConfigurator = $ container -> findDefinition ( 'grumphp.parser.php.configurator.traverser' ) ; foreach ( $ container -> findTaggedServiceIds ( self :: TAG ) as $ id => $ tags ) { $ definition = $ container -> findDefinition ( $ id ) ; $ this -> markServiceAsPrototype ( $ definition ) ; foreach ( $ tags as $ tag ) { $ alias = array_key_exists ( 'alias' , $ tag ) ? $ tag [ 'alias' ] : $ id ; $ traverserConfigurator -> addMethodCall ( 'registerVisitorId' , [ $ alias , $ id ] ) ; } } }
Sets the visitors as non shared services . This will make sure that the state of the visitor won t need to be reset after an iteration of the traverser .
7,841
public function markServiceAsPrototype ( Definition $ definition ) { if ( method_exists ( $ definition , 'setShared' ) ) { $ definition -> setShared ( false ) ; return ; } if ( method_exists ( $ definition , 'setScope' ) ) { $ definition -> setScope ( 'prototype' ) ; return ; } throw new RuntimeException ( 'The visitor could not be marked as unshared' ) ; }
This method can be used to make the service shared cross - version . From Symfony 2 . 8 the setShared method was available . The 2 . 7 version is the LTS so we still need to support it .
7,842
public function postPackageInstall ( PackageEvent $ event ) { $ operation = $ event -> getOperation ( ) ; $ package = $ operation -> getPackage ( ) ; if ( ! $ this -> guardIsGrumPhpPackage ( $ package ) ) { return ; } $ this -> configureScheduled = true ; $ this -> initScheduled = true ; }
When this package is updated the git hook is also initialized .
7,843
public function postPackageUpdate ( PackageEvent $ event ) { $ operation = $ event -> getOperation ( ) ; $ package = $ operation -> getTargetPackage ( ) ; if ( ! $ this -> guardIsGrumPhpPackage ( $ package ) ) { return ; } $ this -> initScheduled = true ; }
When this package is updated the git hook is also updated .
7,844
public function prePackageUninstall ( PackageEvent $ event ) { $ operation = $ event -> getOperation ( ) ; $ package = $ operation -> getPackage ( ) ; if ( ! $ this -> guardIsGrumPhpPackage ( $ package ) ) { return ; } $ this -> deInitGitHook ( ) ; }
When this package is uninstalled the generated git hooks need to be removed .
7,845
protected function useExoticConfigFile ( ) { try { $ configPath = $ this -> paths ( ) -> getAbsolutePath ( $ this -> input -> getOption ( 'config' ) ) ; if ( $ configPath !== $ this -> paths ( ) -> getDefaultConfigPath ( ) ) { return $ this -> paths ( ) -> getRelativeProjectPath ( $ configPath ) ; } } catch ( FileNotFoundException $ e ) { } return null ; }
This method will tell you which exotic configuration file should be used .
7,846
public static function integrate ( Event $ event ) { $ filesystem = new Filesystem ( ) ; $ composerBinDir = $ event -> getComposer ( ) -> getConfig ( ) -> get ( 'bin-dir' ) ; $ executable = getcwd ( ) . '/bin/grumphp' ; $ composerExecutable = $ composerBinDir . '/grumphp' ; $ filesystem -> copy ( self :: noramlizePath ( $ executable ) , self :: noramlizePath ( $ composerExecutable ) ) ; $ commandlineArgs = ProcessArgumentsCollection :: forExecutable ( $ composerExecutable ) ; $ commandlineArgs -> add ( 'git:init' ) ; $ process = ProcessFactory :: fromArguments ( $ commandlineArgs ) ; $ process -> run ( ) ; if ( ! $ process -> isSuccessful ( ) ) { $ event -> getIO ( ) -> write ( '<fg=red>GrumPHP can not sniff your commits. Did you specify the correct git-dir?</fg=red>' ) ; $ event -> getIO ( ) -> write ( '<fg=red>' . $ process -> getErrorOutput ( ) . '</fg=red>' ) ; return ; } $ event -> getIO ( ) -> write ( '<fg=yellow>' . $ process -> getOutput ( ) . '</fg=yellow>' ) ; }
This method makes sure that GrumPHP registers itself during development .
7,847
public function getAsciiContentPath ( string $ resource ) { if ( null === $ this -> container -> getParameter ( 'ascii' ) ) { return null ; } $ paths = $ this -> container -> getParameter ( 'ascii' ) ; if ( ! array_key_exists ( $ resource , $ paths ) ) { return null ; } if ( \ is_array ( $ paths [ $ resource ] ) ) { shuffle ( $ paths [ $ resource ] ) ; return reset ( $ paths [ $ resource ] ) ; } return $ paths [ $ resource ] ; }
Get ascii content path from grumphp . yml file .
7,848
private function updateUserConfigPath ( string $ configPath ) : string { if ( $ configPath !== $ this -> getDefaultConfigPath ( ) ) { $ configPath = getcwd ( ) . DIRECTORY_SEPARATOR . $ configPath ; } return $ configPath ; }
Prefixes the cwd to the path given by the user .
7,849
private function getSubjectLine ( $ context ) { $ commitMessage = $ context -> getCommitMessage ( ) ; $ lines = $ this -> getCommitMessageLinesWithoutComments ( $ commitMessage ) ; return ( string ) $ lines [ 0 ] ; }
Gets a clean subject line from the commit message
7,850
private function doSaveStash ( ) { $ pending = $ this -> repository -> getWorkingCopy ( ) -> getDiffPending ( ) ; if ( ! \ count ( $ pending -> getFiles ( ) ) ) { return ; } try { $ this -> io -> write ( [ '<fg=yellow>Detected unstaged changes... Stashing them!</fg=yellow>' ] ) ; $ this -> repository -> run ( 'stash' , [ 'save' , '--quiet' , '--keep-index' , uniqid ( 'grumphp' ) ] ) ; } catch ( Exception $ e ) { $ this -> io -> write ( [ sprintf ( '<fg=red>Failed stashing changes: %s</fg=red>' , $ e -> getMessage ( ) ) ] ) ; return ; } $ this -> stashIsApplied = true ; $ this -> registerShutdownHandler ( ) ; }
Check if there is a pending diff and stash the changes .
7,851
private function registerShutdownHandler ( ) { if ( $ this -> shutdownFunctionRegistered ) { return ; } $ subscriber = $ this ; register_shutdown_function ( function ( ) use ( $ subscriber ) { if ( ! $ error = error_get_last ( ) ) { return ; } if ( \ in_array ( $ error [ 'type' ] , [ E_DEPRECATED , E_USER_DEPRECATED , E_CORE_WARNING , E_CORE_ERROR ] , true ) ) { return ; } $ subscriber -> handleErrors ( ) ; } ) ; $ this -> shutdownFunctionRegistered = true ; }
Make sure to fetch errors and pop the stash before crashing .
7,852
public static function supportsFlags ( ) : bool { $ rc = new ReflectionClass ( Yaml :: class ) ; $ method = $ rc -> getMethod ( 'parse' ) ; $ params = $ method -> getParameters ( ) ; return 'flags' === $ params [ 1 ] -> getName ( ) ; }
This method can be used to determine the Symfony Linter version . If this method returns true you are using Symfony YAML > 3 . 1 .
7,853
public function sortByPriority ( GrumPHP $ grumPHP ) : self { $ priorityQueue = new SplPriorityQueue ( ) ; $ stableSortIndex = PHP_INT_MAX ; foreach ( $ this -> getIterator ( ) as $ task ) { $ metadata = $ grumPHP -> getTaskMetadata ( $ task -> getName ( ) ) ; $ priorityQueue -> insert ( $ task , [ $ metadata [ 'priority' ] , $ stableSortIndex -- ] ) ; } return new self ( array_values ( iterator_to_array ( $ priorityQueue ) ) ) ; }
This method sorts the tasks by highest priority first .
7,854
public static function ensureProjectBinDirInSystemPath ( string $ binDir ) { $ pathStr = 'PATH' ; if ( ! isset ( $ _SERVER [ $ pathStr ] ) && isset ( $ _SERVER [ 'Path' ] ) ) { $ pathStr = 'Path' ; } if ( ! is_dir ( $ binDir ) ) { return ; } $ binDir = realpath ( $ binDir ) ; $ hasBindDirInPath = preg_match ( '{(^|' . PATH_SEPARATOR . ')' . preg_quote ( $ binDir ) . '($|' . PATH_SEPARATOR . ')}' , $ _SERVER [ $ pathStr ] ) ; if ( ! $ hasBindDirInPath && isset ( $ _SERVER [ $ pathStr ] ) ) { $ _SERVER [ $ pathStr ] = $ binDir . PATH_SEPARATOR . getenv ( $ pathStr ) ; putenv ( $ pathStr . '=' . $ _SERVER [ $ pathStr ] ) ; } }
Composer contains some logic to prepend the current bin dir to the system PATH . To make sure this application works the same in CLI and Composer modus we ll have to ensure that the bin path is always prefixed .
7,855
public function paths ( array $ patterns ) : self { $ filter = new Iterator \ PathFilterIterator ( $ this -> getIterator ( ) , $ patterns , [ ] ) ; return new self ( iterator_to_array ( $ filter ) ) ; }
Filter by paths .
7,856
public function notPaths ( array $ pattern ) : self { $ filter = new Iterator \ PathFilterIterator ( $ this -> getIterator ( ) , [ ] , $ pattern ) ; return new self ( iterator_to_array ( $ filter ) ) ; }
Adds rules that filenames must not match .
7,857
public function filter ( Closure $ closure ) : self { $ filter = new Iterator \ CustomFilterIterator ( $ this -> getIterator ( ) , [ $ closure ] ) ; return new self ( iterator_to_array ( $ filter ) ) ; }
Filters the iterator with an anonymous function .
7,858
protected function buildConfiguration ( InputInterface $ input , OutputInterface $ output ) : array { $ helper = $ this -> getHelper ( 'question' ) ; $ questionString = $ this -> createQuestionString ( 'Do you want to create a grumphp.yml file?' , 'Yes' ) ; $ question = new ConfirmationQuestion ( $ questionString , true ) ; if ( ! $ helper -> ask ( $ input , $ output , $ question ) ) { return [ ] ; } $ default = $ this -> guessGitDir ( ) ; $ questionString = $ this -> createQuestionString ( 'In which folder is GIT initialized?' , $ default ) ; $ question = new Question ( $ questionString , $ default ) ; $ question -> setValidator ( [ $ this , 'pathValidator' ] ) ; $ gitDir = $ helper -> ask ( $ input , $ output , $ question ) ; $ default = $ this -> guessBinDir ( ) ; $ questionString = $ this -> createQuestionString ( 'Where can we find the executables?' , $ default ) ; $ question = new Question ( $ questionString , $ default ) ; $ question -> setValidator ( [ $ this , 'pathValidator' ] ) ; $ binDir = $ helper -> ask ( $ input , $ output , $ question ) ; $ tasks = [ ] ; if ( $ input -> isInteractive ( ) ) { $ question = new ChoiceQuestion ( 'Which tasks do you want to run?' , $ this -> getAvailableTasks ( $ this -> config ) ) ; $ question -> setMultiselect ( true ) ; $ tasks = ( array ) $ helper -> ask ( $ input , $ output , $ question ) ; } return [ 'parameters' => [ 'git_dir' => $ gitDir , 'bin_dir' => $ binDir , 'tasks' => array_map ( function ( $ task ) { return null ; } , array_flip ( $ tasks ) ) , ] , ] ; }
This method will ask the developer for it s input and will result in a configuration array .
7,859
protected function guessBinDir ( ) : string { $ defaultBinDir = $ this -> config -> getBinDir ( ) ; if ( ! $ this -> composer ( ) -> hasConfiguration ( ) ) { return $ defaultBinDir ; } $ config = $ this -> composer ( ) -> getConfiguration ( ) ; if ( ! $ config -> has ( 'bin-dir' ) ) { return $ defaultBinDir ; } return $ config -> get ( 'bin-dir' , Config :: RELATIVE_PATHS ) ; }
Make a guess to the bin dir .
7,860
public function convert ( $ string , $ option = PINYIN_DEFAULT ) { $ pinyin = $ this -> romanize ( $ string , $ option ) ; return $ this -> splitWords ( $ pinyin , $ option ) ; }
Convert string to pinyin .
7,861
public function permalink ( $ string , $ delimiter = '-' , $ option = PINYIN_DEFAULT ) { if ( \ is_int ( $ delimiter ) ) { list ( $ option , $ delimiter ) = array ( $ delimiter , '-' ) ; } if ( ! in_array ( $ delimiter , array ( '_' , '-' , '.' , '' ) , true ) ) { throw new InvalidArgumentException ( "Delimiter must be one of: '_', '-', '', '.'." ) ; } return implode ( $ delimiter , $ this -> convert ( $ string , $ option | \ PINYIN_KEEP_NUMBER | \ PINYIN_KEEP_ENGLISH ) ) ; }
Return a pinyin permalink from string .
7,862
public function abbr ( $ string , $ delimiter = '' , $ option = PINYIN_DEFAULT ) { if ( \ is_int ( $ delimiter ) ) { list ( $ option , $ delimiter ) = array ( $ delimiter , '' ) ; } return implode ( $ delimiter , array_map ( function ( $ pinyin ) { return \ is_numeric ( $ pinyin ) ? $ pinyin : mb_substr ( $ pinyin , 0 , 1 ) ; } , $ this -> convert ( $ string , $ option ) ) ) ; }
Return first letters .
7,863
public function phrase ( $ string , $ delimiter = ' ' , $ option = PINYIN_DEFAULT ) { if ( \ is_int ( $ delimiter ) ) { list ( $ option , $ delimiter ) = array ( $ delimiter , ' ' ) ; } return implode ( $ delimiter , $ this -> convert ( $ string , $ option ) ) ; }
Chinese phrase to pinyin .
7,864
public function sentence ( $ string , $ delimiter = ' ' , $ option = \ PINYIN_NO_TONE ) { if ( \ is_int ( $ delimiter ) ) { list ( $ option , $ delimiter ) = array ( $ delimiter , ' ' ) ; } return implode ( $ delimiter , $ this -> convert ( $ string , $ option | \ PINYIN_KEEP_PUNCTUATION | \ PINYIN_KEEP_ENGLISH | \ PINYIN_KEEP_NUMBER ) ) ; }
Chinese to pinyin sentence .
7,865
public function getLoader ( ) { if ( ! ( $ this -> loader instanceof DictLoaderInterface ) ) { $ dataDir = dirname ( __DIR__ ) . '/data/' ; $ loaderName = $ this -> loader ; $ this -> loader = new $ loaderName ( $ dataDir ) ; } return $ this -> loader ; }
Return dict loader .
7,866
protected function romanize ( $ string , $ option = \ PINYIN_DEFAULT ) { $ string = $ this -> prepare ( $ string , $ option ) ; $ dictLoader = $ this -> getLoader ( ) ; if ( $ this -> hasOption ( $ option , \ PINYIN_NAME ) ) { $ string = $ this -> convertSurname ( $ string , $ dictLoader ) ; } $ dictLoader -> map ( function ( $ dictionary ) use ( & $ string ) { $ string = strtr ( $ string , $ dictionary ) ; } ) ; return $ string ; }
Convert Chinese to pinyin .
7,867
protected function convertSurname ( $ string , $ dictLoader ) { $ dictLoader -> mapSurname ( function ( $ dictionary ) use ( & $ string ) { foreach ( $ dictionary as $ surname => $ pinyin ) { if ( 0 === strpos ( $ string , $ surname ) ) { $ string = $ pinyin . mb_substr ( $ string , mb_strlen ( $ surname , 'UTF-8' ) , mb_strlen ( $ string , 'UTF-8' ) - 1 , 'UTF-8' ) ; break ; } } } ) ; return $ string ; }
Convert Chinese Surname to pinyin .
7,868
protected function splitWords ( $ pinyin , $ option ) { $ split = array_filter ( preg_split ( '/\s+/i' , $ pinyin ) ) ; if ( ! $ this -> hasOption ( $ option , PINYIN_TONE ) ) { foreach ( $ split as $ index => $ pinyin ) { $ split [ $ index ] = $ this -> formatTone ( $ pinyin , $ option ) ; } } return array_values ( $ split ) ; }
Split pinyin string to words .
7,869
protected function prepare ( $ string , $ option = \ PINYIN_DEFAULT ) { $ string = preg_replace_callback ( '~[a-z0-9_-]+~i' , function ( $ matches ) { return "\t" . $ matches [ 0 ] ; } , $ string ) ; $ regex = array ( '\p{Han}' , '\p{Z}' , '\p{M}' , "\t" ) ; if ( $ this -> hasOption ( $ option , \ PINYIN_KEEP_NUMBER ) ) { \ array_push ( $ regex , '\p{N}' ) ; } if ( $ this -> hasOption ( $ option , \ PINYIN_KEEP_ENGLISH ) ) { \ array_push ( $ regex , 'a-zA-Z' ) ; } if ( $ this -> hasOption ( $ option , \ PINYIN_KEEP_PUNCTUATION ) ) { $ punctuations = array_merge ( $ this -> punctuations , array ( "\t" => ' ' , ' ' => ' ' ) ) ; $ string = trim ( str_replace ( array_keys ( $ punctuations ) , $ punctuations , $ string ) ) ; \ array_push ( $ regex , preg_quote ( implode ( array_merge ( array_keys ( $ this -> punctuations ) , $ this -> punctuations ) ) , '~' ) ) ; } return preg_replace ( \ sprintf ( '~[^%s]~u' , implode ( $ regex ) ) , '' , $ string ) ; }
Pre - process .
7,870
protected function getGenerator ( array $ handles ) { foreach ( $ handles as $ handle ) { $ handle -> seek ( 0 ) ; while ( false === $ handle -> eof ( ) ) { $ string = str_replace ( [ '\'' , ' ' , PHP_EOL , ',' ] , '' , $ handle -> fgets ( ) ) ; if ( false === strpos ( $ string , '=>' ) ) { continue ; } list ( $ string , $ pinyin ) = explode ( '=>' , $ string ) ; yield $ string => $ pinyin ; } } }
get Generator syntax .
7,871
protected function traversing ( Generator $ generator , Closure $ callback ) { foreach ( $ generator as $ string => $ pinyin ) { $ callback ( [ $ string => $ pinyin ] ) ; } }
Traverse the stream .
7,872
public function extractTagAttributes ( $ code ) { $ param = array ( ) ; $ regexes = array ( '([a-zA-Z0-9_]+)=([^"\'\s>]+)' , '([a-zA-Z0-9_]+)=["]([^"]*)["]' , "([a-zA-Z0-9_]+)=[']([^']*)[']" ) ; foreach ( $ regexes as $ regex ) { preg_match_all ( '/' . $ regex . '/is' , $ code , $ match ) ; $ amountMatch = count ( $ match [ 0 ] ) ; for ( $ k = 0 ; $ k < $ amountMatch ; $ k ++ ) { $ param [ trim ( strtolower ( $ match [ 1 ] [ $ k ] ) ) ] = trim ( $ match [ 2 ] [ $ k ] ) ; } } return $ param ; }
Extract the list of attribute = > value inside an HTML tag
7,873
public function getOldValues ( ) { return isset ( $ this -> table [ count ( $ this -> table ) - 1 ] ) ? $ this -> table [ count ( $ this -> table ) - 1 ] : $ this -> value ; }
Get the vales of the parent if exist
7,874
public function setDefaultFont ( $ default = null ) { $ old = $ this -> defaultFont ; $ this -> defaultFont = $ default ; if ( $ default ) { $ this -> value [ 'font-family' ] = $ default ; } return $ old ; }
Define the Default Font to use if the font does not exist or if no font asked
7,875
public function setPosition ( ) { $ currentX = $ this -> pdf -> GetX ( ) ; $ currentY = $ this -> pdf -> GetY ( ) ; $ this -> value [ 'xc' ] = $ currentX ; $ this -> value [ 'yc' ] = $ currentY ; if ( $ this -> value [ 'position' ] === 'relative' || $ this -> value [ 'position' ] === 'absolute' ) { if ( $ this -> value [ 'right' ] !== null ) { $ x = $ this -> getLastWidth ( true ) - $ this -> value [ 'right' ] - $ this -> value [ 'width' ] ; if ( $ this -> value [ 'margin' ] [ 'r' ] ) { $ x -= $ this -> value [ 'margin' ] [ 'r' ] ; } } else { $ x = $ this -> value [ 'left' ] ; if ( $ this -> value [ 'margin' ] [ 'l' ] ) { $ x += $ this -> value [ 'margin' ] [ 'l' ] ; } } if ( $ this -> value [ 'bottom' ] !== null ) { $ y = $ this -> getLastHeight ( true ) - $ this -> value [ 'bottom' ] - $ this -> value [ 'height' ] ; if ( $ this -> value [ 'margin' ] [ 'b' ] ) { $ y -= $ this -> value [ 'margin' ] [ 'b' ] ; } } else { $ y = $ this -> value [ 'top' ] ; if ( $ this -> value [ 'margin' ] [ 't' ] ) { $ y += $ this -> value [ 'margin' ] [ 't' ] ; } } if ( $ this -> value [ 'position' ] === 'relative' ) { $ this -> value [ 'x' ] = $ currentX + $ x ; $ this -> value [ 'y' ] = $ currentY + $ y ; } else { $ this -> value [ 'x' ] = $ this -> getLastAbsoluteX ( ) + $ x ; $ this -> value [ 'y' ] = $ this -> getLastAbsoluteY ( ) + $ y ; } } else { $ this -> value [ 'x' ] = $ currentX ; $ this -> value [ 'y' ] = $ currentY ; if ( $ this -> value [ 'margin' ] [ 'l' ] ) { $ this -> value [ 'x' ] += $ this -> value [ 'margin' ] [ 'l' ] ; } if ( $ this -> value [ 'margin' ] [ 't' ] ) { $ this -> value [ 'y' ] += $ this -> value [ 'margin' ] [ 't' ] ; } } $ this -> pdf -> SetXY ( $ this -> value [ 'x' ] , $ this -> value [ 'y' ] ) ; }
Set the New position for the current Tag
7,876
public function getLastHeight ( $ mode = false ) { for ( $ k = count ( $ this -> table ) - 1 ; $ k >= 0 ; $ k -- ) { if ( $ this -> table [ $ k ] [ 'height' ] ) { $ h = $ this -> table [ $ k ] [ 'height' ] ; if ( $ mode ) { $ h += $ this -> table [ $ k ] [ 'border' ] [ 't' ] [ 'width' ] + $ this -> table [ $ k ] [ 'padding' ] [ 't' ] + 0.02 ; $ h += $ this -> table [ $ k ] [ 'border' ] [ 'b' ] [ 'width' ] + $ this -> table [ $ k ] [ 'padding' ] [ 'b' ] + 0.02 ; } return $ h ; } } return $ this -> pdf -> getH ( ) - $ this -> pdf -> gettMargin ( ) - $ this -> pdf -> getbMargin ( ) ; }
Get the height of the parent
7,877
public function getLastValue ( $ key ) { $ nb = count ( $ this -> table ) ; if ( $ nb > 0 ) { return $ this -> table [ $ nb - 1 ] [ $ key ] ; } else { return null ; } }
Get the last value for a specific key
7,878
protected function getLastAbsoluteX ( ) { for ( $ k = count ( $ this -> table ) - 1 ; $ k >= 0 ; $ k -- ) { if ( $ this -> table [ $ k ] [ 'x' ] && $ this -> table [ $ k ] [ 'position' ] ) { return $ this -> table [ $ k ] [ 'x' ] ; } } return $ this -> pdf -> getlMargin ( ) ; }
Get the last absolute X
7,879
protected function getLastAbsoluteY ( ) { for ( $ k = count ( $ this -> table ) - 1 ; $ k >= 0 ; $ k -- ) { if ( $ this -> table [ $ k ] [ 'y' ] && $ this -> table [ $ k ] [ 'position' ] ) { return $ this -> table [ $ k ] [ 'y' ] ; } } return $ this -> pdf -> gettMargin ( ) ; }
Get the last absolute Y
7,880
protected function duplicateBorder ( & $ val ) { if ( count ( $ val ) == 1 ) { $ val [ 1 ] = $ val [ 0 ] ; $ val [ 2 ] = $ val [ 0 ] ; $ val [ 3 ] = $ val [ 0 ] ; } elseif ( count ( $ val ) == 2 ) { $ val [ 2 ] = $ val [ 0 ] ; $ val [ 3 ] = $ val [ 1 ] ; } elseif ( count ( $ val ) == 3 ) { $ val [ 3 ] = $ val [ 1 ] ; } }
Duplicate the borders if needed
7,881
protected function analyseStyle ( $ code ) { $ code = preg_replace ( '/[\s]+/' , ' ' , $ code ) ; $ code = preg_replace ( '/\/\*.*?\*\//s' , '' , $ code ) ; preg_match_all ( '/([^{}]+){([^}]*)}/isU' , $ code , $ match ) ; $ amountMatch = count ( $ match [ 0 ] ) ; for ( $ k = 0 ; $ k < $ amountMatch ; $ k ++ ) { $ names = strtolower ( trim ( $ match [ 1 ] [ $ k ] ) ) ; $ styles = trim ( $ match [ 2 ] [ $ k ] ) ; $ styles = explode ( ';' , $ styles ) ; $ css = array ( ) ; foreach ( $ styles as $ style ) { $ tmp = explode ( ':' , $ style ) ; if ( count ( $ tmp ) > 1 ) { $ cod = $ tmp [ 0 ] ; unset ( $ tmp [ 0 ] ) ; $ tmp = implode ( ':' , $ tmp ) ; $ css [ trim ( strtolower ( $ cod ) ) ] = trim ( $ tmp ) ; } } $ names = explode ( ',' , $ names ) ; foreach ( $ names as $ name ) { $ name = trim ( $ name ) ; if ( strpos ( $ name , ':' ) !== false ) { continue ; } if ( ! isset ( $ this -> css [ $ name ] ) ) { $ this -> css [ $ name ] = $ css ; } else { $ this -> css [ $ name ] = array_merge ( $ this -> css [ $ name ] , $ css ) ; } } } $ this -> cssKeys = array_flip ( array_keys ( $ this -> css ) ) ; }
Read a css content
7,882
protected function openSvg ( $ properties ) { if ( ! $ this -> svgDrawer -> isDrawing ( ) ) { $ e = new HtmlParsingException ( 'The asked [' . $ this -> getName ( ) . '] tag is not in a [DRAW] tag' ) ; $ e -> setInvalidTag ( $ this -> getName ( ) ) ; throw $ e ; } $ transform = null ; if ( array_key_exists ( 'transform' , $ properties ) ) { $ transform = $ this -> svgDrawer -> prepareTransform ( $ properties [ 'transform' ] ) ; } $ this -> pdf -> doTransform ( $ transform ) ; $ this -> parsingCss -> save ( ) ; }
Open the SVG tag
7,883
public function open ( $ properties ) { $ this -> parsingCss -> save ( ) ; $ this -> overrideStyles ( ) ; $ this -> parsingCss -> analyse ( $ this -> getName ( ) , $ properties ) ; $ this -> parsingCss -> setPosition ( ) ; $ this -> parsingCss -> fontSet ( ) ; return true ; }
Open the HTML tag
7,884
protected function displayLine ( $ name , $ timeTotal , $ timeStep , $ memoryUsage , $ memoryPeak ) { $ output = str_pad ( $ name , 30 , ' ' , STR_PAD_RIGHT ) . str_pad ( $ timeTotal , 12 , ' ' , STR_PAD_LEFT ) . str_pad ( $ timeStep , 12 , ' ' , STR_PAD_LEFT ) . str_pad ( $ memoryUsage , 15 , ' ' , STR_PAD_LEFT ) . str_pad ( $ memoryPeak , 15 , ' ' , STR_PAD_LEFT ) ; if ( $ this -> htmlOutput ) { $ output = '<pre style="padding:0; margin:0">' . $ output . '</pre>' ; } echo $ output . "\n" ; }
display a debug line
7,885
public function start ( ) { $ time = microtime ( true ) ; $ this -> startTime = $ time ; $ this -> lastTime = $ time ; $ this -> displayLine ( 'step' , 'time' , 'delta' , 'memory' , 'peak' ) ; $ this -> addStep ( 'Init debug' ) ; return $ this ; }
Start the debugger
7,886
public function addStep ( $ name , $ level = null ) { if ( $ level === true ) { $ this -> level ++ ; } $ time = microtime ( true ) ; $ usage = memory_get_usage ( ) ; $ peak = memory_get_peak_usage ( ) ; $ type = ( $ level === true ? ' Begin' : ( $ level === false ? ' End' : '' ) ) ; $ this -> displayLine ( str_repeat ( ' ' , $ this -> level ) . $ name . $ type , number_format ( ( $ time - $ this -> startTime ) * 1000 , 1 , '.' , ' ' ) . ' ms' , number_format ( ( $ time - $ this -> lastTime ) * 1000 , 1 , '.' , ' ' ) . ' ms' , number_format ( $ usage / 1024 , 1 , '.' , ' ' ) . ' Ko' , number_format ( $ peak / 1024 , 1 , '.' , ' ' ) . ' Ko' ) ; $ this -> lastTime = $ time ; if ( $ level === false ) { $ this -> level -- ; } return $ this ; }
add a debug step
7,887
public function convertBackground ( $ css , & $ value ) { $ text = '/url\(([^)]*)\)/isU' ; if ( preg_match ( $ text , $ css , $ match ) ) { $ value [ 'image' ] = $ this -> convertBackgroundImage ( $ match [ 0 ] ) ; $ css = preg_replace ( $ text , '' , $ css ) ; $ css = preg_replace ( '/[\s]+/' , ' ' , $ css ) ; } $ css = preg_replace ( '/,[\s]+/' , ',' , $ css ) ; $ css = explode ( ' ' , $ css ) ; $ pos = '' ; foreach ( $ css as $ val ) { $ ok = false ; $ color = $ this -> convertToColor ( $ val , $ ok ) ; if ( $ ok ) { $ value [ 'color' ] = $ color ; } elseif ( $ val === 'transparent' ) { $ value [ 'color' ] = null ; } else { $ repeat = $ this -> convertBackgroundRepeat ( $ val ) ; if ( $ repeat ) { $ value [ 'repeat' ] = $ repeat ; } else { $ pos .= ( $ pos ? ' ' : '' ) . $ val ; } } } if ( $ pos ) { $ pos = $ this -> convertBackgroundPosition ( $ pos , $ ok ) ; if ( $ ok ) { $ value [ 'position' ] = $ pos ; } } }
Analyse a background
7,888
public function convertBackgroundColor ( $ css ) { $ res = null ; if ( $ css === 'transparent' ) { return null ; } return $ this -> convertToColor ( $ css , $ res ) ; }
Parse a background color
7,889
public function convertBackgroundRepeat ( $ css ) { switch ( $ css ) { case 'repeat' : return array ( true , true ) ; case 'repeat-x' : return array ( true , false ) ; case 'repeat-y' : return array ( false , true ) ; case 'no-repeat' : return array ( false , false ) ; } return null ; }
Parse a background repeat
7,890
protected function loadExtensions ( ) { if ( $ this -> extensionsLoaded ) { return ; } foreach ( $ this -> extensions as $ extension ) { foreach ( $ extension -> getTags ( ) as $ tag ) { if ( ! $ tag instanceof TagInterface ) { throw new Html2PdfException ( 'The ExtensionInterface::getTags() method must return an array of TagInterface.' ) ; } $ this -> addTagObject ( $ tag ) ; } } $ this -> extensionsLoaded = true ; }
Initialize the registered extensions
7,891
protected function addTagObject ( TagInterface $ tagObject ) { $ tagName = strtolower ( $ tagObject -> getName ( ) ) ; $ this -> tagObjects [ $ tagName ] = $ tagObject ; }
register a tag object
7,892
protected function getTagObject ( $ tagName ) { if ( ! $ this -> extensionsLoaded ) { $ this -> loadExtensions ( ) ; } if ( ! array_key_exists ( $ tagName , $ this -> tagObjects ) ) { return null ; } $ tagObject = $ this -> tagObjects [ $ tagName ] ; $ tagObject -> setParsingCssObject ( $ this -> parsingCss ) ; $ tagObject -> setCssConverterObject ( $ this -> cssConverter ) ; $ tagObject -> setPdfObject ( $ this -> pdf ) ; if ( ! is_null ( $ this -> debug ) ) { $ tagObject -> setDebugObject ( $ this -> debug ) ; } return $ tagObject ; }
get the tag object from a tag name
7,893
public function setModeDebug ( DebugInterface $ debugObject = null ) { if ( is_null ( $ debugObject ) ) { $ this -> debug = new Debug ( ) ; } else { $ this -> debug = $ debugObject ; } $ this -> debug -> start ( ) ; return $ this ; }
set the debug mode to On
7,894
public function addFont ( $ family , $ style = '' , $ file = '' ) { $ this -> pdf -> AddFont ( $ family , $ style , $ file ) ; return $ this ; }
add a font see TCPDF function addFont
7,895
public function createIndex ( $ titre = 'Index' , $ sizeTitle = 20 , $ sizeBookmark = 15 , $ bookmarkTitle = true , $ displayPage = true , $ onPage = null , $ fontName = null , $ marginTop = null ) { if ( $ fontName === null ) { $ fontName = 'helvetica' ; } $ oldPage = $ this -> _INDEX_NewPage ( $ onPage ) ; if ( $ marginTop !== null ) { $ marginTop = $ this -> cssConverter -> convertToMM ( $ marginTop ) ; $ this -> pdf -> SetY ( $ this -> pdf -> GetY ( ) + $ marginTop ) ; } $ this -> pdf -> createIndex ( $ this , $ titre , $ sizeTitle , $ sizeBookmark , $ bookmarkTitle , $ displayPage , $ onPage , $ fontName ) ; if ( $ oldPage ) { $ this -> pdf -> setPage ( $ oldPage ) ; } }
display a automatic index from the bookmarks
7,896
public function writeHTML ( $ html ) { $ html = $ this -> parsingHtml -> prepareHtml ( $ html ) ; $ html = $ this -> parsingCss -> extractStyle ( $ html ) ; $ this -> parsingHtml -> parse ( $ this -> lexer -> tokenize ( $ html ) ) ; $ this -> _makeHTMLcode ( ) ; return $ this ; }
convert HTML to PDF
7,897
public function previewHTML ( $ html ) { $ html = $ this -> parsingHtml -> prepareHtml ( $ html ) ; $ html = preg_replace ( '/<page([^>]*)>/isU' , '<hr>Page : $1<hr><div$1>' , $ html ) ; $ html = preg_replace ( '/<page_header([^>]*)>/isU' , '<hr>Page Header : $1<hr><div$1>' , $ html ) ; $ html = preg_replace ( '/<page_footer([^>]*)>/isU' , '<hr>Page Footer : $1<hr><div$1>' , $ html ) ; $ html = preg_replace ( '/<\/page([^>]*)>/isU' , '</div><hr>' , $ html ) ; $ html = preg_replace ( '/<\/page_header([^>]*)>/isU' , '</div><hr>' , $ html ) ; $ html = preg_replace ( '/<\/page_footer([^>]*)>/isU' , '</div><hr>' , $ html ) ; $ html = preg_replace ( '/<bookmark([^>]*)>/isU' , '<hr>bookmark : $1<hr>' , $ html ) ; $ html = preg_replace ( '/<\/bookmark([^>]*)>/isU' , '' , $ html ) ; $ html = preg_replace ( '/<barcode([^>]*)>/isU' , '<hr>barcode : $1<hr>' , $ html ) ; $ html = preg_replace ( '/<\/barcode([^>]*)>/isU' , '' , $ html ) ; $ html = preg_replace ( '/<qrcode([^>]*)>/isU' , '<hr>qrcode : $1<hr>' , $ html ) ; $ html = preg_replace ( '/<\/qrcode([^>]*)>/isU' , '' , $ html ) ; echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head> <title>HTML View</title> <meta http-equiv="Content-Type" content="text/html; charset=' . $ this -> _encoding . '" > </head> <body style="padding: 10px; font-size: 10pt;font-family: Verdana;"> ' . $ html . ' </body></html>' ; }
Preview the HTML before conversion
7,898
public function initSubHtml ( $ format , $ orientation , $ marge , $ page , $ defLIST , $ myLastPageGroup , $ myLastPageGroupNb ) { $ this -> _isSubPart = true ; $ this -> parsingCss -> setOnlyLeft ( ) ; $ this -> _setNewPage ( $ format , $ orientation , null , null , ( $ myLastPageGroup !== null ) ) ; $ this -> _saveMargin ( 0 , 0 , $ marge ) ; $ this -> _defList = $ defLIST ; $ this -> _page = $ page ; $ this -> pdf -> setMyLastPageGroup ( $ myLastPageGroup ) ; $ this -> pdf -> setMyLastPageGroupNb ( $ myLastPageGroupNb ) ; $ this -> pdf -> SetXY ( 0 , 0 ) ; $ this -> parsingCss -> fontSet ( ) ; }
init a sub Html2Pdf . do not use it directly . Only the method createSubHTML must use it
7,899
protected function setDefaultMargins ( $ margins ) { if ( ! is_array ( $ margins ) ) { $ margins = array ( $ margins , $ margins , $ margins , $ margins ) ; } if ( ! isset ( $ margins [ 2 ] ) ) { $ margins [ 2 ] = $ margins [ 0 ] ; } if ( ! isset ( $ margins [ 3 ] ) ) { $ margins [ 3 ] = 8 ; } $ this -> _defaultLeft = $ this -> cssConverter -> convertToMM ( $ margins [ 0 ] . 'mm' ) ; $ this -> _defaultTop = $ this -> cssConverter -> convertToMM ( $ margins [ 1 ] . 'mm' ) ; $ this -> _defaultRight = $ this -> cssConverter -> convertToMM ( $ margins [ 2 ] . 'mm' ) ; $ this -> _defaultBottom = $ this -> cssConverter -> convertToMM ( $ margins [ 3 ] . 'mm' ) ; }
set the default margins of the page