idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
14,100
public static function newlines ( $ value , array $ options = array ( ) ) { $ options = $ options + array ( 'cr' => true , 'lf' => true , 'crlf' => true , 'limit' => 2 , 'trim' => true ) ; if ( $ options [ 'limit' ] ) { $ pattern = '/(?:%s){' . $ options [ 'limit' ] . ',}/u' ; } else { $ pattern = '/(?:%s)+/u' ; $ replace = '' ; } if ( $ options [ 'crlf' ] ) { $ value = preg_replace ( sprintf ( $ pattern , '\r\n' ) , ( isset ( $ replace ) ? $ replace : "\r\n" ) , $ value ) ; } if ( $ options [ 'cr' ] ) { $ value = preg_replace ( sprintf ( $ pattern , '\r' ) , ( isset ( $ replace ) ? $ replace : "\r" ) , $ value ) ; } if ( $ options [ 'lf' ] ) { $ value = preg_replace ( sprintf ( $ pattern , '\n' ) , ( isset ( $ replace ) ? $ replace : "\n" ) , $ value ) ; } if ( $ options [ 'trim' ] ) { $ value = trim ( $ value ) ; } return $ value ; }
Sanitize a string by removing excess CRLF characters .
14,101
public static function whitespace ( $ value , array $ options = array ( ) ) { $ options = $ options + array ( 'space' => true , 'tab' => true , 'limit' => 2 , 'strip' => true , 'trim' => true ) ; if ( $ options [ 'limit' ] ) { $ pattern = '/%s{' . $ options [ 'limit' ] . ',}/u' ; } else { $ pattern = '/%s+/u' ; $ replace = '' ; } if ( $ options [ 'tab' ] ) { $ value = preg_replace ( sprintf ( $ pattern , '\t' ) , ( isset ( $ replace ) ? $ replace : "\t" ) , $ value ) ; } if ( $ options [ 'space' ] ) { $ value = preg_replace ( sprintf ( $ pattern , ' ' ) , ( isset ( $ replace ) ? $ replace : ' ' ) , $ value ) ; } if ( $ options [ 'strip' ] ) { $ value = str_replace ( chr ( 0xCA ) , ' ' , $ value ) ; } if ( $ options [ 'trim' ] ) { $ value = trim ( $ value ) ; } return $ value ; }
Sanitize a string by removing excess whitespace and tab characters .
14,102
public function setModel ( IModel $ model , $ initRepo = true ) { $ this -> model = $ model ; if ( $ initRepo ) $ this -> initRepository ( ) ; return $ this ; }
Sets the model to class
14,103
protected function initRepository ( ) { if ( $ this -> model === null || ( $ this -> model !== null && ! in_array ( 'DScribe\Core\IModel' , class_implements ( $ this -> model ) ) ) ) return false ; if ( $ this -> repository !== null && $ this -> model -> getTableName ( ) === $ this -> repository -> getTableName ( ) ) return true ; $ repository = ( $ this -> repositoryClass !== null ) ? $ this -> repositoryClass : 'DBScribe\Repository' ; $ this -> repository = new $ repository ( $ this -> model , engineGet ( 'DB' ) , true ) ; }
Initializes the repository
14,104
protected function prepareInject ( ) { $ model = ( $ this -> model ) ? $ this -> model : $ this -> getModule ( ) . '\Models\\' . $ this -> getClassName ( ) ; if ( is_object ( $ model ) ) $ model = get_class ( $ model ) ; if ( ! class_exists ( $ model ) ) return array_merge ( parent :: prepareInject ( ) , $ this -> getConfigInject ( 'services' ) ) ; return array_merge ( parent :: prepareInject ( ) , $ this -> getConfigInject ( 'services' ) , array ( 'model' => array ( 'class' => $ model ) , ) ) ; }
prepares injection of classes
14,105
public function addSubscriberService ( $ serviceId , $ class ) { $ rfc = new \ ReflectionClass ( $ class ) ; if ( ! $ rfc -> implementsInterface ( 'Symfony\Component\EventDispatcher\EventSubscriberInterface' ) ) { throw new \ InvalidArgumentException ( "$class must implement Symfony\Component\EventDispatcher\EventSubscriberInterface" ) ; } foreach ( $ class :: getSubscribedEvents ( ) as $ eventName => $ params ) { if ( is_string ( $ params ) ) { $ this -> addListenerService ( $ eventName , array ( $ serviceId , $ params ) , 0 ) ; } elseif ( is_string ( $ params [ 0 ] ) ) { $ this -> addListenerService ( $ eventName , array ( $ serviceId , $ params [ 0 ] ) , isset ( $ params [ 1 ] ) ? $ params [ 1 ] : 0 ) ; } else { foreach ( $ params as $ listener ) { $ this -> addListenerService ( $ eventName , array ( $ serviceId , $ listener [ 0 ] ) , isset ( $ listener [ 1 ] ) ? $ listener [ 1 ] : 0 ) ; } } } }
Adds a service as event subscriber
14,106
public function normalize ( Schema $ schema ) : array { $ this -> schema = $ schema ; $ schemaDesc = [ ] ; $ schemaDesc [ 'tables' ] = [ ] ; foreach ( $ schema -> getTables ( ) as $ table ) { $ schemaDesc [ 'tables' ] [ $ table -> getName ( ) ] = $ this -> normalizeTable ( $ table ) ; } return $ schemaDesc ; }
Normalize a Schema object into an array descriptor
14,107
public function removeMedia ( MediaInterface $ media ) { if ( $ this -> medias -> contains ( $ media ) ) { $ this -> medias -> removeElement ( $ media ) ; } return $ this ; }
Removes the media .
14,108
public function toArray ( ) { return array ( 'eid' => $ this -> eid , 'id' => $ this -> id , 'description' => $ this -> description , 'months' => $ this -> months , 'startfee' => $ this -> startFee , 'invoicefee' => $ this -> invoiceFee , 'interestrate' => $ this -> interestRate , 'minamount' => $ this -> minAmount , 'country' => $ this -> country , 'type' => $ this -> type , 'expire' => $ this -> expire ) ; }
Returns an associative array mirroring this PClass .
14,109
public function isValid ( $ now = null ) { if ( $ this -> expire == null || $ this -> expire == '-' || $ this -> expire <= 0 ) { return true ; } if ( $ now === null || ! is_numeric ( $ now ) ) { $ now = time ( ) ; } return ( $ now > $ this -> expire ) ? false : true ; }
Checks whether this PClass is valid .
14,110
protected function helper ( $ classname ) { $ directories = explode ( '.' , $ classname ) ; $ amount = count ( $ directories ) - 1 ; $ namespace = Router :: getRoute ( ) -> getModule ( ) . '\\' . str_replace ( DIRECTORY_SEPARATOR , '\\' , Application :: get ( [ 'directory' , 'helper' ] ) ) ; foreach ( $ directories as $ index => $ directory ) { if ( $ amount === $ index ) { $ namespace .= Application :: get ( [ 'prefix' , 'helper' ] ) . $ directory ; break ; } $ namespace .= $ directory . '\\' ; } return new $ namespace ; }
Loads a helper class in current module directory
14,111
protected function fails ( $ fieldname = null ) { $ helper = new StringToArray ( ) ; return $ helper -> execute ( $ fieldname , null , Message :: getErrors ( true ) ) ; }
Get the error message from the validator by fieldname
14,112
protected function passes ( $ fieldname = null ) { $ helper = new StringToArray ( ) ; return true === Request :: isPost ( ) && null === $ helper -> execute ( $ fieldname , null , Message :: getErrors ( true ) ) ; }
Returns if there is no validation error for the given fieldname when request method is equal to POST
14,113
public function buildKeysChoices ( MediaImport $ import ) { $ prefix = $ import -> getFilesystem ( ) ; $ fs = $ this -> mountManager -> getFilesystem ( $ prefix ) ; $ contents = $ fs -> listContents ( '' , true ) ; $ choices = [ ] ; foreach ( $ contents as $ object ) { if ( ! ( $ object [ 'type' ] == 'dir' || substr ( $ object [ 'path' ] , 0 , 1 ) == '.' ) ) { $ key = sprintf ( '%s://%s' , $ prefix , $ object [ 'path' ] ) ; $ choices [ $ key ] = $ object [ 'path' ] ; } } return $ choices ; }
Builds the keys choices .
14,114
public function bind ( callable $ codeBlock ) { assert ( $ this -> result === null , "'Eventually' instance may not be mutated after code-block execution." ) ; return static :: unit ( function ( $ success ) use ( $ codeBlock ) { $ this -> run ( function ( $ value ) use ( $ codeBlock , $ success ) { return $ codeBlock ( $ value ) -> run ( $ success ) ; } ) ; } ) ; }
Binds the given callable to the monad s managed code - block s successful execution .
14,115
public function isNoDateStrategy ( Document $ doc = null , $ prefix = '150_' ) { $ prefix = 'ups/' ; return file_exists ( $ this -> cdnPath . $ prefix . $ doc -> getTitle ( ) ) ; }
Check using no date strategy
14,116
public function getConfig ( $ configName , array $ configPaths = array ( ) ) : ConfigORM { $ directories = ( empty ( $ configPaths ) ? $ this -> configPaths : $ configPaths ) ; $ configName = strtolower ( $ configName ) ; if ( isset ( $ this -> cfg [ $ configName ] ) ) { return $ this -> cfg [ $ configName ] ; } $ this -> cfg [ $ configName ] = $ this -> loadConfigFile ( $ configName , $ directories ) ; return $ this -> cfg [ $ configName ] ; }
Retrieve a config file object
14,117
protected function loadConfigFile ( $ configName , array $ configPaths ) : ConfigORM { foreach ( $ configPaths as $ directory ) { $ file = $ directory . DS . 'config.' . $ configName . '.php' ; if ( file_exists ( $ file ) ) { return new ConfigORM ( $ file ) ; break ; } } $ file = Core :: $ coreDir . DS . 'Config' . DS . 'config.' . $ configName . '.php' ; if ( file_exists ( $ file ) ) { return new ConfigORM ( $ file ) ; } throw new ConfigException ( "Could not load config. File $configName not found" , 1 ) ; }
Determine whether the file exists and if so load the ConfigORM
14,118
public function removeConfigPath ( $ directory ) { if ( ( $ key = array_search ( $ directory , $ this -> configPaths ) ) !== false ) { unset ( $ this -> configPaths [ $ key ] ) ; } }
Remove a path where config files can be found
14,119
public function getContent ( ) { try { if ( $ this -> response ) { if ( isset ( $ this -> response [ 'content' ] ) ) { return $ this -> response [ 'content' ] ; } else { return $ this -> response ; } } } catch ( Exception $ e ) { $ message = 'Error File: ' . $ e -> getFile ( ) . ' - Line: ' . $ e -> getLine ( ) . ' - Code: ' . $ e -> getCode ( ) . ' - Message: ' . $ e -> getMessage ( ) ; $ this -> debug -> error ( __FUNCTION__ , $ message ) ; return $ message ; } return NULL ; }
Function getContent - Get Body Content from Request
14,120
public function sendRequest ( ) { try { if ( mb_strlen ( $ this -> url ) >= 9 ) { $ response = $ this -> useFileGetContents ( ) ; $ this -> response = $ response ; return $ response ; } } catch ( Exception $ e ) { $ message = "Error: " . __CLASS__ . ": Please make sure to set a URL to fetch - Line: " . $ e -> getLine ( ) . ' - Msg: ' . $ e -> getMessage ( ) ; $ this -> debug -> error ( __FUNCTION__ , $ message ) ; return $ message ; } return NULL ; }
Let s go to Request
14,121
public function getPostBody ( ) { $ output = '' ; if ( $ this -> isJson ) { $ jsonPretty = ( $ this -> isJsonPretty ? JSON_PRETTY_PRINT : NULL ) ; if ( count ( $ this -> data ) > 0 ) { $ output = json_encode ( $ this -> data , $ jsonPretty ) ; } } elseif ( $ this -> isXML ) { $ output = $ this -> data ; } elseif ( count ( $ this -> data ) > 0 ) { $ output = http_build_query ( $ this -> data ) ; } return $ output ; }
Get the post body - either JSON encoded or ready to be sent as a form post
14,122
public function getQueryString ( ) { $ query_string = '' ; if ( count ( $ this -> query_string ) > 0 ) { $ query_string .= http_build_query ( $ this -> query_string ) ; } if ( $ this -> method != 'POST' ) { if ( count ( $ this -> data ) > 0 ) { $ query_string .= http_build_query ( $ this -> data ) ; } } if ( mb_strlen ( $ query_string ) > 0 ) { $ query_string = ( mb_strpos ( $ this -> url , '?' ) ? '&' : '?' ) . $ query_string ; } return $ query_string ; }
Get the query string by merging any supplied string with that of the generated components .
14,123
public function setMethod ( $ method = '' ) { if ( mb_strlen ( $ method ) == 0 ) { $ this -> debug -> debug ( __FUNCTION__ , 'Set Default Method = GET if $method is does not exist' ) ; $ method = 'GET' ; } else { $ method = strtoupper ( $ method ) ; $ validMethods = [ 'GET' , 'HEAD' , 'PUT' , 'POST' , 'DELETE' ] ; if ( ! in_array ( $ method , $ validMethods ) ) { $ message = "Error: " . __CLASS__ . ": The requested method (${method}) is not valid here" ; $ this -> debug -> error ( __FUNCTION__ , $ message ) ; return $ message ; } } $ this -> method = $ method ; return $ this ; }
Set the HTTP method GET HEAD PUT POST are valid
14,124
public function setData ( $ data = [ ] ) { if ( ! is_array ( $ data ) && is_string ( $ data ) ) { $ data = parse_str ( $ data ) ; } if ( count ( $ data ) == 0 ) { $ this -> data = [ ] ; } else { $ this -> data = $ data ; } $ this -> debug -> debug ( __FUNCTION__ , 'Data into Request: ' , $ this -> data ) ; }
Set Data contents Must be supplied as an array
14,125
public function setQueryString ( $ query_string = [ ] ) { if ( ! is_array ( $ query_string ) && is_string ( $ query_string ) ) { $ query_string = parse_str ( $ query_string ) ; } if ( count ( $ query_string ) == 0 ) { $ this -> query_string = [ ] ; } else { $ this -> query_string = $ query_string ; } }
Set query string data Must be supplied as an array
14,126
public function setCookies ( $ cookies = [ ] ) { if ( ! is_array ( $ cookies ) ) { $ this -> cookies = [ ] ; } else { $ this -> cookies = $ cookies ; $ this -> trackCookies = TRUE ; } }
Set any cookies to be included in the headers Must be supplied as an array
14,127
public function setTrackCookies ( $ value = FALSE ) { if ( ! $ value ) { $ this -> trackCookies = FALSE ; } else { $ this -> trackCookies = TRUE ; } }
Should cookies be tracked?
14,128
public function setJsonPretty ( $ value = FALSE ) { if ( ! $ value ) { $ this -> isJsonPretty = FALSE ; } else { $ this -> isJsonPretty = TRUE ; } }
Should JSON being sent be encoded in an easily readable format? Only useful for debugging
14,129
public function setVerifyPeer ( $ value = FALSE ) { if ( ! $ value ) { $ this -> verifyPeer = FALSE ; } else { $ this -> verifyPeer = TRUE ; } }
Should SSL peers be verified?
14,130
public function parseReturnHeaders ( $ headers ) { $ head = [ ] ; foreach ( $ headers as $ k => $ v ) { $ t = explode ( ':' , $ v , 2 ) ; if ( isset ( $ t [ 1 ] ) ) { $ head [ trim ( $ t [ 0 ] ) ] = trim ( $ t [ 1 ] ) ; } else { $ head [ ] = $ v ; if ( preg_match ( "#HTTP/[0-9\.]+\s+([0-9]+)#" , $ v , $ out ) ) { $ head [ 'reponse_code' ] = intval ( $ out [ 1 ] ) ; } } } $ this -> debug -> debug ( __FUNCTION__ , 'Response Header: ' , $ head ) ; return $ head ; }
Parse HTTP response headers
14,131
public function registerService ( $ service , $ name = '' ) { if ( empty ( $ name ) ) { $ name = Assist :: classNameShort ( $ service ) ; } static :: $ container -> offsetSet ( strtolower ( $ name ) , $ service ) ; }
Register a service
14,132
public function run ( ) { $ request = $ this -> getService ( 'request-handler' ) ; $ request -> incoming ( $ this ) ; $ helpers = static :: $ container [ 'helpers' ] ; foreach ( $ helpers as $ helper => $ options ) { $ this -> registerService ( new $ helper ( $ options ) ) ; } $ this -> getService ( 'session-handler' ) -> start ( ) ; if ( $ this -> getService ( 'router' ) -> routeIsCallable ( ) ) { $ this -> executeCallback ( ) ; return ; } $ this -> executeUnitExtenders ( $ this -> getActiveUnit ( ) ) ; $ this -> executeService ( ) ; }
Run the application - Incoming request will be handled - Registration in the application will be done - Session will be started - Service will be executed
14,133
public function executeUnitExtenders ( string $ unit ) { $ extenders = $ this -> getService ( 'unit-extenders' ) ; if ( ! is_array ( $ extenders ) ) { return ; } foreach ( $ extenders as $ extender ) { if ( ! class_exists ( $ extender ) ) { continue ; } $ resolver = $ this -> getService ( 'resolver' ) ; try { $ resolver -> resolve ( $ extender , Extender :: EXECUTE_METHOD , $ this ) ; } catch ( Base $ e ) { $ this -> getService ( 'response-handler' ) -> setContent ( new Content ( $ e -> getMessage ( ) ) ) -> send ( ) ; } } }
Execute unit extenders
14,134
public function terminate ( ) { $ eventHandler = $ this -> getService ( 'event-handler' ) ; $ eventHandler -> getEvent ( TerminateApplication :: class ) -> attach ( new LogBeforeTerminate ( ) ) ; $ eventHandler -> getEvent ( TerminateApplication :: class ) -> attach ( new ExitApplication ( ) ) ; $ eventHandler -> fire ( TerminateApplication :: class , [ 'app' => $ this ] ) ; }
Fire TerminateApplication event with two framework watchers . One to log and one to actually exit .
14,135
protected function createComponentForm ( string $ name ) : Form { $ form = new Form ( $ this , $ name ) ; $ form -> setTranslator ( $ this -> translator ) ; $ this -> formContainer -> getForm ( $ form ) ; $ form -> onSuccess [ ] = $ this -> eventContainer ; return $ form ; }
Create component form .
14,136
private function isPathAccessible ( $ path ) { $ uri = $ this -> httpUtils -> generateUri ( $ this -> requestStack -> getMasterRequest ( ) , $ path ) ; $ res = $ this -> browser -> get ( $ uri ) ; if ( $ res -> isSuccessful ( ) ) { return true ; } return false ; }
Returns whether the given path is accessible through http or not .
14,137
private function camelize ( $ string , $ lower = true ) { $ words = explode ( '_' , strtolower ( $ string ) ) ; $ camelized = '' ; foreach ( $ words as $ word ) { if ( strpos ( $ word , '_' ) === false ) { $ camelized .= ucfirst ( trim ( $ word ) ) ; } } return ( $ lower ) ? lcfirst ( $ camelized ) : $ camelized ; }
Convert underscored string to lower|upper camelCase
14,138
public function getConfigurationFactory ( ) { if ( null === $ this -> configurationFactory ) { $ this -> configurationFactory = new Configuration \ ConfigurationFactory ( ) ; } return $ this -> configurationFactory ; }
Returns the configuration factory .
14,139
public function getConfigurationRegistry ( ) { if ( null === $ this -> configurationRegistry ) { $ this -> configurationRegistry = new Configuration \ ConfigurationRegistry ( ) ; } return $ this -> configurationRegistry ; }
Returns the configuration registry .
14,140
public function getEventDispatcher ( ) { if ( null === $ this -> eventDispatcher ) { $ this -> eventDispatcher = new Dispatcher \ ResourceEventDispatcher ( ) ; $ this -> eventDispatcher -> setConfigurationRegistry ( $ this -> getConfigurationRegistry ( ) ) ; $ this -> eventDispatcher -> setEventQueue ( $ this -> getEventQueue ( ) ) ; } return $ this -> eventDispatcher ; }
Returns the event dispatcher .
14,141
public function getLocaleProvider ( ) { if ( null === $ this -> localeProvider ) { $ this -> localeProvider = new Locale \ LocaleProvider ( 'fr' , 'en' , [ 'fr' , 'en' ] ) ; } return $ this -> localeProvider ; }
Returns the locale provider .
14,142
public function getEventQueue ( ) { if ( null === $ this -> eventQueue ) { $ this -> eventQueue = new Event \ EventQueue ( $ this -> getConfigurationRegistry ( ) , $ this -> getEventDispatcher ( ) ) ; } return $ this -> eventQueue ; }
Returns the event queue .
14,143
public function getPersistenceEventQueue ( ) { if ( null === $ this -> persistenceEventQueue ) { $ this -> persistenceEventQueue = new Persistence \ PersistenceEventQueue ( $ this -> getConfigurationRegistry ( ) , $ this -> getEventDispatcher ( ) ) ; } return $ this -> persistenceEventQueue ; }
Returns the persistence event queue .
14,144
public function getPersistenceHelper ( ) { if ( null === $ this -> persistenceHelper ) { $ this -> persistenceHelper = new Doctrine \ ORM \ PersistenceHelper ( $ this -> em , $ this -> getPersistenceEventQueue ( ) ) ; } return $ this -> persistenceHelper ; }
Returns the persistence helper .
14,145
private function getStreamByPathScheme ( $ path ) { $ scheme = parse_url ( $ path , PHP_URL_SCHEME ) ; return $ this -> streamManager -> getStream ( $ scheme ) ; }
Returns the stream instance by the uri scheme in path .
14,146
private function isStreamWritable ( $ path ) { $ stream = $ this -> getStreamByPathScheme ( $ path ) ; if ( $ stream instanceof StreamInterface ) { return $ stream -> isWritable ( ) ; } return false ; }
Returns true if the stream for the path is writable .
14,147
function maybe_make_link ( $ url ) { if ( array_key_exists ( $ url , $ this -> links ) ) { if ( is_array ( $ this -> links [ $ url ] ) ) { $ output = $ this -> links [ $ url ] [ 0 ] ; } else { $ output = $ this -> links [ $ url ] ; } } else { $ output = $ url ; } return $ output ; }
Conditionally makes a hyperlink based on an internal class variable .
14,148
public function getVariable ( $ variable ) { if ( true === isset ( $ this -> variables [ $ variable ] ) ) { return $ this -> variables [ $ variable ] ; } }
Getter for returning variables by key
14,149
final protected function fsockopen ( $ hostname , $ port = - 1 , & $ errno = 0 , & $ errstr = '' , $ timeout = null ) { $ this -> fhandle = fsockopen ( $ hostname , $ port , $ errno , $ errstr , $ timeout ) ; return $ this ; }
Open Internet or Unix domain socket connection
14,150
final protected function fwrite ( $ string , $ length = null ) { return is_int ( $ length ) ? fwrite ( $ this -> fhandle , $ string , $ length ) : fwrite ( $ this -> fhandle , $ string ) ; }
Binary - safe file write
14,151
final protected function fread ( $ length = null ) { if ( ! is_int ( $ length ) ) { $ length = $ this -> fstat ( 'size' ) ; } return fread ( $ this -> fhandle , $ length ) ; }
Binary - safe file read
14,152
final protected function fgetcsv ( $ length = 0 , $ delimiter = ',' , $ enclosure = '"' , $ escape = '\\' ) { return fgetcsv ( $ this -> fhandle , $ length , $ delimiter , $ enclosure , $ escape ) ; }
Gets line from file pointer and parse for CSV fields
14,153
final protected function fputcsv ( array $ fields , $ delimiter = ',' , $ enclosure = '"' , $ escape_char = '\\' ) { return fputcsv ( $ this -> fhandle , $ fields , $ delimiter , $ enclosure , $ escape_char ) ; }
Format line as CSV and write to file pointer
14,154
final protected function fscanf ( $ format , array & $ params = array ( ) ) { if ( empty ( $ params ) ) { return fscanf ( $ this -> fhandle , $ format ) ; } array_shift ( $ params , $ this -> fhandle , $ format ) ; $ results = call_user_func_array ( 'fscanf' , $ params ) ; array_splice ( $ params , 2 ) ; return $ results ; }
Parses input from a file according to a format
14,155
private function fallBackRoute ( RequestInterface $ request ) : Route { $ parts = explode ( '/' , $ request -> getPathInfo ( ) ) ; if ( count ( $ parts ) == 2 && empty ( $ parts [ 1 ] ) ) { return $ this -> getDefaultRoute ( $ request ) ; } $ actionName = 'index' ; $ controllerName = ucfirst ( $ parts [ 1 ] ) ; if ( count ( $ parts ) > 2 ) { $ actionName = $ parts [ 2 ] ; } $ endPoint = new RouteEndpoint ( $ this -> context -> getControllerNamespace ( ) , $ controllerName , $ actionName , $ request -> getMethod ( ) ) ; return new Route ( '/' . $ parts [ 1 ] . '/' . $ actionName , $ endPoint ) ; }
If we cannot match a Route with the RouteCollection we will try to find a Controller & Action that matches the uri
14,156
public function add ( $ id , $ service , $ replace = false ) { if ( $ this -> has ( $ id ) == true && $ replace == false ) { throw new ServiceExistsException ( $ id ) ; } $ this -> services [ $ id ] = $ service ; }
Add service to container
14,157
public function setStatus ( int $ code ) : Response { $ this -> statusText = Status :: getText ( $ code ) ; $ this -> statusCode = $ code ; return $ this ; }
Set the status code and text
14,158
public function addHeader ( string $ key , string $ value ) : Response { $ this -> headers -> add ( $ key , $ value ) ; return $ this ; }
Add a header Allows for adding multiple headers with the same key
14,159
protected function getQueryItems ( ) { $ result = parent :: getQueryItems ( ) ; $ asDwnl = self :: AS_DWNL ; $ asAcc = self :: AS_ACCOUNT ; $ tbl = $ this -> resource -> getTableName ( EDownline :: ENTITY_NAME ) ; $ as = $ asDwnl ; $ cols = [ self :: A_MLM_ID => EDownline :: A_MLM_ID ] ; $ cond = $ as . '.' . EDownline :: A_CUSTOMER_REF . '=' . $ asAcc . '.' . EAccount :: A_CUST_ID ; $ result -> joinLeft ( [ $ as => $ tbl ] , $ cond , $ cols ) ; return $ result ; }
SELECT ... FROM prxgt_acc_account AS paa LEFT JOIN prxgt_acc_type_asset AS pata ON pata . id = paa . asset_type_id LEFT JOIN customer_entity AS ce ON ce . entity_id = paa . customer_id LEFT JOIN prxgt_dwnl_customer AS dwnl ON dwnl . customer_ref = paa . customer_id
14,160
protected function generateId ( ) : int { if ( $ this -> getId ( ) !== null ) { return $ this -> getId ( ) ; } $ maxIdLength = \ mb_strlen ( ( string ) PHP_INT_MAX ) - 1 ; $ id = mb_substr ( crc32 ( $ this -> getModelId ( ) ) , $ maxIdLength - self :: ID_PATH_HASH_LENGTH ) . mb_substr ( crc32 ( $ this -> getActualPath ( ) ) , self :: ID_PATH_HASH_LENGTH ) ; return ( int ) $ id ; }
Returns existed id or generate unique id based on model id and file path .
14,161
protected function setDefaultMetadataCache ( $ cache , ServiceLocatorInterface $ serviceLocator ) { $ metadataCache = null ; if ( is_string ( $ cache ) ) { if ( $ serviceLocator -> has ( $ cache ) ) { $ metadataCache = $ serviceLocator -> get ( $ cache ) ; } } else if ( $ cache instanceof Zend_Cache_Core ) { $ metadataCache = $ cache ; } if ( $ metadataCache instanceof Zend_Cache_Core ) { Zend_Db_Table :: setDefaultMetadataCache ( $ metadataCache ) ; } }
Set the default metadata cache
14,162
protected function checkUnknownOptions ( array $ options ) { $ unsupportedOptions = array_diff_key ( $ options , $ this -> supportedOptions ) ; if ( [ ] !== ( $ unsupportedOptions ) ) { throw new InvalidServiceOptionsException ( 'Unsupported validation option(s) found: ' . implode ( ', ' , array_keys ( $ unsupportedOptions ) ) , 1456397655 ) ; } }
Checks if an unknown option exists in the given options array .
14,163
protected function checkRequiredOptions ( array $ options ) { array_walk ( $ this -> supportedOptions , function ( $ supportedOptionData , $ supportedOptionName , $ options ) { if ( isset ( $ supportedOptionData [ 1 ] ) && true === $ supportedOptionData [ 1 ] && empty ( $ supportedOptionData [ 0 ] ) && ! array_key_exists ( $ supportedOptionName , $ options ) ) { throw new InvalidServiceOptionsException ( 'Required validation option not set: ' . $ supportedOptionName , 1456397839 ) ; } } , $ options ) ; }
Will check if the required options are correctly filled .
14,164
protected function fillOptionsWithValues ( array $ options ) { return array_merge ( array_map ( function ( $ value ) { if ( false === is_array ( $ value ) ) { throw new InvalidTypeException ( 'Supported options of a service must be an array with a value as first entry, and a flag to tell if the option is required in the second entry.' , 1459249834 ) ; } return $ value [ 0 ] ; } , $ this -> supportedOptions ) , $ options ) ; }
Will fill the options of this service with the given values .
14,165
protected function delay ( $ priority , callable $ callback ) { if ( false === MathUtility :: canBeInterpretedAsInteger ( $ priority ) ) { throw new InvalidTypeException ( 'The priority must be an integer, ' . gettype ( $ priority ) . ' was given.' , 1457014282 ) ; } if ( false === isset ( static :: $ delayedCallbacks [ $ priority ] ) ) { static :: $ delayedCallbacks [ $ priority ] = [ ] ; } static :: $ delayedCallbacks [ $ priority ] [ ] = $ callback ; }
Use this function to delay a certain part of the script during an event dispatch . This allows to run parts of the script in a sorted way based on a priority value .
14,166
public function runDelayedCallbacks ( AbstractServiceDTO $ dto ) { krsort ( static :: $ delayedCallbacks ) ; foreach ( static :: $ delayedCallbacks as $ callbacks ) { foreach ( $ callbacks as $ callback ) { $ callback ( $ dto ) ; } } static :: $ delayedCallbacks = [ ] ; }
Will run every delayed callback which was registered during an event .
14,167
protected function sanitize ( ) { return [ 'slug' => Str :: slug ( $ this -> get ( $ this -> has ( 'slug' ) ? 'slug' : 'title' , '' ) ) , 'seo_title' => $ this -> get ( empty ( $ this -> get ( 'seo_title' ) ) ? 'title' : 'seo_title' ) , ] ; }
Sanitize the inputs .
14,168
public function validateForbiddenTLD ( $ email , $ specifiedTLDs = array ( ) ) { $ forbiddenTLDs = $ this -> getTheForbiddenTLDs ( $ specifiedTLDs ) ; if ( empty ( $ forbiddenTLDs ) ) return true ; $ validation = true ; foreach ( $ forbiddenTLDs as $ forbiddenTLD ) { $ lengthOfForbiddenTLD = $ this -> lengthForbiddenTLD ( $ forbiddenTLD ) ; $ lastCharactersOfEmail = $ this -> lastCharactersOfEmail ( $ email , $ lengthOfForbiddenTLD ) ; if ( $ this -> compareEmailWithForbiddenTLD ( $ lastCharactersOfEmail , $ forbiddenTLD ) ) { $ validation = false ; } } return $ validation ; }
Validate Top Level Domains
14,169
public function denormalize ( $ input ) { $ lcPropertyName = lcfirst ( $ input ) ; $ snakeCasedName = '' ; $ len = strlen ( $ lcPropertyName ) ; for ( $ i = 0 ; $ i < $ len ; ++ $ i ) { if ( ctype_upper ( $ lcPropertyName [ $ i ] ) ) { $ snakeCasedName .= '_' . strtolower ( $ lcPropertyName [ $ i ] ) ; } else { $ snakeCasedName .= strtolower ( $ lcPropertyName [ $ i ] ) ; } } return $ snakeCasedName ; }
Converts a string like myInput to my_input
14,170
public function persist ( $ eloquent , $ field , $ value , $ name ) { return $ this -> handle ( $ eloquent , $ field , $ value , $ name ) ; }
Persist route query
14,171
private function freshOrNull ( ClassMetadata $ classMetadata = null ) { if ( null === $ classMetadata ) { return ; } return $ this -> freshnessValidator -> isFresh ( $ classMetadata ) ? $ classMetadata : null ; }
Internal method for handling refreshing of metadata .
14,172
private function handleLocalizationCommon ( ) { $ this -> handleLanguageIntoSession ( ) ; $ localizationFile = $ this -> getCommonLocaleFolder ( ) . '/locale/' . $ this -> tCmnSession -> get ( 'lang' ) . '/LC_MESSAGES/' . $ this -> commonLibFlags [ 'localization_domain' ] . '.mo' ; $ translations = new \ Gettext \ Translations ( ) ; $ translations -> addFromMoFile ( $ localizationFile ) ; $ this -> tCmnLb = new \ Gettext \ Translator ( ) ; $ this -> tCmnLb -> loadTranslations ( $ translations ) ; }
Takes care of instantiation of localization libraries used within current module for multi - languages support
14,173
public function setDividedResult ( $ fAbove , $ fBelow , $ mArguments = null ) { if ( ( $ fAbove == 0 ) || ( $ fBelow == 0 ) ) { return 0 ; } $ numberToFormat = ( $ fAbove / $ fBelow ) ; if ( is_numeric ( $ mArguments ) ) { $ frMinMax = [ 'MinFractionDigits' => $ mArguments , 'MaxFractionDigits' => $ mArguments , ] ; return $ this -> setNumberFormat ( $ numberToFormat , $ frMinMax ) ; } return $ this -> setNumberFormat ( round ( $ numberToFormat , $ mArguments ) ) ; }
Returns proper result from a mathematical division in order to avoid Zero division error or Infinite results
14,174
public function startBrokerSession ( ) { if ( isset ( $ this -> brokerId ) ) { return ; } $ sid = $ this -> getBrokerSessionID ( ) ; if ( $ sid === false ) { return $ this -> fail ( "Broker didn't send a session key" , 400 ) ; } $ linkedId = $ this -> cache -> get ( $ sid ) ; if ( ! $ linkedId ) { return $ this -> fail ( "The broker session id isn't attached to a user session" , 403 ) ; } if ( session_status ( ) === PHP_SESSION_ACTIVE ) { if ( $ linkedId !== session_id ( ) ) { throw new \ Exception ( "Session has already started" , 400 ) ; } return ; } session_id ( $ linkedId ) ; session_start ( ) ; $ this -> brokerId = $ this -> validateBrokerSessionId ( $ sid ) ; }
Start the session for broker requests to the SSO server
14,175
protected function generateSessionId ( $ brokerId , $ token ) { $ broker = $ this -> getBrokerInfo ( $ brokerId ) ; if ( ! isset ( $ broker ) ) { return null ; } return "SSO-{$brokerId}-{$token}-" . hash ( 'sha256' , 'session' . $ token . $ broker [ 'secret' ] ) ; }
Generate session id from session token
14,176
protected function detectReturnType ( ) { if ( isset ( $ _GET [ 'cookie' ] ) ) { $ this -> returnType = 'none' ; return ; } elseif ( ! empty ( $ _GET [ 'return_url' ] ) ) { $ this -> returnType = 'redirect' ; } elseif ( ! empty ( $ _GET [ 'callback' ] ) ) { $ this -> returnType = 'jsonp' ; } elseif ( strpos ( $ _SERVER [ 'HTTP_ACCEPT' ] , 'image/' ) !== false ) { $ this -> returnType = 'image' ; } elseif ( strpos ( $ _SERVER [ 'HTTP_ACCEPT' ] , 'application/json' ) !== false ) { $ this -> returnType = 'json' ; } }
Detect the type for the HTTP response . Should only be done for an attach request .
14,177
public function attach ( ) { $ this -> detectReturnType ( ) ; if ( empty ( $ _REQUEST [ 'broker' ] ) ) { return $ this -> fail ( "No broker specified" , 400 ) ; } if ( empty ( $ _REQUEST [ 'token' ] ) ) { return $ this -> fail ( "No token specified" , 400 ) ; } if ( ! $ this -> returnType ) { return $ this -> fail ( "No return url specified" , 400 ) ; } $ checksum = $ this -> generateAttachChecksum ( $ _REQUEST [ 'broker' ] , $ _REQUEST [ 'token' ] ) ; if ( empty ( $ _REQUEST [ 'checksum' ] ) || $ checksum != $ _REQUEST [ 'checksum' ] ) { return $ this -> fail ( "Invalid checksum" , 400 ) ; } $ this -> startUserSession ( ) ; $ sid = $ this -> generateSessionId ( $ _REQUEST [ 'broker' ] , $ _REQUEST [ 'token' ] ) ; $ this -> cache -> set ( $ sid , $ this -> getSessionData ( 'id' ) ) ; $ this -> outputAttachSuccess ( ) ; }
Attach a user session to a broker session
14,178
protected function outputAttachSuccess ( ) { if ( $ this -> returnType === 'image' ) { $ this -> outputImage ( ) ; } if ( $ this -> returnType === 'json' || $ this -> returnType === 'none' ) { header ( 'Content-type: application/json; charset=UTF-8' ) ; echo json_encode ( [ 'success' => 'attached' ] ) ; } if ( $ this -> returnType === 'jsonp' ) { $ data = json_encode ( [ 'success' => 'attached' ] ) ; echo $ _REQUEST [ 'callback' ] . "($data, 200);" ; } if ( $ this -> returnType === 'redirect' ) { $ url = $ _REQUEST [ 'return_url' ] ; header ( "Location: $url" , true , 307 ) ; echo "You're being redirected to <a href='{$url}'>$url</a>" ; } }
Output on a successful attach
14,179
protected function getSessionData ( $ key ) { if ( $ key === 'id' ) { return session_id ( ) ; } return isset ( $ _SESSION [ $ key ] ) ? $ _SESSION [ $ key ] : null ; }
Get session data
14,180
protected function fail ( $ message , $ http_status = 500 ) { if ( ! empty ( $ this -> options [ 'fail_exception' ] ) ) { throw new Exception ( $ message , $ http_status ) ; } if ( $ http_status === 500 ) { trigger_error ( $ message , E_USER_WARNING ) ; } if ( $ this -> returnType === 'jsonp' ) { echo $ _REQUEST [ 'callback' ] . "(" . json_encode ( [ 'error' => $ message ] ) . ", $http_status);" ; exit ( ) ; } if ( $ this -> returnType === 'redirect' ) { $ url = $ _REQUEST [ 'return_url' ] . '?sso_error=' . $ message ; header ( "Location: $url" , true , 307 ) ; echo "You're being redirected to <a href='{$url}'>$url</a>" ; exit ( ) ; } http_response_code ( $ http_status ) ; header ( 'Content-type: application/json; charset=UTF-8' ) ; echo json_encode ( [ 'error' => $ message ] ) ; exit ( ) ; }
An error occured .
14,181
public static function uInt ( & $ value , $ options = [ 'max' => null , 'min' => null , 'default' => null ] ) { $ value = ( int ) $ value ; self :: processUNum ( $ value , $ options ) ; return $ value ; }
filter positive int
14,182
public static function ufloat ( & $ value , $ options = [ 'max' => null , 'min' => null , 'default' => null ] ) { $ value = ( float ) $ value ; self :: processUNum ( $ value , $ options ) ; return $ value ; }
filter positive float
14,183
protected static function processUNum ( & $ value , $ options ) { if ( ! isset ( $ options [ 'min' ] ) || empty ( $ options [ 'min' ] ) || $ options [ 'min' ] < 0 ) { $ options [ 'min' ] = 0 ; } self :: processNum ( $ value , $ options ) ; }
process positive number
14,184
public static function start ( callable $ readCache , callable $ storeCache ) { self :: $ annotations = $ readCache ( ) ; if ( ! is_array ( self :: $ annotations ) ) { self :: flush ( ) ; throw new \ RuntimeException ( 'Cached annotation data is not an array' ) ; } self :: $ unserialized = [ ] ; self :: $ cacheChanged = false ; self :: $ storeCache = $ storeCache ; register_shutdown_function ( [ __CLASS__ , '__shutdown' ] ) ; }
start annotation cache with given cache storage logic
14,185
public static function startFromFileCache ( string $ cacheFile ) { self :: start ( function ( ) use ( $ cacheFile ) { if ( file_exists ( $ cacheFile ) ) { return unserialize ( file_get_contents ( $ cacheFile ) ) ; } return [ ] ; } , function ( array $ annotationData ) use ( $ cacheFile ) { file_put_contents ( $ cacheFile , serialize ( $ annotationData ) ) ; } ) ; }
starts annotation cache with given cache file
14,186
public static function put ( Annotations $ annotations ) { self :: $ annotations [ $ annotations -> target ( ) ] = serialize ( $ annotations ) ; self :: $ unserialized [ $ annotations -> target ( ) ] = $ annotations ; self :: $ cacheChanged = true ; }
store annotations in the cache
14,187
public static function get ( string $ target ) { if ( ! self :: has ( $ target ) ) { return null ; } if ( ! isset ( self :: $ unserialized [ $ target ] ) ) { self :: $ unserialized [ $ target ] = unserialize ( self :: $ annotations [ $ target ] ) ; } return self :: $ unserialized [ $ target ] ; }
returns list of all annotations for given target
14,188
public function load ( $ file ) { if ( ! is_string ( $ file ) || ! file_exists ( $ file ) ) { throw new InvalidArgumentException ( 'File must be a valid file.' ) ; } $ data = include $ file ; if ( ! is_array ( $ data ) ) { throw new RuntimeException ( 'File did not return an array.' ) ; } return $ this -> set ( $ data ) ; }
Load a configuration file .
14,189
protected function updateDynamicContent ( $ content , $ placeholders ) { foreach ( $ placeholders as $ name => $ statements ) { $ placeholders [ $ name ] = $ this -> getView ( ) -> evaluateDynamicContent ( $ statements ) ; } return strtr ( $ content , $ placeholders ) ; }
Replaces placeholders in content by results of evaluated dynamic statements .
14,190
public static function filterInteger ( $ int , $ min = ~ PHP_INT_MAX , $ max = PHP_INT_MAX , $ default = 0 ) { return filter_var ( $ int , FILTER_VALIDATE_INT , array ( 'options' => array ( 'default' => $ default , 'min_range' => $ min , 'max_range' => $ max ) ) ) ; }
Filter an integer .
14,191
public function buildCompiledFilepath ( ) { $ _compile_id = isset ( $ this -> smarty -> compile_id ) ? preg_replace ( '![^\w\|]+!' , '_' , $ this -> smarty -> compile_id ) : null ; $ _flag = ( int ) $ this -> smarty -> config_read_hidden + ( int ) $ this -> smarty -> config_booleanize * 2 + ( int ) $ this -> smarty -> config_overwrite * 4 ; $ _filepath = sha1 ( $ this -> source -> name . $ _flag ) ; if ( $ this -> smarty -> use_sub_dirs ) { $ _filepath = substr ( $ _filepath , 0 , 2 ) . DS . substr ( $ _filepath , 2 , 2 ) . DS . substr ( $ _filepath , 4 , 2 ) . DS . $ _filepath ; } $ _compile_dir_sep = $ this -> smarty -> use_sub_dirs ? DS : '^' ; if ( isset ( $ _compile_id ) ) { $ _filepath = $ _compile_id . $ _compile_dir_sep . $ _filepath ; } $ _compile_dir = $ this -> smarty -> getCompileDir ( ) ; return $ _compile_dir . $ _filepath . '.' . basename ( $ this -> source -> name ) . '.config' . '.php' ; }
Get file path .
14,192
public function whereNot ( \ Closure $ callback , string $ appendRule = 'AND' ) : self { $ groupQuery = $ this -> resolveCriteriaGroupClosure ( $ callback ) ; $ this -> where [ ] = new CriteriaCriterion ( $ groupQuery -> where , true , $ appendRule ) ; return $ this ; }
Adds a group of criteria wrapped by NOT .
14,193
public function whereRaw ( string $ query , array $ bindings = [ ] , string $ appendRule = 'AND' ) : self { $ this -> where [ ] = new RawCriterion ( new Raw ( $ query , $ bindings ) , $ appendRule ) ; return $ this ; }
Adds a raw SQL criterion to the WHERE section .
14,194
public function whereBetween ( $ column , $ min , $ max , bool $ not = false , string $ appendRule = 'AND' ) : self { $ column = $ this -> checkStringValue ( 'Argument $column' , $ column ) ; $ min = $ this -> checkScalarOrNullValue ( 'The left between value' , $ min ) ; $ max = $ this -> checkScalarOrNullValue ( 'The right between value' , $ max ) ; $ this -> where [ ] = new BetweenCriterion ( $ column , $ min , $ max , $ not , $ appendRule ) ; return $ this ; }
Adds a BETWEEN criterion to the WHERE section .
14,195
public function orWhereBetween ( $ column , $ min , $ max ) : self { return $ this -> whereBetween ( $ column , $ min , $ max , false , 'OR' ) ; }
Adds a BETWEEN criterion to the WHERE section with the OR append rule . See the readme for more info about append rules .
14,196
public function whereNotBetween ( $ column , $ min , $ max ) : self { return $ this -> whereBetween ( $ column , $ min , $ max , true ) ; }
Adds a NOT BETWEEN criterion to the WHERE section .
14,197
public function orWhereNotBetween ( $ column , $ min , $ max ) : self { return $ this -> whereBetween ( $ column , $ min , $ max , true , 'OR' ) ; }
Adds a NOT BETWEEN criterion to the WHERE section with the OR append rule . See the readme for more info about append rules .
14,198
public function whereIn ( $ column , $ values , bool $ not = false , string $ appendRule = 'AND' ) : self { $ column = $ this -> checkStringValue ( 'Argument $column' , $ column ) ; if ( ! is_array ( $ values ) && ! ( $ values instanceof \ Closure ) && ! ( $ values instanceof Query ) && ! ( $ values instanceof StatementInterface ) ) { return $ this -> handleException ( InvalidArgumentException :: create ( 'The IN value' , $ values , [ 'array' , \ Closure :: class , Query :: class , StatementInterface :: class , 'null' ] ) ) ; } if ( is_array ( $ values ) ) { foreach ( $ values as $ index => & $ value ) { $ value = $ this -> checkScalarOrNullValue ( 'Argument $values[' . $ index . ']' , $ value ) ; } } elseif ( $ values instanceof \ Closure ) { $ values = $ this -> resolveSubQueryClosure ( $ values ) ; } $ this -> where [ ] = new InCriterion ( $ column , $ values , $ not , $ appendRule ) ; return $ this ; }
Adds a IN criterion to the WHERE section .
14,199
public function whereNull ( $ column , bool $ not = false , string $ appendRule = 'AND' ) : self { $ column = $ this -> checkStringValue ( 'Argument $column' , $ column ) ; $ this -> where [ ] = new NullCriterion ( $ column , ! $ not , $ appendRule ) ; return $ this ; }
Adds a IS NULL criterion to the WHERE section .