idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
50,900
protected function closeDoctrineConnections ( ) { foreach ( app ( 'db' ) -> getConnections ( ) as $ connection ) { call_user_func ( \ Closure :: bind ( function ( ) { $ this -> doctrineConnection = null ; } , $ connection , $ connection ) ) ; } }
Close all Doctrine connections in order to prevent Too many connections errors when running many tests .
50,901
public function seed ( ) { $ this -> addLastModel ( ) ; $ insertedPKs = [ ] ; foreach ( $ this -> quantities as $ modelClass => $ quantity ) { $ attributes = [ ] ; $ pivotRecords = [ ] ; $ translations = [ ] ; $ this -> modelPopulators [ $ modelClass ] -> setGuessedColumnFormatters ( true ) ; for ( $ i = 0 ; $ i < $ quantity ; $ i ++ ) { list ( $ createdModel , $ pivotTables , $ currentPivotRecords , $ foreignKeys ) = $ this -> modelPopulators [ $ modelClass ] -> getInsertRecords ( $ insertedPKs ) ; if ( $ primaryKey = $ createdModel -> getKey ( ) ) { $ insertedPKs [ $ modelClass ] [ ] = $ primaryKey ; } $ attributes [ ] = $ createdModel -> getAttributes ( ) ; if ( $ currentPivotRecords ) { $ pivotRecords [ ] = $ currentPivotRecords ; } if ( $ createdModel -> relationLoaded ( 'translations' ) ) { foreach ( $ createdModel -> translations as $ translation ) { $ translations [ $ i ] [ ] = $ translation -> getAttributes ( ) ; } } } foreach ( array_chunk ( $ attributes , 500 ) as $ chunk ) { $ createdModel -> insert ( $ chunk ) ; } if ( ! isset ( $ insertedPKs [ $ modelClass ] ) ) { $ insertedPKs [ $ modelClass ] = $ this -> getInsertedPKs ( $ createdModel , count ( $ attributes ) ) ; } $ this -> insertPivotRecords ( $ createdModel -> getConnection ( ) , $ pivotTables , $ pivotRecords , $ foreignKeys , $ insertedPKs [ $ modelClass ] ) ; $ this -> insertTranslations ( $ createdModel , $ translations , $ insertedPKs [ $ modelClass ] ) ; } $ this -> forgetAddedModels ( ) ; $ this -> closeDoctrineConnections ( ) ; return $ insertedPKs ; }
Populate a database minimizing the number of queries .
50,902
protected function setColumns ( $ model ) { $ schema = $ model -> getConnection ( ) -> getDoctrineSchemaManager ( ) ; $ platform = $ schema -> getDatabasePlatform ( ) ; $ platform -> registerDoctrineTypeMapping ( 'enum' , 'string' ) ; list ( $ table , $ database ) = $ this -> getTableAndDatabase ( $ model ) ; $ this -> columns = $ model -> getConnection ( ) -> getDoctrineConnection ( ) -> fetchAll ( $ platform -> getListTableColumnsSQL ( $ table , $ database ) ) ; $ this -> rejectVirtualColumns ( ) ; $ columns = $ this -> columns ; $ this -> columns = call_user_func ( \ Closure :: bind ( function ( ) use ( $ table , $ database , $ columns ) { return $ this -> _getPortableTableColumnList ( $ table , $ database , $ columns ) ; } , $ schema , $ schema ) ) ; return $ this -> unquoteColumnNames ( $ platform -> getIdentifierQuoteCharacter ( ) ) ; }
Get the columns of a model s table .
50,903
protected function getTableAndDatabase ( $ model ) { $ table = $ model -> getConnection ( ) -> getTablePrefix ( ) . $ model -> getTable ( ) ; $ database = null ; if ( strpos ( $ table , '.' ) ) { list ( $ database , $ table ) = explode ( '.' , $ table ) ; } return [ $ table , $ database ] ; }
Get the table and database names of a model .
50,904
protected function unquoteColumnNames ( $ quoteCharacter ) { foreach ( $ this -> columns as $ columnName => $ columnData ) { if ( Str :: startsWith ( $ columnName , $ quoteCharacter ) ) { $ this -> columns [ substr ( $ columnName , 1 , - 1 ) ] = Arr :: pull ( $ this -> columns , $ columnName ) ; } } }
Unquote column names that have been quoted by Doctrine because they are reserved keywords .
50,905
protected function getGuessedColumnFormatters ( $ model , $ seeding , $ populateForeignKeys = false ) { $ this -> setColumns ( $ model ) ; $ formatters = [ ] ; $ nameGuesser = new Name ( $ this -> generator ) ; $ columnTypeGuesser = new ColumnTypeGuesser ( $ this -> generator ) ; foreach ( $ this -> columns as $ columnName => $ column ) { if ( $ model instanceof Model && $ columnName === $ model -> getKeyName ( ) && $ column -> getAutoincrement ( ) ) { continue ; } if ( method_exists ( $ model , 'getDeletedAtColumn' ) && $ columnName === $ model -> getDeletedAtColumn ( ) ) { continue ; } if ( ! $ seeding && $ model instanceof Model && ( $ columnName === $ model -> getCreatedAtColumn ( ) || $ columnName === $ model -> getUpdatedAtColumn ( ) ) ) { continue ; } $ formatter = $ nameGuesser -> guessFormat ( $ columnName , $ column -> getLength ( ) ) ? : $ columnTypeGuesser -> guessFormat ( $ column , $ model -> getTable ( ) ) ; if ( ! $ formatter ) { continue ; } if ( $ column -> getNotnull ( ) || ! $ seeding ) { $ formatters [ $ columnName ] = $ formatter ; } else { $ formatters [ $ columnName ] = function ( ) use ( $ formatter ) { return rand ( 0 , 1 ) ? $ formatter ( ) : null ; } ; } } return $ populateForeignKeys ? $ this -> populateForeignKeys ( $ formatters , $ seeding ) : $ formatters ; }
Guess the column formatters based on the columns names or types or on whether they are a foreign key .
50,906
protected function populateForeignKeys ( array $ formatters , $ seeding ) { foreach ( $ this -> relations as $ relation ) { if ( $ relation instanceof MorphTo ) { $ this -> associateMorphTo ( $ formatters , $ relation , $ seeding ) ; } elseif ( $ relation instanceof BelongsTo ) { $ this -> associateBelongsTo ( $ formatters , $ relation , $ seeding ) ; } } return $ formatters ; }
Set the closures that will be used to populate the foreign keys using the previously added related models .
50,907
protected function associateBelongsTo ( array & $ formatters , BelongsTo $ relation , $ seeding ) { $ relatedClass = get_class ( $ relation -> getRelated ( ) ) ; $ foreignKey = $ relation -> { $ this -> getBelongsToForeignKeyNameMethod ( ) } ( ) ; if ( ! isset ( $ this -> columns [ $ foreignKey ] ) ) { return ; } $ alwaysAssociate = $ this -> columns [ $ foreignKey ] -> getNotnull ( ) || ! $ seeding ; $ formatters [ $ foreignKey ] = function ( $ model , $ insertedPKs ) use ( $ relatedClass , $ alwaysAssociate ) { if ( ! isset ( $ insertedPKs [ $ relatedClass ] ) ) { return null ; } if ( $ alwaysAssociate ) { return $ this -> generator -> randomElement ( $ insertedPKs [ $ relatedClass ] ) ; } return $ this -> generator -> optional ( ) -> randomElement ( $ insertedPKs [ $ relatedClass ] ) ; } ; }
Set the closure that will be used to populate the foreign key of a Belongs To relation .
50,908
protected function associateMorphTo ( array & $ formatters , MorphTo $ relation , $ seeding ) { $ foreignKey = last ( explode ( '.' , $ relation -> { $ this -> getBelongsToForeignKeyNameMethod ( ) } ( ) ) ) ; $ morphType = last ( explode ( '.' , $ relation -> getMorphType ( ) ) ) ; $ alwaysAssociate = $ this -> columns [ $ foreignKey ] -> getNotnull ( ) || ! $ seeding ; $ formatters [ $ foreignKey ] = function ( $ model , $ insertedPKs ) use ( $ alwaysAssociate ) { if ( ! ( $ morphOwner = $ this -> pickMorphOwner ( $ insertedPKs , $ alwaysAssociate ) ) ) { return null ; } $ randomElement = $ this -> generator -> randomElement ( $ insertedPKs [ $ morphOwner ] ) ; return $ randomElement ; } ; $ formatters [ $ morphType ] = function ( $ model , $ insertedPKs ) use ( $ alwaysAssociate ) { if ( ! ( $ morphOwner = $ this -> pickMorphOwner ( $ insertedPKs , $ alwaysAssociate ) ) ) { return null ; } return ( new $ morphOwner ) -> getMorphClass ( ) ; } ; }
Set the closure that will be used to populate the foreign key of a Morph To relation .
50,909
protected function pickMorphOwner ( array $ insertedPKs , $ alwaysAssociate ) { $ owners = $ this -> populator -> getMorphToClasses ( get_class ( $ this -> model ) ) ; if ( $ this -> morphOwner === false ) { if ( ! $ alwaysAssociate && rand ( 0 , 1 ) ) { return $ this -> morphOwner = null ; } $ owners = array_filter ( $ owners , function ( $ owner ) use ( $ insertedPKs ) { return isset ( $ insertedPKs [ $ owner ] ) ; } ) ; return $ this -> morphOwner = $ this -> generator -> randomElement ( $ owners ) ; } return tap ( $ this -> morphOwner , function ( ) { $ this -> morphOwner = false ; } ) ; }
Select a random owning class for a Morph To relation .
50,910
public function setGuessedColumnFormatters ( $ seeding ) { $ this -> guessedFormatters = $ this -> unsetForeignKeys ( $ this -> getGuessedColumnFormatters ( $ this -> relation , $ seeding ) ) ; }
Set the guessed column formatters for extra attributes of the pivot table .
50,911
protected function getForeignKeyName ( ) { if ( method_exists ( $ this -> relation , 'getQualifiedForeignPivotKeyName' ) ) { $ method = 'getQualifiedForeignPivotKeyName' ; } elseif ( method_exists ( $ this -> relation , 'getQualifiedForeignKeyName' ) ) { $ method = 'getQualifiedForeignKeyName' ; } else { $ method = 'getForeignKey' ; } ; return last ( explode ( '.' , $ this -> relation -> $ method ( ) ) ) ; }
Get the foreign key for the relation .
50,912
protected function getRelatedKeyName ( ) { if ( method_exists ( $ this -> relation , 'getQualifiedRelatedPivotKeyName' ) ) { $ method = 'getQualifiedRelatedPivotKeyName' ; } elseif ( method_exists ( $ this -> relation , 'getQualifiedRelatedKeyName' ) ) { $ method = 'getQualifiedRelatedKeyName' ; } else { $ method = 'getOtherKey' ; } ; return last ( explode ( '.' , $ this -> relation -> $ method ( ) ) ) ; }
Get the related key for the relation .
50,913
public function execute ( Model $ currentParent , array $ insertedPKs ) { if ( ! isset ( $ insertedPKs [ $ this -> relatedClass ] ) ) { return ; } $ this -> updateParentKey ( $ currentParent ) ; $ this -> relation -> attach ( collect ( $ this -> pickRelatedIds ( $ insertedPKs ) ) -> mapWithKeys ( function ( $ relatedId ) use ( $ insertedPKs , $ currentParent ) { return [ $ relatedId => $ this -> getExtraAttributes ( $ insertedPKs , $ currentParent ) ] ; } ) -> all ( ) ) ; }
Populate the pivot table .
50,914
protected function updateParentKey ( Model $ currentParent ) { $ parentModel = $ this -> relation -> getParent ( ) ; $ keyName = $ parentModel -> getKeyName ( ) ; $ parentModel -> $ keyName = $ currentParent -> $ keyName ; }
Set the primary key of the parent model to the one of the model being built . This is necessary because the relation was instantiated on ModelPopulator s construction .
50,915
protected function pickRelatedIds ( array $ insertedPKs ) { return $ this -> generator -> randomElements ( $ insertedPKs [ $ this -> relatedClass ] , $ this -> getQuantity ( $ insertedPKs ) ) ; }
Select the related ids to attach .
50,916
protected function getQuantity ( array $ insertedPKs ) { if ( is_int ( $ this -> quantity ) ) { return $ this -> quantity ; } if ( $ this -> quantity === 'random' ) { return mt_rand ( 0 , count ( $ insertedPKs [ $ this -> relatedClass ] ) ) ; } return count ( $ insertedPKs [ $ this -> relatedClass ] ) ; }
Get the number of models to attach .
50,917
protected function getExtraAttributes ( array $ insertedPKs , Model $ currentParent ) { if ( ! $ this -> guessedFormatters ) { return [ ] ; } $ extra = array_merge ( $ this -> guessedFormatters , $ this -> customAttributes ) ; return $ this -> evaluateClosureFormatters ( $ extra , $ insertedPKs , $ currentParent ) ; }
Get the extra attributes .
50,918
protected function evaluateClosureFormatters ( array $ extra , array $ insertedPKs , Model $ currentParent ) { return array_map ( function ( $ formatter ) use ( $ insertedPKs , $ currentParent ) { return is_callable ( $ formatter ) ? $ formatter ( $ currentParent , $ insertedPKs ) : $ formatter ; } , $ extra ) ; }
Evaluate closure formatters .
50,919
public function bootstrapRelations ( ) { $ this -> relations = $ this -> getRelations ( ) ; foreach ( $ this -> relations as $ relation ) { if ( $ relation instanceof BelongsToMany ) { $ this -> setPivotPopulator ( $ relation ) ; } elseif ( $ relation instanceof MorphOneOrMany ) { $ this -> addMorphClass ( $ relation ) ; } } }
Set the model s relations and do some processing with them .
50,920
protected function getRelations ( ) { return collect ( get_class_methods ( $ this -> model ) ) -> reject ( function ( $ methodName ) { return method_exists ( Model :: class , $ methodName ) ; } ) -> filter ( function ( $ methodName ) { $ methodCode = $ this -> getMethodCode ( $ methodName ) ; return collect ( [ 'belongsTo' , 'morphTo' , 'morphOne' , 'morphMany' , 'belongsToMany' , 'morphedByMany' , ] ) -> contains ( function ( $ relationName ) use ( $ methodCode ) { return stripos ( $ methodCode , "\$this->$relationName(" ) ; } ) ; } ) -> map ( function ( $ methodName ) { return $ this -> model -> $ methodName ( ) ; } ) -> filter ( function ( $ relation ) { return $ relation instanceof Relation ; } ) -> all ( ) ; }
Get the model s relations .
50,921
protected function getMethodCode ( $ method ) { $ reflection = new \ ReflectionMethod ( $ this -> model , $ method ) ; $ file = new \ SplFileObject ( $ reflection -> getFileName ( ) ) ; $ file -> seek ( $ reflection -> getStartLine ( ) - 1 ) ; $ methodCode = '' ; while ( $ file -> key ( ) < $ reflection -> getEndLine ( ) ) { $ methodCode .= $ file -> current ( ) ; $ file -> next ( ) ; } $ methodCode = trim ( preg_replace ( '/\s\s+/' , '' , $ methodCode ) ) ; $ start = strpos ( $ methodCode , 'function(' ) ; $ length = strrpos ( $ methodCode , '}' ) - $ start + 1 ; return substr ( $ methodCode , $ start , $ length ) ; }
Get the source code of a method of the model .
50,922
protected function setPivotPopulator ( BelongsToMany $ relation ) { $ relatedClass = get_class ( $ relation -> getRelated ( ) ) ; if ( ! $ this -> populator -> wasAdded ( $ relatedClass ) ) { return ; } $ this -> pivotPopulators [ $ relatedClass ] = new PivotPopulator ( $ this , $ relation , $ this -> generator ) ; }
Set the PivotPopulator of a BelongsToMany relation .
50,923
public function pivotAttributes ( array $ pivotAttributes ) { foreach ( $ pivotAttributes as $ relatedClass => $ attributes ) { $ this -> pivotPopulators [ $ relatedClass ] -> setCustomAttributes ( $ attributes ) ; } return $ this ; }
Set custom attributes that will override the formatters of the extra attributes of pivot tables .
50,924
protected function addMorphClass ( MorphOneOrMany $ relation ) { $ this -> populator -> addMorphClass ( get_class ( $ this -> model ) , get_class ( $ relation -> getRelated ( ) ) ) ; }
Save a potential owning class for a child class in a many - to - one or one - to - one polymorphic relation with it so that the child model will be associated to one of its owners when it is populated .
50,925
public function setGuessedColumnFormatters ( $ seeding ) { $ this -> guessedFormatters = $ this -> getGuessedColumnFormatters ( $ this -> model , $ seeding , true ) ; if ( $ this -> dimsavTranslatable ( ) ) { $ this -> guessDimsavFormatters ( $ seeding ) ; } else { $ this -> guessMultilingualFormatters ( ) ; } $ this -> setGuessedPivotFormatters ( $ seeding ) ; }
Set the guessed column formatters for the model being built .
50,926
public function setGuessedPivotFormatters ( $ seeding ) { foreach ( $ this -> pivotPopulators as $ pivotPopulator ) { $ pivotPopulator -> setGuessedColumnFormatters ( $ seeding ) ; if ( $ seeding ) { $ pivotPopulator -> attachRandomQuantity ( ) ; } } }
Set the guessed column formatters for the extra columns of the pivot tables of the BelongsToMany relations of the model being built .
50,927
protected function fillModel ( Model $ model , array $ insertedPKs ) { $ attributes = $ this -> mergeAttributes ( $ model ) ; $ closureAttributes = [ ] ; foreach ( $ attributes as $ key => $ value ) { if ( $ value instanceof \ Closure ) { $ closureAttributes [ $ key ] = $ value ; } else { $ model -> $ key = $ value ; } } foreach ( $ closureAttributes as $ key => $ value ) { $ model -> $ key = $ value ( $ model , $ insertedPKs ) ; } }
Fill a model using the available attributes .
50,928
protected function mergeAttributes ( Model $ model ) { $ factoryAttributes = $ this -> getFactoryAttributes ( $ model ) ; $ isTranslation = $ this -> isTranslation ( $ model ) ; return array_merge ( $ isTranslation ? $ this -> guessedTranslationFormatters : $ this -> guessedFormatters , $ factoryAttributes , $ isTranslation ? $ this -> customTranslatableAttributes : $ this -> customAttributes ) ; }
Merge the guessed factory and custom attributes .
50,929
protected function getFactoryAttributes ( Model $ model ) { $ factory = app ( Eloquent \ Factory :: class ) ; $ states = $ this -> isTranslation ( $ model ) ? $ this -> translationStates : $ this -> states ; $ modelClass = get_class ( $ model ) ; $ modelIsDefined = call_user_func ( \ Closure :: bind ( function ( ) use ( $ modelClass ) { return isset ( $ this -> definitions [ $ modelClass ] ) ; } , $ factory , $ factory ) ) ; if ( ! $ modelIsDefined ) { if ( ! $ states ) { return [ ] ; } $ factory -> define ( $ modelClass , function ( ) { return [ ] ; } ) ; } return $ factory -> raw ( $ modelClass , $ this -> getStateAttributes ( $ factory , $ states , $ modelClass ) ) ; }
Get the model factory attributes of the model being built .
50,930
protected function getStateAttributes ( $ factory , $ states , $ modelClass ) { return collect ( $ states ) -> flatMap ( function ( $ state ) use ( $ factory , $ modelClass ) { $ stateClosure = call_user_func ( \ Closure :: bind ( function ( ) use ( $ modelClass , $ state ) { if ( ! isset ( $ this -> states [ $ modelClass ] [ $ state ] ) ) { throw new \ InvalidArgumentException ( "Unable to locate [{$state}] state for [{$modelClass}]." ) ; } return $ this -> states [ $ modelClass ] [ $ state ] ; } , $ factory , $ factory ) ) ; return $ stateClosure ( $ this -> generator ) ; } ) -> all ( ) ; }
Get the factory state attributes of the model being built .
50,931
protected function callModifiers ( array $ insertedPKs ) { foreach ( $ this -> modifiers as $ modifier ) { $ modifier ( $ this -> model , $ insertedPKs ) ; } }
Call the modifiers .
50,932
public function raw ( $ customAttributes = [ ] ) { if ( is_string ( $ customAttributes ) ) { return $ this -> populator -> raw ( ... func_get_args ( ) ) ; } return $ this -> make ( $ customAttributes ) -> toArray ( ) ; }
Create the given model and convert it to an array .
50,933
public function create ( $ customAttributes = [ ] ) { if ( is_string ( $ customAttributes ) ) { return $ this -> populator -> create ( ... func_get_args ( ) ) ; } return $ this -> make ( $ customAttributes , true ) ; }
Create an instance of the given model and persist it to the database .
50,934
public function getOwners ( ) { return collect ( $ this -> belongsToRelations ( ) ) -> reject ( function ( $ relation ) { return array_key_exists ( $ relation -> { $ this -> getBelongsToForeignKeyNameMethod ( ) } ( ) , $ this -> customAttributes ) || array_key_exists ( $ relation -> { $ this -> getBelongsToForeignKeyNameMethod ( ) } ( ) , $ this -> getFactoryAttributes ( $ this -> model ) ) || $ relation -> getRelated ( ) instanceof $ this -> model || ! isset ( $ this -> columns [ $ relation -> getRelated ( ) -> getForeignKey ( ) ] ) ; } ) -> map ( function ( $ relation ) { return get_class ( $ relation -> getRelated ( ) ) ; } ) -> all ( ) ; }
Get the model s owners class names .
50,935
public function guessFormat ( Column $ column , $ tableName ) { switch ( $ column -> getType ( ) -> getName ( ) ) { case 'smallint' : return function ( ) { return mt_rand ( 0 , 65535 ) ; } ; case 'integer' : return function ( ) { return mt_rand ( 0 , intval ( '2147483647' ) ) ; } ; case 'bigint' : return function ( ) { return mt_rand ( 0 , intval ( '18446744073709551615' ) ) ; } ; case 'float' : return function ( ) { return mt_rand ( 0 , intval ( '4294967295' ) ) / mt_rand ( 1 , intval ( '4294967295' ) ) ; } ; case 'decimal' : $ maxDigits = $ column -> getPrecision ( ) ; $ maxDecimalDigits = $ column -> getScale ( ) ; $ max = 10 ** ( $ maxDigits - $ maxDecimalDigits ) ; return function ( ) use ( $ maxDecimalDigits , $ max ) { $ value = $ this -> generator -> randomFloat ( $ maxDecimalDigits , 0 , $ max ) ; if ( $ value == $ max ) { return $ max - ( 1 / $ maxDecimalDigits ) ; } return $ value ; } ; case 'string' : $ size = $ column -> getLength ( ) ? : 60 ; if ( $ size > 99 ) { $ size = 99 ; } return function ( ) use ( $ size , $ column , $ tableName ) { if ( $ size >= 5 ) { return $ this -> generator -> text ( $ size ) ; } $ columnName = "$tableName.{$column->getName()}" ; throw new \ InvalidArgumentException ( "$columnName is a string shorter than 5 characters," . " but Faker's text() can only generate text of at least 5 characters." . PHP_EOL . "Please specify a more accurate formatter for $columnName." ) ; } ; case 'text' : return function ( ) { return $ this -> generator -> text ; } ; case 'guid' : return function ( ) { return $ this -> generator -> uuid ; } ; case 'date' : case 'datetime' : case 'datetimetz' : return function ( ) { return $ this -> generator -> datetime ; } ; case 'time' : return function ( ) { return $ this -> generator -> time ; } ; case 'boolean' : return function ( ) { return $ this -> generator -> boolean ; } ; case 'json' : case 'json_array' : return function ( ) { return json_encode ( [ $ this -> generator -> word => $ this -> generator -> word ] ) ; } ; default : return null ; } }
Guess a column s formatter based on its type .
50,936
public static function parse ( string $ input , bool $ resultAsObject = false ) { try { $ data = self :: doParse ( $ input , $ resultAsObject ) ; } catch ( SyntaxErrorException $ e ) { $ exception = new ParseException ( $ e -> getMessage ( ) , - 1 , null , null , $ e ) ; if ( $ token = $ e -> getToken ( ) ) { $ exception -> setParsedLine ( $ token -> getLine ( ) ) ; } throw $ exception ; } return $ data ; }
Parses TOML into a PHP array .
50,937
public static function parseFile ( string $ filename , bool $ resultAsObject = false ) { if ( ! is_file ( $ filename ) ) { throw new ParseException ( sprintf ( 'File "%s" does not exist.' , $ filename ) ) ; } if ( ! is_readable ( $ filename ) ) { throw new ParseException ( sprintf ( 'File "%s" cannot be read.' , $ filename ) ) ; } try { $ data = self :: doParse ( file_get_contents ( $ filename ) , $ resultAsObject ) ; } catch ( SyntaxErrorException $ e ) { $ exception = new ParseException ( $ e -> getMessage ( ) ) ; $ exception -> setParsedFile ( $ filename ) ; if ( $ token = $ e -> getToken ( ) ) { $ exception -> setParsedLine ( $ token -> getLine ( ) ) ; } throw $ exception ; } return $ data ; }
Parses a TOML file into a PHP array .
50,938
public function addValue ( string $ key , $ val , string $ comment = '' ) : TomlBuilder { $ this -> currentKey = $ key ; $ this -> exceptionIfKeyEmpty ( $ key ) ; $ this -> addKey ( $ key ) ; if ( ! $ this -> isUnquotedKey ( $ key ) ) { $ key = '"' . $ key . '"' ; } $ line = "{$key} = {$this->dumpValue($val)}" ; if ( ! empty ( $ comment ) ) { $ line .= ' ' . $ this -> dumpComment ( $ comment ) ; } $ this -> append ( $ line , true ) ; return $ this ; }
Adds a key value pair
50,939
public function addTable ( string $ key ) : TomlBuilder { $ this -> exceptionIfKeyEmpty ( $ key ) ; $ addPreNewline = $ this -> currentLine > 0 ? true : false ; $ keyParts = explode ( '.' , $ key ) ; foreach ( $ keyParts as $ keyPart ) { $ this -> exceptionIfKeyEmpty ( $ keyPart , "Table: \"{$key}\"." ) ; $ this -> exceptionIfKeyIsNotUnquotedKey ( $ keyPart ) ; } $ line = "[{$key}]" ; $ this -> addTableKey ( $ key ) ; $ this -> append ( $ line , true , false , $ addPreNewline ) ; return $ this ; }
Adds a table .
50,940
public function addComment ( string $ comment ) : TomlBuilder { $ this -> append ( $ this -> dumpComment ( $ comment ) , true ) ; return $ this ; }
Adds a comment line
50,941
protected function getEscapedCharacters ( ) : array { if ( self :: $ escapedSpecialCharacters !== null ) { return self :: $ escapedSpecialCharacters ; } return self :: $ escapedSpecialCharacters = \ array_values ( self :: $ specialCharactersMapping ) ; }
Returns the escaped characters for basic strings
50,942
protected function getSpecialCharacters ( ) : array { if ( self :: $ specialCharacters !== null ) { return self :: $ specialCharacters ; } return self :: $ specialCharacters = \ array_keys ( self :: $ specialCharactersMapping ) ; }
Returns the special characters for basic strings
50,943
protected function addKey ( string $ key ) : void { if ( ! $ this -> keyStore -> isValidKey ( $ key ) ) { throw new DumpException ( "The key \"{$key}\" has already been defined previously." ) ; } $ this -> keyStore -> addKey ( $ key ) ; }
Adds a key to the store
50,944
protected function addTableKey ( string $ key ) : void { if ( ! $ this -> keyStore -> isValidTableKey ( $ key ) ) { throw new DumpException ( "The table key \"{$key}\" has already been defined previously." ) ; } if ( $ this -> keyStore -> isRegisteredAsArrayTableKey ( $ key ) ) { throw new DumpException ( "The table \"{$key}\" has already been defined as previous array of tables." ) ; } $ this -> keyStore -> addTableKey ( $ key ) ; }
Adds a table key to the store
50,945
protected function addArrayOfTableKey ( string $ key ) : void { if ( ! $ this -> keyStore -> isValidArrayTableKey ( $ key ) ) { throw new DumpException ( "The array of table key \"{$key}\" has already been defined previously." ) ; } if ( $ this -> keyStore -> isTableImplicitFromArryTable ( $ key ) ) { throw new DumpException ( "The key \"{$key}\" has been defined as a implicit table from a previous array of tables." ) ; } $ this -> keyStore -> addArrayTableKey ( $ key ) ; }
Adds an array of table key to the store
50,946
protected function dumpValue ( $ val ) : string { switch ( true ) { case is_string ( $ val ) : return $ this -> dumpString ( $ val ) ; case is_array ( $ val ) : return $ this -> dumpArray ( $ val ) ; case is_int ( $ val ) : return $ this -> dumpInteger ( $ val ) ; case is_float ( $ val ) : return $ this -> dumpFloat ( $ val ) ; case is_bool ( $ val ) : return $ this -> dumpBool ( $ val ) ; case $ val instanceof \ Datetime : return $ this -> dumpDatetime ( $ val ) ; default : throw new DumpException ( "Data type not supporter at the key: \"{$this->currentKey}\"." ) ; } }
Dumps a value
50,947
protected function append ( string $ val , bool $ addPostNewline = false , bool $ addIndentation = false , bool $ addPreNewline = false ) : void { if ( $ addPreNewline ) { $ this -> output .= "\n" ; ++ $ this -> currentLine ; } if ( $ addIndentation ) { $ val = $ this -> prefix . $ val ; } $ this -> output .= $ val ; if ( $ addPostNewline ) { $ this -> output .= "\n" ; ++ $ this -> currentLine ; } }
Adds content to the output
50,948
protected function getNextVersion ( $ resourceId ) { $ candidate = 0 ; foreach ( $ this -> getRevisions ( $ resourceId ) as $ revision ) { $ version = $ revision -> getVersion ( ) ; if ( is_numeric ( $ version ) && $ version > $ candidate ) { $ candidate = $ version ; } } return $ candidate + 1 ; }
Helper to determin suitable next version nr
50,949
static public function getPropertyStorageMap ( $ triples ) { $ referencer = ServiceManager :: getServiceManager ( ) -> get ( FileReferenceSerializer :: SERVICE_ID ) ; $ map = [ ] ; foreach ( $ triples as $ triple ) { if ( self :: isFileReference ( $ triple ) ) { $ source = $ referencer -> unserialize ( $ triple -> object ) ; $ map [ $ triple -> predicate ] = $ source -> getFileSystemId ( ) ; } } return $ map ; }
Determines origins of stored files
50,950
private function restCall ( $ uri , $ data ) { try { $ client = new Client ( [ 'base_uri' => $ this -> baseUrl ] ) ; $ response = $ client -> request ( 'POST' , $ uri , [ 'json' => $ data ] ) ; $ rawBody = $ response -> getBody ( ) -> getContents ( ) ; $ body = json_decode ( $ rawBody , true ) ; } catch ( RequestException $ e ) { $ response = $ e -> getResponse ( ) ; $ rawBody = is_null ( $ response ) ? '{"Status":-98,"message":"http connection error"}' : $ response -> getBody ( ) -> getContents ( ) ; $ body = json_decode ( $ rawBody , true ) ; } if ( ! isset ( $ result [ 'Status' ] ) ) { $ result [ 'Status' ] = - 99 ; } return $ body ; }
request rest and return the response .
50,951
public function request ( $ callbackURL , $ Amount , $ Description , $ Email = null , $ Mobile = null , $ additionalData = null ) { $ inputs = [ 'MerchantID' => $ this -> merchantID , 'CallbackURL' => $ callbackURL , 'Amount' => $ Amount , 'Description' => $ Description , ] ; if ( ! is_null ( $ Email ) ) { $ inputs [ 'Email' ] = $ Email ; } if ( ! is_null ( $ Mobile ) ) { $ inputs [ 'Mobile' ] = $ Mobile ; } if ( ! is_null ( $ additionalData ) ) { $ inputs [ 'AdditionalData' ] = $ additionalData ; $ results = $ this -> driver -> requestWithExtra ( $ inputs ) ; } else { $ results = $ this -> driver -> request ( $ inputs ) ; } if ( empty ( $ results [ 'Authority' ] ) ) { $ results [ 'Authority' ] = null ; } $ this -> Authority = $ results [ 'Authority' ] ; return $ results ; }
send request for money to zarinpal and redirect if there was no error .
50,952
public function verify ( $ amount , $ authority ) { if ( count ( func_get_args ( ) ) == 3 ) { $ amount = func_get_arg ( 1 ) ; $ authority = func_get_arg ( 2 ) ; } $ inputs = [ 'MerchantID' => $ this -> merchantID , 'Authority' => $ authority , 'Amount' => $ amount , ] ; return $ this -> driver -> verifyWithExtra ( $ inputs ) ; }
verify that the bill is paid or not by checking authority amount and status .
50,953
public function initialize ( ) { Facade :: setContainer ( $ this -> container ) ; if ( null !== $ loader = $ this -> loader ) { $ loader -> register ( ) ; } }
Configures the facades and registers the aliases loader when activated .
50,954
public function initialize ( ) { $ this -> capsule -> bootEloquent ( ) ; if ( 'default' !== $ this -> defaultConnection ) { $ this -> capsule -> getDatabaseManager ( ) -> setDefaultConnection ( $ this -> defaultConnection ) ; } }
Initializes the Eloquent ORM .
50,955
private static function resolveFacadeInstance ( $ accessor ) { if ( is_object ( $ accessor ) ) { return $ accessor ; } if ( isset ( static :: $ facadeInstances [ $ accessor ] ) ) { return static :: $ facadeInstances [ $ accessor ] ; } if ( static :: $ container -> has ( $ accessor ) ) { return static :: $ facadeInstances [ $ accessor ] = static :: $ container -> get ( $ accessor ) ; } throw new \ LogicException ( sprintf ( 'Unknown facade accessor "%s"' , print_r ( $ accessor , true ) ) ) ; }
Resolves the provided accessor into an object instance .
50,956
public function getHeaders ( ) { if ( $ this -> _headers === null ) { $ this -> _headers = new HeaderCollection ( ) ; foreach ( $ this -> swooleRequest -> server as $ name => $ value ) { if ( strncmp ( $ name , 'HTTP_' , 5 ) === 0 ) { $ name = str_replace ( ' ' , '-' , ucwords ( strtolower ( str_replace ( '_' , ' ' , substr ( $ name , 5 ) ) ) ) ) ; $ this -> _headers -> add ( $ name , $ value ) ; } } } return $ this -> _headers ; }
Returns the header collection . The header collection contains incoming HTTP headers .
50,957
public function getServerPort ( ) { return isset ( $ this -> swooleRequest -> server [ 'SERVER_PORT' ] ) ? ( int ) $ this -> swooleRequest -> server [ 'SERVER_PORT' ] : null ; }
Returns the server port number .
50,958
public function getPort ( ) { if ( $ this -> _port === null ) { $ this -> _port = ! $ this -> getIsSecureConnection ( ) && isset ( $ this -> swooleRequest -> server [ 'SERVER_PORT' ] ) ? ( int ) $ this -> swooleRequest -> server [ 'SERVER_PORT' ] : 80 ; } return $ this -> _port ; }
Returns the port to use for insecure requests . Defaults to 80 or the port specified by the server if the current request is insecure .
50,959
protected function getComponentId ( $ object ) { $ app = Yii :: $ app -> getApplication ( ) ; $ components = $ app -> getComponents ( false ) ; foreach ( $ components as $ id => $ component ) { if ( $ object === $ component ) { return $ id ; } } return false ; }
find the Component Id
50,960
public static function createChild ( \ Closure $ callback ) { $ puid = Context :: getcoroutine ( ) ; return \ Swoole \ Coroutine :: create ( function ( ) use ( $ puid , $ callback ) { Context :: markParent ( $ puid ) ; \ Swoole \ Coroutine :: call_user_func ( $ callback ) ; } ) ; }
Create child coroutine in case to use parent s context
50,961
public function onWorkerStop ( SwooleServer $ server , $ worker_id ) { $ contexts = Yii :: $ context -> getContextData ( ) ; foreach ( $ contexts as $ context ) { $ application = $ context [ Context :: COROUTINE_APP ] ?? null ; if ( empty ( $ application ) ) { continue ; } $ targets = $ application -> getLog ( ) -> targets ; foreach ( $ targets as $ target ) { $ target -> export ( ) ; } } }
To flush Log into LogTargets
50,962
protected function onEndRequest ( ) { Yii :: getLogger ( ) -> flush ( ) ; Yii :: getLogger ( ) -> flush ( true ) ; Yii :: $ context -> destory ( ) ; }
To flush log To destroy context
50,963
public function columnCount ( ) { if ( empty ( $ this -> _resultData ) || empty ( $ this -> _resultData -> result ) ) { return 0 ; } return count ( @ $ this -> _resultData -> result [ 0 ] ) ; }
Returns the number of columns in the result set
50,964
protected function convertExceptionToArray ( $ exception ) { if ( ! YII_DEBUG && ! $ exception instanceof UserException && ! $ exception instanceof HttpException ) { $ exception = new HttpException ( 500 , Yii :: t ( 'yii' , 'An internal server error occurred.' ) ) ; } $ array = [ 'code' => $ exception -> getCode ( ) , 'data' => new \ stdClass ( ) , 'message' => $ exception -> getMessage ( ) , ] ; if ( $ exception instanceof HttpException ) { $ array [ 'code' ] = $ exception -> statusCode ; } if ( $ exception instanceof ApiException && ! empty ( $ exception -> model ) ) { $ array = [ 'code' => 422 , 'data' => $ exception -> model -> getErrors ( ) , 'message' => 'Data Validation Failed.' , ] ; } if ( YII_DEBUG ) { $ array [ 'type' ] = get_class ( $ exception ) ; if ( ! $ exception instanceof UserException ) { $ array [ 'file' ] = $ exception -> getFile ( ) ; $ array [ 'line' ] = $ exception -> getLine ( ) ; $ array [ 'stack-trace' ] = explode ( "\n" , $ exception -> getTraceAsString ( ) ) ; if ( $ exception instanceof \ yii \ db \ Exception ) { $ array [ 'error-info' ] = $ exception -> errorInfo ; } } if ( ( $ prev = $ exception -> getPrevious ( ) ) !== null ) { $ array [ 'previous' ] = $ this -> convertExceptionToArray ( $ prev ) ; } } return $ array ; }
Converts an exception into an array .
50,965
protected function runComponentBootstrap ( ) { foreach ( $ this -> bootstrapComponents as $ component ) { if ( $ component instanceof BootstrapInterface ) { Yii :: trace ( 'Bootstrap with ' . get_class ( $ component ) . '::bootstrap()' , __METHOD__ ) ; $ component -> bootstrap ( $ this ) ; } } }
Eet the Component boot each request . But it may cause some error or memory leak es . Debug and Gii Component
50,966
public function doQuery ( $ sql , $ isExecute = false , $ method = 'fetch' , $ fetchMode = null , $ forRead = null ) { if ( $ forRead || $ forRead === null && $ this -> db -> getSchema ( ) -> isReadQuery ( $ sql ) ) { $ pdo = $ this -> db -> getSlavePdo ( ) ; } else { $ pdo = $ this -> db -> getMasterPdo ( ) ; } return $ pdo -> doQuery ( $ sql , $ isExecute , $ method , $ fetchMode ) ; }
Execute sql by mysql pool
50,967
public function generate ( Config $ config ) { $ parts = array ( ) ; if ( $ config -> parent ) { $ parent = $ config -> parent -> isRepresentant ( ) ? $ config -> parent -> parent : $ config -> parent ; $ parts [ ] = $ this -> generate ( $ parent ) ; } $ parts [ ] = $ this -> getPrefix ( $ config ) ; return implode ( '_' , array_filter ( $ parts ) ) ; }
recursively build a route name
50,968
public function onKernelView ( GetResponseForControllerResultEvent $ event ) { $ request = $ event -> getRequest ( ) ; try { $ viewName = $ this -> viewNameDeducer -> deduce ( $ request ) ; } catch ( NotInBundleException $ e ) { return ; } catch ( NoControllerNameException $ e ) { return ; } $ viewParams = $ event -> getControllerResult ( ) ; if ( ! is_array ( $ viewParams ) && ! is_null ( $ viewParams ) ) { return ; } if ( $ this -> templating -> exists ( $ viewName ) ) { $ response = $ this -> templating -> renderResponse ( $ viewName , $ viewParams ? : array ( ) ) ; $ event -> setResponse ( $ response ) ; return ; } $ this -> missingViewHandler -> handleMissingView ( $ event , $ viewName , $ viewParams ? : array ( ) ) ; }
Patches response on empty responses .
50,969
public function deducePath ( $ logicalName ) { $ path = $ this -> nameParser -> parse ( $ logicalName ) -> getPath ( ) ; return $ this -> pathExpander -> expand ( $ path ) ; }
Returns the path corresponding to the specified view name
50,970
public function check ( ) { if ( self :: isChecked ( ) === false ) { exec ( ( $ this -> java ? : 'java' ) . ' -version 2> /dev/null' , $ output , $ return ) ; if ( $ return != 0 ) { throw new Exception ( 'Java command not found' ) ; } elseif ( file_exists ( $ this -> path ) === false ) { throw new Exception ( 'Apache Tika app JAR not found' ) ; } self :: setChecked ( true ) ; } }
Check Java binary JAR path or server connection
50,971
public function request ( $ type , $ file = null ) { $ this -> check ( ) ; if ( isset ( $ this -> cache [ sha1 ( $ file ) ] [ $ type ] ) ) { return $ this -> cache [ sha1 ( $ file ) ] [ $ type ] ; } $ arguments = $ this -> getArguments ( $ type , $ file ) ; $ file = parent :: checkRequest ( $ type , $ file ) ; if ( $ file ) { $ arguments [ ] = escapeshellarg ( $ file ) ; } $ jar = escapeshellarg ( $ this -> path ) ; $ command = ( $ this -> java ? : 'java' ) . " -jar $jar " . implode ( ' ' , $ arguments ) ; $ response = $ this -> exec ( $ command ) ; if ( $ type == 'meta' ) { $ response = str_replace ( basename ( $ file ) . '"}{' , '", ' , $ response ) ; if ( defined ( 'PHP_WINDOWS_VERSION_MAJOR' ) ) { $ response = utf8_encode ( $ response ) ; } $ response = Metadata :: make ( $ response , $ file ) ; } if ( in_array ( $ type , [ 'lang' , 'meta' ] ) ) { $ this -> cache [ sha1 ( $ file ) ] [ $ type ] = $ response ; } return $ response ; }
Configure and make a request and return its results
50,972
public function exec ( $ command ) { $ exit = - 1 ; $ logfile = sys_get_temp_dir ( ) . DIRECTORY_SEPARATOR . 'tika-error.log' ; $ descriptors = [ [ 'pipe' , 'r' ] , [ 'pipe' , 'w' ] , [ 'file' , $ logfile , 'a' ] ] ; $ process = proc_open ( $ command , $ descriptors , $ pipes ) ; $ callback = $ this -> callback ; if ( is_resource ( $ process ) ) { fclose ( $ pipes [ 0 ] ) ; $ this -> response = '' ; while ( $ chunk = stream_get_line ( $ pipes [ 1 ] , $ this -> chunkSize ) ) { if ( ! is_null ( $ callback ) ) { $ callback ( $ chunk ) ; } $ this -> response .= $ chunk ; } fclose ( $ pipes [ 1 ] ) ; $ exit = proc_close ( $ process ) ; } if ( $ exit > 0 ) { throw new Exception ( "Unexpected exit value ($exit) for command $command" ) ; } return trim ( $ this -> response ) ; }
Run the command and return its results
50,973
protected function getArguments ( $ type , $ file = null ) { $ arguments = [ ] ; switch ( $ type ) { case 'html' : $ arguments [ ] = '--html' ; break ; case 'lang' : $ arguments [ ] = '--language' ; break ; case 'mime' : $ arguments [ ] = '--detect' ; break ; case 'meta' : $ arguments [ ] = '--metadata --json' ; break ; case 'text' : $ arguments [ ] = '--text' ; break ; case 'text-main' : $ arguments [ ] = '--text-main' ; break ; case 'mime-types' : $ arguments [ ] = '--list-supported-types' ; break ; case 'detectors' : $ arguments [ ] = '--list-detectors' ; break ; case 'parsers' : $ arguments [ ] = '--list-parsers' ; break ; case 'version' : $ arguments [ ] = '--version' ; break ; default : throw new Exception ( "Unknown type $type" ) ; } return $ arguments ; }
Get the arguments to run the command
50,974
public static function make ( $ param1 = null , $ param2 = null , $ options = [ ] ) { if ( preg_match ( '/\.jar$/' , func_get_arg ( 0 ) ) ) { return new CLIClient ( $ param1 , $ param2 ) ; } else { return new WebClient ( $ param1 , $ param2 , $ options ) ; } }
Get a class instance throwing an exception if check fails
50,975
public static function prepare ( $ param1 = null , $ param2 = null , $ options = [ ] ) { self :: $ check = false ; return self :: make ( $ param1 , $ param2 , $ options ) ; }
Get a class instance delaying the check
50,976
public function setChunkSize ( $ size ) { if ( static :: MODE == 'cli' && is_numeric ( $ size ) ) { $ this -> chunkSize = ( int ) $ size ; } elseif ( static :: MODE == 'web' ) { throw new Exception ( 'Chunk size is not supported on web mode' ) ; } else { throw new Exception ( "$size is not a valid chunk size" ) ; } return $ this ; }
Set the chunk size for secuential read
50,977
public function getMainText ( $ file , $ callback = null ) { if ( ! is_null ( $ callback ) ) { $ this -> setCallback ( $ callback ) ; } return $ this -> request ( 'text-main' , $ file ) ; }
Extracts main text
50,978
public function checkRequest ( $ type , $ file ) { if ( in_array ( $ type , [ 'detectors' , 'mime-types' , 'parsers' , 'version' ] ) ) { } elseif ( ! preg_match ( '/^http/' , $ file ) && ! file_exists ( $ file ) ) { throw new Exception ( "File $file can't be opened" ) ; } elseif ( preg_match ( '/^http/' , $ file ) && ! preg_match ( '/200/' , get_headers ( $ file ) [ 0 ] ) ) { throw new Exception ( "File $file can't be opened" , 2 ) ; } elseif ( preg_match ( '/^http/' , $ file ) && $ this -> downloadRemote ) { $ file = $ this -> downloadFile ( $ file ) ; } return $ file ; }
Check the request before executing
50,979
protected function downloadFile ( $ file ) { $ dest = tempnam ( sys_get_temp_dir ( ) , 'TIKA' ) ; $ fp = fopen ( $ dest , 'w+' ) ; if ( $ fp === false ) { throw new Exception ( "$dest can't be opened" ) ; } $ ch = curl_init ( $ file ) ; curl_setopt ( $ ch , CURLOPT_FILE , $ fp ) ; curl_setopt ( $ ch , CURLOPT_TIMEOUT , 5 ) ; curl_exec ( $ ch ) ; if ( curl_errno ( $ ch ) ) { throw new Exception ( curl_error ( $ ch ) ) ; } $ code = curl_getinfo ( $ ch , CURLINFO_HTTP_CODE ) ; curl_close ( $ ch ) ; if ( $ code != 200 ) { throw new Exception ( "$file can't be downloaded" , $ code ) ; } return $ dest ; }
Download file to a temporary folder
50,980
public static function make ( $ response , $ file ) { if ( empty ( $ response ) || trim ( $ response ) == '' ) { throw new Exception ( 'Empty response' ) ; } $ meta = json_decode ( $ response ) ; if ( json_last_error ( ) ) { $ message = function_exists ( 'json_last_error_msg' ) ? json_last_error_msg ( ) : 'Error parsing JSON response' ; throw new Exception ( $ message , json_last_error ( ) ) ; } $ mime = is_array ( $ meta -> { 'Content-Type' } ) ? current ( $ meta -> { 'Content-Type' } ) : $ meta -> { 'Content-Type' } ; switch ( current ( explode ( '/' , $ mime ) ) ) { case 'image' : $ instance = new ImageMetadata ( $ meta , $ file ) ; break ; default : $ instance = new DocumentMetadata ( $ meta , $ file ) ; } return $ instance ; }
Return an instance of Metadata based on content type
50,981
public function setUrl ( $ url ) { $ url = parse_url ( $ url ) ; $ this -> setHost ( $ url [ 'host' ] ) ; if ( isset ( $ url [ 'port' ] ) ) { $ this -> setPort ( $ url [ 'port' ] ) ; } return $ this ; }
Set the host and port using an URL
50,982
public function request ( $ type , $ file = null ) { static $ retries = [ ] ; $ this -> check ( ) ; if ( isset ( $ this -> cache [ sha1 ( $ file ) ] [ $ type ] ) ) { return $ this -> cache [ sha1 ( $ file ) ] [ $ type ] ; } elseif ( ! isset ( $ retries [ sha1 ( $ file ) ] ) ) { $ retries [ sha1 ( $ file ) ] = $ this -> retries ; } list ( $ resource , $ headers ) = $ this -> getParameters ( $ type , $ file ) ; $ file = parent :: checkRequest ( $ type , $ file ) ; $ options = $ this -> getCurlOptions ( $ type , $ file ) ; foreach ( $ headers as $ header ) { $ options [ CURLOPT_HTTPHEADER ] [ ] = $ header ; } $ options [ CURLOPT_URL ] = $ this -> getUrl ( ) . "/$resource" ; list ( $ response , $ status ) = $ this -> exec ( $ options ) ; if ( isset ( $ options [ CURLOPT_INFILE ] ) && is_resource ( $ options [ CURLOPT_INFILE ] ) ) { fclose ( $ options [ CURLOPT_INFILE ] ) ; } if ( $ status == 200 ) { if ( $ type == 'meta' ) { $ response = Metadata :: make ( $ response , $ file ) ; } if ( in_array ( $ type , [ 'lang' , 'meta' ] ) ) { $ this -> cache [ sha1 ( $ file ) ] [ $ type ] = $ response ; } } elseif ( $ status == 204 ) { $ response = null ; } elseif ( $ status == 500 && $ retries [ sha1 ( $ file ) ] -- ) { $ response = $ this -> request ( $ type , $ file ) ; } else { $ this -> error ( $ status , $ resource ) ; } return $ response ; }
Configure make a request and return its results
50,983
protected function exec ( array $ options = [ ] ) { $ curl = curl_init ( ) ; foreach ( $ options as $ option => $ value ) { curl_setopt ( $ curl , $ option , $ value ) ; } if ( is_null ( $ this -> callback ) ) { $ this -> response = curl_exec ( $ curl ) ; } else { $ this -> response = '' ; curl_exec ( $ curl ) ; } if ( curl_errno ( $ curl ) ) { throw new Exception ( curl_error ( $ curl ) , curl_errno ( $ curl ) ) ; } return [ trim ( $ this -> response ) , curl_getinfo ( $ curl , CURLINFO_HTTP_CODE ) ] ; }
Make a request to Apache Tika Server
50,984
protected function getParameters ( $ type , $ file = null ) { $ headers = [ ] ; if ( ! empty ( $ file ) && preg_match ( '/^http/' , $ file ) ) { $ headers [ ] = "fileUrl:$file" ; } switch ( $ type ) { case 'html' : $ resource = 'tika' ; $ headers [ ] = 'Accept: text/html' ; break ; case 'lang' : $ resource = 'language/stream' ; break ; case 'mime' : $ name = basename ( $ file ) ; $ resource = 'detect/stream' ; $ headers [ ] = "Content-Disposition: attachment, filename=$name" ; break ; case 'meta' : $ resource = 'meta' ; $ headers [ ] = 'Accept: application/json' ; break ; case 'text' : $ resource = 'tika' ; $ headers [ ] = 'Accept: text/plain' ; break ; case 'text-main' : $ resource = 'tika/main' ; $ headers [ ] = 'Accept: text/plain' ; break ; case 'detectors' : case 'parsers' : case 'mime-types' : case 'version' : $ resource = $ type ; break ; default : throw new Exception ( "Unknown type $type" ) ; } return [ $ resource , $ headers ] ; }
Get the parameters to make the request
50,985
protected function getCurlOptions ( $ type , $ file = null ) { $ options = $ this -> options ; if ( ! is_null ( $ this -> callback ) ) { $ callback = $ this -> callback ; $ options [ CURLOPT_WRITEFUNCTION ] = function ( $ handler , $ data ) use ( $ callback ) { $ this -> response .= $ data ; $ callback ( $ data ) ; return strlen ( $ data ) ; } ; } if ( $ file && preg_match ( '/^http/' , $ file ) ) { } elseif ( $ file && file_exists ( $ file ) && is_readable ( $ file ) ) { $ options [ CURLOPT_INFILE ] = fopen ( $ file , 'r' ) ; $ options [ CURLOPT_INFILESIZE ] = filesize ( $ file ) ; } elseif ( in_array ( $ type , [ 'detectors' , 'mime-types' , 'parsers' , 'version' ] ) ) { $ options [ CURLOPT_PUT ] = false ; } else { throw new Exception ( "File $file can't be opened" ) ; } return $ options ; }
Get the cURL options
50,986
public function setAutocomplete ( $ bool ) { if ( ! in_array ( $ bool , [ TRUE , FALSE , NULL ] , TRUE ) ) { throw new InvalidArgumentException ( 'valid values are only true/false/null' ) ; } $ this -> autocomplete = $ bool ; return $ this ; }
Turns autocomplete on or off .
50,987
public function getControl ( ) { return self :: makeCheckbox ( $ this -> getHtmlName ( ) , $ this -> getHtmlId ( ) , $ this -> translate ( $ this -> caption ) , $ this -> value , FALSE , $ this -> required , $ this -> disabled , $ this -> getRules ( ) ) ; }
Generates a checkbox
50,988
public static function makeCheckbox ( $ name , $ htmlId , $ caption = NULL , $ checked = FALSE , $ value = FALSE , $ required = FALSE , $ disabled = FALSE , $ rules = NULL ) { $ label = Html :: el ( 'label' , [ 'class' => [ 'custom-control' , 'custom-checkbox' ] ] ) ; $ input = Html :: el ( 'input' , [ 'type' => 'checkbox' , 'class' => [ 'custom-control-input' ] , 'name' => $ name , 'disabled' => $ disabled , 'required' => $ required , 'checked' => $ checked , 'id' => $ htmlId , 'data-nette-rules' => $ rules ? Nette \ Forms \ Helpers :: exportRules ( $ rules ) : FALSE , ] ) ; if ( $ value !== FALSE ) { $ input -> attrs += [ 'value' => $ value , ] ; } $ label -> addHtml ( $ input ) ; $ label -> addHtml ( Html :: el ( 'label' , [ 'class' => [ 'custom-control-label' ] , 'for' => $ htmlId , ] ) -> setText ( $ caption ) ) ; $ line = Html :: el ( 'div' ) ; $ line -> addHtml ( $ label ) ; return $ label ; }
Makes a Bootstrap checkbox HTML
50,989
public function addDateTime ( $ name , $ label ) { $ comp = new DateTimeInput ( $ label ) ; $ this -> addComponent ( $ comp , $ name ) ; return $ comp ; }
Adds a datetime input .
50,990
public function flatAssocArray ( array $ array ) { $ ret = [ ] ; foreach ( $ array as $ key => $ value ) { if ( is_array ( $ value ) ) { $ ret += $ this -> flatAssocArray ( $ value ) ; } else { $ ret [ $ key ] = $ value ; } } return $ ret ; }
Processes an associative array in a way that it has no nesting . Keys for nested arrays are lost but nested arrays are merged .
50,991
public function makeOptionList ( $ items , callable $ optionArgs , array & $ valuesRendered = [ ] ) { $ ret = [ ] ; foreach ( $ items as $ value => $ caption ) { if ( is_int ( $ value ) ) { $ value = ( string ) $ value ; } if ( is_array ( $ caption ) ) { $ option = Html :: el ( 'optgroup' , [ 'label' => $ value ] ) ; $ nested = $ this -> makeOptionList ( $ caption , $ optionArgs , $ valuesRendered ) ; foreach ( $ nested as $ item ) { $ option -> addHtml ( $ item ) ; } } else { if ( in_array ( $ value , $ valuesRendered ) ) { throw new InvalidArgumentException ( "Value '$value' is used multiple times." ) ; } $ valuesRendered [ ] = $ value ; $ option = Html :: el ( 'option' , array_merge ( [ 'value' => ( string ) $ value ] , $ optionArgs ( $ value , $ caption ) ) ) ; $ option -> setText ( $ caption ) ; } $ ret [ ] = $ option ; } return $ ret ; }
Makes array of &lt ; option&gt ; . Can handle associative arrays just fine . Checks for duplicate values .
50,992
protected function isValueDisabled ( $ value ) { $ disabled = $ this -> disabled ; if ( is_array ( $ disabled ) ) { return isset ( $ disabled [ $ value ] ) && $ disabled [ $ value ] ; } elseif ( ! is_bool ( $ disabled ) ) { return $ disabled == $ value ; } return FALSE ; }
Check if a specific value is disabled . If whole control is disabled returns false .
50,993
protected function isValueSelected ( $ value ) { $ val = $ this -> getValue ( ) ; if ( is_null ( $ value ) ) { return FALSE ; } elseif ( is_array ( $ val ) ) { return in_array ( $ value , $ val ) ; } return $ value == $ val ; }
Self - explanatory
50,994
public function configElem ( $ config , $ el = NULL ) { if ( is_scalar ( $ config ) ) { $ config = $ this -> fetchConfig ( $ config ) ; } if ( isset ( $ config [ Cnf :: elementName ] ) ) { $ name = $ config [ Cnf :: elementName ] ; if ( ! $ el ) { $ el = Html :: el ( $ name ) ; } else { $ el -> setName ( $ name ) ; } } if ( $ el instanceof Html && $ el != NULL ) { foreach ( $ config as $ key => $ value ) { if ( in_array ( $ key , [ Cnf :: classSet , Cnf :: classAdd , Cnf :: classAdd , Cnf :: classRemove ] ) ) { if ( ! is_array ( $ value ) ) { $ value = [ $ value ] ; } $ origClass = $ el -> getAttribute ( 'class' ) ; $ newClass = $ origClass ; if ( $ origClass === NULL ) { $ newClass = [ ] ; } elseif ( ! is_array ( $ origClass ) ) { $ newClass = explode ( ' ' , $ el -> getAttribute ( 'class' ) ) ; } $ el -> setAttribute ( 'class' , $ newClass ) ; $ origClass = $ newClass ; } if ( $ key == Cnf :: classSet ) { $ el -> setAttribute ( 'class' , $ value ) ; } elseif ( $ key == Cnf :: classAdd ) { $ el -> setAttribute ( 'class' , array_merge ( $ origClass , $ value ) ) ; } elseif ( $ key == Cnf :: classRemove ) { $ el -> setAttribute ( 'class' , array_diff ( $ origClass , $ value ) ) ; } elseif ( $ key == Cnf :: attributes ) { foreach ( $ value as $ attr => $ attrVal ) { $ el -> setAttribute ( $ attr , $ attrVal ) ; } } } } if ( isset ( $ config [ Cnf :: container ] ) ) { $ container = $ this -> configElem ( $ config [ Cnf :: container ] , NULL ) ; if ( $ container !== NULL && $ el !== NULL ) { $ elClone = clone $ el ; $ container -> setHtml ( $ elClone ) ; } $ el = $ container ; } return $ el ; }
Turns configuration or and existing element and configures it appropriately
50,995
public function renderBody ( ) { $ translator = $ this -> form -> getTranslator ( ) ; $ groups = Html :: el ( ) ; foreach ( $ this -> form -> getGroups ( ) as $ group ) { if ( ! $ group -> getControls ( ) || ! $ group -> getOption ( RendererOptions :: visual ) ) { continue ; } $ container = $ group -> getOption ( RendererOptions :: container , NULL ) ; if ( is_string ( $ container ) ) { $ container = $ this -> configElem ( Cnf :: group , Html :: el ( $ container ) ) ; } elseif ( $ container instanceof Html ) { $ container = $ this -> configElem ( Cnf :: group , $ container ) ; } else { $ container = $ this -> getElem ( Cnf :: group ) ; } $ container -> setAttribute ( 'id' , $ group -> getOption ( RendererOptions :: id ) ) ; $ label = $ group -> getOption ( RendererOptions :: label ) ; if ( $ label instanceof Html ) { $ label = $ this -> configElem ( Cnf :: groupLabel , $ label ) ; } elseif ( is_string ( $ label ) ) { if ( $ translator !== NULL ) { $ label = $ translator -> translate ( $ label ) ; } $ labelHtml = $ this -> getElem ( Cnf :: groupLabel ) ; $ labelHtml -> setText ( $ label ) ; $ label = $ labelHtml ; } if ( ! empty ( $ label ) ) { $ container -> addHtml ( $ label ) ; } $ controls = $ this -> renderControls ( $ group ) ; if ( ! empty ( $ controls ) ) { $ container -> addHtml ( $ controls ) ; } $ groups -> addHtml ( $ container ) ; } $ formControls = $ this -> renderControls ( $ this -> form ) ; $ out = Html :: el ( ) ; if ( ! empty ( $ formControls ) ) { $ out -> addHtml ( $ formControls ) ; } if ( ! empty ( $ groups ) ) { $ out -> addHtml ( $ groups ) ; } return $ out ; }
Renders form body .
50,996
public function renderControl ( Nette \ Forms \ IControl $ control ) { $ controlHtml = $ control -> getControl ( ) ; $ control -> setOption ( RendererOptions :: _rendered , TRUE ) ; if ( ( $ this -> form -> showValidation || $ control -> hasErrors ( ) ) && $ control instanceof IValidationInput ) { $ controlHtml = $ control -> showValidation ( $ controlHtml ) ; } $ controlHtml = $ this -> configElem ( Cnf :: input , $ controlHtml ) ; return $ controlHtml ; }
Renders control part of visual row of controls .
50,997
public function renderControls ( $ parent ) { if ( ! ( $ parent instanceof Nette \ Forms \ Container || $ parent instanceof Nette \ Forms \ ControlGroup ) ) { throw new Nette \ InvalidArgumentException ( 'Argument must be Nette\Forms\Container or Nette\Forms\ControlGroup instance.' ) ; } $ html = Html :: el ( ) ; $ hidden = Html :: el ( ) ; foreach ( $ parent -> getControls ( ) as $ control ) { if ( $ control -> getOption ( RendererOptions :: _rendered , FALSE ) ) { continue ; } if ( $ control instanceof BootstrapRow ) { $ html -> addHtml ( $ control -> render ( ) ) ; } else { if ( $ control -> getOption ( RendererOptions :: type ) == 'hidden' ) { $ isHidden = TRUE ; $ pairHtml = $ this -> renderControl ( $ control ) ; } else { $ pairHtml = $ this -> renderPair ( $ control ) ; $ isHidden = FALSE ; } if ( $ this -> groupHidden && $ isHidden ) { $ hidden -> addHtml ( $ pairHtml ) ; } else { $ html -> addHtml ( $ pairHtml ) ; } } } $ html -> addHtml ( $ hidden ) ; return $ html ; }
Renders group of controls .
50,998
public function renderLabel ( Nette \ Forms \ IControl $ control ) { $ controlLabel = $ control -> getLabel ( ) ; if ( $ controlLabel instanceof Html && $ controlLabel -> getName ( ) == 'label' ) { $ controlLabel = $ this -> configElem ( Cnf :: label , $ controlLabel ) ; $ labelHtml = $ controlLabel ; } elseif ( $ controlLabel === NULL ) { return Html :: el ( ) ; } else { $ labelHtml = $ this -> getElem ( Cnf :: label ) ; if ( $ controlLabel ) { $ labelHtml -> setHtml ( $ controlLabel ) ; } } return $ labelHtml ; }
Renders label part of visual row of controls .
50,999
public function renderPair ( Nette \ Forms \ IControl $ control ) { $ pairHtml = $ this -> configElem ( Cnf :: pair ) ; $ pairHtml -> id = $ control -> getOption ( RendererOptions :: id ) ; $ labelHtml = $ this -> renderLabel ( $ control ) ; if ( ! empty ( $ labelHtml ) ) { $ pairHtml -> addHtml ( $ labelHtml ) ; } $ nonLabel = $ this -> getElem ( Cnf :: nonLabel ) ; $ controlHtml = $ this -> renderControl ( $ control ) ; $ feedbackHtml = $ this -> renderFeedback ( $ control ) ; $ descriptionHtml = $ this -> renderDescription ( $ control ) ; if ( ! empty ( $ controlHtml ) ) { $ nonLabel -> addHtml ( $ controlHtml ) ; } if ( ! empty ( $ feedbackHtml ) ) { $ nonLabel -> addHtml ( $ feedbackHtml ) ; } if ( ! empty ( $ descriptionHtml ) ) { $ nonLabel -> addHtml ( $ descriptionHtml ) ; } if ( ! empty ( $ nonLabel ) ) { $ pairHtml -> addHtml ( $ nonLabel ) ; } return $ pairHtml -> render ( 0 ) ; }
Renders single visual row .