idx
int64 0
60.3k
| question
stringlengths 64
4.24k
| target
stringlengths 5
618
|
|---|---|---|
400
|
public function markPostponed ( ) : bool { $ this -> owner -> { $ this -> statusAttribute } = Status :: POSTPONED ; if ( $ this -> beforeModeration ( ) ) { return $ this -> owner -> save ( ) ; } return false ; }
|
Change model status to Postponed
|
401
|
public function markPending ( ) : bool { $ this -> owner -> { $ this -> statusAttribute } = Status :: PENDING ; if ( $ this -> beforeModeration ( ) ) { return $ this -> owner -> save ( ) ; } return false ; }
|
Change model status to Pending
|
402
|
protected function getModeratedByAttributeValue ( ) : ? int { $ user = Yii :: $ app -> get ( 'user' , false ) ; return $ user && ! $ user -> isGuest ? $ user -> id : null ; }
|
Get value for moderatedByAttribute
|
403
|
protected function getAttributesFromDb ( ) { $ connection_name = Config :: get ( 'laravel-import-export::baseconf.connection_name' ) ; return DB :: connection ( $ connection_name ) -> table ( $ this -> config [ "table" ] ) -> select ( $ this -> createSelect ( ) ) -> get ( ) ; }
|
Get the data from db
|
404
|
protected function createSelect ( $ config = null ) { $ config = $ config ? $ config : $ this -> config ; $ select = array ( ) ; if ( ( $ columns = $ config [ "columns" ] ) ) { foreach ( $ columns as $ db_key => $ export_key ) { $ select [ ] = "{$db_key} as {$export_key}" ; } } return $ select ; }
|
Create select to make the CsvFile attributes to export
|
405
|
public function URL ( ) { $ p = $ this -> parse ( ) ; $ link = '' ; $ link .= ( ! empty ( $ p [ 'scheme' ] ) ) ? $ p [ 'scheme' ] . '://' : false ; $ link .= ( ! empty ( $ p [ 'user' ] ) ) ? $ p [ 'user' ] . ':' : false ; $ link .= ( ! empty ( $ p [ 'pass' ] ) ) ? $ p [ 'pass' ] . '@' : false ; $ link .= ( ! empty ( $ p [ 'host' ] ) ) ? $ p [ 'host' ] : false ; $ link .= ( ! empty ( $ p [ 'path' ] ) ) ? $ p [ 'path' ] : false ; if ( ! empty ( $ p [ 'query' ] ) ) { parse_str ( $ p [ 'query' ] , $ get_array ) ; $ link .= '?' . http_build_query ( $ get_array , '' , '&' ) ; } $ link .= ( ! empty ( $ p [ 'fragment' ] ) ) ? '#' . $ p [ 'fragment' ] : false ; return $ link ; }
|
Return constructed URL
|
406
|
public function parse ( $ component = false ) { $ parts = parse_url ( $ this -> RAW ( ) ) ; if ( ! $ component ) { return $ parts ; } elseif ( ! empty ( $ parts [ $ component ] ) ) { return $ parts [ $ component ] ; } else { return false ; } }
|
Parse the URL string .
|
407
|
protected function getControllerAnnotation ( \ ReflectionFunctionAbstract $ controller , string $ annotationClass ) { if ( $ controller instanceof \ ReflectionMethod ) { $ annotations = $ this -> annotationReader -> getMethodAnnotations ( $ controller ) ; foreach ( $ annotations as $ annotation ) { if ( $ annotation instanceof $ annotationClass ) { return $ annotation ; } } $ class = $ controller -> getDeclaringClass ( ) ; $ classes = $ this -> reflectionTools -> getClassHierarchy ( $ class ) ; foreach ( $ classes as $ class ) { $ annotations = $ this -> annotationReader -> getClassAnnotations ( $ class ) ; foreach ( $ annotations as $ annotation ) { if ( $ annotation instanceof $ annotationClass ) { return $ annotation ; } } } } return null ; }
|
Finds an annotation on the controller class or method .
|
408
|
protected function hasControllerAnnotation ( \ ReflectionFunctionAbstract $ controller , string $ annotationClass ) : bool { return $ this -> getControllerAnnotation ( $ controller , $ annotationClass ) !== null ; }
|
Checks whether a controller has an annotation on the class or method .
|
409
|
public function processConfiguration ( $ config ) { $ factory = new ConfigurationProcessorFactory ( ) ; $ processor = $ factory -> create ( gettype ( $ config ) ) ; $ config = $ processor -> convertToObjectConfiguration ( $ config ) ; $ processor -> validate ( $ config ) ; $ this -> config = $ config ; }
|
processConfiguration Conversion de la configuration en object NavitiaConfiguration Validation de la configuration
|
410
|
public function process ( $ query , $ format = null , $ timeout = 6000 , $ pagination = true ) { $ this -> timeout = $ timeout ; $ factory = new RequestProcessorFactory ( ) ; $ processor = $ factory -> create ( gettype ( $ query ) ) ; $ request = $ processor -> convertToObjectRequest ( $ query ) ; $ validation = $ this -> validate ( $ request ) ; if ( $ validation -> count ( ) === 0 ) { $ result = $ this -> callApi ( $ request , $ format ) ; $ pagination_total_result_le_pagination_item_per_page = false ; if ( isset ( $ result -> pagination ) ) { if ( $ result -> pagination -> total_result <= $ result -> pagination -> items_per_page ) { $ pagination_total_result_le_pagination_item_per_page = true ; } } if ( $ pagination !== false || $ pagination_total_result_le_pagination_item_per_page ) { return $ result ; } else { return $ this -> deletePagination ( $ request , $ format , $ result ) ; } } else { return $ validation ; } }
|
Conversion de query en object NavitiaRequest Validation de la requete et appel Navitia si requete valide
|
411
|
public function deletePagination ( $ request , $ format , $ result ) { $ parameters = $ request -> getParameters ( ) ; if ( isset ( $ result -> pagination ) ) { $ result_pagination_total_result = $ result -> pagination -> total_result ; } else { $ result_pagination_total_result = 0 ; } if ( gettype ( $ parameters ) === 'string' ) { $ parameters .= '&count=' . $ result_pagination_total_result ; } if ( gettype ( $ parameters ) === 'array' ) { $ parameters [ 'count' ] = $ result_pagination_total_result ; } $ request -> setParameters ( $ parameters ) ; return $ this -> callApi ( $ request , $ format ) ; }
|
Function to delete Navitia pagination Retrieve the result count and call again with count
|
412
|
public function validate ( NavitiaRequestInterface $ request ) { $ validator = Validation :: createValidatorBuilder ( ) -> enableAnnotationMapping ( ) -> getValidator ( ) ; $ violations = $ validator -> validate ( $ request -> processParameters ( ) ) ; return $ violations ; }
|
Permet de valider une requete avec les contraintes en annotations
|
413
|
public function setPoints ( $ points ) { if ( is_array ( $ points ) || $ points instanceof \ Traversable ) { array_walk ( $ points , function ( & $ point , $ index ) { if ( ! $ point instanceof PointInterface ) { if ( is_array ( $ point ) && count ( $ point ) == 2 ) { list ( $ x , $ y ) = array_values ( $ point ) ; $ point = new Point ( $ x , $ y ) ; } else { $ msg = "Point at index #$index does not implement " . "PointReduction\\Common\\PointInterface" ; throw new InvalidArgumentException ( $ msg ) ; } } } ) ; $ this -> points = $ points ; } else { $ msg = "All points must be a traversable object, or array. " . gettype ( $ points ) . " given." ; throw new InvalidArgumentException ( $ msg ) ; } }
|
Set subject points
|
414
|
protected function areaOfTriangle ( PointInterface $ a , PointInterface $ b , PointInterface $ c ) { list ( $ ax , $ ay ) = $ a -> getCoordinates ( ) ; list ( $ bx , $ by ) = $ b -> getCoordinates ( ) ; list ( $ cx , $ cy ) = $ c -> getCoordinates ( ) ; $ area = $ ax * ( $ by - $ cy ) ; $ area += $ bx * ( $ cy - $ ay ) ; $ area += $ cx * ( $ ay - $ by ) ; return abs ( $ area / 2 ) ; }
|
Calculate the area of a triangle
|
415
|
protected function distanceBetweenPoints ( PointInterface $ head , PointInterface $ tail ) { return sqrt ( self :: pythagorus ( $ head , $ tail ) ) ; }
|
Calculate the distance between to points
|
416
|
protected function pythagorus ( PointInterface $ a , PointInterface $ b ) { list ( $ ax , $ ay ) = $ a -> getCoordinates ( ) ; list ( $ bx , $ by ) = $ b -> getCoordinates ( ) ; return pow ( $ ax - $ bx , 2 ) + pow ( $ ay - $ by , 2 ) ; }
|
Calculate Pythagoras distance .
|
417
|
public function setGcProbability ( int $ dividend , int $ divisor ) : void { $ this -> gcDividend = $ dividend ; $ this -> gcDivisor = $ divisor ; }
|
Sets the probability for the garbage collection to be triggered on any given request .
|
418
|
public function handleRequest ( Request $ request ) : void { $ this -> reset ( ) ; $ this -> readSessionId ( $ request ) ; if ( $ this -> isTimeToCollectGarbage ( ) ) { $ this -> collectGarbage ( ) ; } $ this -> inRequest = true ; }
|
Reads the session cookie from the request .
|
419
|
public function handleResponse ( Response $ response ) : void { if ( $ this -> id === null ) { return ; } $ this -> writeSessionId ( $ response ) ; $ this -> reset ( ) ; }
|
Writes the session cookie to the Response .
|
420
|
private function reset ( ) : void { $ this -> id = null ; $ this -> data = [ ] ; $ this -> inRequest = false ; }
|
Resets the session status .
|
421
|
public static function get ( UTCDateTime $ date ) : DateTime { $ date = $ date -> toDateTime ( ) ; $ date -> setTimezone ( new DateTimeZone ( date_default_timezone_get ( ) ) ) ; return $ date ; }
|
Retrieves DateTime instance using default timezone .
|
422
|
public static function format ( UTCDateTime $ date , string $ format = 'd/m/Y H:i:s' ) : string { return self :: get ( $ date ) -> format ( $ format ) ; }
|
Retrieves formated date time using timezone .
|
423
|
public function addConnection ( Connection $ connection ) : bool { $ this -> init ( ) ; $ this -> connectionPool -> addConnection ( $ connection ) ; return true ; }
|
Main entry point to openning a connection and start using Mongolid in pure PHP . After adding a connection into the Manager you are ready to persist and query your models .
|
424
|
public function setEventTrigger ( EventTriggerInterface $ eventTrigger ) { $ this -> init ( ) ; $ eventService = new EventTriggerService ( ) ; $ eventService -> registerEventDispatcher ( $ eventTrigger ) ; $ this -> container -> instance ( EventTriggerService :: class , $ eventService ) ; }
|
Sets the event trigger for Mongolid events .
|
425
|
protected function init ( ) { if ( $ this -> container ) { return ; } $ this -> container = new Container ( ) ; $ this -> connectionPool = new Pool ( ) ; $ this -> cacheComponent = new CacheComponent ( ) ; $ this -> container -> instance ( Pool :: class , $ this -> connectionPool ) ; $ this -> container -> instance ( CacheComponentInterface :: class , $ this -> cacheComponent ) ; Ioc :: setContainer ( $ this -> container ) ; static :: $ singleton = $ this ; }
|
Initializes the Mongolid manager .
|
426
|
public static function deleteUnderscore ( $ param ) { $ parts = explode ( '_' , $ param ) ; $ result = array_shift ( $ parts ) ; foreach ( $ parts as $ part ) { $ result .= ucfirst ( $ part ) ; } return $ result ; }
|
Fonction permettant de supprimer les underscores
|
427
|
public static function setter ( $ request , $ params ) { if ( is_array ( $ params ) ) { foreach ( $ params as $ property => $ value ) { $ property = Utils :: deleteUnderscore ( $ property ) ; $ setter = 'set' . ucfirst ( $ property ) ; if ( method_exists ( $ request , $ setter ) ) { $ request -> $ setter ( $ value ) ; } else { throw new NavitiaCreationException ( sprintf ( 'Neither property "%s" nor method "%s"' . 'nor method "%s" exist.' , $ property , 'get' . ucfirst ( $ property ) , $ setter ) ) ; } } } else { throw new NavitiaCreationException ( sprintf ( 'The parameter (type "%s") will be an Array' , gettype ( $ params ) ) ) ; } return $ request ; }
|
Fonction permettant de setter
|
428
|
protected function generateCacheKey ( ) : string { return sprintf ( '%s:%s:%s' , $ this -> command , $ this -> collection -> getNamespace ( ) , md5 ( serialize ( $ this -> params ) ) ) ; }
|
Generates an unique cache key for the cursor in it s current state .
|
429
|
protected function storeOriginalLimit ( ) { if ( isset ( $ this -> params [ 1 ] [ 'limit' ] ) ) { $ this -> originalLimit = $ this -> params [ 1 ] [ 'limit' ] ; } if ( $ this -> originalLimit > self :: DOCUMENT_LIMIT ) { $ this -> limit ( self :: DOCUMENT_LIMIT ) ; } }
|
Stores the original limit clause of the query .
|
430
|
protected function getOriginalCursor ( ) : Traversable { if ( $ this -> ignoreCache ) { return parent :: getCursor ( ) ; } if ( $ this -> getLimit ( ) ) { $ this -> params [ 1 ] [ 'limit' ] = $ this -> getLimit ( ) - $ this -> position ; } $ skipped = $ this -> params [ 1 ] [ 'skip' ] ?? 0 ; $ this -> skip ( $ skipped + $ this -> position - 1 ) ; $ this -> ignoreCache = true ; return $ this -> getOriginalCursor ( ) ; }
|
Returns the DriverCursor considering the documents that have already been retrieved from cache .
|
431
|
private function updateRecord ( string $ id , string $ key , string $ value ) : bool { $ query = sprintf ( 'UPDATE %s SET %s = ?, %s = CASE WHEN %s = ? THEN %s + 1 ELSE ? END WHERE %s = ? AND %s = ?' , $ this -> options [ 'table-name' ] , $ this -> options [ 'value-column' ] , $ this -> options [ 'last-access-column' ] , $ this -> options [ 'last-access-column' ] , $ this -> options [ 'last-access-column' ] , $ this -> options [ 'id-column' ] , $ this -> options [ 'key-column' ] ) ; $ statement = $ this -> pdo -> prepare ( $ query ) ; $ statement -> execute ( [ $ value , $ time = time ( ) , $ time , $ id , $ key ] ) ; return $ statement -> rowCount ( ) !== 0 ; }
|
Updates the record with the given id and key .
|
432
|
private function insertRecord ( string $ id , string $ key , string $ value ) : void { $ query = sprintf ( 'INSERT INTO %s (%s, %s, %s, %s) VALUES(?, ?, ?, ?)' , $ this -> options [ 'table-name' ] , $ this -> options [ 'id-column' ] , $ this -> options [ 'key-column' ] , $ this -> options [ 'value-column' ] , $ this -> options [ 'last-access-column' ] ) ; $ statement = $ this -> pdo -> prepare ( $ query ) ; $ statement -> execute ( [ $ id , $ key , $ value , time ( ) ] ) ; }
|
Creates a new record with the given id and key .
|
433
|
public function regenerateId ( ) : bool { $ id = $ this -> generateSessionId ( ) ; if ( $ this -> storage -> updateId ( $ this -> id , $ id ) ) { $ this -> id = $ id ; return true ; } return false ; }
|
Regenerates the session id .
|
434
|
private function checkSessionId ( string $ id ) : bool { if ( preg_match ( '/^[A-Za-z0-9]+$/' , $ id ) !== 1 ) { return false ; } if ( strlen ( $ id ) !== $ this -> idLength ) { return false ; } return true ; }
|
Checks the validity of a session ID sent in a cookie .
|
435
|
public function showPreview ( $ maxwidth = 500 , $ height = '56%' ) { $ this -> display_video = $ maxwidth ; $ this -> preview_height = $ height ; return $ this ; }
|
Display a video preview
|
436
|
public function getPreview ( ) { $ url = trim ( $ this -> value ) ; if ( ! $ this -> display_video || ! $ url ) { return false ; } $ obj = VideoLink :: create ( ) -> setValue ( $ url ) ; if ( $ obj -> iFrameURL ) { return $ obj -> Iframe ( $ this -> display_video , $ this -> preview_height ) ; } }
|
Return video preview
|
437
|
public function getVideoTitle ( ) { $ url = trim ( $ this -> value ) ; return VideoLink :: create ( ) -> setValue ( $ url ) -> Title ; }
|
Return video title
|
438
|
protected function json ( $ data , bool $ encode = true ) : Response { if ( $ encode ) { $ data = json_encode ( $ data ) ; } return $ this -> createResponse ( $ data , 'application/json' ) ; }
|
Returns a JSON response .
|
439
|
public function getConnection ( ) { if ( $ chosenConn = $ this -> connections -> pop ( ) ) { $ this -> connections -> push ( $ chosenConn ) ; return $ chosenConn ; } }
|
Gets a connection from the pool . It will cycle through the existent connections .
|
440
|
public function html ( string $ text , bool $ lineBreaks = false ) : string { $ html = htmlspecialchars ( $ text , ENT_QUOTES , 'UTF-8' ) ; return $ lineBreaks ? nl2br ( $ html ) : $ html ; }
|
HTML - escapes a text string .
|
441
|
public function createRating ( $ id = null ) { $ class = $ this -> getClass ( ) ; $ rating = new $ class ; if ( null !== $ id ) { $ rating -> setId ( $ id ) ; } $ this -> dispatcher -> dispatch ( DCSRatingEvents :: RATING_CREATE , new Event \ RatingEvent ( $ rating ) ) ; return $ rating ; }
|
Creates an empty rating instance
|
442
|
public function first ( ) { $ this -> rewind ( ) ; $ document = $ this -> getCursor ( ) -> current ( ) ; if ( ! $ document ) { return ; } return $ this -> getAssembler ( ) -> assemble ( $ document , $ this -> entitySchema ) ; }
|
Returns the first element of the cursor .
|
443
|
public function unserialize ( $ serialized ) { $ attributes = unserialize ( $ serialized ) ; $ conn = Ioc :: make ( Pool :: class ) -> getConnection ( ) ; $ db = $ conn -> defaultDatabase ; $ collectionObject = $ conn -> getRawConnection ( ) -> $ db -> { $ attributes [ 'collection' ] } ; foreach ( $ attributes as $ key => $ value ) { $ this -> $ key = $ value ; } $ this -> collection = $ collectionObject ; }
|
Unserializes this object . Re - creating the database connection .
|
444
|
private function getFunctionParameters ( string $ onEvent , callable $ function , array $ objects ) : array { $ parameters = [ ] ; $ reflectionFunction = $ this -> reflectionTools -> getReflectionFunction ( $ function ) ; foreach ( $ reflectionFunction -> getParameters ( ) as $ reflectionParameter ) { $ parameterClass = $ reflectionParameter -> getClass ( ) ; if ( $ parameterClass !== null ) { $ parameterClassName = $ parameterClass -> getName ( ) ; if ( isset ( $ objects [ $ parameterClassName ] ) ) { $ parameters [ ] = $ objects [ $ parameterClassName ] ; continue ; } } throw $ this -> cannotResolveParameter ( $ onEvent , array_keys ( $ objects ) , $ reflectionParameter ) ; } return $ parameters ; }
|
Resolves the parameters to call the given function .
|
445
|
public function createCursor ( Schema $ entitySchema , Collection $ collection , string $ command , array $ params , bool $ cacheable = false ) : Cursor { $ cursorClass = $ cacheable ? CacheableCursor :: class : Cursor :: class ; return new $ cursorClass ( $ entitySchema , $ collection , $ command , $ params ) ; }
|
Creates a new instance of a non embedded Cursor .
|
446
|
public function reduce ( $ target ) { $ kill = count ( $ this ) - $ target ; while ( $ kill -- > 0 ) { $ idx = 1 ; $ minArea = $ this -> areaOfTriangle ( $ this -> points [ 0 ] , $ this -> points [ 1 ] , $ this -> points [ 2 ] ) ; foreach ( range ( 2 , $ this -> lastKey ( - 2 ) ) as $ segment ) { $ area = $ this -> areaOfTriangle ( $ this -> points [ $ segment - 1 ] , $ this -> points [ $ segment ] , $ this -> points [ $ segment + 1 ] ) ; if ( $ area < $ minArea ) { $ minArea = $ area ; $ idx = $ segment ; } } array_splice ( $ this -> points , $ idx , 1 ) ; } return $ this -> points ; }
|
Reduce points with Visvalingam - Whyatt algorithm .
|
447
|
public function limit ( int $ amount ) { $ this -> items = array_slice ( $ this -> items , 0 , $ amount ) ; return $ this ; }
|
Limits the number of results returned .
|
448
|
public function sort ( array $ fields ) { foreach ( array_reverse ( $ fields ) as $ key => $ direction ) { usort ( $ this -> items , function ( $ a , $ b ) use ( $ key , $ direction ) { $ a = is_object ( $ a ) ? ( $ a -> $ key ?? null ) : ( $ a [ $ key ] ?? null ) ; $ b = is_object ( $ b ) ? ( $ b -> $ key ?? null ) : ( $ b [ $ key ] ?? null ) ; return ( $ a <=> $ b ) * $ direction ; } ) ; } return $ this ; }
|
Sorts the results by given fields .
|
449
|
public function skip ( int $ amount ) { $ this -> items = array_slice ( $ this -> items , $ amount ) ; return $ this ; }
|
Skips a number of results .
|
450
|
protected function getSchemaForEntity ( ) : Schema { if ( $ this -> entityClass instanceof Schema ) { return $ this -> entityClass ; } $ model = new $ this -> entityClass ( ) ; if ( $ model instanceof ActiveRecord ) { return $ model -> getSchema ( ) ; } return new DynamicSchema ( ) ; }
|
Retrieve a schema based on Entity Class .
|
451
|
protected function getSelectSchema ( $ name ) { $ data_types = array ( "string" => "string" , "integer" => "integer" , "increments" => "increments" , "bigIncrements" => "bigIncrements" , "bigInteger" => "bigInteger" , "smallInteger" => "smallInteger" , "float" => "float" , "double" => "double" , "decimal" => "decimal" , "boolean" => "boolean" , "date" => "date" , "dateTime" => "dateTime" , "time" => "time" , "blob" => "binary" , ) ; $ select = Form :: label ( $ name , 'Type: ' , array ( "class" => "control-label col-lg-2" ) ) . "<div class=\"col-lg-10\">" . Form :: select ( $ name , $ data_types , '' , array ( "class" => "form-control" ) ) . "</div>" ; return $ select ; }
|
Return a select for the type of data to create
|
452
|
protected function getCsvTableStr ( CsvFileHandler $ csv_handler , CsvFile $ csv_file ) { if ( ! $ csv_file ) { throw new NoDataException ( ) ; } $ table = new Table ( ) ; $ table -> setConfig ( array ( "table-hover" => true , "table-condensed" => false , "table-responsive" => true , "table-striped" => true , ) ) ; if ( $ csv_header = $ csv_file -> getCsvHeader ( ) ) { $ table -> setHeader ( $ csv_header ) ; } $ exchange_data = Session :: get ( $ this -> exchange_key ) ; $ max_num_lines = $ exchange_data [ "max_lines" ] ; foreach ( $ csv_file as $ csv_line_key => $ csv_line ) { if ( $ csv_line_key >= $ max_num_lines ) break ; $ table -> addRows ( $ csv_line -> getElements ( ) ) ; } return $ table -> getHtml ( ) ; }
|
Return the table rappresenting the csv data
|
453
|
public function processForm ( array $ input = null , $ validator = null , $ csv_handler = null ) { if ( $ input ) { $ this -> form_input = $ input ; } else { $ this -> fillFormInput ( ) ; } $ validator = ( $ validator ) ? $ validator : new ValidatorFormInputModel ( $ this ) ; $ csv_handler = ( $ csv_handler ) ? $ csv_handler : new CsvFileHandler ( ) ; if ( $ validator -> validateInput ( ) && $ this -> checkColumns ( ) ) { $ csv_file = $ csv_handler -> getTemporary ( ) ; if ( $ csv_file ) { try { $ csv_handler -> updateHeaders ( $ csv_file , $ this -> form_input [ "columns" ] , $ this -> form_input [ "table_name" ] ) ; } catch ( UnalignedArrayException $ e ) { $ this -> appendError ( "No_temporary" , "Invalid Column names." ) ; return $ this -> getIsExecuted ( ) ; } try { $ csv_handler -> saveToDb ( $ this -> form_input [ 'types' ] ) ; $ this -> is_executed = true ; } catch ( HeadersNotSetException $ e ) { $ this -> appendError ( "Save_err" , "Cannot save data: check if dmbs support transaction." ) ; } catch ( PDOException $ e ) { $ this -> appendError ( "Save_err" , $ e -> getMessage ( ) ) ; } catch ( Exception $ e ) { $ this -> appendError ( "Save_err" , $ e -> getMessage ( ) ) ; } } else { $ this -> appendError ( "No_temporary" , "No data available to save" ) ; } } return $ this -> getIsExecuted ( ) ; }
|
Process the form and return the next state
|
454
|
protected function checkColumns ( ) { $ success = false ; if ( ! empty ( $ this -> form_input [ 'columns' ] ) ) { $ success = true ; } else { $ this -> appendError ( "No_columns" , "No column name setted: you need to fill atleast one \"column_\" field" ) ; } return $ success ; }
|
Check the column field if atleast one exists
|
455
|
protected function clearDynamic ( array & $ data ) { if ( ! $ this -> schema -> dynamic ) { $ data = array_intersect_key ( $ data , $ this -> schema -> fields ) ; } }
|
If the schema is not dynamic remove all non specified fields .
|
456
|
public function parseField ( $ value , string $ fieldType ) { if ( method_exists ( $ this -> schema , $ fieldType ) ) { return $ this -> schema -> $ fieldType ( $ value ) ; } if ( null === $ value || is_array ( $ value ) && empty ( $ value ) ) { return $ value ; } if ( in_array ( $ fieldType , $ this -> castableTypes ) ) { return $ this -> cast ( $ value , $ fieldType ) ; } if ( 'schema.' == substr ( $ fieldType , 0 , 7 ) ) { return $ this -> mapToSchema ( $ value , substr ( $ fieldType , 7 ) ) ; } return $ value ; }
|
Parse a value based on a field yype of the schema .
|
457
|
protected function parseToArray ( $ object ) : array { if ( ! is_array ( $ object ) ) { $ attributes = method_exists ( $ object , 'getAttributes' ) ? $ object -> getAttributes ( ) : get_object_vars ( $ object ) ; return $ attributes ; } return $ object ; }
|
Parses an object to an array before sending it to the SchemaMapper .
|
458
|
public function view ( $ view , array $ data = array ( ) ) { $ this -> view = $ view ; $ this -> viewData = $ data ; return $ this ; }
|
Set the view for the mail message .
|
459
|
public function isPublic ( ) { if ( $ this -> getIsActive ( ) && ( $ this -> getPublishAt ( ) -> getTimestamp ( ) < time ( ) ) && ( ! $ this -> getExpiresAt ( ) || $ this -> getExpiresAt ( ) -> getTimestamp ( ) > time ( ) ) ) { return true ; } return false ; }
|
Is visible for user?
|
460
|
public function getUrlGenerator ( ) { if ( isset ( $ this -> urlGenerator ) ) { return $ this -> urlGenerator ; } else if ( ! isset ( static :: $ urlGeneratorResolver ) ) { throw new RuntimeException ( "URL Generator resolver not set on Paginator." ) ; } return $ this -> urlGenerator = call_user_func ( static :: $ urlGeneratorResolver , $ this ) ; }
|
Get the URL Generator instance .
|
461
|
public function setItems ( $ items ) { $ this -> items = ( $ items instanceof Collection ) ? $ items : Collection :: make ( $ items ) ; return $ this ; }
|
Set the paginator s underlying collection .
|
462
|
protected function addWhere ( QueryBuilder $ query , $ key , $ extraValue ) { if ( $ extraValue === 'NULL' ) { $ query -> whereNull ( $ key ) ; } elseif ( $ extraValue === 'NOT_NULL' ) { $ query -> whereNotNull ( $ key ) ; } else { $ query -> where ( $ key , $ extraValue ) ; } }
|
Add a WHERE clause to the given query .
|
463
|
protected function generate ( ) { foreach ( $ this -> listFiles as $ key => $ file ) { $ filePath = $ this -> makeFilePath ( $ this -> listFolders [ $ key ] , $ this -> data [ 'name' ] ) ; $ this -> resolveByPath ( $ filePath ) ; $ file = $ this -> formatContent ( $ file ) ; $ find = basename ( $ filePath ) ; $ filePath = strrev ( preg_replace ( strrev ( "/$find/" ) , '' , strrev ( $ filePath ) , 1 ) ) ; $ filePath = $ filePath . $ file ; if ( $ this -> files -> exists ( $ filePath ) ) { return $ this -> error ( $ this -> type . ' already exists!' ) ; } $ this -> makeDirectory ( $ filePath ) ; foreach ( $ this -> signOption as $ option ) { if ( $ this -> option ( $ option ) ) { $ stubFile = $ this -> listStubs [ $ option ] [ $ key ] ; $ this -> resolveByOption ( $ this -> option ( $ option ) ) ; break ; } } if ( ! isset ( $ stubFile ) ) { $ stubFile = $ this -> listStubs [ 'default' ] [ $ key ] ; } $ this -> files -> put ( $ filePath , $ this -> getStubContent ( $ stubFile ) ) ; } return $ this -> info ( $ this -> type . ' created successfully.' ) ; }
|
generate the console command .
|
464
|
protected function parseName ( $ name ) { if ( str_contains ( $ name , '\\' ) ) { $ name = str_replace ( '\\' , '/' , $ name ) ; } if ( str_contains ( $ name , '/' ) ) { $ formats = collect ( explode ( '/' , $ name ) ) -> map ( function ( $ name ) { return Str :: studly ( $ name ) ; } ) ; $ name = $ formats -> implode ( '/' ) ; } else { $ name = Str :: studly ( $ name ) ; } return $ name ; }
|
Parse class name of the Package .
|
465
|
protected function makeFilePath ( $ folder , $ name ) { $ folder = ltrim ( $ folder , '\/' ) ; $ folder = rtrim ( $ folder , '\/' ) ; $ name = ltrim ( $ name , '\/' ) ; $ name = rtrim ( $ name , '\/' ) ; if ( $ this -> packageInfo -> get ( 'type' ) == 'module' ) { return $ this -> packagesPath . DS . $ this -> packageInfo -> get ( 'basename' ) . DS . $ folder . DS . $ name ; } return $ this -> packagesPath . DS . $ this -> packageInfo -> get ( 'basename' ) . DS . 'src' . DS . $ folder . DS . $ name ; }
|
Make FilePath .
|
466
|
protected function getNamespace ( $ file ) { $ basename = $ this -> packageInfo -> get ( 'basename' ) ; if ( $ this -> packageInfo -> get ( 'type' ) == 'module' ) { $ namespace = str_replace ( $ this -> packagesPath . DS . $ basename , '' , $ file ) ; } else { $ namespace = str_replace ( $ this -> packagesPath . DS . $ basename . DS . 'src' , '' , $ file ) ; } $ find = basename ( $ namespace ) ; $ namespace = strrev ( preg_replace ( strrev ( "/$find/" ) , '' , strrev ( $ namespace ) , 1 ) ) ; $ namespace = $ this -> packageInfo -> get ( 'namespace' ) . '\\' . trim ( $ namespace , '\\/' ) ; return str_replace ( '/' , '\\' , $ namespace ) ; }
|
Get Namespace of the current file .
|
467
|
protected function getBaseNamespace ( ) { if ( $ this -> packageInfo -> get ( 'type' ) == 'module' ) { return $ this -> packages -> getModulesNamespace ( ) ; } return $ this -> packages -> getPackagesNamespace ( ) ; }
|
Get the configured Package base namespace .
|
468
|
protected function reset ( $ slug ) { if ( ! $ this -> packages -> exists ( $ slug ) ) { return $ this -> error ( 'Package does not exist.' ) ; } $ this -> requireMigrations ( $ slug ) ; $ this -> migrator -> setconnection ( $ this -> input -> getOption ( 'database' ) ) ; $ pretend = $ this -> input -> getOption ( 'pretend' ) ; while ( true ) { $ count = $ this -> migrator -> rollback ( $ pretend , $ slug ) ; foreach ( $ this -> migrator -> getNotes ( ) as $ note ) { $ this -> output -> writeln ( $ note ) ; } if ( $ count == 0 ) break ; } }
|
Run the migration reset for the specified Package .
|
469
|
public function getPackagePath ( $ slug ) { if ( Str :: length ( $ slug ) > 3 ) { $ package = Str :: studly ( $ slug ) ; } else { $ package = Str :: upper ( $ slug ) ; } return $ this -> getPackagesPath ( ) . DS . $ package . DS ; }
|
Get local path for the specified Package .
|
470
|
public function getModulePath ( $ slug ) { if ( Str :: length ( $ slug ) > 3 ) { $ module = Str :: studly ( $ slug ) ; } else { $ module = Str :: upper ( $ slug ) ; } return $ this -> getModulesPath ( ) . DS . $ module . DS ; }
|
Get path for the specified Module .
|
471
|
public function getThemePath ( $ slug ) { if ( Str :: length ( $ slug ) > 3 ) { $ theme = Str :: studly ( $ slug ) ; } else { $ theme = Str :: upper ( $ slug ) ; } return $ this -> getThemesPath ( ) . DS . $ theme . DS ; }
|
Get path for the specified Theme .
|
472
|
public function optimize ( ) { $ path = $ this -> getCachePath ( ) ; $ packages = $ this -> getPackages ( ) ; $ this -> writeCache ( $ path , $ packages ) ; }
|
Update cached repository of packages information .
|
473
|
public function writeCache ( $ path , $ packages ) { $ data = array ( ) ; foreach ( $ packages -> all ( ) as $ key => $ package ) { $ properties = ( $ package instanceof Collection ) ? $ package -> all ( ) : $ package ; $ properties [ 'path' ] = str_replace ( '\\' , '/' , $ properties [ 'path' ] ) ; ksort ( $ properties ) ; $ data [ ] = $ properties ; } $ data = var_export ( $ data , true ) ; $ content = <<<PHP<?phpreturn $data;PHP ; $ this -> files -> put ( $ path , $ content ) ; }
|
Write the service cache file to disk .
|
474
|
public function isCacheExpired ( $ cachePath , $ path ) { if ( ! $ this -> files -> exists ( $ cachePath ) ) { return true ; } $ lastModified = $ this -> files -> lastModified ( $ path ) ; if ( $ lastModified >= $ this -> files -> lastModified ( $ cachePath ) ) { return true ; } return false ; }
|
Determine if the cache file is expired .
|
475
|
protected function getPackageName ( $ package ) { if ( strpos ( $ package , '/' ) === false ) { return $ package ; } list ( $ vendor , $ namespace ) = explode ( '/' , $ package ) ; return $ namespace ; }
|
Get the name for a Package .
|
476
|
protected function createReadPdo ( array $ config ) { $ readConfig = $ this -> getReadConfig ( $ config ) ; return $ this -> createConnector ( $ readConfig ) -> connect ( $ readConfig ) ; }
|
Create a new PDO instance for reading .
|
477
|
public function start ( ) { $ httpServer = $ this -> getHttpServer ( ) ; if ( $ httpServer -> isRunning ( ) ) { $ serverStatus = $ httpServer -> getServerSetting ( ) ; \ output ( ) -> writeln ( "<error>The server have been running!(PID: {$serverStatus['masterPid']})</error>" , true , true ) ; } else { $ serverStatus = $ httpServer -> getServerSetting ( ) ; } $ this -> setStartArgs ( $ httpServer ) ; $ httpStatus = $ httpServer -> getHttpSetting ( ) ; $ tcpStatus = $ httpServer -> getTcpSetting ( ) ; $ workerNum = $ httpServer -> setting [ 'worker_num' ] ; $ httpHost = $ httpStatus [ 'host' ] ; $ httpPort = $ httpStatus [ 'port' ] ; $ httpMode = $ httpStatus [ 'mode' ] ; $ httpType = $ httpStatus [ 'type' ] ; $ tcpEnable = $ serverStatus [ 'tcpable' ] ; $ tcpHost = $ tcpStatus [ 'host' ] ; $ tcpPort = $ tcpStatus [ 'port' ] ; $ tcpType = $ tcpStatus [ 'type' ] ; $ tcpEnable = $ tcpEnable ? '<info>Enabled</info>' : '<warning>Disabled</warning>' ; $ lines = [ ' Server Information ' , '********************************************************************' , "* HTTP | host: <note>$httpHost</note>, port: <note>$httpPort</note>, type: <note>$httpType</note>, worker: <note>$workerNum</note>, mode: <note>$httpMode</note>" , "* TCP | host: <note>$tcpHost</note>, port: <note>$tcpPort</note>, type: <note>$tcpType</note>, worker: <note>$workerNum</note> ($tcpEnable)" , '********************************************************************' , ] ; \ output ( ) -> writeln ( implode ( "\n" , $ lines ) ) ; $ httpServer -> start ( ) ; }
|
Start http server
|
478
|
public function reload ( ) { $ httpServer = $ this -> getHttpServer ( ) ; if ( ! $ httpServer -> isRunning ( ) ) { output ( ) -> writeln ( '<error>The server is not running! cannot reload</error>' , true , true ) ; } output ( ) -> writeln ( sprintf ( '<info>Server %s is reloading</info>' , input ( ) -> getScript ( ) ) ) ; $ reloadTask = input ( ) -> hasOpt ( 't' ) ; $ httpServer -> reload ( $ reloadTask ) ; output ( ) -> writeln ( sprintf ( '<success>Server %s reload success</success>' , input ( ) -> getScript ( ) ) ) ; }
|
Reload worker processes
|
479
|
public function stop ( ) { $ httpServer = $ this -> getHttpServer ( ) ; if ( ! $ httpServer -> isRunning ( ) ) { \ output ( ) -> writeln ( '<error>The server is not running! cannot stop</error>' , true , true ) ; } $ serverStatus = $ httpServer -> getServerSetting ( ) ; $ pidFile = $ serverStatus [ 'pfile' ] ; \ output ( ) -> writeln ( sprintf ( '<info>Swoft %s is stopping ...</info>' , input ( ) -> getScript ( ) ) ) ; $ result = $ httpServer -> stop ( ) ; if ( ! $ result ) { \ output ( ) -> writeln ( sprintf ( '<error>Swoft %s stop fail</error>' , input ( ) -> getScript ( ) ) , true , true ) ; } @ unlink ( $ pidFile ) ; output ( ) -> writeln ( sprintf ( '<success>Swoft %s stop success!</success>' , input ( ) -> getScript ( ) ) ) ; }
|
Stop the http server
|
480
|
public function restart ( ) { $ httpServer = $ this -> getHttpServer ( ) ; if ( $ httpServer -> isRunning ( ) ) { $ this -> stop ( ) ; } $ httpServer -> setDaemonize ( ) ; $ this -> start ( ) ; }
|
Restart the http server
|
481
|
protected function validateMethod ( $ method ) : void { if ( ! \ is_string ( $ method ) ) { throw new \ InvalidArgumentException ( 'HTTP method must be a string' ) ; } else if ( ! \ preg_match ( HeaderInterface :: RFC7230_TOKEN , $ method ) ) { throw new \ InvalidArgumentException ( \ sprintf ( 'The given method "%s" is not valid' , $ method ) ) ; } }
|
Validates the given method
|
482
|
protected function validateRequestTarget ( $ requestTarget ) : void { if ( ! \ is_string ( $ requestTarget ) ) { throw new \ InvalidArgumentException ( 'HTTP request-target must be a string' ) ; } else if ( ! \ preg_match ( '/^[\x21-\x7E\x80-\xFF]+$/' , $ requestTarget ) ) { throw new \ InvalidArgumentException ( \ sprintf ( 'The given request-target "%s" is not valid' , $ requestTarget ) ) ; } }
|
Validates the given request - target
|
483
|
public function map ( Router $ router ) { $ router -> group ( array ( 'namespace' => $ this -> namespace ) , function ( $ router ) { $ basePath = $ this -> guessPackageRoutesPath ( ) ; if ( is_readable ( $ path = $ basePath . DS . 'Api.php' ) ) { $ router -> group ( array ( 'prefix' => 'api' , 'middleware' => 'api' ) , function ( $ router ) use ( $ path ) { require $ path ; } ) ; } if ( is_readable ( $ path = $ basePath . DS . 'Web.php' ) ) { $ router -> group ( array ( 'middleware' => 'web' ) , function ( $ router ) use ( $ path ) { require $ path ; } ) ; } } ) ; }
|
Define the routes for the module .
|
484
|
protected function addRouteMiddleware ( $ routeMiddleware ) { if ( is_array ( $ routeMiddleware ) && ( count ( $ routeMiddleware ) > 0 ) ) { foreach ( $ routeMiddleware as $ key => $ middleware ) { $ this -> middleware ( $ key , $ middleware ) ; } } }
|
Add middleware to the router .
|
485
|
protected function addMiddlewareGroups ( $ middlewareGroups ) { if ( is_array ( $ middlewareGroups ) && ( count ( $ middlewareGroups ) > 0 ) ) { foreach ( $ middlewareGroups as $ key => $ groupMiddleware ) { foreach ( $ groupMiddleware as $ middleware ) { $ this -> pushMiddlewareToGroup ( $ key , $ middleware ) ; } } } }
|
Add middleware groups to the router .
|
486
|
public function socketAuth ( $ channel , $ socketId , $ customData = null ) { if ( preg_match ( '/^[-a-z0-9_=@,.;]+$/i' , $ channel ) !== 1 ) { throw new BroadcastException ( 'Invalid channel name ' . $ channel ) ; } if ( preg_match ( '/^(?:\/[a-z0-9]+#)?[a-z0-9]+$/i' , $ socketId ) !== 1 ) { throw new BroadcastException ( 'Invalid socket ID ' . $ socketId ) ; } if ( ! is_null ( $ customData ) ) { $ signature = hash_hmac ( 'sha256' , $ socketId . ':' . $ channel . ':' . $ customData , $ this -> secretKey , false ) ; } else { $ signature = hash_hmac ( 'sha256' , $ socketId . ':' . $ channel , $ this -> secretKey , false ) ; } $ signature = array ( 'auth' => $ signature ) ; if ( ! is_null ( $ customData ) ) { $ signature [ 'payload' ] = $ customData ; } return json_encode ( $ signature ) ; }
|
Creates a socket signature .
|
487
|
public function hasProperty ( ) { if ( ! array_key_exists ( $ this -> data [ 1 ] , ( array ) $ this -> data [ 0 ] ) ) { throw new DidNotMatchException ( ) ; } return $ this -> data [ 0 ] -> { $ this -> data [ 1 ] } ; }
|
Assert that an object has a property . Returns the properties value .
|
488
|
protected function addImpliedCommands ( ) { if ( count ( $ this -> columns ) > 0 && ! $ this -> creating ( ) ) { array_unshift ( $ this -> commands , $ this -> createCommand ( 'add' ) ) ; } $ this -> addFluentIndexes ( ) ; }
|
Add the commands that are implied by the blueprint .
|
489
|
protected function dropIndexCommand ( $ command , $ type , $ index ) { $ columns = array ( ) ; if ( is_array ( $ index ) ) { $ columns = $ index ; $ index = $ this -> createIndexName ( $ type , $ columns ) ; } return $ this -> indexCommand ( $ command , $ columns , $ index ) ; }
|
Create a new drop index command on the blueprint .
|
490
|
public function removeColumn ( $ name ) { $ this -> columns = array_values ( array_filter ( $ this -> columns , function ( $ c ) use ( $ name ) { return $ c [ 'attributes' ] [ 'name' ] != $ name ; } ) ) ; return $ this ; }
|
Remove a column from the schema blueprint .
|
491
|
protected function addCommand ( $ name , array $ parameters = array ( ) ) { $ this -> commands [ ] = $ command = $ this -> createCommand ( $ name , $ parameters ) ; return $ command ; }
|
Add a new command to the blueprint .
|
492
|
protected function withErrorBag ( $ errorBag , callable $ callback ) { $ this -> validatesRequestErrorBag = $ errorBag ; call_user_func ( $ callback ) ; $ this -> validatesRequestErrorBag = null ; }
|
Execute a Closure within with a given error bag set as the default bag .
|
493
|
protected function isValidatable ( $ rule , $ attribute , $ value ) { return $ this -> presentOrRuleIsImplicit ( $ rule , $ attribute , $ value ) && $ this -> passesOptionalCheck ( $ attribute ) && $ this -> hasNotFailedPreviousRuleIfPresenceRule ( $ rule , $ attribute ) ; }
|
Determine if the attribute is validatable .
|
494
|
protected function addError ( $ attribute , $ rule , $ parameters ) { $ message = $ this -> getMessage ( $ attribute , $ rule ) ; $ message = $ this -> doReplacements ( $ message , $ attribute , $ rule , $ parameters ) ; $ this -> messages -> add ( $ attribute , $ message ) ; }
|
Add an error message to the validator s collection of messages .
|
495
|
protected function validateSame ( $ attribute , $ value , $ parameters ) { $ this -> requireParameterCount ( 1 , $ parameters , 'same' ) ; $ other = Arr :: get ( $ this -> data , $ parameters [ 0 ] ) ; return ( isset ( $ other ) && $ value == $ other ) ; }
|
Validate that two attributes match .
|
496
|
protected function validateBeforeWithFormat ( $ format , $ value , $ parameters ) { $ param = $ this -> getValue ( $ parameters [ 0 ] ) ? : $ parameters [ 0 ] ; return $ this -> checkDateTimeOrder ( $ format , $ value , $ param ) ; }
|
Validate the date is before a given date with a given format .
|
497
|
protected function validateAfterWithFormat ( $ format , $ value , $ parameters ) { $ param = $ this -> getValue ( $ parameters [ 0 ] ) ? : $ parameters [ 0 ] ; return $ this -> checkDateTimeOrder ( $ format , $ param , $ value ) ; }
|
Validate the date is after a given date with a given format .
|
498
|
protected function callReplacer ( $ message , $ attribute , $ rule , $ parameters ) { $ callback = $ this -> replacers [ $ rule ] ; if ( $ callback instanceof Closure ) { return call_user_func_array ( $ callback , func_get_args ( ) ) ; } else if ( is_string ( $ callback ) ) { return $ this -> callClassBasedReplacer ( $ callback , $ message , $ attribute , $ rule , $ parameters ) ; } }
|
Call a custom validator message replacer .
|
499
|
public function translate ( $ message , array $ params = array ( ) ) { if ( isset ( $ this -> messages [ $ message ] ) && ! empty ( $ this -> messages [ $ message ] ) ) { $ message = $ this -> messages [ $ message ] ; } if ( empty ( $ params ) ) { return $ message ; } $ formatter = new MessageFormatter ( ) ; return $ formatter -> format ( $ message , $ params , $ this -> locale ) ; }
|
Translate a message with optional formatting
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.