idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
3,900
protected function followRequestRedirects ( RequestInterface $ request ) { $ response = null ; $ attempts = 0 ; while ( $ attempts < $ this -> redirectLimit ) { $ attempts ++ ; $ response = $ this -> getHttpClient ( ) -> send ( $ request , [ 'allow_redirects' => false ] ) ; if ( $ this -> isRedirect ( $ response ) ) { $ redirectUrl = new Uri ( $ response -> getHeader ( 'Location' ) [ 0 ] ) ; $ request = $ request -> withUri ( $ redirectUrl ) ; } else { break ; } } return $ response ; }
Retrieves a response for a given request and retrieves subsequent responses with authorization headers if a redirect is detected .
3,901
protected function isRedirect ( ResponseInterface $ response ) { $ statusCode = $ response -> getStatusCode ( ) ; return $ statusCode > 300 && $ statusCode < 400 && $ response -> hasHeader ( 'Location' ) ; }
Determines if a given response is a redirect .
3,902
public function setRedirectLimit ( $ limit ) { if ( ! is_int ( $ limit ) ) { throw new InvalidArgumentException ( 'redirectLimit must be an integer.' ) ; } if ( $ limit < 1 ) { throw new InvalidArgumentException ( 'redirectLimit must be greater than or equal to one.' ) ; } $ this -> redirectLimit = $ limit ; return $ this ; }
Updates the redirect limit .
3,903
private function getValueByKey ( array $ data , $ key , $ default = null ) { if ( ! is_string ( $ key ) || empty ( $ key ) || ! count ( $ data ) ) { return $ default ; } if ( strpos ( $ key , '.' ) !== false ) { $ keys = explode ( '.' , $ key ) ; foreach ( $ keys as $ innerKey ) { if ( ! is_array ( $ data ) || ! array_key_exists ( $ innerKey , $ data ) ) { return $ default ; } $ data = $ data [ $ innerKey ] ; } return $ data ; } return array_key_exists ( $ key , $ data ) ? $ data [ $ key ] : $ default ; }
Returns a value by key using dot notation .
3,904
protected function getAuthorizationHeaders ( $ token = null ) { if ( $ token === null ) { return [ ] ; } $ ts = time ( ) ; $ id = $ this -> getTokenId ( $ token ) ; $ nonce = $ this -> getRandomState ( 16 ) ; $ mac = $ this -> getMacSignature ( $ id , $ ts , $ nonce ) ; $ parts = [ ] ; foreach ( compact ( 'id' , 'ts' , 'nonce' , 'mac' ) as $ key => $ value ) { $ parts [ ] = sprintf ( '%s="%s"' , $ key , $ value ) ; } return [ 'Authorization' => 'MAC ' . implode ( ', ' , $ parts ) ] ; }
Returns the authorization headers for the mac grant .
3,905
public function getRequestWithOptions ( $ method , $ uri , array $ options = [ ] ) { $ options = $ this -> parseOptions ( $ options ) ; return $ this -> getRequest ( $ method , $ uri , $ options [ 'headers' ] , $ options [ 'body' ] , $ options [ 'version' ] ) ; }
Creates a request using a simplified array of options .
3,906
public function prepareRequestParameters ( array $ defaults , array $ options ) { $ defaults [ 'grant_type' ] = $ this -> getName ( ) ; $ required = $ this -> getRequiredRequestParameters ( ) ; $ provided = array_merge ( $ defaults , $ options ) ; $ this -> checkRequiredParameters ( $ required , $ provided ) ; return $ provided ; }
Prepares an access token request s parameters by checking that all required parameters are set then merging with any given defaults .
3,907
public function getAuthorizationUrl ( array $ options = [ ] ) { $ base = $ this -> getBaseAuthorizationUrl ( ) ; $ params = $ this -> getAuthorizationParameters ( $ options ) ; $ query = $ this -> getAuthorizationQuery ( $ params ) ; return $ this -> appendQuery ( $ base , $ query ) ; }
Builds the authorization URL .
3,908
public function authorize ( array $ options = [ ] , callable $ redirectHandler = null ) { $ url = $ this -> getAuthorizationUrl ( $ options ) ; if ( $ redirectHandler ) { return $ redirectHandler ( $ url , $ this ) ; } header ( 'Location: ' . $ url ) ; exit ; }
Redirects the client for authorization .
3,909
protected function appendQuery ( $ url , $ query ) { $ query = trim ( $ query , '?&' ) ; if ( $ query ) { $ glue = strstr ( $ url , '?' ) === false ? '?' : '&' ; return $ url . $ glue . $ query ; } return $ url ; }
Appends a query string to a URL .
3,910
protected function verifyGrant ( $ grant ) { if ( is_string ( $ grant ) ) { return $ this -> grantFactory -> getGrant ( $ grant ) ; } $ this -> grantFactory -> checkGrant ( $ grant ) ; return $ grant ; }
Checks that a provided grant is valid or attempts to produce one if the provided grant is a string .
3,911
protected function getAccessTokenUrl ( array $ params ) { $ url = $ this -> getBaseAccessTokenUrl ( $ params ) ; if ( $ this -> getAccessTokenMethod ( ) === self :: METHOD_GET ) { $ query = $ this -> getAccessTokenQuery ( $ params ) ; return $ this -> appendQuery ( $ url , $ query ) ; } return $ url ; }
Returns the full URL to use when requesting an access token .
3,912
public function getRequest ( $ method , $ url , array $ options = [ ] ) { return $ this -> createRequest ( $ method , $ url , null , $ options ) ; }
Returns a PSR - 7 request instance that is not authenticated .
3,913
public function getHeaders ( $ token = null ) { if ( $ token ) { return array_merge ( $ this -> getDefaultHeaders ( ) , $ this -> getAuthorizationHeaders ( $ token ) ) ; } return $ this -> getDefaultHeaders ( ) ; }
Returns all headers used by this provider for a request .
3,914
private function checkRequiredParameters ( array $ names , array $ params ) { foreach ( $ names as $ name ) { $ this -> checkRequiredParameter ( $ name , $ params ) ; } }
Checks for multiple required parameters in a hash .
3,915
protected function fillProperties ( array $ options = [ ] ) { if ( isset ( $ options [ 'guarded' ] ) ) { unset ( $ options [ 'guarded' ] ) ; } foreach ( $ options as $ option => $ value ) { if ( property_exists ( $ this , $ option ) && ! $ this -> isGuarded ( $ option ) ) { $ this -> { $ option } = $ value ; } } }
Attempts to mass assign the given options to explicitly defined properties skipping over any properties that are defined in the guarded array .
3,916
private function load ( ) { $ english = $ this -> getTranslations ( __DIR__ , 'en' ) ; $ languages = $ this -> getLanguages ( ) ; $ this -> compareTranslations ( $ english , $ languages ) ; }
Compare translations and generate file .
3,917
private function getTranslations ( $ directory , $ language ) { $ contentJson = '' ; $ directoryJson = ( $ language == 'en' ) ? '/en/' : '/../json/' ; $ fileJson = $ directory . $ directoryJson . $ language . '.json' ; if ( file_exists ( $ fileJson ) ) { $ contentJson = json_decode ( file_get_contents ( $ fileJson ) , true ) ; } return [ 'json' => $ contentJson , 'auth' => include ( $ directory . '/' . $ language . '/auth.php' ) , 'pagination' => include ( $ directory . '/' . $ language . '/pagination.php' ) , 'passwords' => include ( $ directory . '/' . $ language . '/passwords.php' ) , 'validation' => include ( $ directory . '/' . $ language . '/validation.php' ) , ] ; }
Returns array of translations by language .
3,918
private function getLanguages ( ) { $ directories = glob ( $ this -> basePath . '/*' , GLOB_ONLYDIR ) ; $ languages = array_map ( function ( $ dir ) { $ name = basename ( $ dir ) ; return in_array ( $ name , $ this -> excluded , true ) ? null : $ name ; } , $ directories ) ; return array_filter ( $ languages ) ; }
Returns list of languages .
3,919
private function compareTranslations ( array $ default , array $ languages ) { foreach ( $ languages as $ language ) { $ this -> addOutput ( $ language ) ; $ current = $ this -> getTranslations ( $ this -> basePath , $ language ) ; foreach ( $ default as $ key => $ values ) { $ valuesKeys = array_keys ( $ values ) ; foreach ( $ valuesKeys as $ key2 ) { if ( in_array ( $ key2 , [ 'custom' , 'attributes' ] , true ) ) { continue ; } if ( ! isset ( $ current [ $ key ] [ $ key2 ] ) ) { $ this -> addOutput ( $ language , " * {$key} : {$key2} : not present" ) ; } elseif ( $ current [ $ key ] [ $ key2 ] === $ default [ $ key ] [ $ key2 ] ) { $ this -> addOutput ( $ language , " * {$key} : {$key2}" ) ; } } } } }
Compare translations .
3,920
private function addOutput ( string $ key , string $ value = null ) { if ( ! array_key_exists ( $ key , $ this -> output ) ) { $ this -> output [ $ key ] = [ ] ; } $ this -> output [ $ key ] [ ] = $ value ; }
Adding elements to the resulting array .
3,921
private function getOutput ( ) { $ output = "# Todo list\n\n" ; $ columns = 12 ; $ captions = implode ( '|' , array_fill ( 0 , $ columns , ' ' ) ) ; $ subcaptions = implode ( '|' , array_fill ( 0 , $ columns , ':---:' ) ) ; $ output .= "|$captions|\n" ; $ output .= "|$subcaptions|\n" ; $ menu = [ ] ; foreach ( array_keys ( $ this -> output ) as $ language ) { $ menu [ ] = "[$language](#$language)" ; } $ rows = array_chunk ( $ menu , $ columns ) ; array_map ( function ( $ row ) use ( & $ output ) { $ row = implode ( ' | ' , $ row ) ; $ output .= $ row . "\n" ; } , $ rows ) ; $ output .= "\n\n" ; foreach ( $ this -> output as $ language => $ values ) { $ output .= "#### {$language}:\n" ; $ output .= implode ( PHP_EOL , $ values ) ; $ output .= "\n\n[ [to top](#todo-list) ]\n\n" ; } return $ output ; }
Forming the page content for output .
3,922
public function executeMigration ( MigrationInterface $ migration , $ direction = MigrationInterface :: UP , $ fake = false ) { $ direction = ( $ direction === MigrationInterface :: UP ) ? MigrationInterface :: UP : MigrationInterface :: DOWN ; $ migration -> setMigratingUp ( $ direction === MigrationInterface :: UP ) ; $ startTime = time ( ) ; $ migration -> setAdapter ( $ this -> getAdapter ( ) ) ; if ( ! $ fake ) { if ( $ this -> getAdapter ( ) -> hasTransactions ( ) ) { $ this -> getAdapter ( ) -> beginTransaction ( ) ; } if ( method_exists ( $ migration , MigrationInterface :: CHANGE ) ) { if ( $ direction === MigrationInterface :: DOWN ) { $ proxyAdapter = AdapterFactory :: instance ( ) -> getWrapper ( 'proxy' , $ this -> getAdapter ( ) ) ; $ migration -> setAdapter ( $ proxyAdapter ) ; $ migration -> change ( ) ; $ proxyAdapter -> executeInvertedCommands ( ) ; $ migration -> setAdapter ( $ this -> getAdapter ( ) ) ; } else { $ migration -> change ( ) ; } } else { $ migration -> { $ direction } ( ) ; } if ( $ this -> getAdapter ( ) -> hasTransactions ( ) ) { $ this -> getAdapter ( ) -> commitTransaction ( ) ; } } $ this -> getAdapter ( ) -> migrated ( $ migration , $ direction , date ( 'Y-m-d H:i:s' , $ startTime ) , date ( 'Y-m-d H:i:s' , time ( ) ) ) ; }
Executes the specified migration on this environment .
3,923
public function executeSeed ( SeedInterface $ seed ) { $ seed -> setAdapter ( $ this -> getAdapter ( ) ) ; if ( $ this -> getAdapter ( ) -> hasTransactions ( ) ) { $ this -> getAdapter ( ) -> beginTransaction ( ) ; } if ( method_exists ( $ seed , SeedInterface :: RUN ) ) { $ seed -> run ( ) ; } if ( $ this -> getAdapter ( ) -> hasTransactions ( ) ) { $ this -> getAdapter ( ) -> commitTransaction ( ) ; } }
Executes the specified seeder on this environment .
3,924
protected function parseAgnosticDsn ( array $ options ) { if ( isset ( $ options [ 'dsn' ] ) && is_string ( $ options [ 'dsn' ] ) ) { $ regex = '#^(?P<adapter>[^\\:]+)\\://(?:(?P<user>[^\\:@]+)(?:\\:(?P<pass>[^@]*))?@)?' . '(?P<host>[^\\:@/]+)(?:\\:(?P<port>[1-9]\\d*))?/(?P<name>[^\?]+)(?:\?(?P<query>.*))?$#' ; if ( preg_match ( $ regex , trim ( $ options [ 'dsn' ] ) , $ parsedOptions ) ) { $ additionalOpts = [ ] ; if ( isset ( $ parsedOptions [ 'query' ] ) ) { parse_str ( $ parsedOptions [ 'query' ] , $ additionalOpts ) ; } $ validOptions = [ 'adapter' , 'user' , 'pass' , 'host' , 'port' , 'name' ] ; $ parsedOptions = array_filter ( array_intersect_key ( $ parsedOptions , array_flip ( $ validOptions ) ) ) ; $ options = array_merge ( $ additionalOpts , $ parsedOptions , $ options ) ; unset ( $ options [ 'dsn' ] ) ; } } return $ options ; }
Parse a database - agnostic DSN into individual options .
3,925
public function getCurrentVersion ( ) { $ versions = $ this -> getVersions ( ) ; $ version = 0 ; if ( ! empty ( $ versions ) ) { $ version = end ( $ versions ) ; } $ this -> setCurrentVersion ( $ version ) ; return $ this -> currentVersion ; }
Gets the current version of the environment .
3,926
public static function build ( Table $ table , $ columns , array $ options = [ ] ) { $ index = $ columns ; if ( ! $ columns instanceof Index ) { $ index = new Index ( ) ; if ( is_string ( $ columns ) ) { $ columns = [ $ columns ] ; } $ index -> setColumns ( $ columns ) ; $ index -> setOptions ( $ options ) ; } return new static ( $ table , $ index ) ; }
Creates a new AddIndex object after building the index object with the provided arguments
3,927
protected function getDefaultValueDefinition ( $ default , $ columnType = null ) { if ( is_string ( $ default ) && 'CURRENT_TIMESTAMP' !== $ default ) { $ default = $ this -> getConnection ( ) -> quote ( $ default ) ; } elseif ( is_bool ( $ default ) ) { $ default = $ this -> castToBool ( $ default ) ; } elseif ( $ columnType === static :: PHINX_TYPE_BOOLEAN ) { $ default = $ this -> castToBool ( ( bool ) $ default ) ; } return isset ( $ default ) ? 'DEFAULT ' . $ default : '' ; }
Get the defintion for a DEFAULT statement .
3,928
protected function getColumnCommentSqlDefinition ( Column $ column , $ tableName ) { $ comment = ( strcasecmp ( $ column -> getComment ( ) , 'NULL' ) !== 0 ) ? $ this -> getConnection ( ) -> quote ( $ column -> getComment ( ) ) : 'NULL' ; return sprintf ( 'COMMENT ON COLUMN %s.%s IS %s;' , $ this -> quoteTableName ( $ tableName ) , $ this -> quoteColumnName ( $ column -> getName ( ) ) , $ comment ) ; }
Gets the PostgreSQL Column Comment Definition for a column object .
3,929
public function dropSchema ( $ schemaName ) { $ sql = sprintf ( "DROP SCHEMA IF EXISTS %s CASCADE;" , $ this -> quoteSchemaName ( $ schemaName ) ) ; $ this -> execute ( $ sql ) ; }
Drops the specified schema table .
3,930
public function getAllSchemas ( ) { $ sql = "SELECT schema_name FROM information_schema.schemata WHERE schema_name <> 'information_schema' AND schema_name !~ '^pg_'" ; $ items = $ this -> fetchAll ( $ sql ) ; $ schemaNames = [ ] ; foreach ( $ items as $ item ) { $ schemaNames [ ] = $ item [ 'schema_name' ] ; } return $ schemaNames ; }
Returns schemas .
3,931
protected function getColumnSqlDefinition ( Column $ column ) { if ( $ column -> getType ( ) instanceof Literal ) { $ def = ( string ) $ column -> getType ( ) ; } else { $ sqlType = $ this -> getSqlType ( $ column -> getType ( ) , $ column -> getLimit ( ) ) ; $ def = strtoupper ( $ sqlType [ 'name' ] ) ; } if ( $ column -> getPrecision ( ) && $ column -> getScale ( ) ) { $ def .= '(' . $ column -> getPrecision ( ) . ',' . $ column -> getScale ( ) . ')' ; } elseif ( isset ( $ sqlType [ 'limit' ] ) ) { $ def .= '(' . $ sqlType [ 'limit' ] . ')' ; } if ( ( $ values = $ column -> getValues ( ) ) && is_array ( $ values ) ) { $ def .= "('" . implode ( "', '" , $ values ) . "')" ; } $ def .= $ column -> getEncoding ( ) ? ' CHARACTER SET ' . $ column -> getEncoding ( ) : '' ; $ def .= $ column -> getCollation ( ) ? ' COLLATE ' . $ column -> getCollation ( ) : '' ; $ def .= ( ! $ column -> isSigned ( ) && isset ( $ this -> signedColumnTypes [ $ column -> getType ( ) ] ) ) ? ' unsigned' : '' ; $ def .= ( $ column -> isNull ( ) == false ) ? ' NOT NULL' : ' NULL' ; $ def .= $ column -> isIdentity ( ) ? ' AUTO_INCREMENT' : '' ; $ def .= $ this -> getDefaultValueDefinition ( $ column -> getDefault ( ) , $ column -> getType ( ) ) ; if ( $ column -> getComment ( ) ) { $ def .= ' COMMENT ' . $ this -> getConnection ( ) -> quote ( $ column -> getComment ( ) ) ; } if ( $ column -> getUpdate ( ) ) { $ def .= ' ON UPDATE ' . $ column -> getUpdate ( ) ; } return $ def ; }
Gets the MySQL Column Definition for a Column object .
3,932
public function describeTable ( $ tableName ) { $ options = $ this -> getOptions ( ) ; $ sql = sprintf ( "SELECT * FROM information_schema.tables WHERE table_schema = '%s' AND table_name = '%s'" , $ options [ 'name' ] , $ tableName ) ; return $ this -> fetchRow ( $ sql ) ; }
Describes a database table . This is a MySQL adapter specific method .
3,933
private function printMissingVersion ( $ version , $ maxNameLength ) { $ this -> getOutput ( ) -> writeln ( sprintf ( ' <error>up</error> %14.0f %19s %19s <comment>%s</comment> <error>** MISSING **</error>' , $ version [ 'version' ] , $ version [ 'start_time' ] , $ version [ 'end_time' ] , str_pad ( $ version [ 'migration_name' ] , $ maxNameLength , ' ' ) ) ) ; if ( $ version && $ version [ 'breakpoint' ] ) { $ this -> getOutput ( ) -> writeln ( ' <error>BREAKPOINT SET</error>' ) ; } }
Print Missing Version
3,934
public function migrateToDateTime ( $ environment , \ DateTime $ dateTime , $ fake = false ) { $ versions = array_keys ( $ this -> getMigrations ( $ environment ) ) ; $ dateString = $ dateTime -> format ( 'YmdHis' ) ; $ outstandingMigrations = array_filter ( $ versions , function ( $ version ) use ( $ dateString ) { return $ version <= $ dateString ; } ) ; if ( count ( $ outstandingMigrations ) > 0 ) { $ migration = max ( $ outstandingMigrations ) ; $ this -> getOutput ( ) -> writeln ( 'Migrating to version ' . $ migration ) ; $ this -> migrate ( $ environment , $ migration , $ fake ) ; } }
Migrate to the version of the database on a given date .
3,935
public function executeMigration ( $ name , MigrationInterface $ migration , $ direction = MigrationInterface :: UP , $ fake = false ) { $ this -> getOutput ( ) -> writeln ( '' ) ; $ this -> getOutput ( ) -> writeln ( ' ==' . ' <info>' . $ migration -> getVersion ( ) . ' ' . $ migration -> getName ( ) . ':</info>' . ' <comment>' . ( $ direction === MigrationInterface :: UP ? 'migrating' : 'reverting' ) . '</comment>' ) ; $ migration -> preFlightCheck ( $ direction ) ; $ start = microtime ( true ) ; $ this -> getEnvironment ( $ name ) -> executeMigration ( $ migration , $ direction , $ fake ) ; $ end = microtime ( true ) ; $ migration -> postFlightCheck ( $ direction ) ; $ this -> getOutput ( ) -> writeln ( ' ==' . ' <info>' . $ migration -> getVersion ( ) . ' ' . $ migration -> getName ( ) . ':</info>' . ' <comment>' . ( $ direction === MigrationInterface :: UP ? 'migrated' : 'reverted' ) . ' ' . sprintf ( '%.4fs' , $ end - $ start ) . '</comment>' ) ; }
Execute a migration against the specified environment .
3,936
public function executeSeed ( $ name , SeedInterface $ seed ) { $ this -> getOutput ( ) -> writeln ( '' ) ; $ this -> getOutput ( ) -> writeln ( ' ==' . ' <info>' . $ seed -> getName ( ) . ':</info>' . ' <comment>seeding</comment>' ) ; $ start = microtime ( true ) ; $ this -> getEnvironment ( $ name ) -> executeSeed ( $ seed ) ; $ end = microtime ( true ) ; $ this -> getOutput ( ) -> writeln ( ' ==' . ' <info>' . $ seed -> getName ( ) . ':</info>' . ' <comment>seeded' . ' ' . sprintf ( '%.4fs' , $ end - $ start ) . '</comment>' ) ; }
Execute a seeder against the specified environment .
3,937
public function seed ( $ environment , $ seed = null ) { $ seeds = $ this -> getSeeds ( ) ; if ( $ seed === null ) { foreach ( $ seeds as $ seeder ) { if ( array_key_exists ( $ seeder -> getName ( ) , $ seeds ) ) { $ this -> executeSeed ( $ environment , $ seeder ) ; } } } else { if ( array_key_exists ( $ seed , $ seeds ) ) { $ this -> executeSeed ( $ environment , $ seeds [ $ seed ] ) ; } else { throw new \ InvalidArgumentException ( sprintf ( 'The seed class "%s" does not exist' , $ seed ) ) ; } } }
Run database seeders against an environment .
3,938
protected function getSeedFiles ( ) { $ config = $ this -> getConfig ( ) ; $ paths = $ config -> getSeedPaths ( ) ; $ files = [ ] ; foreach ( $ paths as $ path ) { $ files = array_merge ( $ files , Util :: glob ( $ path . DIRECTORY_SEPARATOR . '*.php' ) ) ; } $ files = array_unique ( $ files ) ; return $ files ; }
Returns a list of seed files found in the provided seed paths .
3,939
public function toggleBreakpoint ( $ environment , $ version ) { $ migrations = $ this -> getMigrations ( $ environment ) ; $ this -> getMigrations ( $ environment ) ; $ env = $ this -> getEnvironment ( $ environment ) ; $ versions = $ env -> getVersionLog ( ) ; if ( empty ( $ versions ) || empty ( $ migrations ) ) { return ; } if ( $ version === null ) { $ lastVersion = end ( $ versions ) ; $ version = $ lastVersion [ 'version' ] ; } if ( 0 != $ version && ! isset ( $ migrations [ $ version ] ) ) { $ this -> output -> writeln ( sprintf ( '<comment>warning</comment> %s is not a valid version' , $ version ) ) ; return ; } $ env -> getAdapter ( ) -> toggleBreakpoint ( $ migrations [ $ version ] ) ; $ versions = $ env -> getVersionLog ( ) ; $ this -> getOutput ( ) -> writeln ( ' Breakpoint ' . ( $ versions [ $ version ] [ 'breakpoint' ] ? 'set' : 'cleared' ) . ' for <info>' . $ version . '</info>' . ' <comment>' . $ migrations [ $ version ] -> getName ( ) . '</comment>' ) ; }
Toggles the breakpoint for a specific version .
3,940
public function removeBreakpoints ( $ environment ) { $ this -> getOutput ( ) -> writeln ( sprintf ( ' %d breakpoints cleared.' , $ this -> getEnvironment ( $ environment ) -> getAdapter ( ) -> resetAllBreakpoints ( ) ) ) ; }
Remove all breakpoints
3,941
protected function normalizeAction ( $ action ) { $ constantName = 'static::' . str_replace ( ' ' , '_' , strtoupper ( trim ( $ action ) ) ) ; if ( ! defined ( $ constantName ) ) { throw new \ InvalidArgumentException ( 'Unknown action passed: ' . $ action ) ; } return constant ( $ constantName ) ; }
From passed value checks if it s correct and fixes if needed
3,942
protected function getColumnCommentSqlDefinition ( Column $ column , $ tableName ) { $ currentComment = $ this -> getColumnComment ( $ tableName , $ column -> getName ( ) ) ; $ comment = ( strcasecmp ( $ column -> getComment ( ) , 'NULL' ) !== 0 ) ? $ this -> getConnection ( ) -> quote ( $ column -> getComment ( ) ) : '\'\'' ; $ command = $ currentComment === false ? 'sp_addextendedproperty' : 'sp_updateextendedproperty' ; return sprintf ( "EXECUTE %s N'MS_Description', N%s, N'SCHEMA', N'%s', N'TABLE', N'%s', N'COLUMN', N'%s';" , $ command , $ comment , $ this -> schema , $ tableName , $ column -> getName ( ) ) ; }
Gets the SqlServer Column Comment Defininition for a column object .
3,943
protected function getChangeDefault ( $ tableName , Column $ newColumn ) { $ constraintName = "DF_{$tableName}_{$newColumn->getName()}" ; $ default = $ newColumn -> getDefault ( ) ; $ instructions = new AlterInstructions ( ) ; if ( $ default === null ) { $ default = 'DEFAULT NULL' ; } else { $ default = ltrim ( $ this -> getDefaultValueDefinition ( $ default ) ) ; } if ( empty ( $ default ) ) { return $ instructions ; } $ instructions -> addPostStep ( sprintf ( 'ALTER TABLE %s ADD CONSTRAINT %s %s FOR %s' , $ this -> quoteTableName ( $ tableName ) , $ constraintName , $ default , $ this -> quoteColumnName ( $ newColumn -> getName ( ) ) ) ) ; return $ instructions ; }
Returns the instructions to change a column default value
3,944
protected function getColumnSqlDefinition ( Column $ column , $ create = true ) { $ buffer = [ ] ; if ( $ column -> getType ( ) instanceof Literal ) { $ buffer [ ] = ( string ) $ column -> getType ( ) ; } else { $ sqlType = $ this -> getSqlType ( $ column -> getType ( ) ) ; $ buffer [ ] = strtoupper ( $ sqlType [ 'name' ] ) ; $ noLimits = [ 'bigint' , 'int' , 'tinyint' ] ; if ( ! in_array ( $ sqlType [ 'name' ] , $ noLimits ) && ( $ column -> getLimit ( ) || isset ( $ sqlType [ 'limit' ] ) ) ) { $ buffer [ ] = sprintf ( '(%s)' , $ column -> getLimit ( ) ? $ column -> getLimit ( ) : $ sqlType [ 'limit' ] ) ; } } if ( $ column -> getPrecision ( ) && $ column -> getScale ( ) ) { $ buffer [ ] = '(' . $ column -> getPrecision ( ) . ',' . $ column -> getScale ( ) . ')' ; } $ properties = $ column -> getProperties ( ) ; $ buffer [ ] = $ column -> getType ( ) === 'filestream' ? 'FILESTREAM' : '' ; $ buffer [ ] = isset ( $ properties [ 'rowguidcol' ] ) ? 'ROWGUIDCOL' : '' ; $ buffer [ ] = $ column -> isNull ( ) ? 'NULL' : 'NOT NULL' ; if ( $ create === true ) { if ( $ column -> getDefault ( ) === null && $ column -> isNull ( ) ) { $ buffer [ ] = ' DEFAULT NULL' ; } else { $ buffer [ ] = $ this -> getDefaultValueDefinition ( $ column -> getDefault ( ) ) ; } } if ( $ column -> isIdentity ( ) ) { $ buffer [ ] = 'IDENTITY(1, 1)' ; } return implode ( ' ' , $ buffer ) ; }
Gets the SqlServer Column Definition for a Column object .
3,945
protected function getIndexSqlDefinition ( Index $ index , $ tableName ) { if ( is_string ( $ index -> getName ( ) ) ) { $ indexName = $ index -> getName ( ) ; } else { $ columnNames = $ index -> getColumns ( ) ; $ indexName = sprintf ( '%s_%s' , $ tableName , implode ( '_' , $ columnNames ) ) ; } $ def = sprintf ( "CREATE %s INDEX %s ON %s (%s);" , ( $ index -> getType ( ) === Index :: UNIQUE ? 'UNIQUE' : '' ) , $ indexName , $ this -> quoteTableName ( $ tableName ) , '[' . implode ( '],[' , $ index -> getColumns ( ) ) . ']' ) ; return $ def ; }
Gets the SqlServer Index Definition for an Index object .
3,946
protected function getForeignKeySqlDefinition ( ForeignKey $ foreignKey , $ tableName ) { $ constraintName = $ foreignKey -> getConstraint ( ) ? : $ tableName . '_' . implode ( '_' , $ foreignKey -> getColumns ( ) ) ; $ def = ' CONSTRAINT ' . $ this -> quoteColumnName ( $ constraintName ) ; $ def .= ' FOREIGN KEY ("' . implode ( '", "' , $ foreignKey -> getColumns ( ) ) . '")' ; $ def .= " REFERENCES {$this->quoteTableName($foreignKey->getReferencedTable()->getName())} (\"" . implode ( '", "' , $ foreignKey -> getReferencedColumns ( ) ) . '")' ; if ( $ foreignKey -> getOnDelete ( ) ) { $ def .= " ON DELETE {$foreignKey->getOnDelete()}" ; } if ( $ foreignKey -> getOnUpdate ( ) ) { $ def .= " ON UPDATE {$foreignKey->getOnUpdate()}" ; } return $ def ; }
Gets the SqlServer Foreign Key Definition for an ForeignKey object .
3,947
public function isDryRunEnabled ( ) { $ input = $ this -> getInput ( ) ; return ( $ input && $ input -> hasOption ( 'dry-run' ) ) ? ( bool ) $ input -> getOption ( 'dry-run' ) : false ; }
Determines if instead of executing queries a dump to standard output is needed
3,948
public function merge ( AlterInstructions $ other ) { $ this -> alterParts = array_merge ( $ this -> alterParts , $ other -> getAlterParts ( ) ) ; $ this -> postSteps = array_merge ( $ this -> postSteps , $ other -> getPostSteps ( ) ) ; }
Merges another AlterInstructions object to this one
3,949
public function execute ( $ alterTemplate , callable $ executor ) { if ( $ this -> alterParts ) { $ alter = sprintf ( $ alterTemplate , implode ( ', ' , $ this -> alterParts ) ) ; $ executor ( $ alter ) ; } $ state = [ ] ; foreach ( $ this -> postSteps as $ instruction ) { if ( is_callable ( $ instruction ) ) { $ state = $ instruction ( $ state ) ; continue ; } $ executor ( $ instruction ) ; } }
Executes the ALTER instruction and all of the post steps .
3,950
public static function build ( Table $ table , $ columns , $ referencedTable , $ referencedColumns = [ 'id' ] , array $ options = [ ] , $ name = null ) { if ( is_string ( $ referencedColumns ) ) { $ referencedColumns = [ $ referencedColumns ] ; } if ( is_string ( $ referencedTable ) ) { $ referencedTable = new Table ( $ referencedTable ) ; } $ fk = new ForeignKey ( ) ; $ fk -> setReferencedTable ( $ referencedTable ) -> setColumns ( $ columns ) -> setReferencedColumns ( $ referencedColumns ) -> setOptions ( $ options ) ; if ( $ name !== null ) { $ fk -> setConstraint ( $ name ) ; } return new static ( $ table , $ fk ) ; }
Creates a new AddForeignKey object after building the foreign key with the passed attributes
3,951
public static function getExistingMigrationClassNames ( $ path ) { $ classNames = [ ] ; if ( ! is_dir ( $ path ) ) { return $ classNames ; } $ phpFiles = glob ( $ path . DIRECTORY_SEPARATOR . '*.php' ) ; foreach ( $ phpFiles as $ filePath ) { if ( preg_match ( '/([0-9]+)_([_a-z0-9]*).php/' , basename ( $ filePath ) ) ) { $ classNames [ ] = static :: mapFileNameToClassName ( basename ( $ filePath ) ) ; } } return $ classNames ; }
Gets an array of all the existing migration class names .
3,952
public static function mapClassNameToFileName ( $ className ) { $ arr = preg_split ( '/(?=[A-Z])/' , $ className ) ; unset ( $ arr [ 0 ] ) ; $ fileName = static :: getCurrentTimestamp ( ) . '_' . strtolower ( implode ( $ arr , '_' ) ) . '.php' ; return $ fileName ; }
Turn migration names like CreateUserTable into file names like 12345678901234_create_user_table . php or LimitResourceNamesTo30Chars into 12345678901234_limit_resource_names_to_30_chars . php .
3,953
public static function mapFileNameToClassName ( $ fileName ) { $ matches = [ ] ; if ( preg_match ( static :: MIGRATION_FILE_NAME_PATTERN , $ fileName , $ matches ) ) { $ fileName = $ matches [ 1 ] ; } return str_replace ( ' ' , '' , ucwords ( str_replace ( '_' , ' ' , $ fileName ) ) ) ; }
Turn file names like 12345678901234_create_user_table . php into class names like CreateUserTable .
3,954
public static function loadPhpFile ( $ filename ) { $ filePath = realpath ( $ filename ) ; $ isReadable = @ \ fopen ( $ filePath , 'r' ) !== false ; if ( ! $ filePath || ! $ isReadable ) { throw new \ Exception ( sprintf ( "Cannot open file %s \n" , $ filename ) ) ; } include_once $ filePath ; return $ filePath ; }
Takes the path to a php file and attempts to include it if readable
3,955
public static function build ( Table $ table , $ columnName , $ newName ) { $ column = new Column ( ) ; $ column -> setName ( $ columnName ) ; return new static ( $ table , $ column , $ newName ) ; }
Creates a new RenameColumn object after building the passed arguments
3,956
protected function createPlan ( $ actions ) { $ this -> gatherCreates ( $ actions ) ; $ this -> gatherUpdates ( $ actions ) ; $ this -> gatherTableMoves ( $ actions ) ; $ this -> gatherIndexes ( $ actions ) ; $ this -> gatherConstraints ( $ actions ) ; $ this -> resolveConflicts ( ) ; }
Parses the given Intent and creates the separate steps to execute
3,957
public function execute ( AdapterInterface $ executor ) { foreach ( $ this -> tableCreates as $ newTable ) { $ executor -> createTable ( $ newTable -> getTable ( ) , $ newTable -> getColumns ( ) , $ newTable -> getIndexes ( ) ) ; } collection ( $ this -> updatesSequence ( ) ) -> unfold ( ) -> each ( function ( $ updates ) use ( $ executor ) { $ executor -> executeActions ( $ updates -> getTable ( ) , $ updates -> getActions ( ) ) ; } ) ; }
Executes this plan using the given AdapterInterface
3,958
protected function resolveConflicts ( ) { $ moveActions = collection ( $ this -> tableMoves ) -> unfold ( function ( $ move ) { return $ move -> getActions ( ) ; } ) ; foreach ( $ moveActions as $ action ) { if ( $ action instanceof DropTable ) { $ this -> tableUpdates = $ this -> forgetTable ( $ action -> getTable ( ) , $ this -> tableUpdates ) ; $ this -> constraints = $ this -> forgetTable ( $ action -> getTable ( ) , $ this -> constraints ) ; $ this -> indexes = $ this -> forgetTable ( $ action -> getTable ( ) , $ this -> indexes ) ; } } $ this -> tableUpdates = collection ( $ this -> tableUpdates ) -> unfold ( new ActionSplitter ( RenameColumn :: class , ChangeColumn :: class , function ( RenameColumn $ a , ChangeColumn $ b ) { return $ a -> getNewName ( ) == $ b -> getColumnName ( ) ; } ) ) -> toList ( ) ; $ this -> constraints = collection ( $ this -> constraints ) -> map ( function ( AlterTable $ alter ) { return $ this -> remapContraintAndIndexConflicts ( $ alter ) ; } ) -> unfold ( new ActionSplitter ( DropForeignKey :: class , AddForeignKey :: class , function ( DropForeignKey $ a , AddForeignKey $ b ) { return $ a -> getForeignKey ( ) -> getColumns ( ) === $ b -> getForeignKey ( ) -> getColumns ( ) ; } ) ) -> toList ( ) ; }
Deletes certain actions from the plan if they are found to be conflicting or redundant .
3,959
protected function forgetTable ( Table $ table , $ actions ) { $ result = [ ] ; foreach ( $ actions as $ action ) { if ( $ action -> getTable ( ) -> getName ( ) === $ table -> getName ( ) ) { continue ; } $ result [ ] = $ action ; } return $ result ; }
Deletes all actions related to the given table and keeps the rest
3,960
protected function forgetDropIndex ( Table $ table , array $ columns , array $ actions ) { $ dropIndexActions = new ArrayObject ( ) ; $ indexes = collection ( $ actions ) -> map ( function ( $ alter ) use ( $ table , $ columns , $ dropIndexActions ) { if ( $ alter -> getTable ( ) -> getName ( ) !== $ table -> getName ( ) ) { return $ alter ; } $ newAlter = new AlterTable ( $ table ) ; collection ( $ alter -> getActions ( ) ) -> map ( function ( $ action ) use ( $ columns ) { if ( ! $ action instanceof DropIndex ) { return [ $ action , null ] ; } if ( $ action -> getIndex ( ) -> getColumns ( ) === $ columns ) { return [ null , $ action ] ; } return [ $ action , null ] ; } ) -> each ( function ( $ tuple ) use ( $ newAlter , $ dropIndexActions ) { list ( $ action , $ dropIndex ) = $ tuple ; if ( $ action ) { $ newAlter -> addAction ( $ action ) ; } if ( $ dropIndex ) { $ dropIndexActions -> append ( $ dropIndex ) ; } } ) ; return $ newAlter ; } ) -> toArray ( ) ; return [ $ indexes , $ dropIndexActions -> getArrayCopy ( ) ] ; }
Deletes any DropIndex actions for the given table and exact columns
3,961
protected function gatherCreates ( $ actions ) { collection ( $ actions ) -> filter ( function ( $ action ) { return $ action instanceof CreateTable ; } ) -> map ( function ( $ action ) { return [ $ action -> getTable ( ) -> getName ( ) , new NewTable ( $ action -> getTable ( ) ) ] ; } ) -> each ( function ( $ step ) { $ this -> tableCreates [ $ step [ 0 ] ] = $ step [ 1 ] ; } ) ; collection ( $ actions ) -> filter ( function ( $ action ) { return $ action instanceof AddColumn || $ action instanceof AddIndex ; } ) -> filter ( function ( $ action ) { return isset ( $ this -> tableCreates [ $ action -> getTable ( ) -> getName ( ) ] ) ; } ) -> each ( function ( $ action ) { $ table = $ action -> getTable ( ) ; if ( $ action instanceof AddColumn ) { $ this -> tableCreates [ $ table -> getName ( ) ] -> addColumn ( $ action -> getColumn ( ) ) ; } if ( $ action instanceof AddIndex ) { $ this -> tableCreates [ $ table -> getName ( ) ] -> addIndex ( $ action -> getIndex ( ) ) ; } } ) ; }
Collects all table creation actions from the given intent
3,962
protected function gatherUpdates ( $ actions ) { collection ( $ actions ) -> filter ( function ( $ action ) { return $ action instanceof AddColumn || $ action instanceof ChangeColumn || $ action instanceof RemoveColumn || $ action instanceof RenameColumn ; } ) -> reject ( function ( $ action ) { return isset ( $ this -> tableCreates [ $ action -> getTable ( ) -> getName ( ) ] ) ; } ) -> each ( function ( $ action ) { $ table = $ action -> getTable ( ) ; $ name = $ table -> getName ( ) ; if ( ! isset ( $ this -> tableUpdates [ $ name ] ) ) { $ this -> tableUpdates [ $ name ] = new AlterTable ( $ table ) ; } $ this -> tableUpdates [ $ name ] -> addAction ( $ action ) ; } ) ; }
Collects all alter table actions from the given intent
3,963
protected function gatherTableMoves ( $ actions ) { collection ( $ actions ) -> filter ( function ( $ action ) { return $ action instanceof DropTable || $ action instanceof RenameTable || $ action instanceof ChangePrimaryKey || $ action instanceof ChangeComment ; } ) -> each ( function ( $ action ) { $ table = $ action -> getTable ( ) ; $ name = $ table -> getName ( ) ; if ( ! isset ( $ this -> tableMoves [ $ name ] ) ) { $ this -> tableMoves [ $ name ] = new AlterTable ( $ table ) ; } $ this -> tableMoves [ $ name ] -> addAction ( $ action ) ; } ) ; }
Collects all alter table drop and renames from the given intent
3,964
protected function gatherIndexes ( $ actions ) { collection ( $ actions ) -> filter ( function ( $ action ) { return $ action instanceof AddIndex || $ action instanceof DropIndex ; } ) -> reject ( function ( $ action ) { return isset ( $ this -> tableCreates [ $ action -> getTable ( ) -> getName ( ) ] ) ; } ) -> each ( function ( $ action ) { $ table = $ action -> getTable ( ) ; $ name = $ table -> getName ( ) ; if ( ! isset ( $ this -> indexes [ $ name ] ) ) { $ this -> indexes [ $ name ] = new AlterTable ( $ table ) ; } $ this -> indexes [ $ name ] -> addAction ( $ action ) ; } ) ; }
Collects all index creation and drops from the given intent
3,965
protected function gatherConstraints ( $ actions ) { collection ( $ actions ) -> filter ( function ( $ action ) { return $ action instanceof AddForeignKey || $ action instanceof DropForeignKey ; } ) -> each ( function ( $ action ) { $ table = $ action -> getTable ( ) ; $ name = $ table -> getName ( ) ; if ( ! isset ( $ this -> constraints [ $ name ] ) ) { $ this -> constraints [ $ name ] = new AlterTable ( $ table ) ; } $ this -> constraints [ $ name ] -> addAction ( $ action ) ; } ) ; }
Collects all foreign key creation and drops from the given intent
3,966
public static function build ( Table $ table , array $ columns = [ ] ) { $ index = new Index ( ) ; $ index -> setColumns ( $ columns ) ; return new static ( $ table , $ index ) ; }
Creates a new DropIndex object after assembling the passed arguments .
3,967
public static function buildFromName ( Table $ table , $ name ) { $ index = new Index ( ) ; $ index -> setName ( $ name ) ; return new static ( $ table , $ index ) ; }
Creates a new DropIndex when the name of the index to drop is known .
3,968
public static function build ( Table $ table , $ columnName , $ type = null , $ options = [ ] ) { $ column = new Column ( ) ; $ column -> setName ( $ columnName ) ; $ column -> setType ( $ type ) ; $ column -> setOptions ( $ options ) ; return new static ( $ table , $ column ) ; }
Returns a new AddColumn object after assembling the given commands
3,969
protected function getClass ( $ name ) { if ( empty ( $ this -> adapters [ $ name ] ) ) { throw new \ RuntimeException ( sprintf ( 'Adapter "%s" has not been registered' , $ name ) ) ; } return $ this -> adapters [ $ name ] ; }
Get an adapter class by name .
3,970
protected function getWrapperClass ( $ name ) { if ( empty ( $ this -> wrappers [ $ name ] ) ) { throw new \ RuntimeException ( sprintf ( 'Wrapper "%s" has not been registered' , $ name ) ) ; } return $ this -> wrappers [ $ name ] ; }
Get a wrapper class by name .
3,971
public function preFlightCheck ( $ direction = null ) { if ( method_exists ( $ this , MigrationInterface :: CHANGE ) ) { if ( method_exists ( $ this , MigrationInterface :: UP ) || method_exists ( $ this , MigrationInterface :: DOWN ) ) { $ this -> output -> writeln ( sprintf ( '<comment>warning</comment> Migration contains both change() and/or up()/down() methods. <options=bold>Ignoring up() and down()</>.' ) ) ; } } }
Perform checks on the migration print a warning if there are potential problems .
3,972
public function postFlightCheck ( $ direction = null ) { foreach ( $ this -> tables as $ table ) { if ( $ table -> hasPendingActions ( ) ) { throw new \ RuntimeException ( 'Migration has pending actions after execution!' ) ; } } }
Perform checks on the migration after completion
3,973
protected function locateConfigFile ( InputInterface $ input ) { $ configFile = $ input -> getOption ( 'configuration' ) ; $ useDefault = false ; if ( $ configFile === null || $ configFile === false ) { $ useDefault = true ; } $ cwd = getcwd ( ) ; $ locator = new FileLocator ( [ $ cwd . DIRECTORY_SEPARATOR ] ) ; if ( ! $ useDefault ) { return $ locator -> locate ( $ configFile , $ cwd , $ first = true ) ; } $ possibleConfigFiles = [ 'phinx.php' , 'phinx.json' , 'phinx.yml' ] ; foreach ( $ possibleConfigFiles as $ configFile ) { try { return $ locator -> locate ( $ configFile , $ cwd , $ first = true ) ; } catch ( \ InvalidArgumentException $ exception ) { $ lastException = $ exception ; } } throw $ lastException ; }
Returns config file path
3,974
protected function verifyMigrationDirectory ( $ path ) { if ( ! is_dir ( $ path ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Migration directory "%s" does not exist' , $ path ) ) ; } if ( ! is_writable ( $ path ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Migration directory "%s" is not writable' , $ path ) ) ; } }
Verify that the migration directory exists and is writable .
3,975
protected function verifySeedDirectory ( $ path ) { if ( ! is_dir ( $ path ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Seed directory "%s" does not exist' , $ path ) ) ; } if ( ! is_writable ( $ path ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Seed directory "%s" is not writable' , $ path ) ) ; } }
Verify that the seed directory exists and is writable .
3,976
protected function execute ( InputInterface $ input , OutputInterface $ output ) { $ this -> bootstrap ( $ input , $ output ) ; $ seedSet = $ input -> getOption ( 'seed' ) ; $ environment = $ input -> getOption ( 'environment' ) ; if ( $ environment === null ) { $ environment = $ this -> getConfig ( ) -> getDefaultEnvironment ( ) ; $ output -> writeln ( '<comment>warning</comment> no environment specified, defaulting to: ' . $ environment ) ; } else { $ output -> writeln ( '<info>using environment</info> ' . $ environment ) ; } $ envOptions = $ this -> getConfig ( ) -> getEnvironment ( $ environment ) ; if ( isset ( $ envOptions [ 'adapter' ] ) ) { $ output -> writeln ( '<info>using adapter</info> ' . $ envOptions [ 'adapter' ] ) ; } if ( isset ( $ envOptions [ 'wrapper' ] ) ) { $ output -> writeln ( '<info>using wrapper</info> ' . $ envOptions [ 'wrapper' ] ) ; } if ( isset ( $ envOptions [ 'name' ] ) ) { $ output -> writeln ( '<info>using database</info> ' . $ envOptions [ 'name' ] ) ; } else { $ output -> writeln ( '<error>Could not determine database name! Please specify a database name in your config file.</error>' ) ; return ; } if ( isset ( $ envOptions [ 'table_prefix' ] ) ) { $ output -> writeln ( '<info>using table prefix</info> ' . $ envOptions [ 'table_prefix' ] ) ; } if ( isset ( $ envOptions [ 'table_suffix' ] ) ) { $ output -> writeln ( '<info>using table suffix</info> ' . $ envOptions [ 'table_suffix' ] ) ; } $ start = microtime ( true ) ; if ( empty ( $ seedSet ) ) { $ this -> getManager ( ) -> seed ( $ environment ) ; } else { foreach ( $ seedSet as $ seed ) { $ this -> getManager ( ) -> seed ( $ environment , trim ( $ seed ) ) ; } } $ end = microtime ( true ) ; $ output -> writeln ( '' ) ; $ output -> writeln ( '<comment>All Done. Took ' . sprintf ( '%.4fs' , $ end - $ start ) . '</comment>' ) ; }
Run database seeders .
3,977
protected function getDeclaringSql ( $ tableName ) { $ rows = $ this -> fetchAll ( 'select * from sqlite_master where `type` = \'table\'' ) ; $ sql = '' ; foreach ( $ rows as $ table ) { if ( $ table [ 'tbl_name' ] === $ tableName ) { $ sql = $ table [ 'sql' ] ; } } return $ sql ; }
Returns the original CREATE statement for the give table
3,978
protected function copyDataToNewTable ( $ tableName , $ tmpTableName , $ writeColumns , $ selectColumns ) { $ sql = sprintf ( 'INSERT INTO %s(%s) SELECT %s FROM %s' , $ this -> quoteTableName ( $ tableName ) , implode ( ', ' , $ writeColumns ) , implode ( ', ' , $ selectColumns ) , $ this -> quoteTableName ( $ tmpTableName ) ) ; $ this -> execute ( $ sql ) ; }
Copies all the data from a tmp table to another table
3,979
protected function copyAndDropTmpTable ( $ instructions , $ tableName ) { $ instructions -> addPostStep ( function ( $ state ) use ( $ tableName ) { $ this -> copyDataToNewTable ( $ tableName , $ state [ 'tmpTableName' ] , $ state [ 'writeColumns' ] , $ state [ 'selectColumns' ] ) ; $ this -> execute ( sprintf ( 'DROP TABLE %s' , $ this -> quoteTableName ( $ state [ 'tmpTableName' ] ) ) ) ; return $ state ; } ) ; return $ instructions ; }
Modifies the passed instructions to copy all data from the tmp table into the provided table and then drops the tmp table .
3,980
protected function calculateNewTableColumns ( $ tableName , $ columnName , $ newColumnName ) { $ columns = $ this -> fetchAll ( sprintf ( 'pragma table_info(%s)' , $ this -> quoteTableName ( $ tableName ) ) ) ; $ selectColumns = [ ] ; $ writeColumns = [ ] ; $ columnType = null ; $ found = false ; foreach ( $ columns as $ column ) { $ selectName = $ column [ 'name' ] ; $ writeName = $ selectName ; if ( $ selectName == $ columnName ) { $ writeName = $ newColumnName ; $ found = true ; $ columnType = $ column [ 'type' ] ; $ selectName = $ newColumnName === false ? $ newColumnName : $ selectName ; } $ selectColumns [ ] = $ selectName ; $ writeColumns [ ] = $ writeName ; } $ selectColumns = array_filter ( $ selectColumns , 'strlen' ) ; $ writeColumns = array_filter ( $ writeColumns , 'strlen' ) ; $ selectColumns = array_map ( [ $ this , 'quoteColumnName' ] , $ selectColumns ) ; $ writeColumns = array_map ( [ $ this , 'quoteColumnName' ] , $ writeColumns ) ; if ( ! $ found ) { throw new \ InvalidArgumentException ( sprintf ( 'The specified column doesn\'t exist: ' . $ columnName ) ) ; } return compact ( 'writeColumns' , 'selectColumns' , 'columnType' ) ; }
Returns the columns and type to use when copying a table to another in the process of altering a table
3,981
protected function beginAlterByCopyTable ( $ tableName ) { $ instructions = new AlterInstructions ( ) ; $ instructions -> addPostStep ( function ( $ state ) use ( $ tableName ) { $ createSQL = $ this -> getDeclaringSql ( $ tableName ) ; $ tmpTableName = 'tmp_' . $ tableName ; $ this -> execute ( sprintf ( 'ALTER TABLE %s RENAME TO %s' , $ this -> quoteTableName ( $ tableName ) , $ this -> quoteTableName ( $ tmpTableName ) ) ) ; return compact ( 'createSQL' , 'tmpTableName' ) + $ state ; } ) ; return $ instructions ; }
Returns the initial instructions to alter a table using the rename - alter - copy strategy
3,982
protected function getIndexSqlDefinition ( Table $ table , Index $ index ) { if ( $ index -> getType ( ) === Index :: UNIQUE ) { $ def = 'UNIQUE INDEX' ; } else { $ def = 'INDEX' ; } if ( is_string ( $ index -> getName ( ) ) ) { $ indexName = $ index -> getName ( ) ; } else { $ indexName = $ table -> getName ( ) . '_' ; foreach ( $ index -> getColumns ( ) as $ column ) { $ indexName .= $ column . '_' ; } $ indexName .= 'index' ; } $ def .= ' `' . $ indexName . '`' ; return $ def ; }
Gets the SQLite Index Definition for an Index object .
3,983
protected function getForeignKeySqlDefinition ( ForeignKey $ foreignKey ) { $ def = '' ; if ( $ foreignKey -> getConstraint ( ) ) { $ def .= ' CONSTRAINT ' . $ this -> quoteColumnName ( $ foreignKey -> getConstraint ( ) ) ; } else { $ columnNames = [ ] ; foreach ( $ foreignKey -> getColumns ( ) as $ column ) { $ columnNames [ ] = $ this -> quoteColumnName ( $ column ) ; } $ def .= ' FOREIGN KEY (' . implode ( ',' , $ columnNames ) . ')' ; $ refColumnNames = [ ] ; foreach ( $ foreignKey -> getReferencedColumns ( ) as $ column ) { $ refColumnNames [ ] = $ this -> quoteColumnName ( $ column ) ; } $ def .= ' REFERENCES ' . $ this -> quoteTableName ( $ foreignKey -> getReferencedTable ( ) -> getName ( ) ) . ' (' . implode ( ',' , $ refColumnNames ) . ')' ; if ( $ foreignKey -> getOnDelete ( ) ) { $ def .= ' ON DELETE ' . $ foreignKey -> getOnDelete ( ) ; } if ( $ foreignKey -> getOnUpdate ( ) ) { $ def .= ' ON UPDATE ' . $ foreignKey -> getOnUpdate ( ) ; } } return $ def ; }
Gets the SQLite Foreign Key Definition for an ForeignKey object .
3,984
protected function execute ( InputInterface $ input , OutputInterface $ output ) { $ path = $ this -> resolvePath ( $ input ) ; $ format = strtolower ( $ input -> getOption ( 'format' ) ) ; $ this -> writeConfig ( $ path , $ format ) ; $ output -> writeln ( "<info>created</info> {$path}" ) ; }
Initializes the application .
3,985
public function getTargetFromDate ( $ date ) { if ( ! preg_match ( '/^\d{4,14}$/' , $ date ) ) { throw new \ InvalidArgumentException ( 'Invalid date. Format is YYYY[MM[DD[HH[II[SS]]]]].' ) ; } $ dateStrlenToAppend = [ 14 => '' , 12 => '00' , 10 => '0000' , 8 => '000000' , 6 => '01000000' , 4 => '0101000000' , ] ; if ( ! isset ( $ dateStrlenToAppend [ strlen ( $ date ) ] ) ) { throw new \ InvalidArgumentException ( 'Invalid date. Format is YYYY[MM[DD[HH[II[SS]]]]].' ) ; } $ target = $ date . $ dateStrlenToAppend [ strlen ( $ date ) ] ; $ dateTime = \ DateTime :: createFromFormat ( 'YmdHis' , $ target ) ; if ( $ dateTime === false ) { throw new \ InvalidArgumentException ( 'Invalid date. Format is YYYY[MM[DD[HH[II[SS]]]]].' ) ; } return $ dateTime -> format ( 'YmdHis' ) ; }
Get Target from Date
3,986
public function getStatus ( $ env = null ) { $ command = [ 'status' ] ; if ( $ env ? : $ this -> hasOption ( 'environment' ) ) { $ command += [ '-e' => $ env ? : $ this -> getOption ( 'environment' ) ] ; } if ( $ this -> hasOption ( 'configuration' ) ) { $ command += [ '-c' => $ this -> getOption ( 'configuration' ) ] ; } if ( $ this -> hasOption ( 'parser' ) ) { $ command += [ '-p' => $ this -> getOption ( 'parser' ) ] ; } return $ this -> executeRun ( $ command ) ; }
Returns the output from running the status command .
3,987
public function getMigrate ( $ env = null , $ target = null ) { $ command = [ 'migrate' ] ; if ( $ env ? : $ this -> hasOption ( 'environment' ) ) { $ command += [ '-e' => $ env ? : $ this -> getOption ( 'environment' ) ] ; } if ( $ this -> hasOption ( 'configuration' ) ) { $ command += [ '-c' => $ this -> getOption ( 'configuration' ) ] ; } if ( $ this -> hasOption ( 'parser' ) ) { $ command += [ '-p' => $ this -> getOption ( 'parser' ) ] ; } if ( $ target ) { $ command += [ '-t' => $ target ] ; } return $ this -> executeRun ( $ command ) ; }
Returns the output from running the migrate command .
3,988
public function getRollback ( $ env = null , $ target = null ) { $ command = [ 'rollback' ] ; if ( $ env ? : $ this -> hasOption ( 'environment' ) ) { $ command += [ '-e' => $ env ? : $ this -> getOption ( 'environment' ) ] ; } if ( $ this -> hasOption ( 'configuration' ) ) { $ command += [ '-c' => $ this -> getOption ( 'configuration' ) ] ; } if ( $ this -> hasOption ( 'parser' ) ) { $ command += [ '-p' => $ this -> getOption ( 'parser' ) ] ; } if ( isset ( $ target ) ) { $ command += [ '-t' => $ target ] ; } return $ this -> executeRun ( $ command ) ; }
Returns the output from running the rollback command .
3,989
protected function getOption ( $ key ) { if ( ! isset ( $ this -> options [ $ key ] ) ) { return null ; } return $ this -> options [ $ key ] ; }
Get option from options array
3,990
protected function executeRun ( array $ command ) { $ stream = fopen ( 'php://temp' , 'w+' ) ; $ this -> exit_code = $ this -> app -> doRun ( new ArrayInput ( $ command ) , new StreamOutput ( $ stream ) ) ; $ result = stream_get_contents ( $ stream , - 1 , 0 ) ; fclose ( $ stream ) ; return $ result ; }
Execute a command capturing output and storing the exit code .
3,991
public function setPrecisionAndScale ( $ precision , $ scale ) { $ this -> setLimit ( $ precision ) ; $ this -> scale = $ scale ; return $ this ; }
Sets the number precision and scale for decimal or float column .
3,992
public function setValues ( $ values ) { if ( ! is_array ( $ values ) ) { $ values = preg_split ( '/,\s*/' , $ values ) ; } $ this -> values = $ values ; return $ this ; }
Sets field values .
3,993
public function setCollation ( $ collation ) { $ allowedTypes = [ AdapterInterface :: PHINX_TYPE_CHAR , AdapterInterface :: PHINX_TYPE_STRING , AdapterInterface :: PHINX_TYPE_TEXT , ] ; if ( ! in_array ( $ this -> getType ( ) , $ allowedTypes ) ) { throw new \ UnexpectedValueException ( 'Collation may be set only for types: ' . implode ( ', ' , $ allowedTypes ) ) ; } $ this -> collation = $ collation ; return $ this ; }
Sets the column collation .
3,994
public function setEncoding ( $ encoding ) { $ allowedTypes = [ AdapterInterface :: PHINX_TYPE_CHAR , AdapterInterface :: PHINX_TYPE_STRING , AdapterInterface :: PHINX_TYPE_TEXT , ] ; if ( ! in_array ( $ this -> getType ( ) , $ allowedTypes ) ) { throw new \ UnexpectedValueException ( 'Character set may be set only for types: ' . implode ( ', ' , $ allowedTypes ) ) ; } $ this -> encoding = $ encoding ; return $ this ; }
Sets the column character set .
3,995
public function setOptions ( $ options ) { $ validOptions = $ this -> getValidOptions ( ) ; $ aliasOptions = $ this -> getAliasedOptions ( ) ; foreach ( $ options as $ option => $ value ) { if ( isset ( $ aliasOptions [ $ option ] ) ) { $ option = $ aliasOptions [ $ option ] ; } if ( ! in_array ( $ option , $ validOptions , true ) ) { throw new \ RuntimeException ( sprintf ( '"%s" is not a valid column option.' , $ option ) ) ; } $ method = 'set' . ucfirst ( $ option ) ; $ this -> $ method ( $ value ) ; } return $ this ; }
Utility method that maps an array of column options to this objects methods .
3,996
public static function fromYaml ( $ configFilePath ) { $ configFile = file_get_contents ( $ configFilePath ) ; $ configArray = Yaml :: parse ( $ configFile ) ; if ( ! is_array ( $ configArray ) ) { throw new \ RuntimeException ( sprintf ( 'File \'%s\' must be valid YAML' , $ configFilePath ) ) ; } return new static ( $ configArray , $ configFilePath ) ; }
Create a new instance of the config class using a Yaml file path .
3,997
public static function fromJson ( $ configFilePath ) { $ configArray = json_decode ( file_get_contents ( $ configFilePath ) , true ) ; if ( ! is_array ( $ configArray ) ) { throw new \ RuntimeException ( sprintf ( 'File \'%s\' must be valid JSON' , $ configFilePath ) ) ; } return new static ( $ configArray , $ configFilePath ) ; }
Create a new instance of the config class using a JSON file path .
3,998
public static function fromPhp ( $ configFilePath ) { ob_start ( ) ; $ configArray = include ( $ configFilePath ) ; ob_end_clean ( ) ; if ( ! is_array ( $ configArray ) ) { throw new \ RuntimeException ( sprintf ( 'PHP file \'%s\' must return an array' , $ configFilePath ) ) ; } return new static ( $ configArray , $ configFilePath ) ; }
Create a new instance of the config class using a PHP file path .
3,999
protected function replaceTokens ( array $ arr ) { $ tokens = [ ] ; foreach ( $ _SERVER as $ varname => $ varvalue ) { if ( 0 === strpos ( $ varname , 'PHINX_' ) ) { $ tokens [ '%%' . $ varname . '%%' ] = $ varvalue ; } } $ tokens [ '%%PHINX_CONFIG_PATH%%' ] = $ this -> getConfigFilePath ( ) ; $ tokens [ '%%PHINX_CONFIG_DIR%%' ] = dirname ( $ this -> getConfigFilePath ( ) ) ; return $ this -> recurseArrayForTokens ( $ arr , $ tokens ) ; }
Replace tokens in the specified array .