idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
19,100
private static function response ( ContainerInterface $ container ) : ResponseInterface { if ( ! $ container -> has ( ResponseInterface :: class ) ) { throw new InvalidArgumentException ( 'Moon received an invalid response instance from the container' ) ; } return $ container -> get ( ResponseInterface :: class ) ; }
Return an instance of the ResponseInterface .
19,101
private static function processor ( ContainerInterface $ container ) : ProcessorInterface { if ( ! $ container -> has ( ProcessorInterface :: class ) ) { return new WebProcessor ( $ container ) ; } return $ container -> get ( ProcessorInterface :: class ) ; }
Return an instance of the ProcessorInterface .
19,102
private static function errorHandler ( ContainerInterface $ container ) : ErrorHandlerInterface { if ( ! $ container -> has ( ErrorHandlerInterface :: class ) ) { return new ErrorHandler ( ) ; } return $ container -> get ( ErrorHandlerInterface :: class ) ; }
Return an instance of the ErrorHandlerInterface .
19,103
private static function invalidRequestHandler ( ContainerInterface $ container ) : InvalidRequestHandlerInterface { if ( ! $ container -> has ( InvalidRequestHandlerInterface :: class ) ) { return new InvalidRequestHandler ( ) ; } return $ container -> get ( InvalidRequestHandlerInterface :: class ) ; }
Return an instance of the NotFoundHandlerInterface .
19,104
private static function matchableRequest ( ContainerInterface $ container ) : MatchableRequestInterface { if ( ! $ container -> has ( MatchableRequestInterface :: class ) ) { return new MatchableRequest ( $ container -> get ( ServerRequestInterface :: class ) ) ; } return $ container -> get ( MatchableRequestInterface :: class ) ; }
Return an instance of the MatchableInterface .
19,105
private static function streamReadLength ( ContainerInterface $ container ) : ? int { return $ container -> has ( self :: STREAM_READ_LENGTH ) ? $ container -> get ( self :: STREAM_READ_LENGTH ) : null ; }
Return the length for read the stream if null is return all the body will be print .
19,106
protected function getFixtureFingerprintArguments ( array $ arguments ) { $ fingerprintArguments = array ( ) ; foreach ( $ arguments as $ arg ) { if ( is_object ( $ arg ) && method_exists ( $ arg , '__toString' ) ) { $ fingerprintArg = ( string ) $ arg ; } else { $ fingerprintArg = $ arg ; } $ fingerprintArguments [ ] = $ fingerprintArg ; } return $ fingerprintArguments ; }
Can be overwritten by classes that use this trait
19,107
public function bind ( $ bindUser = null , $ bindPass = null ) { if ( false === ldap_bind ( $ this -> ldapResource , $ bindUser , $ bindPass ) ) { throw new LdapClientException ( sprintf ( 'LDAP error: (%d) %s' , ldap_errno ( $ this -> ldapResource ) , ldap_error ( $ this -> ldapResource ) ) ) ; } }
Bind to an LDAP server .
19,108
public function getFlash ( $ key ) { if ( $ this -> has ( $ key ) ) { $ flashData = $ _SESSION [ $ key ] ; $ this -> delete ( $ key ) ; return $ flashData ; } }
Gets flash values by given key
19,109
public function initLoader ( Config $ config ) { $ loader = new Loader ( ) ; $ loader -> registerDirs ( [ $ config -> application -> libraryDir , $ config -> application -> pluginDir , $ config -> application -> taskDir ] ) -> register ( ) ; }
Initializes loader Registers library and plugin directory
19,110
public function findOneHavingAccount ( Account $ account ) { $ query = $ this -> createQuery ( ) ; return $ query -> matching ( $ query -> contains ( 'accounts' , $ account ) ) -> execute ( ) -> getFirst ( ) ; }
Finds a Party instance if any which has the given Account attached .
19,111
protected function apply ( iterable $ iterable ) : iterable { return Pipeline :: with ( $ iterable ) -> mapKeys ( function ( $ _ , $ info ) { $ field = is_array ( $ info ) ? ( $ info [ 'field' ] ?? null ) : $ info ; $ newField = $ this -> map [ $ field ] ?? ( $ this -> dynamic ? $ field : null ) ; return isset ( $ newField ) && is_array ( $ info ) ? [ 'field' => $ newField ] + $ info : $ newField ; } ) -> filter ( function ( $ _ , $ info ) { return $ info !== null ; } ) ; }
Apply mapping .
19,112
public function addRoute ( array $ routeArray ) { $ routeKeys = array_keys ( $ routeArray ) ; $ routeValues = array_values ( $ routeArray ) ; $ routeName = reset ( $ routeKeys ) ; $ route = reset ( $ routeValues ) ; $ this -> routes [ $ routeName ] = $ route ; return $ this ; }
Adds single route definition
19,113
public function addModuleRoutes ( array $ module ) { $ routeArray = $ this -> getRouteArrayFromModulePath ( $ module [ 'path' ] ) ; $ this -> addRoutes ( $ routeArray ) ; return $ this ; }
Adds module routes from specified path
19,114
private function getRouteArrayFromModulePath ( $ path ) { $ path = dirname ( $ path ) . '/config/routes.php' ; if ( file_exists ( $ path ) && is_file ( $ path ) ) { return require $ path ; } return array ( ) ; }
Extracts routes from specified path
19,115
private function groupRoutes ( ) { $ routes = array ( ) ; foreach ( $ this -> routeTypes as $ type => $ typeName ) { $ routes [ $ type ] = array ( ) ; } foreach ( $ this -> routes as $ routePattern => $ route ) { if ( ! isset ( $ route [ 'type' ] ) ) { $ route [ 'type' ] = Router :: BASE_ROUTE ; } $ this -> validateRouteType ( $ route [ 'type' ] ) ; $ routes [ $ route [ 'type' ] ] [ $ routePattern ] = $ route ; } $ this -> routes = $ routes ; }
Groups routes by types
19,116
public function setup ( ) { $ this -> groupRoutes ( ) ; foreach ( $ this -> routes as $ type => $ routes ) { foreach ( $ routes as $ name => $ route ) { $ newRoute = new Route ( $ name , $ route ) ; if ( ! $ newRoute -> hasParam ( 'hostname' ) ) { $ newRoute -> setParam ( 'hostname' , $ this -> resolveDefaultHostName ( ) ) ; } $ routeType = $ this -> resolveRouteType ( $ type ) ; $ routeType -> add ( $ this -> getRouter ( ) , $ newRoute ) ; } } }
Setups router Adds rules to router
19,117
private function resolveRouteType ( $ routeType ) { $ typeClassName = sprintf ( '%sRoute' , ucfirst ( $ routeType ) ) ; $ classNamespace = __NAMESPACE__ . '\\Router\\Route\\' . $ typeClassName ; if ( ! array_key_exists ( $ classNamespace , $ this -> resolvedTypes ) ) { $ reflectionClass = new \ ReflectionClass ( $ classNamespace ) ; $ this -> resolvedTypes [ $ classNamespace ] = $ reflectionClass -> newInstance ( ) ; } return $ this -> resolvedTypes [ $ classNamespace ] ; }
Resolves route type
19,118
public static function get ( $ key ) { return self :: has ( $ key ) ? self :: decode ( $ _COOKIE [ $ key ] ) : NULL ; }
Gets data from cookie by given key
19,119
public static function set ( $ key , $ value = '' , $ time = 0 , $ path = '/' , $ domain = '' , $ secure = FALSE , $ httponly = FALSE ) { return setcookie ( $ key , self :: encode ( $ value ) , time ( ) + $ time , $ path , $ domain , $ secure , $ httponly ) ; }
Sets cookie data by given key
19,120
public static function delete ( $ key , $ path = '/' ) { if ( self :: has ( $ key ) ) { setcookie ( $ key , '' , time ( ) - 3600 , $ path ) ; } }
Delete cookie data by given key
19,121
public static function flush ( ) { if ( count ( $ _COOKIE ) > 0 ) { foreach ( $ _COOKIE as $ key => $ value ) { self :: delete ( $ key , '/' ) ; } } }
Deletes whole cookie data
19,122
public function run ( MatchablePipelineCollectionInterface $ pipelines ) : ResponseInterface { try { if ( $ handledResponse = $ this -> handlePipeline ( $ pipelines ) ) { return $ handledResponse ; } $ statusCode = $ this -> matchableRequest -> isPatternMatched ( ) ? StatusCodeInterface :: STATUS_METHOD_NOT_ALLOWED : StatusCodeInterface :: STATUS_NOT_FOUND ; return $ this -> invalidRequestHandler -> __invoke ( $ this -> matchableRequest -> request ( ) , $ this -> response -> withStatus ( $ statusCode ) ) ; } catch ( Throwable $ e ) { return $ this -> errorHandler -> __invoke ( $ e , $ this -> request , $ this -> response ) ; } }
Run the web application and print a Response .
19,123
private function handlePipeline ( MatchablePipelineCollectionInterface $ pipelines ) : ? ResponseInterface { foreach ( $ pipelines as $ pipeline ) { if ( $ pipeline -> matchBy ( $ this -> matchableRequest ) ) { $ stages = \ array_merge ( $ this -> stages ( ) , $ pipeline -> stages ( ) ) ; $ pipelineResponse = $ this -> processor -> processStages ( $ stages , $ this -> matchableRequest -> request ( ) ) ; if ( $ pipelineResponse instanceof ResponseInterface ) { return $ pipelineResponse ; } $ body = $ this -> response -> getBody ( ) ; $ body -> write ( $ pipelineResponse ) ; return $ this -> response -> withBody ( $ body ) ; } } return null ; }
Process the pipelines and return a ResponseInterface if one of this match .
19,124
public function sendResponse ( ResponseInterface $ response ) : void { \ http_response_code ( $ response -> getStatusCode ( ) ) ; foreach ( $ response -> getHeaders ( ) as $ headerName => $ headerValues ) { foreach ( $ headerValues as $ headerValue ) { \ header ( "$headerName: $headerValue" , false ) ; } } $ body = $ response -> getBody ( ) ; if ( $ body -> isSeekable ( ) ) { $ body -> rewind ( ) ; } if ( ! $ body -> isReadable ( ) ) { return ; } if ( null === $ this -> streamReadLength ) { echo $ body -> __toString ( ) ; return ; } while ( ! $ body -> eof ( ) ) { echo $ body -> read ( $ this -> streamReadLength ) ; } }
Send headers and body to the client .
19,125
public function fillObjectProps ( $ arguments ) { foreach ( $ arguments as $ key => $ value ) { if ( ! in_array ( $ key , $ this -> fillable ) ) { throw new \ Exception ( _message ( ExceptionMessages :: INAPPROPRIATE_PROPERTY , $ key ) ) ; } $ this -> $ key = $ value ; } }
Fill Object Properties
19,126
public static function output ( $ message , $ data = null ) { if ( static :: $ mode == "html" ) { static :: html ( $ message , $ data ) ; } else { static :: text ( $ message , $ data ) ; } }
Output a message in the current mode if we are currently debugging
19,127
protected static function indent ( ) { $ char = ( static :: $ mode == "html" ) ? "&nbsp;" : " " ; for ( $ i = 0 ; $ i < static :: $ indent ; $ i ++ ) { for ( $ y = 0 ; $ y < 4 ; $ y ++ ) { echo $ char ; } } }
Output some indentation based on the current level
19,128
public static function text ( $ message , $ data = null ) { if ( ! static :: $ on ) { return ; } echo "--------------------------------------------------------------------------------\n" ; static :: indent ( ) ; echo static :: getTime ( ) . " - " . $ message . "\n" ; if ( is_array ( $ data ) ) { print_r ( $ data ) ; } elseif ( $ data ) { static :: indent ( ) ; echo " " . $ data . "\n" ; } }
Output a message in text mode if we are currently debugging
19,129
public static function html ( $ message , $ data = null ) { if ( ! static :: $ on ) { return ; } echo "<hr>" ; echo "<i>" ; static :: indent ( ) ; echo "<b>" . static :: getTime ( ) . " - " . $ message . "</b>" ; if ( is_array ( $ data ) ) { Html :: print_r ( $ data ) ; } elseif ( $ data ) { static :: indent ( ) ; echo "&nbsp;&nbsp;&nbsp;&nbsp;" . $ data . "<br>" ; } echo "</i>" ; }
Output a message in html mode if we are currently debugging
19,130
public static function call ( $ message , callable $ func ) { $ time = microtime ( true ) ; static :: output ( $ message . " [START]" ) ; static :: $ indent ++ ; $ func ( ) ; static :: $ indent -- ; static :: output ( $ message . " [END] (" . number_format ( microtime ( true ) - $ time , 3 ) . ")" ) ; }
Output a start time run a callable then out the endtime
19,131
public function isExpired ( $ lifetime ) { $ interval = $ this -> createdOn -> diff ( new \ DateTimeImmutable ( ) ) ; return $ interval -> s >= ( int ) $ lifetime ; }
Checks if the token is expired comparing with the given lifetime .
19,132
protected function resolveMeta ( ) : void { expect_type ( $ this -> meta , 'callable' , \ BadMethodCallException :: class ) ; $ meta = i \ function_call ( $ this -> meta ) ; expect_type ( $ meta , 'array' , \ UnexpectedValueException :: class , "Failed to get meta: Expected %2\$s, got %1\$s" ) ; $ this -> meta = $ meta ; }
Resolve metadata if it s still a Closure .
19,133
private function getLocaleFromTypo3 ( Request $ request ) : ? string { $ locale = null ; if ( ( bool ) $ language = $ request -> attributes -> get ( 'language' ) ) { [ $ locale ] = \ explode ( '.' , $ language -> getLocale ( ) ) ; } elseif ( ( bool ) $ site = $ request -> attributes -> get ( 'site' ) ) { [ $ locale ] = \ explode ( '.' , $ site -> getDefaultLanguage ( ) -> getLocale ( ) ) ; } return $ locale ; }
Tries to get the exact locale from TYPO3 if it can be found in the request .
19,134
private function getDenormalizedLocaleFromTypo3 ( Request $ request ) : ? string { if ( ( bool ) $ language = $ request -> attributes -> get ( 'language' ) ) { return \ trim ( $ language -> getBase ( ) -> getPath ( ) , '/' ) ; } if ( ( bool ) $ site = $ request -> attributes -> get ( 'site' ) ) { return \ trim ( $ site -> getDefaultLanguage ( ) -> getBase ( ) -> getPath ( ) , '/' ) ; } return null ; }
Tries to get a denormalized locale for routing resolved from the base path .
19,135
private function getValidationData ( $ markup ) { $ this -> httpRequestParameters [ 'body' ] = $ markup ; $ reponse = $ this -> httpClient -> post ( $ this -> configuration [ self :: ENDPOINT_CONFIG_KEY ] , $ this -> httpRequestParameters ) ; $ responseData = $ reponse -> getBody ( ) -> getContents ( ) ; $ validationData = json_decode ( $ responseData , true ) ; if ( $ validationData === null ) { throw new Exception ( 'Unable to parse W3C Markup Validation Service response.' ) ; } return $ validationData ; }
Sends a validation request to a W3C Markup Validation Service and returns decoded validation data .
19,136
private function getValidationMessages ( array $ validationData ) { $ messages = array ( ) ; $ messagesData = $ validationData [ 'messages' ] ; foreach ( $ messagesData as $ messageData ) { $ message = new W3CMarkupValidatorMessage ( $ messageData ) ; $ messages [ ] = $ message ; } return $ messages ; }
Parses validation data and returns validation messages .
19,137
public function can ( $ permission , $ allowAny = false ) { if ( $ allowAny ) { return $ this -> hasAnyAccess ( is_array ( $ permission ) ? $ permission : [ $ permission ] ) ; } return $ this -> hasAccess ( is_array ( $ permission ) ? $ permission : [ $ permission ] ) ; }
Returns whether the user has the given permission .
19,138
public function isValid ( $ value ) { if ( $ value instanceof PersonName ) { if ( strlen ( trim ( $ value -> getFullName ( ) ) ) === 0 ) { $ this -> addError ( 'The person name cannot be empty.' , 1268676765 ) ; } } }
Checks if the concatenated person name has at least one character .
19,139
public function registerHelpers ( ) { foreach ( glob ( $ this -> getHelpersDirectoryPath ( ) . '*.php' ) as $ file ) { $ helperName = pathinfo ( $ file , PATHINFO_FILENAME ) ; $ this -> registerHelper ( lcfirst ( $ helperName ) ) ; } }
Registers view helpers
19,140
public function initEnvironment ( Config $ config ) { if ( isset ( $ config -> application ) && isset ( $ config -> application -> environment ) ) { $ env = $ config -> application -> environment ; } else { $ env = Constants :: DEFAULT_ENV ; } if ( ! defined ( 'APPLICATION_ENV' ) ) { define ( 'APPLICATION_ENV' , $ env ) ; } $ this -> getDI ( ) -> set ( 'environment' , function ( ) use ( $ env ) { return $ env ; } , true ) ; }
Initializes application environment
19,141
public function dump ( $ inputDirectory , $ outputDirectory , $ dumpVendorModules = true ) { $ modulesList = [ ] ; $ directoryIterator = new \ DirectoryIterator ( $ inputDirectory ) ; foreach ( $ directoryIterator as $ moduleDir ) { if ( $ moduleDir -> isDot ( ) ) { continue ; } $ moduleSettingsFile = $ moduleDir -> getPathname ( ) . DIRECTORY_SEPARATOR . self :: MODULE_SETTINGS_FILE ; if ( ! file_exists ( $ moduleSettingsFile ) ) { continue ; } $ modulesList [ $ moduleDir -> getBasename ( ) ] = [ 'className' => $ moduleDir -> getBasename ( ) . '\\' . pathinfo ( self :: MODULE_SETTINGS_FILE , PATHINFO_FILENAME ) , 'path' => $ moduleSettingsFile ] ; } if ( $ dumpVendorModules ) { $ this -> dumpModulesFromVendor ( $ modulesList ) ; } FileWriter :: writeObject ( $ outputDirectory . self :: MODULE_STATIC_FILE , $ modulesList , true ) ; return $ modulesList ; }
Generates list of modules into source file
19,142
public function dumpModulesFromVendor ( array & $ modulesList ) { if ( ! file_exists ( APP_ROOT . '/composer.json' ) ) { return $ modulesList ; } $ fileContent = file_get_contents ( APP_ROOT . DIRECTORY_SEPARATOR . 'composer.json' ) ; $ json = json_decode ( $ fileContent , true ) ; $ vendorDir = realpath ( APP_ROOT . ( isset ( $ json [ 'config' ] [ 'vendor-dir' ] ) ? DIRECTORY_SEPARATOR . $ json [ 'config' ] [ 'vendor-dir' ] : DIRECTORY_SEPARATOR . 'vendor' ) ) ; foreach ( $ this -> getModuleProviders ( ) as $ provider ) { $ providerDir = $ vendorDir . DIRECTORY_SEPARATOR . $ provider ; $ this -> dumpSingleProviderModulesFromVendor ( $ modulesList , $ providerDir ) ; } return $ modulesList ; }
Extract Vegas modules from composer vegas - cmf vendors .
19,143
private function dumpSingleProviderModulesFromVendor ( array & $ modulesList , $ providerDir ) { $ directoryIterator = new \ DirectoryIterator ( $ providerDir ) ; foreach ( $ directoryIterator as $ libDir ) { if ( $ libDir -> isDot ( ) ) { continue ; } $ moduleSettingsFile = implode ( DIRECTORY_SEPARATOR , [ $ providerDir , $ libDir , 'module' , self :: MODULE_SETTINGS_FILE ] ) ; if ( ! file_exists ( $ moduleSettingsFile ) ) { continue ; } $ baseName = Text :: camelize ( $ libDir -> getBasename ( ) ) ; if ( ! isset ( $ modulesList [ $ baseName ] ) ) { $ modulesList [ $ baseName ] = [ 'className' => $ baseName . '\\' . pathinfo ( self :: MODULE_SETTINGS_FILE , PATHINFO_FILENAME ) , 'path' => $ moduleSettingsFile ] ; } } }
Extracts Vegas modules from specific provider in vendor directory .
19,144
private function getModuleProviders ( ) { $ defaultProviders = [ 'vegas-cmf' ] ; $ appConfig = $ this -> di -> get ( 'config' ) -> application ; if ( ! isset ( $ appConfig -> vendorModuleProvider ) ) { $ providerNames = [ ] ; } else if ( is_string ( $ appConfig -> vendorModuleProvider ) ) { $ providerNames = [ $ appConfig -> vendorModuleProvider ] ; } else { $ providerNames = $ appConfig -> vendorModuleProvider -> toArray ( ) ; } return array_unique ( array_merge ( $ defaultProviders , $ providerNames ) ) ; }
Get available module providers - default is vegas - cmf . Additional providers can be placed under application - > vendorModuleProvider key in config file . Value of the key can be either a string with name or an array with multiple names .
19,145
public function getResponseHeaders ( ) { $ requestHeaders = [ ] ; if ( $ this -> headers instanceof \ ArrayAccess ) { while ( $ this -> headers -> valid ( ) ) { $ requestHeaders [ $ this -> headers -> key ( ) ] = $ this -> headers -> current ( ) ; $ this -> headers -> next ( ) ; } } return $ requestHeaders ; }
Get Response Headers
19,146
public static function runDebuger ( $ view = null ) { self :: $ debugbar = new Debugger ( ) ; self :: $ assets_url = base_url ( ) . '/assets/DebugBar/Resources' ; self :: addQueries ( ) ; self :: addMessages ( ) ; self :: addRoute ( $ view ) ; self :: $ debugbarRenderer = self :: $ debugbar -> getJavascriptRenderer ( ) -> setBaseUrl ( self :: $ assets_url ) ; return self :: $ debugbarRenderer ; }
Runs the debug bar
19,147
private static function addQueries ( ) { self :: $ debugbar -> addCollector ( new MessagesCollector ( 'queries' ) ) ; self :: $ queries = ORM :: get_query_log ( ) ; if ( self :: $ queries ) { foreach ( self :: $ queries as $ query ) { self :: $ debugbar [ 'queries' ] -> info ( $ query ) ; } } }
Collects the queries
19,148
private static function addRoute ( $ view ) { $ uri = RouteController :: $ currentRoute [ 'uri' ] ; $ method = RouteController :: $ currentRoute [ 'method' ] ; $ module = RouteController :: $ currentRoute [ 'module' ] ; $ current_controller = 'modules' . DS . $ module . DS . RouteController :: $ currentRoute [ 'controller' ] ; $ current_action = RouteController :: $ currentRoute [ 'action' ] ; $ args = RouteController :: $ currentRoute [ 'args' ] ; $ route = [ 'Route' => $ uri , 'Method' => $ method , 'Module' => $ module , 'Controller' => $ current_controller , 'Action' => $ current_action , 'View' => '' , 'Args' => $ args , ] ; if ( $ view ) { $ route [ 'View' ] = 'modules/' . RouteController :: $ currentRoute [ 'module' ] . '/Views/' . $ view ; } self :: $ debugbar -> addCollector ( new MessagesCollector ( 'routes' ) ) ; self :: $ debugbar [ 'routes' ] -> info ( $ route ) ; }
Collects the routes
19,149
private static function addMessages ( ) { $ out_data = session ( ) -> get ( 'output' ) ; if ( $ out_data ) { foreach ( $ out_data as $ data ) { self :: $ debugbar [ 'messages' ] -> debug ( $ data ) ; } session ( ) -> delete ( 'output' ) ; } }
Collects the messages
19,150
public function execute ( Input $ input ) : void { $ this -> bus -> handle ( $ this -> messageCreator -> create ( $ this -> command , $ input ) ) ; }
Creates the command with given input and executes it
19,151
private function processForm ( $ values ) { $ form = $ this -> getForm ( $ this -> record ) ; $ form -> bind ( $ values , $ this -> record ) ; if ( $ form -> isValid ( ) ) { return $ this -> record -> save ( ) ; } $ this -> form = $ form ; throw new InvalidFormException ( ) ; }
Processes form with provided values
19,152
public static function resize ( $ options = null ) { $ options = Helper :: getOptions ( $ options , [ "fromPath" => null , "toPath" => null , "width" => null , "height" => null , ] ) ; if ( ! $ fromPath = trim ( $ options [ "fromPath" ] ) ) { throw new \ Exception ( "No from path specified to read from" ) ; } if ( ! $ toPath = trim ( $ options [ "toPath" ] ) ) { throw new \ Exception ( "No to path specified to save to" ) ; } $ maxWidth = round ( $ options [ "width" ] ) ; $ maxHeight = round ( $ options [ "height" ] ) ; list ( $ width , $ height , $ format ) = getimagesize ( $ fromPath ) ; if ( $ width < 1 || $ height < 1 ) { copy ( $ fromPath , $ toPath ) ; return ; } if ( $ maxWidth < 1 && $ maxHeight < 1 ) { copy ( $ fromPath , $ toPath ) ; return ; } if ( $ width < $ maxWidth && $ height < $ maxHeight ) { copy ( $ fromPath , $ toPath ) ; return ; } $ newWidth = $ width ; $ newHeight = $ height ; if ( $ maxHeight && $ newHeight > $ maxHeight ) { $ ratio = $ newWidth / $ newHeight ; $ newHeight = $ maxHeight ; $ newWidth = $ newHeight * $ ratio ; } if ( $ maxWidth && $ newWidth > $ maxWidth ) { $ ratio = $ newHeight / $ newWidth ; $ newWidth = $ maxWidth ; $ newHeight = $ newWidth * $ ratio ; } $ image = static :: create ( $ fromPath , $ format ) ; $ newImage = imagecreatetruecolor ( $ newWidth , $ newHeight ) ; if ( $ format != IMAGETYPE_JPEG ) { imagealphablending ( $ newImage , false ) ; imagesavealpha ( $ newImage , true ) ; $ background = imagecolorallocatealpha ( $ newImage , 255 , 255 , 255 , 127 ) ; imagecolortransparent ( $ newImage , $ background ) ; } imagecopyresampled ( $ newImage , $ image , 0 , 0 , 0 , 0 , $ newWidth , $ newHeight , $ width , $ height ) ; static :: save ( $ newImage , $ toPath , $ format ) ; imagedestroy ( $ image ) ; imagedestroy ( $ newImage ) ; }
Resize an image maintaining the same aspect ratio . If the image is already an appropriate size then it is just copied .
19,153
public static function img ( $ options = null ) { $ options = Helper :: getOptions ( $ options , [ "path" => "images/img" , "basename" => null , "filename" => null , "width" => null , "height" => null , ] ) ; $ path = $ options [ "path" ] ; if ( $ path [ 0 ] == "/" ) { $ fullpath = $ path ; } else { $ fullpath = Env :: path ( $ path , Env :: PATH_DOCUMENT_ROOT ) ; } $ filename = $ options [ "filename" ] ; if ( $ basename = $ options [ "basename" ] ) { $ original = $ fullpath . "/original/" . $ basename ; if ( file_exists ( $ original ) ) { if ( $ ext = static :: getExtension ( $ original ) ) { $ filename = $ basename . "." . $ ext ; copy ( $ original , $ fullpath . "/original/" . $ filename ) ; } } } if ( ! $ filename ) { throw new \ Exception ( "No image filename provided to use" ) ; } $ original = $ fullpath . "/original/" . $ filename ; if ( ! file_exists ( $ original ) ) { throw new \ Exception ( "Original image file does not exist (" . $ original . ")" ) ; } $ w = $ options [ "width" ] ; $ h = $ options [ "height" ] ; if ( ! $ w && ! $ h ) { return $ path . "/original/" . $ filename ; } if ( $ w && $ h ) { $ dir = "max" . $ w . "x" . $ h ; } elseif ( $ w ) { $ dir = "width" . $ w ; } elseif ( $ h ) { $ dir = "height" . $ h ; } $ fullpath .= "/" . $ dir ; $ newfile = $ fullpath . "/" . $ filename ; $ newpath = $ path . "/" . $ dir . "/" . $ filename ; if ( file_exists ( $ newfile ) ) { return $ newpath ; } if ( ! is_dir ( $ fullpath ) ) { mkdir ( $ fullpath , 0777 , true ) ; } static :: resize ( [ "fromPath" => $ original , "toPath" => $ newfile , "width" => $ w , "height" => $ h , ] ) ; return $ newpath ; }
Automatically resize and create images on the fly . If the image already exists then it s path is just passed back .
19,154
public static function create ( $ path , $ format ) { switch ( $ format ) { case IMAGETYPE_JPEG : $ result = imagecreatefromjpeg ( $ path ) ; break ; case IMAGETYPE_PNG : $ result = imagecreatefrompng ( $ path ) ; break ; case IMAGETYPE_GIF : $ result = imagecreatefromgif ( $ path ) ; break ; } if ( ! $ result ) { throw new \ Exception ( "Failing to create image (" . $ path . ")" ) ; } return $ result ; }
Create an image resource from an image on disk .
19,155
public static function save ( $ image , $ path , $ format ) { switch ( $ format ) { case IMAGETYPE_JPEG : $ result = imagejpeg ( $ image , $ path , 100 ) ; break ; case IMAGETYPE_PNG : $ result = imagepng ( $ image , $ path , 9 ) ; break ; case IMAGETYPE_GIF : $ result = imagegif ( $ image , $ path ) ; break ; } if ( ! $ result ) { throw new \ Exception ( "Failed to save image (" . $ path . ")" ) ; } }
Save an image resource to the disk .
19,156
public static function rotate ( $ path , $ rotate = null ) { if ( $ rotate === null ) { $ exif = exif_read_data ( $ path ) ; switch ( $ exif [ "Orientation" ] ) { case 3 : $ rotate = 180 ; break ; case 6 : $ rotate = 90 ; break ; case 8 : $ rotate = - 90 ; break ; } } if ( ! $ rotate ) { return ; } $ format = getimagesize ( $ path ) [ 2 ] ; $ image = static :: create ( $ path , $ format ) ; $ rotate = imagerotate ( $ image , $ rotate * - 1 , 0 ) ; static :: save ( $ rotate , $ path , $ format ) ; }
Rotate an image and save it . If no angle to rotate is passed then we attempt to read it from exif data .
19,157
protected function _engineRender ( $ engines , $ viewPath , $ silence , $ mustClean , $ cache ) { $ basePath = $ this -> _basePath ; $ notExists = true ; if ( is_object ( $ cache ) ) { $ renderLevel = intval ( $ this -> _renderLevel ) ; $ cacheLevel = intval ( $ this -> _cacheLevel ) ; if ( $ renderLevel >= $ cacheLevel ) { if ( $ cache -> isStarted ( ) === false ) { $ viewOptions = $ this -> _options ; if ( is_array ( $ viewOptions ) ) { if ( isset ( $ viewOptions [ 'cache' ] ) ) { $ cacheOptions = $ viewOptions [ 'cache' ] ; if ( is_array ( $ cacheOptions ) ) { if ( isset ( $ cacheOptions [ 'key' ] ) ) { $ key = $ cacheOptions [ 'key' ] ; } if ( isset ( $ cacheOptions [ 'lifetime' ] ) ) { $ lifeTime = $ cacheOptions [ 'lifetime' ] ; } } if ( ! isset ( $ key ) || ! $ key ) { $ key = md5 ( $ viewPath ) ; } if ( ! isset ( $ lifeTime ) ) { $ lifeTime = 0 ; } $ cachedView = $ cache -> start ( $ key , $ lifeTime ) ; if ( ! $ cachedView ) { $ this -> _content = $ cachedView ; return null ; } } if ( ! $ cache -> isFresh ( ) ) { return null ; } } } } } $ viewParams = $ this -> _viewParams ; $ eventsManager = $ this -> _eventsManager ; foreach ( $ engines as $ extension => $ engine ) { $ viewEnginePath = $ basePath . $ this -> resolveFullViewPath ( $ viewPath ) . $ extension ; if ( file_exists ( $ viewEnginePath ) ) { if ( is_object ( $ eventsManager ) ) { $ this -> _activeRenderPath = $ viewEnginePath ; if ( $ eventsManager -> fire ( "view:beforeRenderView" , $ this , $ viewEnginePath ) === false ) { continue ; } } $ engine -> render ( $ viewEnginePath , $ viewParams , $ mustClean ) ; $ notExists = false ; if ( is_object ( $ eventsManager ) ) { $ eventsManager -> fire ( "view:afterRenderView" , $ this ) ; } break ; } } if ( $ notExists ) { if ( is_object ( $ eventsManager ) ) { $ this -> _activeRenderPath = $ viewEnginePath ; $ eventsManager -> fire ( "view:notFoundView" , $ this , $ viewEnginePath ) ; } if ( ! $ silence ) { throw new Exception ( sprintf ( "View %s was not found in the views directory" , $ viewEnginePath ) ) ; } } }
Checks whether view exists on registered extensions and render it
19,158
private function resolveFullViewPath ( $ viewPath ) { if ( strlen ( $ this -> getPartialsDir ( ) ) > 0 && strpos ( $ viewPath , $ this -> getPartialsDir ( ) ) === 0 ) { return $ this -> resolvePartialPath ( $ viewPath ) ; } if ( strpos ( $ viewPath , $ this -> getLayoutsDir ( ) ) === 0 ) { return $ this -> resolveLayoutPath ( $ viewPath ) ; } return $ this -> resolveViewPath ( $ viewPath ) ; }
Resolves full path to view file
19,159
private function resolveViewPath ( $ viewPath ) { $ path = realpath ( $ this -> _viewsDir . dirname ( $ viewPath ) ) . DIRECTORY_SEPARATOR . basename ( $ viewPath ) ; return $ path ; }
Resolves view path
19,160
private function resolvePartialPath ( $ viewPath ) { $ tempViewPath = str_replace ( $ this -> getPartialsDir ( ) , '' , $ viewPath ) ; if ( strpos ( $ tempViewPath , '../' ) === 0 || strpos ( $ tempViewPath , '/../' ) === 0 ) { return $ this -> resolveRelativePath ( $ tempViewPath ) ; } else if ( strpos ( $ tempViewPath , './' ) === 0 ) { return $ this -> resolveLocalPath ( $ tempViewPath ) ; } else if ( ! in_array ( dirname ( $ tempViewPath ) , [ '.' , '..' ] ) && file_exists ( dirname ( $ tempViewPath ) ) ) { return $ tempViewPath ; } return $ this -> resolveGlobalPath ( $ tempViewPath ) ; }
Resolves path to partial
19,161
private function resolveLocalPath ( $ partialPath ) { $ partialDir = str_replace ( './' , '' , dirname ( $ partialPath ) ) ; $ partialsDir = realpath ( sprintf ( '%s%s' , $ this -> _viewsDir , $ partialDir ) ) . DIRECTORY_SEPARATOR ; return $ partialsDir . basename ( $ partialPath ) ; }
Resolves path to local partials directory
19,162
private function resolveRelativePath ( $ partialPath ) { $ partialsDirPath = realpath ( sprintf ( '%s%s' , $ this -> _viewsDir , dirname ( $ partialPath ) ) ) . DIRECTORY_SEPARATOR ; return $ partialsDirPath . basename ( $ partialPath ) ; }
Resolves realpath from relative partial path
19,163
public function render ( $ controllerName , $ actionName , $ params = null ) { if ( empty ( $ this -> controllerViewPath ) ) { $ this -> setControllerViewPath ( $ controllerName ) ; } parent :: render ( $ this -> controllerViewPath , $ actionName , $ params ) ; }
Renders view for controller action
19,164
public function setControllerViewPath ( $ controllerName ) { $ this -> controllerViewPath = str_replace ( '\\' , '/' , strtolower ( $ controllerName ) ) ; $ this -> controllerFullViewPath = $ this -> _viewsDir . $ this -> controllerViewPath ; }
Prepares and sets path for controller view
19,165
public function getUserFromTokenResponse ( $ response ) { $ user = $ this -> mapUserToObject ( $ this -> getUserByToken ( $ token = $ this -> parseAccessToken ( $ response ) ) ) ; $ this -> credentialsResponseBody = $ response ; if ( $ user instanceof User ) { $ user -> setAccessTokenResponseBody ( $ this -> credentialsResponseBody ) ; } return $ user -> setToken ( $ token ) -> setRefreshToken ( $ this -> parseRefreshToken ( $ response ) ) -> setExpiresIn ( $ this -> parseExpiresIn ( $ response ) ) ; }
Retrieve user using token response .
19,166
private function getDbConfig ( ) { if ( file_exists ( MODULES_DIR . DS . $ this -> currentRoute [ 'module' ] . '/Config/database.php' ) ) { $ dbConfig = require_once MODULES_DIR . DS . $ this -> currentRoute [ 'module' ] . '/Config/database.php' ; if ( ! empty ( $ dbConfig ) && is_array ( $ dbConfig ) ) { return $ dbConfig ; } else { throw new \ Exception ( ExceptionMessages :: INCORRECT_CONFIG ) ; } } else { if ( file_exists ( BASE_DIR . '/config/database.php' ) ) { $ dbConfig = require_once BASE_DIR . '/config/database.php' ; if ( ! empty ( $ dbConfig ) && is_array ( $ dbConfig ) ) { return $ dbConfig ; } else { throw new \ Exception ( ExceptionMessages :: INCORRECT_CONFIG ) ; } } else { throw new \ Exception ( ExceptionMessages :: DB_CONFIG_NOT_FOUND ) ; } } }
Get DB Config
19,167
public static function getInstance ( $ name ) { if ( ! isset ( static :: $ instances [ $ name ] ) ) { static :: $ instances [ $ name ] = new CacheInstance ( ) ; } return static :: $ instances [ $ name ] ; }
Get a named instance of CacheInstance for segregating cache data .
19,168
public function reloadBlacklist ( ) { $ this -> cache -> flush ( $ this -> getCacheKey ( ) ) ; $ this -> blackListRegex = null ; $ this -> loadBlacklist ( ) ; }
Reload blacklist data
19,169
public function check ( $ model ) { $ moderated = false ; foreach ( $ model -> getModerateList ( ) as $ id => $ moderation ) { $ rules = explode ( '|' , $ moderation ) ; foreach ( $ rules as $ rule ) { $ action = explode ( ':' , $ rule ) ; $ options = isset ( $ action [ 1 ] ) ? $ action [ 1 ] : null ; $ method = $ action [ 0 ] ; if ( $ this -> $ method ( $ model -> $ id , $ options ) ) { return $ moderated = true ; } } if ( $ moderated === true ) { return $ moderated ; } } return $ moderated ; }
Check model using the moderate rules .
19,170
public function getDriver ( ) { if ( $ this -> driver ) { return $ this -> driver ; } $ config = $ this -> getConfig ( 'drivers.' . $ this -> getConfig ( 'driver' ) , [ ] ) ; $ driver = Arr :: pull ( $ config , 'class' ) ; return $ this -> driver = new $ driver ( $ config , $ this -> locale ) ; }
Get moderation driver .
19,171
protected function loadBlacklist ( ) { if ( $ this -> getConfig ( 'cache.enabled' , false ) === false ) { return $ this -> blackListRegex = $ this -> createRegex ( ) ; } return $ this -> blackListRegex = $ this -> cache -> rememberForever ( $ this -> getCacheKey ( ) , function ( ) { return $ this -> createRegex ( ) ; } ) ; }
Load blacklist data
19,172
protected function createRegex ( ) { if ( empty ( $ list = $ this -> getDriver ( ) -> getList ( ) ) ) { return null ; } return sprintf ( '/\b(%s)\b/i' , implode ( '|' , array_map ( function ( $ value ) { if ( isset ( $ value [ 0 ] ) && $ value [ 0 ] == '[' ) { return $ value ; } else if ( preg_match ( "/\r\n|\r|\n/" , $ value ) ) { return preg_replace ( "/\r\n|\r|\n/" , "|" , $ value ) ; } return preg_quote ( $ value ) ; } , $ list ) ) ) ; }
Create blacklist regex from driver data .
19,173
public function process ( ContainerBuilder $ container ) { $ taggedServices = $ container -> findTaggedServiceIds ( self :: TAG_NAME ) ; foreach ( $ taggedServices as $ id => $ tag ) { $ definition = $ container -> findDefinition ( $ id ) ; $ this -> processTag ( $ tag , $ definition ) ; } }
Adds requested store configuration as an argument to the services
19,174
public static function path ( $ filename ) { if ( $ filename [ 0 ] != "/" ) { $ filename = static :: $ path . "/" . $ filename ; } if ( substr ( $ filename , - 5 ) != ".json" ) { $ filename .= ".json" ; } $ path = pathinfo ( $ filename , PATHINFO_DIRNAME ) ; if ( ! is_dir ( $ path ) ) { if ( ! mkdir ( $ path , 0777 , true ) ) { throw new \ Exception ( "Unable to create cache directory (" . $ path . ")" ) ; } } if ( ! is_writable ( $ path ) ) { if ( ! chmod ( $ path , 0777 ) ) { throw new \ Exception ( "Cache directory (" . $ path . ") is not writable" ) ; } } return $ filename ; }
Generate the fullpath to the cache file based on the passed filename .
19,175
public static function check ( $ filename ) { if ( ! $ filename = static :: path ( $ filename ) ) { return null ; } if ( ! file_exists ( $ filename ) ) { return null ; } return filemtime ( $ filename ) ; }
Check if the specified key has already been cached . If it has been cached then the time the cached data was last modified is returned .
19,176
public static function get ( $ filename , $ mins = 0 ) { if ( ! $ cache = static :: check ( $ filename ) ) { return null ; } $ limit = time ( ) - ( $ mins * 60 ) ; if ( ! $ mins || $ cache > $ limit ) { $ filename = static :: path ( $ filename ) ; $ return = Json :: decodeFromFile ( $ filename ) ; if ( $ return instanceof \ ArrayObject ) { $ return = $ return -> asArray ( ) ; } if ( array_key_exists ( "_disk_cache" , $ return ) ) { $ return = $ return [ "_disk_cache" ] ; } return $ return ; } return null ; }
Get the stored value of the specified key .
19,177
public static function set ( $ filename , $ data ) { $ data = [ "_disk_cache" => $ data ] ; $ filename = static :: path ( $ filename ) ; Json :: encodeToFile ( $ filename , $ data ) ; }
Set the specified key to the specified value .
19,178
public static function clear ( $ filename ) { $ filename = static :: path ( $ filename ) ; if ( ! file_exists ( $ filename ) ) { return ; } if ( ! unlink ( $ filename ) ) { throw new \ Exception ( "Unable to delete file (" . $ filename . ")" ) ; } }
Clear a key within the cache data .
19,179
public static function call ( $ key , callable $ func ) { $ trace = debug_backtrace ( ) ; if ( $ function = $ trace [ 1 ] [ "function" ] ) { $ key = $ function . "_" . $ key ; if ( $ class = $ trace [ 1 ] [ "class" ] ) { $ key = str_replace ( "\\" , "_" , $ class ) . "_" . $ key ; } } if ( static :: check ( $ key ) ) { return static :: get ( $ key ) ; } $ return = $ func ( ) ; static :: set ( $ key , $ return ) ; return $ return ; }
Convience method to retrieve a value if it s cached or run the callback and cache the data now if not .
19,180
public function cleanupPackages ( Storage $ storage , callable $ callback = null ) { $ count = 0 ; $ storageNode = $ storage -> node ( ) ; $ query = new FlowQuery ( [ $ storageNode ] ) ; $ query = $ query -> find ( '[instanceof Neos.MarketPlace:Package]' ) ; $ upstreamPackages = $ this -> getProcessedPackages ( ) ; foreach ( $ query as $ package ) { if ( in_array ( $ package -> getProperty ( 'title' ) , $ upstreamPackages ) ) { continue ; } $ package -> remove ( ) ; if ( $ callback !== null ) { $ callback ( $ package ) ; } $ this -> emitPackageDeleted ( $ package ) ; $ count ++ ; } return $ count ; }
Remove local package not preset in the processed packages list
19,181
public function cleanupVendors ( Storage $ storage , callable $ callback = null ) { $ count = 0 ; $ storageNode = $ storage -> node ( ) ; $ query = new FlowQuery ( [ $ storageNode ] ) ; $ query = $ query -> find ( '[instanceof Neos.MarketPlace:Vendor]' ) ; foreach ( $ query as $ vendor ) { $ hasPackageQuery = new FlowQuery ( [ $ vendor ] ) ; $ packageCount = $ hasPackageQuery -> find ( '[instanceof Neos.MarketPlace:Package]' ) -> count ( ) ; if ( $ packageCount > 0 ) { continue ; } $ vendor -> remove ( ) ; if ( $ callback !== null ) { $ callback ( $ vendor ) ; } $ this -> emitVendorDeleted ( $ vendor ) ; $ count ++ ; } return $ count ; }
Remove vendors without packages
19,182
private function filterResponse ( Response $ response , Request $ request , int $ type ) : string { $ event = new FilterResponseEvent ( $ this -> kernel , $ request , $ type , $ response ) ; $ this -> dispatcher -> dispatch ( KernelEvents :: RESPONSE , $ event ) ; $ this -> dispatcher -> dispatch ( KernelEvents :: FINISH_REQUEST , new FinishRequestEvent ( $ this -> kernel , $ request , $ type ) ) ; $ request -> attributes -> remove ( 'data' ) ; $ request -> attributes -> set ( '_controller' , 'typo3' ) ; $ response = $ event -> getResponse ( ) ; if ( $ response instanceof RedirectResponse ) { $ response -> send ( ) ; $ this -> kernel -> terminate ( $ request , $ response ) ; exit ( ) ; } if ( \ count ( $ response -> headers ) || 200 !== $ response -> getStatusCode ( ) ) { $ response -> sendHeaders ( ) ; } return $ response -> getContent ( ) ; }
Filters a response object and returns the content .
19,183
private function varToString ( $ var ) : string { if ( \ is_object ( $ var ) ) { return \ sprintf ( 'an object of type %s' , \ get_class ( $ var ) ) ; } if ( \ is_array ( $ var ) ) { $ a = [ ] ; foreach ( $ var as $ k => $ v ) { $ a [ ] = \ sprintf ( '%s => ...' , $ k ) ; } return \ sprintf ( 'an array ([%s])' , \ mb_substr ( \ implode ( ', ' , $ a ) , 0 , 255 ) ) ; } if ( \ is_resource ( $ var ) ) { return \ sprintf ( 'a resource (%s)' , \ get_resource_type ( $ var ) ) ; } if ( null === $ var ) { return 'null' ; } if ( false === $ var ) { return 'a boolean value (false)' ; } if ( true === $ var ) { return 'a boolean value (true)' ; } if ( \ is_string ( $ var ) ) { return \ sprintf ( 'a string ("%s%s")' , \ mb_substr ( $ var , 0 , 255 ) , \ mb_strlen ( $ var ) > 255 ? '...' : '' ) ; } if ( \ is_numeric ( $ var ) ) { return \ sprintf ( 'a number (%s)' , ( string ) $ var ) ; } return ( string ) $ var ; }
Returns a human - readable string for the specified variable .
19,184
public function removeElectronicAddress ( ElectronicAddress $ electronicAddress ) { $ this -> electronicAddresses -> removeElement ( $ electronicAddress ) ; if ( $ electronicAddress === $ this -> primaryElectronicAddress ) { $ this -> primaryElectronicAddress = null ; } }
Removes the given electronic address from this person .
19,185
public function setElectronicAddresses ( Collection $ electronicAddresses ) { if ( $ this -> primaryElectronicAddress !== null && ! $ this -> electronicAddresses -> contains ( $ this -> primaryElectronicAddress ) ) { $ this -> primaryElectronicAddress = null ; } $ this -> electronicAddresses = $ electronicAddresses ; }
Sets the electronic addresses of this person .
19,186
public function fetch ( Input $ input ) { return $ this -> bus -> handle ( $ this -> messageCreator -> create ( $ this -> query , $ input ) ) ; }
Creates the query with given input executes it and returns the result
19,187
public function beforeException ( ) { return function ( Event $ event , Dispatcher $ dispatcher , \ Exception $ exception ) { $ resolver = new ExceptionResolver ( ) ; $ resolver -> setDI ( $ dispatcher -> getDI ( ) ) ; $ resolver -> resolve ( $ exception ) ; return false ; } ; }
Event fired when exception is throwing
19,188
public function render ( ) { if ( ! $ this -> isEnabled ( ) ) { return ; } if ( $ this -> isAutomatic ( ) ) { $ this -> addItem ( "ga('send', '" . self :: TYPE_PAGEVIEW . "');" ) ; } if ( $ this -> isAnonymised ( ) ) { $ this -> addItem ( "ga('set', 'anonymizeIp', true);" ) ; } if ( $ this -> application -> environment ( ) === 'dev' ) { $ this -> addItem ( "ga('create', '{$this->id}', { 'cookieDomain': 'none' });" ) ; } else { $ this -> addItem ( "ga('create', '{$this->id}', '{$this->domain}');" ) ; } return $ this -> view -> make ( 'googlitics::analytics' ) -> withItems ( array_reverse ( $ this -> getItems ( ) ) ) -> render ( ) ; }
Renders and returns Google Analytics code .
19,189
public function trackPage ( $ page = null , $ title = null , $ type = self :: TYPE_PAGEVIEW ) { if ( ! defined ( 'self::TYPE_' . strtoupper ( $ type ) ) ) { throw new AnalyticsArgumentException ( 'Type variable can\'t be of this type.' ) ; } $ item = "ga('send', 'pageview');" ; if ( $ page !== null || $ title !== null ) { $ page = ( $ page === null ? "window.location.href" : "'{$page}'" ) ; $ title = ( $ title === null ? "document.title" : "'{$title}'" ) ; $ item = "ga('send', { 'hitType': '{$type}', 'page': {$page}, 'title': {$title} });" ; } $ this -> addItem ( $ item ) ; }
Track a page view .
19,190
public function trackEvent ( $ category , $ action , $ label = null , $ value = null ) { $ item = "ga('send', 'event', '{$category}', '{$action}'" . ( $ label !== null ? ", '{$label}'" : '' ) . ( $ value !== null && is_numeric ( $ value ) ? ", {$value}" : '' ) . ");" ; $ this -> addItem ( $ item ) ; }
Track an event .
19,191
public function trackTransaction ( $ id , array $ options = [ ] ) { $ options [ 'id' ] = $ id ; $ this -> trackEcommerce ( self :: ECOMMERCE_TRANSACTION , $ options ) ; }
Track a transaction .
19,192
public function trackItem ( $ id , $ name , array $ options = [ ] ) { $ options [ 'id' ] = $ id ; $ options [ 'name' ] = $ name ; $ this -> trackEcommerce ( self :: ECOMMERCE_ITEM , $ options ) ; }
Track a transaction item .
19,193
public function trackMetric ( $ category , array $ options = [ ] ) { $ item = "ga('send', 'event', '{$category}'" ; if ( ! empty ( $ options ) ) { $ item .= ", 'action', { " ; foreach ( $ options as $ key => $ value ) { $ item .= "'{$key}': {$value}, " ; } $ item = rtrim ( $ item , ', ' ) . " }" ; } $ item .= ");" ; $ this -> addItem ( $ item ) ; }
Track a metric .
19,194
public function trackException ( $ description = null , $ fatal = false ) { $ item = "ga('send', '" . self :: TYPE_EXCEPTION . "'" ; if ( $ description !== null && is_bool ( $ fatal ) ) { $ item .= ", { " . "'exDescription': '{$description}', " . "'exFatal': " . ( $ fatal ? 'true' : 'false' ) . " }" ; } $ item .= ");" ; $ this -> addItem ( $ item ) ; }
Track an exception .
19,195
public function registerFilters ( ) { foreach ( glob ( $ this -> getFiltersDirectoryPath ( ) . '*.php' ) as $ file ) { $ filterName = pathinfo ( $ file , PATHINFO_FILENAME ) ; $ this -> registerFilter ( lcfirst ( $ filterName ) ) ; } }
Registers view filters from directory
19,196
public function handleLogin ( $ request ) { $ response = $ this -> provider -> redirect ( ) ; $ traitsUsed = class_uses ( $ this -> provider ) ; $ traitTwo = DfOAuthTwoProvider :: class ; $ traitOne = DfOAuthOneProvider :: class ; if ( isset ( $ traitsUsed [ $ traitTwo ] ) ) { $ state = $ this -> provider -> getState ( ) ; if ( ! empty ( $ state ) ) { $ key = static :: CACHE_KEY_PREFIX . $ state ; \ Cache :: put ( $ key , $ this -> getName ( ) , 3 ) ; } } elseif ( isset ( $ traitsUsed [ $ traitOne ] ) ) { $ token = $ this -> provider -> getOAuthToken ( ) ; if ( ! empty ( $ token ) ) { $ key = static :: CACHE_KEY_PREFIX . $ token ; \ Cache :: put ( $ key , $ this -> getName ( ) , 3 ) ; } } if ( ! $ request -> ajax ( ) ) { return $ response ; } $ url = $ response -> getTargetUrl ( ) ; $ result = [ 'response' => [ 'redirect' => true , 'url' => $ url ] ] ; return $ result ; }
Handles login using this service .
19,197
public function handleOAuthCallback ( ) { $ provider = $ this -> getProvider ( ) ; $ user = $ provider -> user ( ) ; return $ this -> loginOAuthUser ( $ user ) ; }
Handles OAuth callback
19,198
public function loginOAuthUser ( OAuthUserContract $ user ) { $ responseBody = $ user -> accessTokenResponseBody ; $ token = $ user -> token ; $ dfUser = $ this -> createShadowOAuthUser ( $ user ) ; $ dfUser -> last_login_date = Carbon :: now ( ) -> toDateTimeString ( ) ; $ dfUser -> confirm_code = null ; $ dfUser -> save ( ) ; $ map = OAuthTokenMap :: whereServiceId ( $ this -> id ) -> whereUserId ( $ dfUser -> id ) -> first ( ) ; if ( empty ( $ map ) ) { OAuthTokenMap :: create ( [ 'user_id' => $ dfUser -> id , 'service_id' => $ this -> id , 'token' => $ token , 'response' => $ responseBody ] ) ; } else { $ map -> update ( [ 'token' => $ token , 'response' => $ responseBody ] ) ; } Session :: setUserInfoWithJWT ( $ dfUser ) ; $ response = Session :: getPublicInfo ( ) ; $ response [ 'oauth_token' ] = $ token ; if ( isset ( $ responseBody [ 'id_token' ] ) ) { $ response [ 'id_token' ] = $ responseBody [ 'id_token' ] ; } return $ response ; }
Logs in OAuth user
19,199
public function createShadowOAuthUser ( OAuthUserContract $ OAuthUser ) { $ fullName = $ OAuthUser -> getName ( ) ; @ list ( $ firstName , $ lastName ) = explode ( ' ' , $ fullName ) ; $ email = $ OAuthUser -> getEmail ( ) ; $ serviceName = $ this -> getName ( ) ; $ providerName = $ this -> getProviderName ( ) ; if ( empty ( $ email ) ) { $ email = $ OAuthUser -> getId ( ) . '+' . $ serviceName . '@' . $ serviceName . '.com' ; } else { list ( $ emailId , $ domain ) = explode ( '@' , $ email ) ; $ email = $ emailId . '+' . $ serviceName . '@' . $ domain ; } $ user = User :: whereEmail ( $ email ) -> first ( ) ; if ( empty ( $ user ) ) { $ data = [ 'username' => $ email , 'name' => $ fullName , 'first_name' => $ firstName , 'last_name' => $ lastName , 'email' => $ email , 'is_active' => true , 'oauth_provider' => $ providerName , ] ; $ user = User :: create ( $ data ) ; } if ( ! empty ( $ defaultRole = $ this -> getDefaultRole ( ) ) ) { User :: applyDefaultUserAppRole ( $ user , $ defaultRole ) ; } if ( ! empty ( $ serviceId = $ this -> getServiceId ( ) ) ) { User :: applyAppRoleMapByService ( $ user , $ serviceId ) ; } return $ user ; }
If does not exists creates a shadow OAuth user using user info provided by the OAuth service provider and assigns default role to this user for all apps in the system . If user already exists then updates user s role for all apps and returns it .