idx int64 0 60.3k | question stringlengths 101 6.21k | target stringlengths 7 803 |
|---|---|---|
23,100 | protected function registerUser ( $ email , $ facebookUserId ) { $ className = $ this -> userService -> getUserClass ( ) ; $ user = ( new $ className ( ) ) ; $ user -> setEmail ( $ email ) -> setFacebookUserId ( $ facebookUserId ) -> setPlainPassword ( base64_encode ( random_bytes ( 20 ) ) ) ; $ this -> userService -> registerUser ( $ user , UserService :: SOURCE_TYPE_FACEBOOK ) ; return $ user ; } | We register the user with their facebook id and email . |
23,101 | public function reIndex ( ) { $ tags = $ this -> select ( [ 'tags.id' , 'taggables.tag_id as pivot_tag_id' ] ) -> join ( 'taggables' , 'tags.id' , '=' , 'taggables.tag_id' ) -> get ( ) -> keyBy ( 'id' ) -> all ( ) ; $ this -> whereNotIn ( 'id' , array_keys ( $ tags ) ) -> delete ( ) ; } | Delete unused tags |
23,102 | public static function toResults ( array $ items ) { $ output = [ ] ; foreach ( $ items as $ current ) { if ( false === ( $ current instanceof Select2ItemInterface ) ) { throw new InvalidArgumentException ( "The item must implements Select2ItemInterface" ) ; } $ output [ ] = [ "id" => $ current -> getSelect2ItemId ( ) , "text" => $ current -> getSelect2ItemText ( ) , ] ; } return $ output ; } | Convert items into a results array . |
23,103 | public function SomeUndefinedLongRunningWork ( $ timeToWorkOnSomething , callable $ onComplete = null ) { if ( $ this -> isExternal ( ) ) { $ timeToWorkOnSomething *= 100 ; echo "Start work $timeToWorkOnSomething msec on thread: " . posix_getpid ( ) . PHP_EOL ; usleep ( $ timeToWorkOnSomething ) ; echo "Completed work $timeToWorkOnSomething msec on thread: " . posix_getpid ( ) ; return "Completed work $timeToWorkOnSomething msec on thread: " . posix_getpid ( ) ; } else { return $ this -> asyncCallOnChild ( __FUNCTION__ , array ( $ timeToWorkOnSomething ) , $ onComplete , function ( AsyncMessage $ messga ) { var_dump ( $ messga -> GetResult ( ) -> getMessage ( ) ) ; } ) ; } } | Function to do some async work on thread class |
23,104 | public function isValid ( ) { if ( $ this -> get ( 'page-template' ) -> getValue ( ) == 'blank' ) { $ this -> setValidationGroup ( [ 'url' , 'title' , 'main-layout' , ] ) ; } else { $ this -> setValidationGroup ( [ 'url' , 'title' , 'page-template' , ] ) ; } return parent :: isValid ( ) ; } | Is Valid method for the new page form . Adds a validation group depending on if it s a new page or a copy of a template . |
23,105 | protected function selectSingle ( string $ query , array $ parameters = [ ] , string $ allowedTags = "" ) { $ statement = $ this -> query ( $ query , $ parameters ) ; $ statement -> setAllowedHtmlTags ( $ allowedTags ) ; $ result = $ statement -> next ( $ this -> fetchStyle ) ; return ( $ result ) ? $ result : null ; } | Execute a SELECT query which should return a single data row . Best suited for queries involving primary key in where . Will return null if the query did not return any results . If more than one row is returned an exception is thrown . |
23,106 | protected function select ( string $ query , array $ parameters = [ ] , string $ allowedTags = "" ) : array { if ( ! is_null ( $ this -> pager ) ) { $ query .= $ this -> pager -> getSqlLimit ( ) ; } $ statement = $ this -> query ( $ query , $ parameters ) ; $ statement -> setAllowedHtmlTags ( $ allowedTags ) ; $ results = [ ] ; while ( $ row = $ statement -> next ( $ this -> fetchStyle ) ) { $ results [ ] = $ row ; } return $ results ; } | Execute a SELECT query which return the entire set of rows in an array . Will return an empty array if the query did not return any results . |
23,107 | protected function transaction ( callable $ callback ) { try { $ this -> database -> beginTransaction ( ) ; $ reflect = new \ ReflectionFunction ( $ callback ) ; if ( $ reflect -> getNumberOfParameters ( ) == 1 ) { $ result = $ callback ( $ this -> database ) ; } elseif ( $ reflect -> getNumberOfParameters ( ) == 0 ) { $ result = $ callback ( ) ; } else { throw new \ InvalidArgumentException ( "Specified callback must have 0 or 1 argument" ) ; } $ this -> database -> commit ( ) ; return $ result ; } catch ( \ Exception $ e ) { $ this -> database -> rollback ( ) ; throw new DatabaseException ( $ e -> getMessage ( ) ) ; } } | Execute a query which should be contain inside a transaction . The specified callback method will optionally receive the Database instance if one argument is defined . Will work with nested transactions if using the TransactionPDO handler . Best suited method for INSERT UPDATE and DELETE queries . |
23,108 | protected function hasRolesOrRedirect ( array $ roles , $ or , $ redirectUrl , $ originUrl = "" ) { $ user = $ this -> getKernelEventListener ( ) -> getUser ( ) ; if ( false === UserHelper :: hasRoles ( $ user , $ roles , $ or ) ) { $ user = null !== $ user ? $ user : new User ( "anonymous" , "" ) ; throw new BadUserRoleException ( $ user , $ roles , $ redirectUrl , $ originUrl ) ; } return true ; } | Determines if the connected user have roles or redirect . |
23,109 | private static function captureHttpRequest ( ) { $ server = $ _SERVER ; $ uri = self :: getCompleteRequestUri ( $ server ) ; $ method = strtoupper ( $ server [ 'REQUEST_METHOD' ] ) ; $ parameters = self :: getParametersFromContentType ( $ server [ 'CONTENT_TYPE' ] ?? ContentType :: PLAIN ) ; if ( isset ( $ parameters [ '__method' ] ) ) { $ method = strtoupper ( $ parameters [ '__method' ] ) ; } self :: $ httpRequest = new Request ( $ uri , $ method , [ 'parameters' => $ parameters , 'cookies' => $ _COOKIE , 'files' => $ _FILES , 'server' => $ server ] ) ; } | Reads the HTTP data to build corresponding request instance . |
23,110 | private static function getParametersFromContentType ( string $ contentType ) : array { $ parameters = array_merge ( self :: getParametersFromGlobal ( $ _GET ) , self :: getParametersFromGlobal ( $ _POST ) , self :: getParametersFromGlobal ( $ _FILES ) ) ; $ paramsSource = [ ] ; $ rawInput = file_get_contents ( 'php://input' ) ; switch ( $ contentType ) { case ContentType :: JSON : $ paramsSource = ( array ) json_decode ( $ rawInput ) ; break ; case ContentType :: XML : case ContentType :: XML_APP : $ xml = new \ SimpleXMLElement ( $ rawInput ) ; $ paramsSource = ( array ) $ xml ; break ; default : parse_str ( $ rawInput , $ paramsSource ) ; } return array_merge ( $ parameters , self :: getParametersFromGlobal ( $ paramsSource ) ) ; } | Load every request parameters depending on the request content type and ensure to properly convert raw data to array parameters . |
23,111 | public function setBody ( $ text ) { if ( is_string ( $ text ) ) { $ this -> lines = explode ( "\n" , $ text ) ; } elseif ( is_array ( $ text ) ) { $ this -> lines = $ text ; } else { throw new InvalidArgumentTypeException ( 'Invalid body type' , $ text , array ( 'string' , 'array' ) ) ; } } | Allow text can be set with array |
23,112 | public function findPublishedVersionByLocator ( LocatorInterface $ locator ) { $ entity = $ this -> findActiveVersionByLocator ( $ locator ) ; if ( $ entity !== null && $ entity -> getStatus ( ) === VersionStatuses :: PUBLISHED ) { return $ entity ; } return null ; } | Finds the most recent published or depublished version of a resource and if it is published returns it otherwise returns null . |
23,113 | protected function findActiveVersionByLocator ( LocatorInterface $ locator ) { $ criteria = new Criteria ( ) ; $ criteria -> where ( $ criteria -> expr ( ) -> in ( 'status' , [ VersionStatuses :: PUBLISHED , VersionStatuses :: DEPUBLISHED ] ) ) ; foreach ( $ locator -> toArray ( ) as $ column => $ value ) { $ criteria -> andWhere ( $ criteria -> expr ( ) -> eq ( $ column , $ value ) ) ; } $ criteria -> orderBy ( [ 'id' => Criteria :: DESC ] ) ; $ criteria -> setMaxResults ( 1 ) ; $ entities = $ this -> entityManger -> getRepository ( $ this -> entityClassName ) -> matching ( $ criteria ) -> toArray ( ) ; if ( isset ( $ entities [ 0 ] ) ) { return $ entities [ 0 ] ; } return null ; } | Find the active version which means the most recent version that is either published or depublished while ignoring unpublished versions |
23,114 | public function addCondition ( $ field , $ value = '' , $ operator = '==' ) { if ( ! in_array ( $ operator , self :: $ conditionOperators ) ) { throw new \ InvalidArgumentException ( 'Invalid operator' ) ; } if ( is_bool ( $ value ) ) { $ value = $ value ? 'true' : 'false' ; } if ( in_array ( $ operator , [ '==' , '!=' ] ) ) { $ this -> conditions [ ] = $ field . $ operator . '"' . $ value . '"' ; } elseif ( $ operator === 'guid' ) { $ this -> conditions [ ] = $ field . '= Guid("' . $ value . '")' ; } else { $ this -> conditions [ ] = $ field . '.' . $ operator . '("' . $ value . '")' ; } return $ this ; } | Add a condition to the request . |
23,115 | public function compileConditions ( ) { $ ret = [ ] ; if ( ! empty ( $ this -> conditions ) ) { $ ret [ 'where' ] = implode ( ' ' , $ this -> conditions ) ; } return $ ret ; } | Compile the conditions array into a query parameter . |
23,116 | public function getRequestParameters ( $ request_parameters ) { $ ret = [ ] ; $ parts = explode ( '&' , $ request_parameters ) ; foreach ( $ parts as $ part ) { list ( $ key , $ value ) = explode ( '=' , $ part ) ; $ key_decoded = urldecode ( $ key ) ; $ value_decoded = urldecode ( $ value ) ; $ ret [ $ key_decoded ] = $ value_decoded ; } return $ ret ; } | Parse the Authorization HTTP Request parameters . |
23,117 | public function handle ( Request $ request , $ type = self :: MASTER_REQUEST , $ catch = true ) { while ( $ route = $ this -> router -> route ( $ request ) ) { $ module = $ route -> getPayload ( ) [ 'module' ] ; $ controller = $ route -> getPayload ( ) [ 'controller' ] ; $ action = $ route -> getPayload ( ) [ 'action' ] ; $ class = str_replace ( [ '{:module}' , '{:controller}' ] , [ $ module , $ controller ] , $ this -> mapping ) ; try { return $ this -> assetManager -> resolve ( $ class , [ 'invoke' => $ action ] ) ; } catch ( \ LogicException $ e ) { $ this -> failures [ ] = [ 'route' => $ route , 'exception' => $ e ] ; } } } | Handles a Request converting it to a Response . |
23,118 | public function cacheKey ( ) { $ this -> cacheKey = $ this -> cacheKey ?? $ this -> generateCacheKey ( auth ( ) -> guest ( ) ? 'guest' : auth ( ) -> user ( ) -> role ) ; return $ this -> cacheKey ; } | Get a unique key of the widget for caching . |
23,119 | public function cacheKeys ( ) { $ keys = [ ] ; $ roles = array_merge ( cache ( 'roles' ) , [ 'guest' ] ) ; foreach ( $ roles as $ role ) { $ keys [ ] = $ this -> generateCacheKey ( $ role ) ; } return implode ( '|' , $ keys ) ; } | Get all keys of the widget for clearing cache . |
23,120 | protected function generateCacheKey ( string $ role ) { return md5 ( serialize ( array_merge ( $ this -> params , [ 'widget' => get_class ( $ this ) , 'app_theme' => app_theme ( ) , 'app_locale' => app_locale ( ) , 'role' => $ role , ] ) ) ) ; } | Generate a unique cache key depending on the input parameters . |
23,121 | public function validator ( ) { return Validator :: make ( $ this -> params , $ this -> rules ( ) , $ this -> messages ( ) , $ this -> attributes ( ) ) ; } | Validate incoming parameters . |
23,122 | protected function castParam ( $ key , $ value ) { if ( is_null ( $ value ) or ! $ this -> hasCast ( $ key ) ) { return $ value ; } switch ( $ this -> getCastType ( $ key ) ) { case 'int' : case 'integer' : return ( int ) $ value ; case 'real' : case 'float' : case 'double' : return ( float ) $ value ; case 'string' : return ( string ) $ value ; case 'bool' : case 'boolean' : return ( bool ) $ value ; case 'array' : return ( array ) $ value ; case 'collection' : return collect ( ( array ) $ value ) ; default : return $ value ; } } | Cast an param to a native PHP type . |
23,123 | public function download ( $ url , callable $ onComplete = null ) { if ( $ this -> isExternal ( ) ) { $ data = file_get_contents ( $ url ) ; sleep ( 3 ) ; echo "Downloaded: " . strlen ( $ data ) . ' bytes from url: ' . $ url . PHP_EOL ; return $ data ; } else { return $ this -> asyncCallOnChild ( __FUNCTION__ , array ( $ url ) , $ onComplete ) ; } } | Function for downloading urls external |
23,124 | protected function registerServiceProviders ( ) { foreach ( $ this -> serviceProviders [ $ this -> flare -> compatibility ( ) ] as $ class ) { $ this -> app -> register ( $ class ) ; } } | Register Service Providers . |
23,125 | public function open ( $ savePath , $ sessionName ) { parent :: open ( $ savePath , $ sessionName ) ; $ this -> cookieKeyName = "key_$sessionName" ; if ( empty ( $ _COOKIE [ $ this -> cookieKeyName ] ) || strpos ( $ _COOKIE [ $ this -> cookieKeyName ] , ':' ) === false ) { $ this -> createEncryptionCookie ( ) ; return true ; } list ( $ this -> cryptKey , $ this -> cryptAuth ) = explode ( ':' , $ _COOKIE [ $ this -> cookieKeyName ] ) ; $ this -> cryptKey = base64_decode ( $ this -> cryptKey ) ; $ this -> cryptAuth = base64_decode ( $ this -> cryptAuth ) ; return true ; } | Called on session_start this method create the . |
23,126 | public function destroy ( $ sessionId ) { parent :: destroy ( $ sessionId ) ; if ( isset ( $ _COOKIE [ $ this -> cookieKeyName ] ) ) { setcookie ( $ this -> cookieKeyName , '' , 1 ) ; unset ( $ _COOKIE [ $ this -> cookieKeyName ] ) ; } return true ; } | Destroy session file on disk and delete encryption cookie if no session is active after deletion . |
23,127 | private function encrypt ( string $ data ) : string { $ cipher = Cryptography :: encrypt ( $ data , $ this -> cryptKey ) ; list ( $ initializationVector , $ cipher ) = explode ( ':' , $ cipher ) ; $ initializationVector = base64_decode ( $ initializationVector ) ; $ cipher = base64_decode ( $ cipher ) ; $ content = $ initializationVector . Cryptography :: getEncryptionAlgorithm ( ) . $ cipher ; $ hmac = hash_hmac ( 'sha256' , $ content , $ this -> cryptAuth ) ; return $ hmac . ':' . base64_encode ( $ initializationVector ) . ':' . base64_encode ( $ cipher ) ; } | Encrypt the specified data using the defined algorithm . Also create an Hmac authentication hash . |
23,128 | private function decrypt ( string $ data ) : string { list ( $ hmac , $ initializationVector , $ cipher ) = explode ( ':' , $ data ) ; $ ivReal = base64_decode ( $ initializationVector ) ; $ cipherReal = base64_decode ( $ cipher ) ; $ validHash = $ ivReal . Cryptography :: getEncryptionAlgorithm ( ) . $ cipherReal ; $ newHmac = hash_hmac ( 'sha256' , $ validHash , $ this -> cryptAuth ) ; if ( $ hmac !== $ newHmac ) { throw new \ RuntimeException ( "Invalid decryption key" ) ; } $ decrypt = Cryptography :: decrypt ( $ initializationVector . ':' . $ cipher , $ this -> cryptKey ) ; return $ decrypt ; } | Decrypt the specified data using the defined algorithm . Also verify the Hmac authentication hash . Returns false if Hmac validation fails . |
23,129 | public function handleMessage ( ThreadCommunicator $ communicator , $ messagePayload ) { $ action = $ messagePayload [ 'action' ] ; $ parameters = $ messagePayload [ 'parameters' ] ; if ( method_exists ( $ this , $ action ) ) { return call_user_func_array ( array ( $ this , $ action ) , $ parameters ) ; } return false ; } | Each message received call this function |
23,130 | public function stop ( ) { if ( $ this -> isExternal ( ) ) { $ this -> communicator -> getLoop ( ) -> stop ( ) ; } else { $ this -> asyncCallOnChild ( __FUNCTION__ , func_get_args ( ) ) ; } } | Stop the external process after all current operations completed |
23,131 | public function join ( ) { if ( $ this -> isExternal ( ) ) { $ this -> communicator -> getLoop ( ) -> stop ( ) ; } else { $ this -> callOnChild ( __FUNCTION__ , func_get_args ( ) ) ; } } | Stop thread after current works done and return |
23,132 | protected function asyncCallOnChild ( $ action , array $ parameters = array ( ) , callable $ onResult = null , callable $ onError = null ) { if ( $ this -> isExternal ( ) ) { throw new \ RuntimeException ( "Calling ClientThread::CallOnChild from Child context. Did you mean ClientThread::CallOnParent?" ) ; } else { return $ this -> communicator -> SendMessageAsync ( $ this -> encode ( $ action , $ parameters ) , $ onResult , $ onError ) ; } } | Asynchronous variation of |
23,133 | public function registerMappings ( ConfigInterface $ config ) { $ configKeys = [ static :: STANDARD_ALIASES => 'mapAliases' , static :: SHARED_ALIASES => 'shareAliases' , static :: ARGUMENT_DEFINITIONS => 'defineArguments' , static :: ARGUMENT_PROVIDERS => 'defineArgumentProviders' , static :: DELEGATIONS => 'defineDelegations' , static :: PREPARATIONS => 'definePreparations' , ] ; try { foreach ( $ configKeys as $ key => $ method ) { $ $ key = $ config -> hasKey ( $ key ) ? $ config -> getKey ( $ key ) : [ ] ; } $ standardAliases = array_merge ( $ sharedAliases , $ standardAliases ) ; } catch ( Exception $ exception ) { throw new InvalidMappingsException ( sprintf ( _ ( 'Failed to read needed keys from config. Reason: "%1$s".' ) , $ exception -> getMessage ( ) ) ) ; } try { foreach ( $ configKeys as $ key => $ method ) { array_walk ( $ $ key , [ $ this , $ method ] ) ; } } catch ( Exception $ exception ) { throw new InvalidMappingsException ( sprintf ( _ ( 'Failed to set up dependency injector. Reason: "%1$s".' ) , $ exception -> getMessage ( ) ) ) ; } } | Register mapping definitions . |
23,134 | protected function defineArguments ( $ argumentSetup , $ alias ) { foreach ( $ argumentSetup as $ key => $ value ) { $ this -> addArgumentDefinition ( $ value , $ alias , [ $ key , null ] ) ; } } | Tell our Injector how arguments are defined . |
23,135 | protected function defineArgumentProviders ( $ argumentSetup , $ argument ) { if ( ! array_key_exists ( 'mappings' , $ argumentSetup ) ) { throw new InvalidMappingsException ( sprintf ( _ ( 'Failed to define argument providers for argument "%1$s". ' . 'Reason: The key "mappings" was not found.' ) , $ argument ) ) ; } array_walk ( $ argumentSetup [ 'mappings' ] , [ $ this , 'addArgumentDefinition' ] , [ $ argument , $ argumentSetup [ 'interface' ] ? : null ] ) ; } | Tell our Injector how to produce required arguments . |
23,136 | protected function addArgumentDefinition ( $ callable , $ alias , $ args ) { list ( $ argument , $ interface ) = $ args ; $ value = is_callable ( $ callable ) ? $ this -> getArgumentProxy ( $ alias , $ interface , $ callable ) : $ callable ; $ argumentDefinition = array_key_exists ( $ alias , $ this -> argumentDefinitions ) ? $ this -> argumentDefinitions [ $ alias ] : [ ] ; if ( $ value instanceof Injection ) { $ argumentDefinition [ $ argument ] = $ value -> getAlias ( ) ; } else { $ argumentDefinition [ ":${argument}" ] = $ value ; } $ this -> argumentDefinitions [ $ alias ] = $ argumentDefinition ; $ this -> define ( $ alias , $ this -> argumentDefinitions [ $ alias ] ) ; } | Add a single argument definition . |
23,137 | protected function getArgumentProxy ( $ alias , $ interface , $ callable ) { if ( null === $ interface ) { $ interface = 'stdClass' ; } $ factory = new LazyLoadingValueHolderFactory ( ) ; $ initializer = function ( & $ wrappedObject , LazyLoadingInterface $ proxy , $ method , array $ parameters , & $ initializer ) use ( $ alias , $ interface , $ callable ) { $ initializer = null ; $ wrappedObject = $ callable ( $ alias , $ interface ) ; return true ; } ; return $ factory -> createProxy ( $ interface , $ initializer ) ; } | Get an argument proxy for a given alias to provide to the injector . |
23,138 | public function alias ( $ original , $ alias ) { if ( empty ( $ original ) || ! is_string ( $ original ) ) { throw new ConfigException ( InjectorException :: M_NON_EMPTY_STRING_ALIAS , InjectorException :: E_NON_EMPTY_STRING_ALIAS ) ; } if ( empty ( $ alias ) || ! is_string ( $ alias ) ) { throw new ConfigException ( InjectorException :: M_NON_EMPTY_STRING_ALIAS , InjectorException :: E_NON_EMPTY_STRING_ALIAS ) ; } $ originalNormalized = $ this -> normalizeName ( $ original ) ; if ( isset ( $ this -> shares [ $ originalNormalized ] ) ) { throw new ConfigException ( sprintf ( InjectorException :: M_SHARED_CANNOT_ALIAS , $ this -> normalizeName ( get_class ( $ this -> shares [ $ originalNormalized ] ) ) , $ alias ) , InjectorException :: E_SHARED_CANNOT_ALIAS ) ; } if ( array_key_exists ( $ originalNormalized , $ this -> shares ) ) { $ aliasNormalized = $ this -> normalizeName ( $ alias ) ; $ this -> shares [ $ aliasNormalized ] = null ; unset ( $ this -> shares [ $ originalNormalized ] ) ; } $ this -> aliases [ $ originalNormalized ] = $ alias ; return $ this ; } | Define an alias for all occurrences of a given typehint |
23,139 | public function inspect ( $ nameFilter = null , $ typeFilter = null ) { $ result = [ ] ; $ name = $ nameFilter ? $ this -> normalizeName ( $ nameFilter ) : null ; if ( empty ( $ typeFilter ) ) { $ typeFilter = static :: I_ALL ; } $ types = [ static :: I_BINDINGS => 'classDefinitions' , static :: I_DELEGATES => 'delegates' , static :: I_PREPARES => 'prepares' , static :: I_ALIASES => 'aliases' , static :: I_SHARES => 'shares' , ] ; foreach ( $ types as $ type => $ source ) { if ( $ typeFilter & $ type ) { $ result [ $ type ] = $ this -> filter ( $ this -> { $ source } , $ name ) ; } } return $ result ; } | Retrieve stored data for the specified definition type |
23,140 | public static function getTemplates ( $ path = null , $ regex = null ) { $ dirs = [ ] ; $ files = [ ] ; $ path = $ path ?? theme_path ( 'views' ) ; $ regex = $ regex ?? '/\.(tpl|ini|css|js|blade\.php)/' ; if ( ! $ path instanceof \ DirectoryIterator ) { $ path = new \ DirectoryIterator ( ( string ) $ path ) ; } foreach ( $ path as $ node ) { if ( $ node -> isDir ( ) and ! $ node -> isDot ( ) ) { if ( count ( $ tree = self :: getTemplates ( $ node -> getPathname ( ) , $ regex ) ) ) { $ dirs [ $ node -> getFilename ( ) ] = $ tree ; } } elseif ( $ node -> isFile ( ) ) { if ( is_null ( $ regex ) or preg_match ( $ regex , $ name = $ node -> getFilename ( ) ) ) { $ data_path = str_replace ( theme_path ( 'views' ) , '' , $ node -> getPathname ( ) ) ; $ files [ $ data_path ] = $ name ; } } } return array_merge ( $ dirs , $ files ) ; } | Creates a tree - structured array of directories and files from a given root folder . |
23,141 | protected function generateUrlOptions ( array $ options ) : array { $ urlOptions = [ ] ; if ( isset ( $ options [ 'date' ] ) ) { $ urlOptions [ 'date' ] = $ options [ 'date' ] -> format ( 'd.m.y' ) ; $ urlOptions [ 'time' ] = $ options [ 'date' ] -> format ( 'H:i' ) ; unset ( $ options [ 'date' ] ) ; } return array_merge ( $ urlOptions , $ options ) ; } | Generate url options . |
23,142 | public function generateHiddenFields ( ) { $ name = $ this -> generateFormName ( ) ; $ token = $ this -> generateToken ( $ name ) ; $ html = '<input type="hidden" name="' . self :: REQUEST_TOKEN_NAME . '" value="' . $ name . '" />' ; $ html .= '<input type="hidden" name="' . self :: REQUEST_TOKEN_VALUE . '" value="' . $ token . '" />' ; return $ html ; } | Returns the corresponding HTML hidden fields for the CSRF . |
23,143 | public function guard ( ) { if ( $ this -> isHttpMethodFiltered ( $ this -> request -> getMethod ( ) ) ) { $ formName = $ this -> getProvidedFormName ( ) ; $ providedToken = $ this -> getProvidedCsrfToken ( ) ; if ( is_null ( $ formName ) || is_null ( $ providedToken ) ) { throw new InvalidCsrfException ( ) ; } if ( ! $ this -> validateToken ( $ formName , $ providedToken ) ) { throw new InvalidCsrfException ( ) ; } } } | Proceeds to filter the current request for any CSRF mismatch . Forms must provide its unique name and corresponding generated csrf token . |
23,144 | public function injectForms ( $ html ) { preg_match_all ( "/<form(.*?)>(.*?)<\\/form>/is" , $ html , $ matches , PREG_SET_ORDER ) ; if ( is_array ( $ matches ) ) { foreach ( $ matches as $ match ) { if ( strpos ( $ match [ 1 ] , "nocsrf" ) !== false ) { continue ; } $ hiddenFields = self :: generateHiddenFields ( ) ; $ html = str_replace ( $ match [ 0 ] , "<form{$match[1]}>{$hiddenFields}{$match[2]}</form>" , $ html ) ; } } return $ html ; } | Automatically adds CSRF hidden fields to any forms present in the given HTML . This method is to be used with automatic injection behavior . |
23,145 | private function generateToken ( string $ formName ) : string { $ token = Cryptography :: randomString ( self :: TOKEN_LENGTH ) ; $ csrfData = Session :: getInstance ( ) -> read ( '__CSRF_TOKEN' , [ ] ) ; $ csrfData [ $ formName ] = $ token ; Session :: getInstance ( ) -> set ( '__CSRF_TOKEN' , $ csrfData ) ; return $ token ; } | Generates and stores in the current session a cryptographically random token that shall be validated with the filter method . |
23,146 | private function validateToken ( string $ formName , string $ token ) : bool { $ sortedCsrf = $ this -> getStoredCsrfToken ( $ formName ) ; if ( ! is_null ( $ sortedCsrf ) ) { $ csrfData = Session :: getInstance ( ) -> read ( '__CSRF_TOKEN' , [ ] ) ; if ( is_null ( $ this -> request -> getHeader ( 'CSRF_KEEP_ALIVE' ) ) && is_null ( $ this -> request -> getParameter ( 'CSRF_KEEP_ALIVE' ) ) ) { $ csrfData [ $ formName ] = '' ; Session :: getInstance ( ) -> set ( '__CSRF_TOKEN' , $ csrfData ) ; } return hash_equals ( $ sortedCsrf , $ token ) ; } return false ; } | Validates the given token with the one stored for the specified form name . Once validated good or not the token is removed from the session . |
23,147 | private function getStoredCsrfToken ( string $ formName ) : ? string { $ csrfData = Session :: getInstance ( ) -> read ( '__CSRF_TOKEN' ) ; if ( is_null ( $ csrfData ) ) { return null ; } return isset ( $ csrfData [ $ formName ] ) ? $ csrfData [ $ formName ] : null ; } | Obtains the CSRF token stored by the server for the corresponding client . Returns null if undefined . |
23,148 | private function isHttpMethodFiltered ( $ method ) : bool { $ method = strtoupper ( $ method ) ; if ( $ this -> getSecured && $ method == "GET" ) { return true ; } elseif ( $ this -> postSecured && $ method == "POST" ) { return true ; } elseif ( $ this -> putSecured && $ method == "PUT" ) { return true ; } elseif ( $ this -> deleteSecured && $ method == "DELETE" ) { return true ; } return false ; } | Checks if the specified method should be filtered . |
23,149 | public function calcAge ( DateTime $ birthDate , DateTime $ refDate = null ) { return DateTimeRenderer :: renderAge ( $ birthDate , $ refDate ) ; } | Calculates an age . |
23,150 | public function formatString ( $ string , $ format ) { $ fmt = str_replace ( "_" , "%s" , $ format ) ; $ str = str_split ( $ string ) ; return vsprintf ( $ fmt , $ str ) ; } | Format a string . |
23,151 | public function getView ( ) { if ( view ( ) -> exists ( $ this -> view ) ) { return $ this -> view ; } if ( view ( ) -> exists ( 'admin.' . $ this -> urlPrefix ( ) . '.index' ) ) { return 'admin.' . $ this -> urlPrefix ( ) . '.index' ; } if ( view ( ) -> exists ( 'admin.' . $ this -> urlPrefix ( ) ) ) { return 'admin.' . $ this -> urlPrefix ( ) ; } if ( view ( ) -> exists ( 'flare::' . $ this -> view ) ) { return 'flare::' . $ this -> view ; } return parent :: getView ( ) ; } | Returns the Module Admin View . |
23,152 | public static function getStringId ( ResourceEntityInterface $ entity = NULL ) { return is_null ( $ entity ) ? NULL : ( string ) $ entity -> getId ( ) ; } | Obtiene el Id de una entidad . |
23,153 | public function newInstance ( string $ createdByUserId , string $ createdReason = Tracking :: UNKNOWN_REASON ) { $ new = parent :: newInstance ( $ createdByUserId , $ createdReason ) ; $ new -> lastPublished = new \ DateTime ( ) ; $ new -> revisions = new ArrayCollection ( ) ; if ( ! empty ( $ new -> publishedRevision ) ) { $ revision = $ new -> publishedRevision -> newInstance ( $ createdByUserId , $ createdReason ) ; $ new -> removePublishedRevision ( ) ; $ new -> revisions -> add ( $ revision ) ; $ new -> setStagedRevision ( $ revision ) ; } elseif ( ! empty ( $ new -> stagedRevision ) ) { $ revision = $ new -> stagedRevision -> newInstance ( $ createdByUserId , $ createdReason ) ; $ new -> setStagedRevision ( $ revision ) ; $ new -> revisions -> add ( $ revision ) ; } return $ new ; } | Get a clone with special logic Any copy will be changed to staged |
23,154 | public function newInstanceIfHasRevision ( string $ createdByUserId , string $ createdReason = Tracking :: UNKNOWN_REASON ) { $ new = parent :: newInstance ( $ createdByUserId , $ createdReason ) ; $ publishedRevision = $ new -> getPublishedRevision ( ) ; if ( empty ( $ publishedRevision ) ) { return null ; } $ new -> lastPublished = new \ DateTime ( ) ; $ new -> revisions = new ArrayCollection ( ) ; $ new -> stagedRevision = null ; $ new -> stagedRevisionId = null ; $ new -> setPublishedRevision ( $ publishedRevision -> newInstance ( $ createdByUserId , $ createdReason ) ) ; return $ new ; } | This is used mainly for site copies to eliminate pages that are not published |
23,155 | public function setPublishedRevision ( Revision $ revision ) { if ( ! empty ( $ this -> stagedRevision ) ) { $ this -> removeStagedRevision ( ) ; } $ revision -> publishRevision ( ) ; $ this -> publishedRevision = $ revision ; $ this -> publishedRevisionId = $ revision -> getRevisionId ( ) ; $ this -> setLastPublished ( new \ DateTime ( ) ) ; } | Set the published published revision for the page |
23,156 | public function setStagedRevision ( Revision $ revision ) { if ( ! empty ( $ this -> publishedRevision ) && $ this -> publishedRevision -> getRevisionId ( ) == $ revision -> getRevisionId ( ) ) { $ this -> removePublishedRevision ( ) ; } $ this -> stagedRevision = $ revision ; $ this -> stagedRevisionId = $ revision -> getRevisionId ( ) ; } | Sets the staged revision |
23,157 | public function setSite ( Site $ site ) { $ this -> site = $ site ; $ this -> siteId = $ site -> getSiteId ( ) ; } | Set site the page belongs to |
23,158 | public function setRevisions ( array $ revisions ) { $ this -> revisions = new ArrayCollection ( ) ; foreach ( $ revisions as $ revision ) { if ( ! $ revision instanceof Revision ) { throw new InvalidArgumentException ( "Invalid Revision passed in. Unable to set array" ) ; } $ this -> revisions -> set ( $ revision -> getRevisionId ( ) , $ revision ) ; } } | Overwrite revisions and Set a group of revisions |
23,159 | public function getLastSavedDraftRevision ( ) { if ( ! empty ( $ this -> lastSavedDraft ) ) { return $ this -> lastSavedDraft ; } $ published = $ this -> publishedRevision ; $ staged = $ this -> stagedRevision ; $ arrayCollection = $ this -> revisions -> toArray ( ) ; $ revision = end ( $ arrayCollection ) ; if ( empty ( $ revision ) ) { return null ; } $ found = false ; while ( ! $ found ) { if ( empty ( $ revision ) ) { break ; } elseif ( ! empty ( $ published ) && $ published -> getRevisionId ( ) == $ revision -> getRevisionId ( ) ) { $ found = false ; } elseif ( ! empty ( $ staged ) && $ staged -> getRevisionId ( ) == $ revision -> getRevisionId ( ) ) { $ found = false ; } elseif ( $ revision -> wasPublished ( ) ) { $ found = false ; } else { $ found = true ; } if ( ! $ found ) { $ revision = prev ( $ arrayCollection ) ; } } return $ this -> lastSavedDraft = $ revision ; } | Return the last draft saved . |
23,160 | public function getRevisionById ( $ revisionId ) { $ revision = $ this -> revisions -> get ( $ revisionId ) ; if ( $ revision !== null ) { return $ revision ; } foreach ( $ this -> revisions as $ revision ) { if ( $ revision -> getRevisionId ( ) === $ revisionId ) { return $ revision ; } } return null ; } | Get a page revision by ID |
23,161 | public function run ( ) { $ guard = $ this -> getMonitoringInputs ( ) ; if ( empty ( $ guard ) ) { throw new \ RuntimeException ( "Nothing to monitor ! Either configure the IDS to monitor at least one input or completely deactivate this feature." ) ; } $ this -> manager -> run ( $ guard ) ; if ( $ this -> manager -> getImpact ( ) > 0 ) { $ data = $ this -> getDetectionData ( $ this -> manager -> getReports ( ) ) ; throw new IntrusionDetectionException ( $ data ) ; } } | Execute the intrusion detection analysis using the specified monitored inputs . If an intrusion is detected the method will launch the detection callback . |
23,162 | private function getMonitoringInputs ( ) : array { $ guard = [ ] ; if ( $ this -> surveillance & self :: REQUEST ) { $ guard [ 'REQUEST' ] = $ _REQUEST ; } if ( $ this -> surveillance & self :: GET ) { $ guard [ 'GET' ] = $ _GET ; } if ( $ this -> surveillance & self :: POST ) { $ guard [ 'POST' ] = $ _POST ; } if ( $ this -> surveillance & self :: COOKIE ) { $ guard [ 'COOKIE' ] = $ _COOKIE ; } return $ guard ; } | Retrieves the monitoring inputs to consider depending on the current configuration . |
23,163 | private function getDetectionData ( $ reports ) : array { $ data = [ 'impact' => 0 , 'detections' => [ ] ] ; foreach ( $ reports as $ report ) { $ variableName = $ report -> getVarName ( ) ; $ filters = $ report -> getFilterMatch ( ) ; if ( ! isset ( $ data [ 'detections' ] [ $ variableName ] ) ) { $ data [ 'detections' ] [ $ variableName ] = [ 'value' => $ report -> getVarValue ( ) , 'events' => [ ] ] ; } foreach ( $ filters as $ filter ) { $ data [ 'detections' ] [ $ variableName ] [ 'events' ] [ ] = [ 'description' => $ filter -> getDescription ( ) , 'impact' => $ filter -> getImpact ( ) ] ; $ data [ 'impact' ] += $ filter -> getImpact ( ) ; } } return $ data ; } | Constructs a custom basic associative array based on the PHPIDS report when an intrusion is detected . Will contains essential data such as impact targeted inputs and detection descriptions . |
23,164 | public function throwDecoys ( ) { $ params = session_get_cookie_params ( ) ; $ len = strlen ( session_id ( ) ) ; foreach ( $ this -> decoys as $ decoy ) { $ value = Cryptography :: randomString ( $ len ) ; setcookie ( $ decoy , $ value , $ params [ 'lifetime' ] , $ params [ 'path' ] , $ params [ 'domain' ] , $ params [ 'secure' ] , $ params [ 'httponly' ] ) ; $ _COOKIE [ $ decoy ] = $ value ; } } | Throw decoy cookies at session start which are configured exactly as the session cookie . This doesn t contribute in pure security measures but contribute in hiding server footprints and add a little more confusion to the overall communication . |
23,165 | public function addRandomDecoys ( $ count ) { for ( $ i = 0 ; $ i < $ count ; ++ $ i ) { $ this -> addDecoy ( Cryptography :: randomString ( 20 ) ) ; } } | Add a certain amount of random decoy cookies that will be sent along the session cookie . This doesn t contribute in pure security measures but contribute in hiding server footprints and add a little more confusion to the overall communication . |
23,166 | public function destroyDecoys ( ) { foreach ( $ this -> decoys as $ decoy ) { setcookie ( $ decoy , '' , 1 ) ; setcookie ( $ decoy , false ) ; unset ( $ _COOKIE [ $ decoy ] ) ; } } | Carefully expires all decoy cookies . Should be called only if decoys are set and on session destroy . |
23,167 | public function OnUncaughtErrorTriggered ( $ errSeverity , $ errMessage , $ errFile , $ errLine , array $ errContext ) { if ( 0 === error_reporting ( ) ) { return false ; } throw new PHPTriggerErrorException ( $ errMessage , $ errLine , $ errFile , $ errSeverity ) ; } | Default error handler callback for |
23,168 | public function OnErrorMessageReachParent ( $ result ) { if ( $ result instanceof SerializableException ) { if ( $ result instanceof SerializableFatalException ) { throw new ThreadFatalException ( $ result -> getMessage ( ) . PHP_EOL . PHP_EOL . $ result -> getTraceAsString ( ) , $ result -> getCode ( ) ) ; } throw new \ Exception ( $ result -> getMessage ( ) . PHP_EOL . PHP_EOL . $ result -> getTraceAsString ( ) , $ result -> getCode ( ) ) ; } return $ result ; } | The result from |
23,169 | public function registerRoutes ( Router $ router ) { $ router -> group ( [ 'prefix' => $ this -> urlPrefix ( ) , 'namespace' => get_called_class ( ) , 'as' => $ this -> urlPrefix ( ) ] , function ( $ router ) { $ this -> registerSubRoutes ( ) ; $ this -> registerController ( $ this -> getController ( ) ) ; } ) ; } | Register the routes for this Admin Section . |
23,170 | public function registerSubRoutes ( ) { if ( ! is_array ( $ this -> subAdmin ) ) { return ; } foreach ( $ this -> subAdmin as $ adminItem ) { $ this -> registerRoute ( $ adminItem -> getController ( ) , $ adminItem -> routeParameters ( ) ) ; } } | Register subRoutes for Defined Admin instances . |
23,171 | public static function registerRoute ( $ controller , $ parameters = [ ] ) { \ Route :: group ( $ parameters , function ( $ controller ) { \ Route :: registerController ( $ controller ) ; } ) ; } | Register an individual route . |
23,172 | public static function getRequested ( $ key = 'namespace' ) { if ( ! \ Route :: current ( ) ) { return ; } $ currentAction = \ Route :: current ( ) -> getAction ( ) ; if ( isset ( $ currentAction [ $ key ] ) ) { return $ currentAction [ $ key ] ; } return ; } | Returns the Requested Route Action as a string namespace is returned by default . |
23,173 | public function getTitle ( ) { if ( ! isset ( $ this -> title ) || ! $ this -> title ) { return Str :: title ( str_replace ( '_' , ' ' , snake_case ( preg_replace ( '/' . static :: CLASS_SUFFIX . '$/' , '' , static :: shortName ( ) ) ) ) ) ; } return $ this -> title ; } | Title of a Admin Section Class . |
23,174 | public function getPluralTitle ( ) { if ( ! isset ( $ this -> pluralTitle ) || ! $ this -> pluralTitle ) { return Str :: plural ( $ this -> getTitle ( ) ) ; } return $ this -> pluralTitle ; } | Plural of the Admin Section Class Title . |
23,175 | public function urlPrefix ( ) { if ( ! isset ( $ this -> urlPrefix ) || ! $ this -> urlPrefix ) { return str_slug ( $ this -> getPluralTitle ( ) ) ; } return $ this -> urlPrefix ; } | URL Prefix to a Admin Section Top Level Page . |
23,176 | public static function fromString ( $ url , Url $ root = null ) { $ instance = new static ( ) ; $ components = static :: parseUrl ( $ url ) ; foreach ( $ components as $ component => $ value ) { $ method = 'set' . Inflector :: camelize ( $ component ) ; call_user_func ( array ( $ instance , $ method ) , $ value ) ; } $ instance -> setOriginal ( $ url ) ; $ instance -> setRoot ( $ root ) ; return $ instance ; } | Construye una instancia a partir de un objeto con una interfaz similar . |
23,177 | public function toArray ( ) { return array ( 'scheme' => $ this -> scheme , 'host' => $ this -> host , 'port' => $ this -> port , 'user' => $ this -> user , 'pass' => $ this -> pass , 'path' => $ this -> path , 'query' => $ this -> query , 'fragment' => $ this -> fragment ) ; } | Convierte la instancia en un array . |
23,178 | public function toAbsoluteUrl ( Url $ root = null ) { $ root = $ this -> getRoot ( ) ? : $ root ; if ( ! $ root -> isUrlAbsolute ( ) ) { throw new \ InvalidArgumentException ( ) ; } if ( ! $ this -> isUrlAbsolute ( ) ) { $ this -> setScheme ( $ root -> getScheme ( ) ) ; $ this -> setHost ( $ root -> getHost ( ) ) ; if ( ! $ this -> isPathAbsolute ( ) ) { $ path = $ root -> getPath ( ) ; $ path = substr ( $ path , 0 , strrpos ( $ path , '/' ) + 1 ) ; $ this -> setPath ( $ path . $ this -> getPath ( ) ) ; } } return $ this ; } | Obtiene la URL absoluta de un path . |
23,179 | public function sendMessageToBrowser ( $ message ) { if ( ! $ this -> outputStarted ) { ob_start ( ) ; echo '<!DOCTYPE html><html lang="en"><head></head><body>' ; $ this -> outputStarted = true ; } echo strip_tags ( $ message , '<h1><p><br><hr>' ) ; echo '<br />' ; echo str_repeat ( " " , 6024 ) , "\n" ; ob_flush ( ) ; flush ( ) ; } | Send message to browser |
23,180 | public static function getExceptionInfo ( Throwable $ t ) : array { return [ 'type' => get_class ( $ t ) , 'message' => $ t -> getMessage ( ) , 'code' => $ t -> getCode ( ) , 'file' => $ t -> getFile ( ) , 'line' => $ t -> getLine ( ) , 'trace' => $ t -> getTraceAsString ( ) , ] ; } | Returns exception info in array . |
23,181 | public static function throwIfNotType ( array $ typesToVariables , bool $ failOnWhitespace = false , bool $ allowNulls = false ) { foreach ( $ typesToVariables as $ type => $ variablesOrVariable ) { self :: handleTypesToVariables ( $ failOnWhitespace , $ allowNulls , $ variablesOrVariable , $ type ) ; } } | Throws an exception if specified variables are not of given types . |
23,182 | public function set ( $ index , $ value = null ) { if ( is_array ( $ index ) ) { $ this -> data = array_merge ( $ this -> data , $ index ) ; } else { $ this -> data [ $ index ] = $ value ; } return $ this ; } | Set a single property or multiple properties at once |
23,183 | public function get ( $ index , $ default = null ) { if ( isset ( $ this -> data [ $ index ] ) ) { return $ this -> data [ $ index ] ; } return $ default ; } | Retreive a value or an optional default |
23,184 | public function setBody ( $ body ) { $ body = json_encode ( $ body ) ; if ( $ error = json_last_error ( ) ) { throw new \ ErrorException ( $ error ) ; } curl_setopt ( $ this -> curlHandler , CURLOPT_POSTFIELDS , $ body ) ; return $ this ; } | Define el cuerpo de un pedido . |
23,185 | public function cut ( string $ lineEnd = PHP_EOL ) : Observable { return $ this -> lift ( function ( ) use ( $ lineEnd ) { return new CutOperator ( $ lineEnd ) ; } ) ; } | Cuts the stream based upon a delimiter . |
23,186 | public function compatibility ( ) { if ( strpos ( $ this -> app -> version ( ) , '5.1.' ) !== false && strpos ( $ this -> app -> version ( ) , '(LTS)' ) !== false ) { return 'LTS' ; } return 'Edge' ; } | Returns the compatibility version of Flare to use . |
23,187 | public function registerHelper ( $ helper , $ class ) { if ( array_key_exists ( $ helper , $ this -> helpers ) ) { throw new Exception ( "Helper method `$helper` has already been defined" ) ; } $ this -> helpers [ $ helper ] = $ class ; } | Register a helper method . |
23,188 | protected function callHelperMethod ( $ method , $ parameters ) { return $ this -> app -> make ( $ this -> helpers [ $ method ] , $ parameters ) ; } | Call a Helper Method . |
23,189 | public function getPrimaryRedirectUrl ( Site $ site ) { $ currentDomain = $ site -> getDomain ( ) -> getDomainName ( ) ; $ ipValidator = new Ip ( ) ; $ isIp = $ ipValidator -> isValid ( $ currentDomain ) ; if ( $ isIp ) { return null ; } $ primaryDomain = $ site -> getDomain ( ) -> getPrimary ( ) ; if ( empty ( $ primaryDomain ) ) { return null ; } if ( $ primaryDomain -> getDomainName ( ) == $ currentDomain ) { return null ; } return $ primaryDomain -> getDomainName ( ) ; } | getPrimaryRedirectUrl If the IP is not a domain and is not the primary return redirect for primary |
23,190 | public function init ( ChainManagerInterface $ chainManager , array $ params = [ ] ) { $ this -> in ( $ chainManager -> getAssetManager ( ) ) ; if ( $ chainManager -> hasEvents ( ) ) { $ event = $ chainManager -> getNextEvent ( ) ; if ( is_object ( $ event ) ) { $ event -> init ( $ chainManager ) ; } } $ this -> out ( $ chainManager -> getAssetManager ( ) ) ; return $ this ; } | Bootstrap this event . |
23,191 | public function canBeImpersonatedPolicy ( Impersonatable $ impersonater , Impersonatable $ impersonated ) { return $ this -> canImpersonatePolicy ( $ impersonater ) && $ impersonated -> canBeImpersonated ( ) ; } | Check if the given user can be impersonated . |
23,192 | public function getList ( ) { $ rcmUserService = $ this -> serviceLocator -> get ( RcmUserService :: class ) ; if ( ! $ rcmUserService -> isAllowed ( ResourceName :: RESOURCE_SITES , 'admin' ) ) { $ this -> getResponse ( ) -> setStatusCode ( Response :: STATUS_CODE_401 ) ; return $ this -> getResponse ( ) ; } $ config = $ this -> getConfig ( ) ; $ pageTypes = $ config [ 'Rcm' ] [ 'pageTypes' ] ; return new ApiJsonModel ( $ pageTypes , 0 , 'Success' ) ; } | getList of available page types |
23,193 | public function isValid ( $ value ) { $ this -> setValue ( $ value ) ; $ pattern = '/^[a-z0-9_\-]*[a-z0-9]$/i' ; $ this -> pageNameOk = true ; if ( ! preg_match ( $ pattern , $ value ) ) { $ this -> error ( self :: PAGE_NAME ) ; $ this -> pageNameOk = false ; } return $ this -> pageNameOk ; } | Is the page name valid? |
23,194 | final public static function getInstance ( ? array $ configurations = null ) : self { if ( is_null ( self :: $ instance ) ) { self :: $ instance = new self ( $ configurations ) ; } return self :: $ instance ; } | Obtain the single allowed instance for Session through singleton pattern method . |
23,195 | public function has ( string $ key , $ value = null ) : bool { return is_null ( $ value ) ? isset ( $ _SESSION [ $ key ] ) : isset ( $ _SESSION [ $ key ] ) && $ _SESSION [ $ key ] == $ value ; } | Determines if the specified key exists in the current session . Optionally if the value argument is used it also validates that the value is exactly the one provided . |
23,196 | public function remove ( string $ key ) { if ( isset ( $ _SESSION [ $ key ] ) ) { $ _SESSION [ $ key ] = '' ; unset ( $ _SESSION [ $ key ] ) ; } } | Removes the session data associated with the provided key . |
23,197 | private function initialize ( ) { $ this -> name = ( isset ( $ this -> configurations [ 'name' ] ) ) ? $ this -> configurations [ 'name' ] : self :: DEFAULT_SESSION_NAME ; $ this -> assignSessionLifetime ( ) ; if ( isset ( $ this -> configurations [ 'encryption_enabled' ] ) && $ this -> configurations [ 'encryption_enabled' ] ) { $ this -> handler = new EncryptedSessionHandler ( ) ; } $ this -> security = new SecuritySession ( $ this -> configurations ) ; } | Initializes all data required from various setting to implement the session class . Can be overwritten by children class to add new features . |
23,198 | private function assignSessionLifetime ( ) { if ( isset ( $ this -> configurations [ 'lifetime' ] ) ) { $ lifetime = $ this -> configurations [ 'lifetime' ] ; ini_set ( 'session.gc_maxlifetime' , $ lifetime * 1.2 ) ; session_set_cookie_params ( $ lifetime ) ; } } | Registers a different session lifetime if configured . Assigns the gc_maxlifetime with a little more time to make sure the client cookie expires before the server garbage collector . |
23,199 | protected function handleBadUserRoleException ( GetResponseForExceptionEvent $ event , BadUserRoleException $ ex ) { if ( null !== $ ex -> getRedirectUrl ( ) ) { $ event -> setResponse ( new RedirectResponse ( $ ex -> getRedirectUrl ( ) ) ) ; } return $ event ; } | Handle a bad user role exception . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.