idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
54,100
public static function prettifyTableName ( $ table , $ prefix = '' ) { if ( $ prefix ) { $ table = self :: removePrefix ( $ table , $ prefix ) ; } return self :: underscoresToCamelCase ( $ table , true ) ; }
Convert a mysql table name to a class name optionally removing a prefix .
54,101
public static function implodeAndQuote ( $ glue , $ pieces ) { foreach ( $ pieces as & $ piece ) { $ piece = self :: singleQuote ( $ piece ) ; } unset ( $ piece ) ; return implode ( $ glue , $ pieces ) ; }
Add a single quote to all pieces then implode with the given glue .
54,102
public static function safePlural ( $ value ) { $ plural = str_plural ( $ value ) ; if ( $ plural == $ value ) { $ plural = $ value . 's' ; echo 'warning: automatic pluralization of ' . $ value . ' failed, using ' . $ plural . LF ; } return $ plural ; }
Use laravel pluralization and if that one fails give a warning and just append s .
54,103
public function buildModel ( $ table , $ baseModel , $ describes , $ foreignKeys , $ namespace = '' , $ prefix = '' ) { $ this -> table = StringUtils :: removePrefix ( $ table , $ prefix ) ; $ this -> baseModel = $ baseModel ; $ this -> foreignKeys = $ this -> filterAndSeparateForeignKeys ( $ foreignKeys [ 'all' ] , $ table ) ; $ foreignKeysByTable = $ foreignKeys [ 'ordered' ] ; if ( ! empty ( $ namespace ) ) { $ this -> namespace = ' namespace ' . $ namespace . ';' ; } $ this -> class = StringUtils :: prettifyTableName ( $ table , $ prefix ) ; $ this -> timestampFields = $ this -> getTimestampFields ( $ this -> baseModel ) ; $ describe = $ describes [ $ table ] ; foreach ( $ describe as $ field ) { if ( $ this -> isPrimaryKey ( $ field ) ) { $ this -> primaryKey = $ field -> Field ; $ this -> incrementing = $ this -> isIncrementing ( $ field ) ; continue ; } if ( $ this -> isTimestampField ( $ field ) ) { $ this -> timestamps = true ; continue ; } if ( $ this -> isDate ( $ field ) ) { $ this -> dates [ ] = $ field -> Field ; } if ( $ this -> isHidden ( $ field ) ) { $ this -> hidden [ ] = $ field -> Field ; continue ; } if ( $ this -> isForeignKey ( $ table , $ field -> Field ) ) { continue ; } $ this -> fillable [ ] = $ field -> Field ; } $ this -> relations = new Relations ( $ table , $ this -> foreignKeys , $ describes , $ foreignKeysByTable , $ prefix , $ namespace ) ; }
First build the model .
54,104
public function createModel ( ) { $ file = '<?php' . $ this -> namespace . LF . LF ; $ file .= '/**' . LF ; $ file .= ' * Eloquent class to describe the ' . $ this -> table . ' table' . LF ; $ file .= ' *' . LF ; $ file .= ' * automatically generated by ModelGenerator.php' . LF ; $ file .= ' */' . LF ; $ file .= 'class ' . $ this -> class . ' extends ' . $ this -> baseModel . LF ; $ file .= '{' . LF ; $ file .= TAB . 'protected $table = ' . StringUtils :: singleQuote ( $ this -> table ) . ';' . LF . LF ; if ( $ this -> primaryKey !== 'id' ) { $ file .= TAB . 'public $primaryKey = ' . StringUtils :: singleQuote ( $ this -> primaryKey ) . ';' . LF . LF ; } if ( ! $ this -> timestamps ) { $ file .= TAB . 'public $timestamps = ' . var_export ( $ this -> timestamps , true ) . ';' . LF . LF ; } if ( ! $ this -> incrementing ) { $ file .= TAB . 'public $incrementing = ' . var_export ( $ this -> incrementing , true ) . ';' . LF . LF ; } if ( ! empty ( $ this -> dates ) ) { $ file .= TAB . 'public function getDates()' . LF ; $ file .= TAB . '{' . LF ; $ file .= TAB . TAB . 'return array(' . StringUtils :: implodeAndQuote ( ', ' , $ this -> dates ) . ');' . LF ; $ file .= TAB . '}' . LF . LF ; } $ wrap = TAB . 'protected $fillable = array(' . StringUtils :: implodeAndQuote ( ', ' , $ this -> fillable ) . ');' . LF . LF ; $ file .= wordwrap ( $ wrap , ModelGenerator :: $ lineWrap , LF . TAB . TAB ) ; if ( ! empty ( $ this -> hidden ) ) { $ file .= TAB . 'protected $hidden = array(' . StringUtils :: implodeAndQuote ( ', ' , $ this -> hidden ) . ');' . LF . LF ; } $ file .= rtrim ( $ this -> relations ) . LF ; $ file .= '}' . LF ; $ this -> fileContents = $ file ; }
Secondly create the model .
54,105
protected function filterAndSeparateForeignKeys ( $ foreignKeys , $ table ) { $ results = [ 'local' => [ ] , 'remote' => [ ] ] ; foreach ( $ foreignKeys as $ foreignKey ) { if ( $ foreignKey -> TABLE_NAME == $ table ) { $ results [ 'local' ] [ ] = $ foreignKey ; } if ( $ foreignKey -> REFERENCED_TABLE_NAME == $ table ) { $ results [ 'remote' ] [ ] = $ foreignKey ; } } return $ results ; }
Only show the keys where table is mentioned .
54,106
public function userLinksAction ( ) { $ response = new Response ( ) ; $ response -> setSharedMaxAge ( 3600 ) ; $ response -> setVary ( 'Cookie' ) ; return $ this -> render ( 'eZDemoBundle::page_header_links.html.twig' , array ( ) , $ response ) ; }
Renders page header links with cache control .
54,107
public function showArticleAction ( View $ view ) { $ view -> addParameters ( [ 'showSummary' => $ this -> container -> getParameter ( 'ezdemo.article.full_view.show_summary' ) , 'showImage' => $ this -> container -> getParameter ( 'ezdemo.article.full_view.show_image' ) , ] ) ; return $ view ; }
Renders article with extra parameters that controls page elements visibility such as image and summary .
54,108
public function viewParentExtraInfoAction ( Location $ location ) { $ repository = $ this -> getRepository ( ) ; $ parentLocation = $ repository -> getLocationService ( ) -> loadLocation ( $ location -> parentLocationId ) ; return $ this -> render ( 'eZDemoBundle:parts/blog:extra_info.html.twig' , array ( 'location' => $ parentLocation ) ) ; }
Displays description tagcloud tags ezarchive and calendar of the parent s of a given location .
54,109
public static function fromString ( $ path ) { $ pathObject = static :: factory ( ) -> create ( $ path ) ; if ( ! $ pathObject instanceof RelativePathInterface ) { throw new Exception \ NonRelativePathException ( $ pathObject ) ; } return $ pathObject ; }
Creates a new relative path instance from its string representation .
54,110
public static function fromDriveAndAtoms ( $ atoms , $ drive = null , $ isAnchored = null , $ hasTrailingSeparator = null ) { return static :: factory ( ) -> createFromDriveAndAtoms ( $ atoms , $ drive , false , $ isAnchored , $ hasTrailingSeparator ) ; }
Creates a new relative Windows path from a set of path atoms and a drive specifier .
54,111
public function matchesDriveOrNull ( $ drive ) { return null === $ drive || ! $ this -> hasDrive ( ) || $ this -> driveSpecifiersMatch ( $ this -> drive ( ) , $ drive ) ; }
Returns true if this path s drive specifier matches the supplied drive specifier or if either drive specifier is null .
54,112
public function join ( RelativePathInterface $ path ) { if ( $ path instanceof RelativeWindowsPathInterface ) { if ( ! $ this -> matchesDriveOrNull ( $ this -> pathDriveSpecifier ( $ path ) ) ) { throw new Exception \ DriveMismatchException ( $ this -> drive ( ) , $ path -> drive ( ) ) ; } if ( $ path -> isAnchored ( ) ) { return $ path -> joinDrive ( $ this -> drive ( ) ) ; } } return parent :: join ( $ path ) ; }
Joins the supplied path to this path .
54,113
public function toAbsolute ( ) { if ( ! $ this -> hasDrive ( ) ) { throw new InvalidPathStateException ( 'Cannot convert relative Windows path to absolute without a ' . 'drive specifier.' ) ; } return $ this -> createPathFromDriveAndAtoms ( $ this -> atoms ( ) , $ this -> drive ( ) , true , false , false ) ; }
Get an absolute version of this path .
54,114
protected function normalizeAbsoluteWindowsPath ( AbsoluteWindowsPathInterface $ path ) { return $ this -> factory ( ) -> createFromDriveAndAtoms ( $ this -> normalizeAbsolutePathAtoms ( $ path -> atoms ( ) ) , $ this -> normalizeDriveSpecifier ( $ path -> drive ( ) ) , true , false , false ) ; }
Normalize an absolute Windows path .
54,115
protected function normalizeRelativeWindowsPath ( RelativeWindowsPathInterface $ path ) { if ( $ path -> isAnchored ( ) ) { $ atoms = $ this -> normalizeAbsolutePathAtoms ( $ path -> atoms ( ) ) ; } else { $ atoms = $ this -> normalizeRelativePathAtoms ( $ path -> atoms ( ) ) ; } return $ this -> factory ( ) -> createFromDriveAndAtoms ( $ atoms , $ this -> normalizeDriveSpecifier ( $ path -> drive ( ) ) , false , $ path -> isAnchored ( ) , false ) ; }
Normalize a relative Windows path .
54,116
public static function fromDriveAndAtoms ( $ drive , $ atoms , $ hasTrailingSeparator = null ) { return static :: factory ( ) -> createFromDriveAndAtoms ( $ atoms , $ drive , true , false , $ hasTrailingSeparator ) ; }
Creates a new absolute Windows path from a set of path atoms and a drive specifier .
54,117
public function toRelative ( ) { return $ this -> createPathFromDriveAndAtoms ( $ this -> atoms ( ) , $ this -> drive ( ) , false , false , false ) ; }
Get a relative version of this path .
54,118
public function showFeedbackFormAction ( Request $ request , ContentView $ view ) { $ feedback = new Feedback ( ) ; $ form = $ this -> createForm ( $ this -> get ( 'ezdemo.form.type.feedback' ) , $ feedback ) ; if ( $ request -> isMethod ( 'POST' ) ) { $ form -> handleRequest ( $ request ) ; if ( $ form -> isValid ( ) ) { $ emailHelper = $ this -> get ( 'ezdemo.email_helper' ) ; $ emailHelper -> sendFeebackMessage ( $ feedback , $ this -> container -> getParameter ( 'ezdemo.feedback_form.email_from' ) , $ this -> container -> getParameter ( 'ezdemo.feedback_form.email_to' ) ) ; $ this -> get ( 'session' ) -> getFlashBag ( ) -> add ( 'notice' , $ this -> get ( 'translator' ) -> trans ( 'Thank you for your message, we will get back to you as soon as possible.' ) ) ; return $ this -> redirect ( $ this -> generateUrl ( $ view -> getLocation ( ) ) ) ; } } $ view -> addParameters ( [ 'form' => $ form -> createView ( ) ] ) ; return $ view ; }
Displays the feedback form and processes posted data . The signature of this method follows the one from the default view controller and adds the Request since we use to handle form data .
54,119
public function breadcrumbHasTheFollowingLinks ( TableNode $ table ) { foreach ( $ table -> getTable ( ) as $ breadcrumbItem ) { $ text = $ breadcrumbItem [ 0 ] ; $ url = $ breadcrumbItem [ 1 ] ; if ( $ url === 'null' ) { $ query = sprintf ( '//ul[@id="wo-breadcrumbs"]/li/span[text()="%s"]' , $ text ) ; } else { $ query = sprintf ( '//ul[@id="wo-breadcrumbs"]/li/a[@href="%s"]/span[text()="%s"]' , $ url , $ text ) ; } Assertion :: assertCount ( 1 , $ this -> getXpath ( ) -> findXpath ( $ query ) ) ; } }
Tests if a link is present in the breadcrumbs .
54,120
public function fromArray ( $ data ) { foreach ( $ data as $ param => $ value ) { if ( ! method_exists ( $ this , 'set' . ucfirst ( $ param ) ) ) { continue ; } $ this -> { 'set' . ucfirst ( $ param ) } ( $ value ) ; } return $ this ; }
Converts array to response model
54,121
public function toArray ( $ method ) { $ vars = get_object_vars ( $ this ) ; $ className = explode ( '\\' , get_called_class ( ) ) ; return $ vars + array ( 'model' => end ( $ className ) ) ; }
Convert object to an associative array
54,122
public static function fromString ( $ path ) { $ pathObject = static :: factory ( ) -> create ( $ path ) ; if ( ! $ pathObject instanceof AbsolutePathInterface ) { throw new Exception \ NonAbsolutePathException ( $ pathObject ) ; } return $ pathObject ; }
Creates a new absolute path from its string representation .
54,123
public function generateContentType ( $ extension ) { if ( ! in_array ( $ extension , InvalidExtensionException :: getValidExtensions ( ) ) ) { throw InvalidExtensionException :: fromExtension ( $ extension ) ; } return sprintf ( 'image/%s' , $ extension == self :: DEFAULT_EXTENSION ? 'jpeg' : $ extension ) ; }
Generates the content - type corresponding to the provided extension
54,124
public function getQrCodeContent ( $ messageOrParams , $ extension = null , $ size = null , $ padding = null ) { if ( $ messageOrParams instanceof Params ) { $ extension = $ messageOrParams -> fromRoute ( 'extension' , $ this -> options -> getExtension ( ) ) ; $ size = $ messageOrParams -> fromRoute ( 'size' , $ this -> options -> getSize ( ) ) ; $ padding = $ messageOrParams -> fromRoute ( 'padding' , $ this -> options -> getPadding ( ) ) ; $ messageOrParams = $ messageOrParams -> fromRoute ( 'message' ) ; } else { $ extension = isset ( $ extension ) ? $ extension : $ this -> options -> getExtension ( ) ; $ size = isset ( $ size ) ? $ size : $ this -> options -> getSize ( ) ; $ padding = isset ( $ padding ) ? $ padding : $ this -> options -> getPadding ( ) ; } $ qrCode = new QrCode ( $ messageOrParams ) ; $ qrCode -> setImageType ( $ extension ) ; $ qrCode -> setSize ( $ size ) ; $ qrCode -> setPadding ( $ padding ) ; return $ qrCode -> get ( ) ; }
Returns a QrCode content to be rendered or saved If the first argument is a Params object all the information will be tried to be fetched for it ignoring any other argument
54,125
protected function initHaltHooks ( ) { set_error_handler ( function ( $ level , $ message , $ file = null , $ line = null ) { $ event = $ this -> getApplicationEvent ( ) ; $ this -> emit ( $ event -> setName ( $ this :: EVENT_HANDLE_ERROR ) , $ level , $ message , $ file , $ line ) ; } ) ; set_exception_handler ( function ( $ exception ) { if ( ! ( $ exception instanceof \ Exception ) ) { $ throwable = $ exception ; $ exception = new \ ErrorException ( $ throwable -> getMessage ( ) , $ throwable -> getCode ( ) , E_ERROR , $ throwable -> getFile ( ) , $ throwable -> getLine ( ) ) ; } $ event = $ this -> getApplicationEvent ( ) ; $ this -> emit ( $ event -> setName ( $ this :: EVENT_SYSTEM_EXCEPTION ) , $ exception ) ; } ) ; if ( method_exists ( $ this , 'shutdown' ) ) { register_shutdown_function ( [ $ this , 'shutdown' ] ) ; } }
Init all hooks which will be execute on system shutdown or error
54,126
public function shutdown ( ) { $ applicationEvent = $ this -> getApplicationEvent ( ) ; $ applicationEvent -> setName ( self :: EVENT_SYSTEM_SHUTDOWN ) ; $ this -> emit ( $ applicationEvent ) ; exit ( ( int ) $ this -> isError ( ) ) ; }
Shutdown application lifecycle
54,127
public function map ( $ name , $ callback , array $ arguments = [ ] ) { $ command = new Command ( $ name , $ callback , $ arguments ) ; $ this -> commands [ $ name ] = $ command ; return $ command ; }
Map first argument to callback
54,128
public function handle ( array $ args = [ ] ) { $ source = array_shift ( $ args ) ; $ applicationEvent = $ this -> getApplicationEvent ( ) ; $ applicationEvent -> setName ( self :: EVENT_REQUEST_RECEIVED ) ; $ applicationEvent -> setSourceFile ( $ source ) ; $ applicationEvent -> setArguments ( $ args ) ; $ this -> emit ( $ applicationEvent ) ; $ dispatcher = new Dispatcher ( $ this -> commands , $ this -> container ) ; $ middlewareRunner = new MiddlewareRunner ( $ this -> getMiddlewares ( ) ) ; $ middlewareRunner -> run ( [ $ applicationEvent -> getArguments ( ) ] , function ( $ args ) use ( $ applicationEvent , $ dispatcher ) { $ dispatcher -> dispatch ( $ args ) ; } ) ; }
Dispatch command from given args
54,129
public function run ( array $ argv = null ) { if ( is_null ( $ argv ) ) { global $ argv ; } $ this -> handle ( $ argv ) ; $ this -> shutdown ( ) ; }
execute console lifecycle
54,130
public function setup ( Model $ model , $ settings = array ( ) ) { if ( $ settings ) { foreach ( $ settings as $ field => $ options ) { $ this -> settings [ $ model -> alias ] [ $ field ] = ( array ) $ options + array ( 'required' => true ) ; } } }
Setup the validation and model settings .
54,131
public function filesize ( Model $ model , $ data , $ size = 5242880 ) { return $ this -> _validate ( $ model , $ data , 'size' , array ( $ size ) ) ; }
Validates an image file size . Default max size is 5 MB .
54,132
public function height ( Model $ model , $ data , $ size ) { return $ this -> _validate ( $ model , $ data , 'height' , array ( $ size ) ) ; }
Checks that the image height is exact .
54,133
public function width ( Model $ model , $ data , $ size ) { return $ this -> _validate ( $ model , $ data , 'width' , array ( $ size ) ) ; }
Checks that the image width is exact .
54,134
public function maxHeight ( Model $ model , $ data , $ size ) { return $ this -> _validate ( $ model , $ data , 'maxHeight' , array ( $ size ) ) ; }
Checks the maximum image height .
54,135
public function maxWidth ( Model $ model , $ data , $ size ) { return $ this -> _validate ( $ model , $ data , 'maxWidth' , array ( $ size ) ) ; }
Checks the maximum image width .
54,136
public function minHeight ( Model $ model , $ data , $ size ) { return $ this -> _validate ( $ model , $ data , 'minHeight' , array ( $ size ) ) ; }
Checks the minimum image height .
54,137
public function minWidth ( Model $ model , $ data , $ size ) { return $ this -> _validate ( $ model , $ data , 'minWidth' , array ( $ size ) ) ; }
Checks the minimum image width .
54,138
public function extension ( Model $ model , $ data , array $ allowed = array ( ) ) { return $ this -> _validate ( $ model , $ data , 'ext' , array ( $ allowed ) ) ; }
Validates the extension .
54,139
public function required ( Model $ model , $ data , $ required = true ) { foreach ( $ data as $ value ) { if ( $ required && $ this -> _isEmpty ( $ value ) ) { return false ; } } return true ; }
Makes sure a file field is required and not optional .
54,140
public function beforeValidate ( Model $ model , $ options = array ( ) ) { if ( empty ( $ this -> settings [ $ model -> alias ] ) ) { return true ; } foreach ( $ this -> settings [ $ model -> alias ] as $ field => $ rules ) { $ validations = array ( ) ; foreach ( $ rules as $ rule => $ setting ) { $ set = $ this -> _defaults [ $ rule ] ; if ( ! is_array ( $ setting ) || ! isset ( $ setting [ 'value' ] ) ) { $ setting = array ( 'value' => $ setting ) ; } switch ( $ rule ) { case 'required' : $ arg = ( bool ) $ setting [ 'value' ] ; break ; case 'type' : case 'mimeType' : case 'extension' : $ arg = ( array ) $ setting [ 'value' ] ; break ; default : $ arg = ( int ) $ setting [ 'value' ] ; break ; } if ( ! isset ( $ setting [ 'rule' ] ) ) { $ setting [ 'rule' ] = array ( $ rule , $ arg ) ; } if ( isset ( $ setting [ 'error' ] ) ) { $ setting [ 'message' ] = $ setting [ 'error' ] ; unset ( $ setting [ 'error' ] ) ; } unset ( $ setting [ 'value' ] ) ; $ set = array_merge ( $ set , $ setting ) ; if ( is_array ( $ arg ) ) { $ arg = implode ( ', ' , $ arg ) ; } $ set [ 'message' ] = __d ( 'uploader' , $ set [ 'message' ] , $ arg ) ; $ validations [ $ rule ] = $ set ; } if ( $ validations ) { if ( ! empty ( $ model -> validate [ $ field ] ) ) { $ currentRules = $ model -> validate [ $ field ] ; if ( isset ( $ currentRules [ 'rule' ] ) ) { $ currentRules = array ( $ currentRules [ 'rule' ] => $ currentRules ) ; } $ validations = $ currentRules + $ validations ; } if ( isset ( $ model -> data [ $ model -> alias ] [ $ field ] [ 'tmp_name' ] ) && isset ( $ validations [ 'notEmpty' ] ) ) { unset ( $ validations [ 'notEmpty' ] ) ; } $ this -> _validations [ $ field ] = $ validations ; $ model -> validate [ $ field ] = $ validations ; } } return true ; }
Build the validation rules and validate .
54,141
public function afterValidate ( Model $ model ) { if ( ! empty ( $ this -> _tempFiles ) ) { foreach ( $ this -> _tempFiles as $ file ) { $ file -> delete ( ) ; } $ this -> _tempFiles = array ( ) ; } return true ; }
Delete the temporary file .
54,142
protected function _allowEmpty ( Model $ model , $ field , $ value ) { if ( isset ( $ this -> _validations [ $ field ] [ 'required' ] ) ) { $ rule = $ this -> _validations [ $ field ] [ 'required' ] ; $ required = isset ( $ rule [ 'rule' ] [ 1 ] ) ? $ rule [ 'rule' ] [ 1 ] : true ; if ( $ this -> _isEmpty ( $ value ) ) { if ( $ rule [ 'allowEmpty' ] ) { return true ; } else if ( $ required ) { return false ; } } } return false ; }
Allow empty file uploads to circumvent file validations .
54,143
protected function _validate ( Model $ model , $ data , $ method , array $ params ) { foreach ( $ data as $ field => $ value ) { if ( $ this -> _allowEmpty ( $ model , $ field , $ value ) ) { return true ; } else if ( $ this -> _isEmpty ( $ value ) ) { return false ; } $ file = null ; if ( is_array ( $ value ) ) { $ file = new File ( $ value ) ; } else if ( ! empty ( $ value ) ) { $ target = md5 ( $ value ) ; $ transit = new Transit ( $ value ) ; $ transit -> setDirectory ( TMP ) ; if ( isset ( $ this -> _tempFiles [ $ target ] ) ) { $ file = $ this -> _tempFiles [ $ target ] ; } else if ( file_exists ( $ value ) ) { if ( $ transit -> importFromLocal ( ) ) { $ file = $ transit -> getOriginalFile ( ) ; $ file -> rename ( $ target ) ; } } else if ( preg_match ( '/^http/i' , $ value ) ) { if ( $ transit -> importFromRemote ( ) ) { $ file = $ transit -> getOriginalFile ( ) ; $ file -> rename ( $ target ) ; } } else { if ( $ transit -> importFromStream ( ) ) { $ file = $ transit -> getOriginalFile ( ) ; $ file -> rename ( $ target ) ; } } if ( $ file && ! isset ( $ this -> _tempFiles [ $ target ] ) ) { $ this -> _tempFiles [ $ target ] = $ file ; } } if ( ! $ file ) { $ this -> log ( sprintf ( 'Invalid upload or import for validation: %s' , json_encode ( $ value ) ) , LOG_DEBUG ) ; return false ; } $ validator = new ImageValidator ( ) ; $ validator -> setFile ( $ file ) ; return call_user_func_array ( array ( $ validator , $ method ) , $ params ) ; } return false ; }
Validate the field against the validation rules .
54,144
public function getConfigurator ( ) { if ( ! $ this -> getContainer ( ) -> has ( Configuration :: class ) ) { $ this -> getContainer ( ) -> share ( Configuration :: class , ( new Configuration ( [ ] , true ) ) ) ; } return $ this -> getContainer ( ) -> get ( Configuration :: class ) ; }
Get configuration container
54,145
public function setConfig ( $ key , $ value = null ) { $ configurator = $ this -> getConfigurator ( ) ; if ( ! is_scalar ( $ key ) ) { $ configuratorClass = get_class ( $ configurator ) ; $ configurator -> merge ( new $ configuratorClass ( $ key , true ) ) ; } else { $ configurator [ $ key ] = $ value ; } return $ this ; }
Set a config item . Add recursive if key is traversable .
54,146
public function getConfig ( $ key = null , $ default = null ) { $ configurator = $ this -> getConfigurator ( ) ; if ( null === $ key ) { return $ configurator ; } return $ configurator -> get ( $ key , $ default ) ; }
Get a config key s value
54,147
public function getEventEmitter ( ) { if ( ! $ this -> getContainer ( ) -> has ( EmitterInterface :: class ) ) { $ this -> getContainer ( ) -> share ( EmitterInterface :: class , new Emitter ( ) ) ; } $ validateContract = $ this -> validateContract ( $ this -> getContainer ( ) -> get ( EmitterInterface :: class ) , EmitterInterface :: class ) ; return $ validateContract ; }
Return the event emitter .
54,148
public function getLogger ( $ channel = 'default' ) { if ( isset ( $ this -> loggers [ $ channel ] ) ) { return $ this -> loggers [ $ channel ] ; } $ logger = $ this -> getContainer ( ) -> get ( LoggerInterface :: class , [ $ channel ] ) ; $ this -> loggers [ $ channel ] = $ logger ; $ contract = $ this -> validateContract ( $ this -> loggers [ $ channel ] , LoggerInterface :: class ) ; return $ contract ; }
Return a logger
54,149
public function validateContract ( $ class , $ contract ) { $ validateObject = function ( $ object ) { $ condition = is_string ( $ object ) ? class_exists ( $ object ) || interface_exists ( $ object ) : is_object ( $ object ) ; if ( false === $ condition ) { $ this -> throwException ( new \ InvalidArgumentException ( 'Class not exists ' . $ object ) ) ; } } ; $ convertClassToString = function ( $ object ) { if ( is_object ( $ object ) ) { $ object = get_class ( $ object ) ; } return is_string ( $ object ) ? $ object : false ; } ; $ validateObject ( $ class ) ; $ validateObject ( $ contract ) ; if ( ! ( $ class instanceof $ contract ) ) { if ( is_object ( $ class ) ) { $ class = get_class ( $ class ) ; } $ this -> throwException ( new \ LogicException ( $ convertClassToString ( $ class ) . ' needs to be an instance of ' . $ convertClassToString ( $ contract ) ) ) ; } return $ class ; }
Validates that class is instance of contract
54,150
protected function bindClosureToInstance ( $ closure , $ instance ) { if ( $ closure instanceof \ Closure ) { $ closure = $ closure -> bind ( $ closure , $ instance , get_class ( $ instance ) ) ; } return $ closure ; }
Bind any closure to application instance
54,151
public function setup ( Model $ model , $ settings = array ( ) ) { if ( ! $ settings ) { return ; } if ( ! isset ( $ this -> _columns [ $ model -> alias ] ) ) { $ this -> _columns [ $ model -> alias ] = array ( ) ; } foreach ( $ settings as $ field => $ attachment ) { $ attachment = Set :: merge ( $ this -> _defaultSettings , $ attachment + array ( 'dbColumn' => $ field ) ) ; if ( ! $ attachment [ 'dbColumn' ] ) { $ attachment [ 'dbColumn' ] = $ field ; } $ columns = array ( $ attachment [ 'dbColumn' ] => $ field ) ; if ( ! $ attachment [ 'tempDir' ] ) { $ attachment [ 'tempDir' ] = TMP ; } if ( ! $ attachment [ 'uploadDir' ] ) { $ attachment [ 'finalPath' ] = $ attachment [ 'finalPath' ] ? : '/files/uploads/' ; $ attachment [ 'uploadDir' ] = WWW_ROOT . $ attachment [ 'finalPath' ] ; } if ( $ attachment [ 'transforms' ] ) { foreach ( $ attachment [ 'transforms' ] as $ dbColumn => $ transform ) { $ transform = Set :: merge ( $ this -> _transformSettings , $ transform + array ( 'uploadDir' => $ attachment [ 'uploadDir' ] , 'finalPath' => $ attachment [ 'finalPath' ] , 'dbColumn' => $ dbColumn ) ) ; if ( $ transform [ 'self' ] ) { $ transform [ 'dbColumn' ] = $ attachment [ 'dbColumn' ] ; } $ columns [ $ transform [ 'dbColumn' ] ] = $ field ; $ attachment [ 'transforms' ] [ $ dbColumn ] = $ transform ; } } $ this -> settings [ $ model -> alias ] [ $ field ] = $ attachment ; $ this -> _columns [ $ model -> alias ] += $ columns ; } }
Save attachment settings .
54,152
public function cleanup ( Model $ model ) { parent :: cleanup ( $ model ) ; $ this -> _uploads = array ( ) ; $ this -> _columns = array ( ) ; }
Cleanup and reset the behavior when its detached .
54,153
public function afterFind ( Model $ model , $ results , $ primary = false ) { $ alias = $ model -> alias ; foreach ( $ results as $ i => $ data ) { if ( empty ( $ data [ $ alias ] ) ) { continue ; } foreach ( $ data [ $ alias ] as $ field => $ value ) { if ( empty ( $ this -> settings [ $ alias ] [ $ field ] ) || ! empty ( $ value ) ) { continue ; } $ attachment = $ this -> _settingsCallback ( $ model , $ this -> settings [ $ alias ] [ $ field ] ) ; if ( $ attachment [ 'defaultPath' ] ) { $ results [ $ i ] [ $ alias ] [ $ attachment [ 'dbColumn' ] ] = $ attachment [ 'defaultPath' ] ; } if ( $ attachment [ 'transforms' ] ) { foreach ( $ attachment [ 'transforms' ] as $ transform ) { if ( $ transform [ 'defaultPath' ] ) { $ results [ $ i ] [ $ alias ] [ $ transform [ 'dbColumn' ] ] = $ transform [ 'defaultPath' ] ; } } } } } return $ results ; }
After a find replace any empty fields with the default path .
54,154
public function beforeDelete ( Model $ model , $ cascade = true ) { if ( empty ( $ model -> id ) ) { return false ; } return $ this -> deleteFiles ( $ model , $ model -> id , array ( ) , true ) ; }
Deletes any files that have been attached to this model .
54,155
public function deleteFiles ( Model $ model , $ id , array $ filter = array ( ) , $ isDelete = false ) { $ columns = $ this -> _columns [ $ model -> alias ] ; $ data = $ this -> _doFind ( $ model , array ( $ model -> alias . '.' . $ model -> primaryKey => $ id ) ) ; if ( empty ( $ data [ $ model -> alias ] ) ) { return false ; } $ model -> set ( $ data ) ; $ save = array ( ) ; foreach ( $ data [ $ model -> alias ] as $ column => $ value ) { if ( empty ( $ columns [ $ column ] ) || empty ( $ value ) ) { continue ; } else if ( $ filter && ! in_array ( $ column , $ filter ) ) { continue ; } if ( $ this -> _deleteFile ( $ model , $ columns [ $ column ] , $ value , $ column ) ) { $ save [ $ column ] = '' ; foreach ( $ this -> settings [ $ model -> alias ] [ $ columns [ $ column ] ] [ 'metaColumns' ] as $ metaKey => $ fieldKey ) { $ save [ $ fieldKey ] = '' ; } } } if ( $ save && ! $ isDelete ) { $ model -> id = $ id ; $ model -> save ( $ save , array ( 'validate' => false , 'callbacks' => false , 'fieldList' => array_keys ( $ save ) ) ) ; } return true ; }
Delete all files associated with a record but do not delete the record .
54,156
public function getUploadedFile ( Model $ model ) { if ( isset ( $ this -> _uploads [ $ model -> alias ] ) ) { return $ this -> _uploads [ $ model -> alias ] -> getOriginalFile ( ) ; } return null ; }
Return the uploaded original File object .
54,157
public function getTransformedFiles ( Model $ model ) { if ( isset ( $ this -> _uploads [ $ model -> alias ] ) ) { return $ this -> _uploads [ $ model -> alias ] -> getTransformedFiles ( ) ; } return array ( ) ; }
Return the transformed File objects .
54,158
protected function _settingsCallback ( Model $ model , array $ options ) { if ( method_exists ( $ model , 'beforeUpload' ) ) { $ options = $ model -> beforeUpload ( $ options ) ; } if ( $ options [ 'transforms' ] && method_exists ( $ model , 'beforeTransform' ) ) { foreach ( $ options [ 'transforms' ] as $ i => $ transform ) { $ options [ 'transforms' ] [ $ i ] = $ model -> beforeTransform ( $ transform ) ; } } if ( $ options [ 'transport' ] && method_exists ( $ model , 'beforeTransport' ) ) { $ options [ 'transport' ] = $ model -> beforeTransport ( $ options [ 'transport' ] ) ; } return $ options ; }
Trigger callback methods to modify attachment settings before uploading .
54,159
protected function _addTransformers ( Model $ model , Transit $ transit , array $ attachment ) { if ( empty ( $ attachment [ 'transforms' ] ) ) { return ; } foreach ( $ attachment [ 'transforms' ] as $ options ) { $ transformer = $ this -> _getTransformer ( $ attachment , $ options ) ; if ( $ options [ 'self' ] ) { $ transit -> addSelfTransformer ( $ transformer ) ; } else { $ transit -> addTransformer ( $ transformer ) ; } } }
Add Transit Transformers based on the attachment settings .
54,160
protected function _setTransporter ( Model $ model , Transit $ transit , array $ attachment ) { if ( empty ( $ attachment [ 'transport' ] ) ) { return ; } $ transit -> setTransporter ( $ this -> _getTransporter ( $ attachment , $ attachment [ 'transport' ] ) ) ; }
Set the Transit Transporter to use based on the attachment settings .
54,161
protected function _getTransformer ( array $ attachment , array $ options ) { $ class = isset ( $ options [ 'method' ] ) ? $ options [ 'method' ] : $ options [ 'class' ] ; switch ( $ class ) { case self :: CROP : return new CropTransformer ( $ options ) ; break ; case self :: FLIP : return new FlipTransformer ( $ options ) ; break ; case self :: RESIZE : return new ResizeTransformer ( $ options ) ; break ; case self :: SCALE : return new ScaleTransformer ( $ options ) ; break ; case self :: ROTATE : return new RotateTransformer ( $ options ) ; break ; case self :: EXIF : return new ExifTransformer ( $ options ) ; break ; case self :: FIT : return new FitTransformer ( $ options ) ; break ; default : if ( isset ( $ attachment [ 'transformers' ] [ $ class ] ) ) { return new $ attachment [ 'transformers' ] [ $ class ] ( $ options ) ; } break ; } throw new InvalidArgumentException ( sprintf ( 'Invalid transform class %s' , $ class ) ) ; }
Return a Transformer based on the options .
54,162
protected function _getTransporter ( array $ attachment , array $ options ) { $ class = $ options [ 'class' ] ; switch ( $ class ) { case self :: S3 : return new S3Transporter ( $ options [ 'accessKey' ] , $ options [ 'secretKey' ] , $ options ) ; break ; case self :: GLACIER : return new GlacierTransporter ( $ options [ 'accessKey' ] , $ options [ 'secretKey' ] , $ options ) ; break ; case self :: CLOUD_FILES : return new CloudFilesTransporter ( $ options [ 'username' ] , $ options [ 'apiKey' ] , $ options ) ; break ; default : if ( isset ( $ attachment [ 'transporters' ] [ $ class ] ) ) { return new $ attachment [ 'transporters' ] [ $ class ] ( $ options ) ; } break ; } throw new InvalidArgumentException ( sprintf ( 'Invalid transport class %s' , $ class ) ) ; }
Return a Transporter based on the options .
54,163
protected function _renameAndMove ( Model $ model , File $ file , array $ options ) { $ nameCallback = null ; if ( $ options [ 'nameCallback' ] && method_exists ( $ model , $ options [ 'nameCallback' ] ) ) { $ nameCallback = array ( $ model , $ options [ 'nameCallback' ] ) ; } if ( $ options [ 'uploadDir' ] ) { $ file -> move ( $ options [ 'uploadDir' ] , $ options [ 'overwrite' ] ) ; } $ file -> rename ( $ nameCallback , $ options [ 'append' ] , $ options [ 'prepend' ] , $ options [ 'overwrite' ] ) ; return ( string ) $ options [ 'finalPath' ] . $ file -> basename ( ) ; }
Rename or move the file and return its relative path .
54,164
protected function _deleteFile ( Model $ model , $ field , $ path , $ column ) { if ( empty ( $ this -> settings [ $ model -> alias ] [ $ field ] ) ) { return false ; } $ attachment = $ this -> _settingsCallback ( $ model , $ this -> settings [ $ model -> alias ] [ $ field ] ) ; $ basePath = $ attachment [ 'uploadDir' ] ? : $ attachment [ 'tempDir' ] ; if ( $ attachment [ 'transforms' ] ) { foreach ( $ attachment [ 'transforms' ] as $ transform ) { if ( $ transform [ 'dbColumn' ] === $ column ) { $ basePath = $ transform [ 'uploadDir' ] ; } } } try { if ( $ attachment [ 'transport' ] ) { $ transporter = $ this -> _getTransporter ( $ attachment , $ attachment [ 'transport' ] ) ; return $ transporter -> delete ( $ path ) ; } else { $ file = new File ( $ basePath . basename ( $ path ) ) ; return $ file -> delete ( ) ; } } catch ( Exception $ e ) { $ this -> log ( $ e -> getMessage ( ) , LOG_DEBUG ) ; } return false ; }
Attempt to delete a file using the attachment settings .
54,165
protected function _cleanupOldFiles ( Model $ model , array $ fields ) { $ columns = $ this -> _columns [ $ model -> alias ] ; $ data = $ this -> _doFind ( $ model , array ( $ model -> alias . '.' . $ model -> primaryKey => $ model -> id ) ) ; if ( empty ( $ data [ $ model -> alias ] ) ) { return ; } foreach ( $ fields as $ column => $ value ) { if ( empty ( $ data [ $ model -> alias ] [ $ column ] ) ) { continue ; } if ( ! empty ( $ this -> settings [ $ model -> alias ] [ $ columns [ $ column ] ] ) ) { $ attachment = $ this -> _settingsCallback ( $ model , $ this -> settings [ $ model -> alias ] [ $ columns [ $ column ] ] ) ; if ( ! $ attachment [ 'cleanup' ] ) { continue ; } } $ previous = $ data [ $ model -> alias ] [ $ column ] ; if ( $ previous !== $ value ) { $ this -> _deleteFile ( $ model , $ columns [ $ column ] , $ previous , $ column ) ; } } }
Delete previous files if a record is being overwritten .
54,166
protected function _prepareTransport ( array $ settings ) { $ config = array ( ) ; if ( ! empty ( $ settings [ 'transportDir' ] ) ) { $ config [ 'folder' ] = $ settings [ 'transportDir' ] ; } if ( ! empty ( $ settings [ 'returnUrl' ] ) ) { $ config [ 'returnUrl' ] = $ settings [ 'returnUrl' ] ; } return $ config ; }
Prepare transport configuration .
54,167
public function getErrorMessage ( $ exception ) { $ application = $ this -> application ; $ errorHandler = $ this -> runner ; $ shouldQuit = $ application -> isError ( ) ; if ( $ application instanceof Application ) { if ( ! $ application -> isXmlRequest ( ) && ! $ application -> isJsonRequest ( ) ) { $ shouldQuit = $ shouldQuit && $ application -> getConfig ( ApplicationInterface :: KEY_ERROR , ApplicationInterface :: DEFAULT_ERROR ) ; } } $ errorHandler -> allowQuit ( $ shouldQuit ) ; $ method = $ errorHandler :: EXCEPTION_HANDLER ; ob_start ( ) ; $ errorHandler -> $ method ( $ exception ) ; $ message = ob_get_clean ( ) ; return $ message ; }
Determine error message by error configuration
54,168
public function decorateException ( $ error ) { $ application = $ this -> application ; if ( is_callable ( $ error ) ) { $ error = $ application -> getContainer ( ) -> call ( $ error , [ $ application ] ) ; } if ( is_object ( $ error ) && ! ( $ error instanceof \ Exception ) ) { $ error = method_exists ( $ error , '__toString' ) ? $ error -> __toString ( ) : 'Error with object ' . get_class ( $ error ) ; } if ( is_resource ( $ error ) ) { $ error = 'Error with resource type ' . get_resource_type ( $ error ) ; } if ( is_array ( $ error ) ) { $ error = implode ( "\n" , $ error ) ; } if ( ! ( $ error instanceof \ Exception ) ) { $ error = new \ Exception ( is_scalar ( $ error ) ? $ error : 'Error with ' . gettype ( $ error ) ) ; } return $ error ; }
Convert any type into an exception
54,169
public function connect ( array $ servers ) { $ memcache = $ this -> getMemcache ( ) ; foreach ( $ servers as $ server ) { $ memcache -> addServer ( $ server [ 'host' ] , $ server [ 'port' ] , $ server [ 'weight' ] ) ; } if ( $ memcache -> getVersion ( ) === false ) { throw new RuntimeException ( "Could not establish Memcache connection." ) ; } return $ memcache ; }
Create a new Memcache connection .
54,170
public function resolve ( $ middlewares ) { $ last = function ( $ request , $ response ) { } ; while ( $ middleware = array_pop ( $ middlewares ) ) { if ( is_object ( $ middleware ) ) { if ( method_exists ( $ middleware , '__invoke' ) ) { $ middleware = [ $ middleware , '__invoke' ] ; } } if ( ! is_callable ( $ middleware ) ) { throw new \ InvalidArgumentException ( 'Middle needs to be callable' ) ; } $ last = function ( ) use ( $ middleware , $ last ) { $ args = func_get_args ( ) ; $ args [ ] = $ last ; return call_user_func_array ( $ middleware , $ args ) ; } ; } return $ last ; }
Resolve middleware queue
54,171
public function isAttributeChanged ( $ name , $ identical = true ) { if ( parent :: isAttributeChanged ( $ name , $ identical ) === true ) { return true ; } $ attributeName = $ this -> getTranslateAttributeName ( $ name ) ; return $ this -> getTranslation ( ) -> isAttributeChanged ( $ attributeName , $ identical ) ; }
Returns a value indicating whether the named attribute has been changed or attribute has been changed in translation relation model .
54,172
public function dispatch ( $ argv ) { $ name = reset ( $ argv ) ; if ( ! $ this -> hasCommand ( $ name ) ) { throw new \ InvalidArgumentException ( 'Command not found' ) ; } $ command = $ this -> commands [ $ name ] ; $ arguments = $ command -> getArguments ( ) ; $ arguments -> parse ( $ argv ) ; $ handler = $ command -> getHandler ( ) ; if ( is_array ( $ handler ) ) { $ class = $ handler [ 0 ] ; $ obj = $ this -> container -> get ( $ class ) ; $ handler [ 0 ] = $ obj ; } call_user_func_array ( $ handler , [ $ arguments ] ) ; }
Dispatch handler for given command
54,173
public function wrap ( $ callable , $ params = [ ] ) { $ kernel = new ClosureHttpKernel ( ) ; if ( is_callable ( $ callable ) ) { $ middleware = $ callable ( $ kernel ) ; } else { $ params = [ 'app' => $ kernel ] + $ params ; $ makeMethod = method_exists ( $ this -> container , 'makeWith' ) ? 'makeWith' : 'make' ; $ middleware = $ this -> container -> $ makeMethod ( $ callable , $ params ) ; } if ( $ middleware instanceof TerminableInterface ) { return new TerminableClosureMiddleware ( $ kernel , $ middleware ) ; } return new ClosureMiddleware ( $ kernel , $ middleware ) ; }
Wrap the StackPHP Middleware in a Laravel Middleware .
54,174
public function getRouter ( ) { if ( ! isset ( $ this -> router ) ) { $ container = clone $ this -> getContainer ( ) ; $ container -> delegate ( new ReflectionContainer ) ; $ this -> router = ( new RouteCollection ( $ container ) ) ; } $ router = $ this -> validateContract ( $ this -> router , RouteCollection :: class ) ; return $ router ; }
Return the router .
54,175
public function getRequest ( ) { if ( ! $ this -> getContainer ( ) -> has ( ServerRequestInterface :: class ) ) { $ this -> getContainer ( ) -> share ( ServerRequestInterface :: class , function ( ) { $ beforeIndexPosition = strpos ( $ _SERVER [ 'PHP_SELF' ] , '/index.php' ) ; if ( false !== $ beforeIndexPosition && $ beforeIndexPosition > 0 ) { $ scriptUrl = substr ( $ _SERVER [ 'PHP_SELF' ] , 0 , $ beforeIndexPosition ) ; $ _SERVER [ 'REQUEST_URI' ] = str_replace ( [ '/index.php' , $ scriptUrl ] , '' , $ _SERVER [ 'REQUEST_URI' ] ) ; } return ServerRequestFactory :: fromGlobals ( ) -> withHeader ( 'content-type' , $ this -> getContentType ( ) ) ; } ) ; } $ request = $ this -> validateContract ( $ this -> getContainer ( ) -> get ( ServerRequestInterface :: class ) , ServerRequestInterface :: class ) ; return $ request ; }
Get the request
54,176
public function getResponseEmitter ( ) { if ( ! $ this -> getContainer ( ) -> has ( Response \ EmitterInterface :: class ) ) { $ this -> getContainer ( ) -> share ( Response \ EmitterInterface :: class , new Response \ SapiEmitter ( ) ) ; } $ contract = $ this -> validateContract ( $ this -> getContainer ( ) -> get ( Response \ EmitterInterface :: class ) , Response \ EmitterInterface :: class ) ; return $ contract ; }
Get response emitter
54,177
public function isAjaxRequest ( ) { return false !== strpos ( strtolower ( ServerRequestFactory :: getHeader ( 'x-requested-with' , $ this -> getRequest ( ) -> getHeaders ( ) , '' ) ) , 'xmlhttprequest' ) && $ this -> isHttpRequest ( ) ; }
Check if request is a ajax request
54,178
public function map ( $ method , $ route , $ action ) { return $ this -> getRouter ( ) -> map ( $ method , $ route , $ this -> bindClosureToInstance ( $ action , $ this ) ) ; }
Add a route to the map .
54,179
public function handle ( ServerRequestInterface $ request , ResponseInterface $ response = null , $ catch = self :: DEFAULT_ERROR_CATCH ) { if ( ! $ this -> getContainer ( ) -> has ( ServerRequestInterface :: class ) ) { $ this -> getContainer ( ) -> share ( ServerRequestInterface :: class , $ request ) ; } $ contentType = ServerRequestFactory :: getHeader ( 'content-type' , $ this -> getRequest ( ) -> getHeaders ( ) , '' ) ; $ this -> setContentType ( $ contentType ) ; if ( $ response === null ) { $ response = $ this -> getResponse ( ) ; } $ applicationEvent = $ this -> getApplicationEvent ( ) ; $ applicationEvent -> setRequest ( $ request ) ; $ applicationEvent -> setResponse ( $ response ) ; try { $ response = $ this -> handleResponse ( $ this -> handleRequest ( $ request ) , $ response ) ; } catch ( \ Exception $ exception ) { $ notFoundException = $ exception instanceof NotFoundException ; $ response = $ this -> handleError ( $ exception , $ request , $ response , $ catch ) -> withStatus ( $ notFoundException ? 404 : 500 ) ; } $ response = $ this -> validateContract ( $ response , ResponseInterface :: class ) ; $ this -> setContentType ( ServerRequestFactory :: getHeader ( 'content-type' , $ response -> getHeaders ( ) , '' ) ) ; return $ response ; }
Convert request into response . If an error occurs Hawkbit tries to handle error as response .
54,180
public function handleRequest ( ServerRequestInterface $ request ) { $ applicationEvent = $ this -> getApplicationEvent ( ) ; $ applicationEvent -> setName ( self :: EVENT_REQUEST_RECEIVED ) ; $ this -> emit ( $ applicationEvent , $ request ) ; return $ applicationEvent -> getRequest ( ) ; }
Convert request into response .
54,181
public function handleError ( $ exception , ServerRequestInterface $ request , ResponseInterface $ response , $ catch = self :: DEFAULT_ERROR_CATCH ) { $ this -> error = true ; $ errorHandler = $ this -> getErrorHandler ( ) ; $ catch = self :: DEFAULT_ERROR_CATCH !== $ catch ? $ catch : $ this -> getConfig ( self :: KEY_ERROR_CATCH , $ catch ) ; $ showError = $ this -> getConfig ( self :: KEY_ERROR , static :: DEFAULT_ERROR ) ; $ this -> pushException ( $ errorHandler -> decorateException ( $ exception ) ) ; try { $ middlewares = $ this -> getRouter ( ) -> getMiddlewareStack ( ) ; $ middlewareRunner = new ExecutionChain ( ) ; foreach ( $ middlewares as $ middleware ) { $ middlewareRunner -> middleware ( $ middleware ) ; } $ response = $ middlewareRunner -> execute ( $ request , $ response ) ; } catch ( \ Exception $ e ) { $ this -> pushException ( $ e ) ; } $ exception = $ this -> getLastException ( ) ; $ message = $ errorHandler -> getErrorMessage ( $ exception ) ; $ errorResponse = $ this -> determineErrorResponse ( $ exception , $ message , $ response , $ request ) ; if ( false === $ catch && true === $ showError ) { $ this -> throwException ( $ exception ) ; } return $ errorResponse ; }
Handle error and return response of error message or throw error if error . catch is disabled .
54,182
public function emitResponse ( ServerRequestInterface $ request , ResponseInterface $ response ) { try { $ this -> getResponseEmitter ( ) -> emit ( $ response ) ; } catch ( \ Exception $ e ) { if ( $ this -> canForceResponseEmitting ( ) ) { $ maxBufferLevel = ob_get_level ( ) ; while ( ob_get_level ( ) > $ maxBufferLevel ) { ob_end_flush ( ) ; } echo $ response -> getBody ( ) ; } else { throw $ e ; } } $ applicationEvent = $ this -> getApplicationEvent ( ) ; $ applicationEvent -> setName ( self :: EVENT_RESPONSE_SENT ) ; $ applicationEvent -> setRequest ( $ request ) ; $ applicationEvent -> setResponse ( $ response ) ; $ this -> emit ( $ applicationEvent ) ; }
Emit a response
54,183
public function shutdown ( $ response = null ) { $ this -> collectGarbage ( ) ; $ applicationEvent = $ this -> getApplicationEvent ( ) ; $ applicationEvent -> setResponse ( $ response ) ; $ applicationEvent -> setName ( self :: EVENT_SYSTEM_SHUTDOWN ) ; $ this -> emit ( $ applicationEvent , $ this -> terminateOutputBuffering ( 1 , $ response ) ) ; }
Finish request . Collect garbage and terminate output buffering
54,184
public function terminateOutputBuffering ( $ level = 0 , $ response = null ) { if ( $ response instanceof ResponseInterface ) { $ body = $ response -> getBody ( ) ; if ( $ body -> isReadable ( ) ) { $ body -> close ( ) ; } } if ( $ this -> isCli ( ) ) { return [ ] ; } if ( ! is_numeric ( $ level ) ) { $ level = 0 ; } if ( ! is_int ( $ level ) ) { $ level = ( int ) $ level ; } if ( - 1 > $ level ) { $ level = 0 ; } $ content = [ ] ; while ( ob_get_level ( ) > $ level ) { $ content [ ] = ob_get_clean ( ) ; } return $ content ; }
Close response stream and terminate output buffering
54,185
private function determineErrorResponse ( $ exception , $ message , ResponseInterface $ response , ServerRequestInterface $ request ) { $ applicationEvent = $ this -> getApplicationEvent ( ) ; $ applicationEvent -> setName ( self :: EVENT_LIFECYCLE_ERROR ) ; $ applicationEvent -> setRequest ( $ request ) ; $ applicationEvent -> setResponse ( $ response ) ; $ applicationEvent -> setErrorResponse ( $ this -> getResponse ( ) ) ; $ this -> emit ( $ applicationEvent , $ exception ) ; $ errorResponse = $ applicationEvent -> getErrorResponse ( ) ; if ( ! $ errorResponse -> getBody ( ) -> isWritable ( ) ) { return $ errorResponse ; } $ content = $ errorResponse -> getBody ( ) -> __toString ( ) ; if ( empty ( $ content ) ) { $ errorResponse -> getBody ( ) -> write ( $ message ) ; } return $ errorResponse ; }
Determines response for error . Emits lifecycle . error event .
54,186
private function recomposeSymfonyRequest ( Request $ request ) { try { try { $ content = $ request -> getContent ( true ) ; } catch ( \ LogicException $ e ) { $ content = $ request -> getContent ( ) ; } } catch ( \ LogicException $ e ) { $ content = file_get_contents ( 'php://input' ) ; } return $ request :: create ( $ request -> getUri ( ) , $ request -> getMethod ( ) , $ request -> getMethod ( ) === 'PATCH' ? $ request -> request -> all ( ) : $ request -> query -> all ( ) , $ request -> cookies -> all ( ) , $ request -> files -> all ( ) , $ request -> server -> all ( ) , $ content ) ; }
Avoid exception throw when request content is null
54,187
public function extendCache ( Application $ app ) { $ app -> resolving ( 'cache' , function ( CacheManager $ cache ) { $ cache -> extend ( 'memcache' , function ( $ app ) { return $ app [ 'memcache.store' ] ; } ) ; } ) ; }
Add the memcache driver to the cache manager .
54,188
public function extendSession ( Application $ app ) { $ app -> resolving ( 'session' , function ( SessionManager $ session ) { $ session -> extend ( 'memcache' , function ( $ app ) { return $ app [ 'memcache.driver' ] ; } ) ; } ) ; }
Add the memcache driver to the session manager .
54,189
public function recognizeErrorResponseHandler ( $ exception , $ inspector , Run $ run ) { $ app = $ this -> application ; $ handlerClass = PrettyPageHandler :: class ; if ( $ app -> isCli ( ) || false === $ app -> getConfig ( ApplicationInterface :: KEY_ERROR , ApplicationInterface :: DEFAULT_ERROR ) ) { $ handlerClass = PlainTextHandler :: class ; } if ( $ app instanceof Application ) { if ( $ app -> isSoapRequest ( ) || $ app -> isXmlRequest ( ) ) { $ handlerClass = XmlResponseHandler :: class ; } elseif ( $ app -> isAjaxRequest ( ) || $ app -> isJsonRequest ( ) ) { $ handlerClass = JsonResponseHandler :: class ; } } $ handler = new $ handlerClass ; $ handler -> setException ( $ exception ) ; $ handler -> setInspector ( $ inspector ) ; $ handler -> setRun ( $ run ) ; return $ handler -> handle ( ) ; }
Recognize response handler for error by content type and environment .
54,190
public function notifySystemWithError ( $ exception ) { $ app = $ this -> application ; $ app -> getLogger ( ) -> error ( $ exception -> getMessage ( ) ) ; $ applicationEvent = $ app -> getApplicationEvent ( ) ; $ applicationEvent -> setName ( ApplicationInterface :: EVENT_SYSTEM_ERROR ) ; $ app -> emit ( $ applicationEvent , $ exception ) ; return Handler :: DONE ; }
Notify system after error occurs
54,191
public function hasMethod ( $ name ) { return parent :: hasMethod ( $ name ) || is_object ( $ this -> getTranslation ( ) ) && $ this -> getTranslation ( ) -> hasMethod ( $ name ) ; }
Returns a value indicating whether a method is defined .
54,192
public function cleanPhone ( $ phone ) { $ response = $ this -> query ( $ this -> prepareUri ( 'clean/phone' ) , [ $ phone ] ) ; $ result = $ this -> populate ( new Phone , $ response ) ; if ( ! $ result instanceof Phone ) { throw new RuntimeException ( 'Unexpected populate result: ' . get_class ( $ result ) . '. Expected: ' . Phone :: class ) ; } return $ result ; }
Cleans phone .
54,193
public function cleanPassport ( $ passport ) { $ response = $ this -> query ( $ this -> prepareUri ( 'clean/passport' ) , [ $ passport ] ) ; $ result = $ this -> populate ( new Passport ( ) , $ response ) ; if ( ! $ result instanceof Passport ) { throw new RuntimeException ( 'Unexpected populate result: ' . get_class ( $ result ) . '. Expected: ' . Passport :: class ) ; } return $ result ; }
Cleans passport .
54,194
public function cleanEmail ( $ email ) { $ response = $ this -> query ( $ this -> prepareUri ( 'clean/email' ) , [ $ email ] ) ; $ result = $ this -> populate ( new Email , $ response ) ; if ( ! $ result instanceof Email ) { throw new RuntimeException ( 'Unexpected populate result: ' . get_class ( $ result ) . '. Expected: ' . Email :: class ) ; } return $ result ; }
Cleans email .
54,195
public function cleanDate ( $ date ) { $ response = $ this -> query ( $ this -> prepareUri ( 'clean/birthdate' ) , [ $ date ] ) ; $ result = $ this -> populate ( new Date , $ response ) ; if ( ! $ result instanceof Date ) { throw new RuntimeException ( 'Unexpected populate result: ' . get_class ( $ result ) . '. Expected: ' . Date :: class ) ; } return $ result ; }
Cleans date .
54,196
public function cleanVehicle ( $ vehicle ) { $ response = $ this -> query ( $ this -> prepareUri ( 'clean/vehicle' ) , [ $ vehicle ] ) ; $ result = $ this -> populate ( new Vehicle , $ response ) ; if ( ! $ result instanceof Vehicle ) { throw new RuntimeException ( 'Unexpected populate result: ' . get_class ( $ result ) . '. Expected: ' . Vehicle :: class ) ; } return $ result ; }
Cleans vehicle .
54,197
protected function query ( $ uri , array $ params = [ ] , $ method = self :: METHOD_POST ) { $ request = new Request ( $ method , $ uri , [ 'Content-Type' => 'application/json' , 'Authorization' => 'Token ' . $ this -> token , 'X-Secret' => $ this -> secret , ] , 0 < count ( $ params ) ? json_encode ( $ params ) : null ) ; $ response = $ this -> httpClient -> send ( $ request , $ this -> httpOptions ) ; $ result = json_decode ( $ response -> getBody ( ) , true ) ; if ( json_last_error ( ) !== JSON_ERROR_NONE ) { throw new RuntimeException ( 'Error parsing response: ' . json_last_error_msg ( ) ) ; } if ( empty ( $ result ) ) { throw new RuntimeException ( 'Empty result' ) ; } return array_shift ( $ result ) ; }
Requests API .
54,198
protected function populate ( AbstractResponse $ object , array $ data ) { $ reflect = new ReflectionClass ( $ object ) ; $ properties = $ reflect -> getProperties ( ReflectionProperty :: IS_PUBLIC ) ; foreach ( $ properties as $ property ) { if ( array_key_exists ( $ property -> name , $ data ) ) { $ object -> { $ property -> name } = $ this -> getValueByAnnotatedType ( $ property , $ data [ $ property -> name ] ) ; } } return $ object ; }
Populates object with data .
54,199
protected function getValueByAnnotatedType ( ReflectionProperty $ property , $ value ) { $ comment = $ property -> getDocComment ( ) ; if ( preg_match ( '/@var (.+?)(\|null)? /' , $ comment , $ matches ) ) { switch ( $ matches [ 1 ] ) { case 'integer' : case 'int' : $ value = ( int ) $ value ; break ; case 'float' : $ value = ( float ) $ value ; break ; } } return $ value ; }
Guesses and converts property type by phpdoc comment .