idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
17,700
private function resetStatus ( ) { $ this -> debug -> info ( 'resetStatus' ) ; $ this -> status = \ array_merge ( $ this -> status , array ( 'currentPageName' => $ this -> persist -> get ( 'currentPage.name' ) , 'completed' => false , 'error' => false , 'postMaxExceeded' => false , 'multipart' => false , 'additionalPages' => array ( ) , 'idCounts' => array ( ) , ) ) ; }
Reset form status
17,701
private function storeValues ( ) { $ this -> debug -> groupCollapsed ( __METHOD__ ) ; if ( ! $ this -> status [ 'submitted' ] ) { $ this -> debug -> groupEnd ( ) ; return ; } if ( isset ( $ _SERVER [ 'REQUEST_METHOD' ] ) && $ _SERVER [ 'REQUEST_METHOD' ] == 'POST' ) { $ this -> debug -> warn ( 'POST method' ) ; if ( isset ( $ _SERVER [ 'CONTENT_LENGTH' ] ) && $ _SERVER [ 'CONTENT_LENGTH' ] > Str :: getBytes ( \ ini_get ( 'post_max_size' ) , true ) ) { $ this -> debug -> warn ( 'post_max_size exceeded' ) ; $ this -> alerts -> add ( 'Your upload has exceeded the ' . Str :: getBytes ( \ ini_get ( 'post_max_size' ) ) . ' limit' ) ; $ this -> status [ 'postMaxExceeded' ] = true ; } $ values = $ _POST ; foreach ( $ _FILES as $ k => $ file ) { if ( $ file [ 'error' ] === UPLOAD_ERR_NO_FILE ) { continue ; } if ( $ file [ 'error' ] === UPLOAD_ERR_OK ) { \ move_uploaded_file ( $ file [ 'tmp_name' ] , $ file [ 'tmp_name' ] ) ; } $ values [ $ k ] = $ file ; } $ this -> status [ 'submitted' ] = true ; $ this -> persist -> set ( 'submitted' , true ) ; $ this -> persist -> set ( 'currentPage.values' , $ values ) ; } elseif ( \ strtolower ( $ this -> cfg [ 'attribs' ] [ 'method' ] ) == 'get' ) { $ this -> debug -> warn ( 'storing GET vals' ) ; $ this -> persist -> set ( 'currentPage.values' , $ _GET ) ; } $ this -> debug -> groupEnd ( ) ; }
Copies request params to persist for storage
17,702
private function produceExchangeInstance ( $ exchangeName ) { if ( isset ( $ this -> declaredExchangeInstances [ $ exchangeName ] ) ) { return $ this -> declaredExchangeInstances [ $ exchangeName ] ; } if ( isset ( $ this -> usedExchangeInstances [ $ exchangeName ] ) ) { return $ this -> usedExchangeInstances [ $ exchangeName ] ; } $ this -> ensureChannel ( ) ; $ exchange = new AMQPExchange ( $ this -> channel ) ; $ exchange -> setName ( $ exchangeName ) ; $ this -> usedExchangeInstances [ $ exchangeName ] = $ exchange ; return $ exchange ; }
It returns a cached exchange or a new one if none exists .
17,703
private function produceQueueInstance ( $ queueName ) { if ( isset ( $ this -> declaredQueueInstances [ $ queueName ] ) ) { return $ this -> declaredQueueInstances [ $ queueName ] ; } if ( isset ( $ this -> usedQueueInstances [ $ queueName ] ) ) { return $ this -> usedQueueInstances [ $ queueName ] ; } $ this -> ensureChannel ( ) ; $ queue = new AMQPQueue ( $ this -> channel ) ; $ queue -> setName ( $ queueName ) ; $ this -> usedQueueInstances [ $ queueName ] = $ queue ; return $ queue ; }
It returns a cached queue or a new one if none exists .
17,704
public function actionLogin ( $ view = 'login' , $ partial = false ) { if ( ! \ Yii :: $ app -> user -> isGuest ) { return $ this -> goHome ( ) ; } $ model = new LoginForm ( ) ; if ( $ model -> load ( Yii :: $ app -> request -> post ( ) ) && $ model -> login ( ) ) { return $ this -> redirect ( $ this -> getLoginRedirect ( ) ) ; } if ( \ Yii :: $ app -> request -> isAjax || $ partial ) { return $ this -> renderAjax ( $ view , compact ( 'model' ) ) ; } return $ this -> render ( $ view , compact ( 'model' ) ) ; }
Renders login form .
17,705
public function actionRegister ( ) { if ( ! \ Yii :: $ app -> user -> isGuest ) { return $ this -> goHome ( ) ; } $ model = new RegisterForm ( ) ; if ( $ model -> load ( Yii :: $ app -> request -> post ( ) ) && $ model -> save ( ) ) { Yii :: $ app -> session -> setFlash ( "success" , Yii :: $ app -> user -> isGuest ? Yii :: t ( 'modules/user' , 'Please confirm registration email!' ) : Yii :: t ( 'modules/user' , 'Registration completed!' ) ) ; return ( ( $ url = $ this -> getLoginRedirect ( ) ) && ! Yii :: $ app -> user -> isGuest ) ? $ this -> redirect ( $ url ) : $ this -> goBack ( ) ; } return $ this -> render ( 'register' , compact ( 'model' ) ) ; }
Registers user .
17,706
public function actionConfirm ( $ auth_key ) { $ model = $ this -> findModel ( true ) ; if ( $ auth_key && ( $ user = $ model :: findOne ( compact ( 'auth_key' ) ) ) ) { Yii :: $ app -> session -> setFlash ( "success" , Yii :: t ( 'modules/user' , "You have successfully completed your registration. Please set your password." ) ) ; Yii :: $ app -> user -> login ( $ user ) ; $ user -> activate ( ) ; } else { Yii :: $ app -> session -> setFlash ( "error" , Yii :: t ( 'modules/user' , "Your auth link is invalid." ) ) ; return $ this -> goHome ( ) ; } $ this -> redirect ( [ 'update' ] ) ; }
For registration confirmation by email auth link .
17,707
public function findModel ( $ new = false ) { $ class = \ Yii :: $ app -> user -> identityClass ; return $ new === true ? new $ class ( ) : Yii :: $ app -> user -> identity ; }
Finds user model .
17,708
public function fetch ( ) { $ ret = array ( ) ; $ pos = 0 ; $ len = count ( $ this -> _arguments ) ; foreach ( $ this -> _descriptors as $ name => $ descriptor ) { $ value = $ descriptor -> getDefault ( ) ; for ( $ i = $ pos ; ; $ i ++ ) { if ( $ i < $ len && $ descriptor -> match ( $ this -> _arguments [ $ i ] ) ) { $ value = $ this -> _arguments [ $ i ] ; $ pos = $ i + 1 ; break ; } else { if ( $ descriptor -> isRequired ( ) ) { throw new InvalidArgumentException ( "Argument is required: `$name`" ) ; } if ( $ i > $ len - 1 ) { break ; } } } $ ret [ $ name ] = $ value ; } return $ ret ; }
Fetches elements from the arguments that matches specific descriptors .
17,709
public function replaceKeys ( FilterResponseEvent $ event ) { if ( ! $ event -> isMasterRequest ( ) ) { return ; } if ( $ this -> controller !== $ event -> getRequest ( ) -> attributes -> get ( '_controller' ) ) { return ; } $ response = $ event -> getResponse ( ) ; $ content = preg_replace ( $ this -> pattern , $ this -> replacement , $ response -> getContent ( ) ) ; $ response -> setContent ( $ content ) ; }
Replace Sylius translation keys .
17,710
private function uriKeyExists ( $ nextUriPart , array $ pageMap ) { if ( array_key_exists ( $ nextUriPart , $ pageMap ) ) { return $ nextUriPart ; } $ keys = array_keys ( $ pageMap ) ; $ variableParts = array_values ( preg_grep ( '/\{(.*)\}/' , $ keys ) ) ; $ variablePartsCount = count ( $ variableParts ) ; if ( $ variablePartsCount === 0 ) { return null ; } elseif ( $ variablePartsCount > 1 ) { throw new RoutingException ( 'Single node has more than one variable key' ) ; } $ variablePartRaw = $ variableParts [ 0 ] ; $ variablePart = preg_replace ( [ '/\{/' , '/\}/' ] , '' , $ variablePartRaw ) ; if ( array_key_exists ( $ variablePart , $ this -> uriVariables ) ) { throw new RoutingException ( 'a key named ' . $ variablePart . ' appears more than once on a single route' ) ; } $ this -> uriVariables [ $ variablePart ] = $ nextUriPart ; return $ variablePartRaw ; }
Checks if there is a key in the page map for the given uri part . If there is a wildcard in the url it will save the wildcard + it s value
17,711
public function getFullPath ( ) { $ key = 'template.templatePath' ; if ( $ this -> type === self :: PART_BODY ) { $ key = 'template.viewPath' ; } $ path = Configuration :: get ( $ key , null ) ; if ( $ path === null ) { throw new ConfigurationException ( "The template.templatePath or template.viewPath isn't configured right or doesn't exists!" ) ; } $ foundView = false ; try { AppManager :: getInstance ( ) -> initApps ( ) ; } catch ( \ Exception $ exception ) { } foreach ( AppManager :: getInstance ( ) -> getApps ( ) as $ app ) { $ testPath = $ app -> getAppDirectory ( ) . DS . $ path . DS . $ this -> getPath ( ) ; if ( is_file ( $ testPath ) ) { $ path = $ testPath ; $ foundView = true ; } } if ( ! $ foundView ) { throw new NotFoundException ( 'Template or view file not found in any apps!' ) ; } return $ path ; }
Get full path of view file .
17,712
private function writeMessage ( string $ level , string $ message , string $ tag , string $ file , int $ line , array $ target_loggers ) { if ( ! $ this -> logger_config -> isLogEnabled ( ) ) { return ; } $ log_level_filter = 'E' ; foreach ( $ this -> logger_config -> getLogLevelFilters ( ) as $ path => $ lv ) { if ( $ this -> route_context === $ path || strpos ( $ this -> route_context , $ path ) === 0 ) { $ log_level_filter = $ lv ; } } $ cmp = self :: compareLogLevel ( $ level , $ log_level_filter ) ; if ( $ cmp > 0 ) { return ; } $ log_tag_filters = $ this -> logger_config -> getTagFilters ( ) ; if ( is_array ( $ log_tag_filters ) && ! empty ( $ log_tag_filters ) ) { if ( ! in_array ( $ tag , $ log_tag_filters ) ) { return ; } } $ msg = new LogMessage ( $ level , $ message , $ tag , $ file , $ line ) ; foreach ( $ target_loggers as $ key ) { if ( isset ( $ this -> loggers [ $ key ] ) && in_array ( $ key , $ target_loggers ) ) { $ this -> loggers [ $ key ] -> writeln ( $ msg ) ; } } }
write a message
17,713
public function terminate ( ) { if ( $ this -> loggers ) { foreach ( $ this -> loggers as $ key => $ logger ) { $ logger -> writeFooter ( ) ; $ logger -> terminate ( ) ; unset ( $ this -> loggers [ $ key ] ) ; } $ this -> loggers = NULL ; } }
shutdown all loggers
17,714
public function trace ( string $ file , int $ line , string $ target , string $ message , string $ tag = NULL ) { self :: log ( $ file , $ line , "T:$target" , $ message , $ tag ) ; }
write trace log
17,715
private function _getLevelAndTargetLoggers ( $ target ) { $ target = strpos ( $ target , ':' ) !== false ? explode ( ':' , $ target ) : [ '' , '*' ] ; list ( $ level , $ target_loggers ) = $ target ; $ target_loggers = explode ( ',' , $ target_loggers ) ; $ target_loggers = array_map ( 'trim' , $ target_loggers ) ; if ( in_array ( '*' , $ target_loggers ) ) { $ target_loggers = array_keys ( $ this -> loggers ) ; } return array ( $ level , $ target_loggers ) ; }
Split target loggers and levels from target list
17,716
public static function instance ( $ object ) { if ( ! is_object ( $ object ) ) { throw new \ InvalidArgumentException ( 'Only objects are allowed to be passed to the helper.' ) ; } $ response = new self ( ) ; $ response -> origin = $ object ; $ response -> target = new ReflectionClass ( $ object ) ; return $ response ; }
Creates and returns the wrapper . Only objects are allowed to be passed else an exception will be thrown . Store the input object to the created wrapper .
17,717
public function parsePath ( ? string $ path = null ) : ? string { if ( $ path === null ) { return null ; } $ path = \ str_replace ( '%DOCUMENT_ROOT%' , $ this -> documentRoot , $ path ) ; $ path = \ str_replace ( [ '\\' , '/' ] , DIRECTORY_SEPARATOR , $ path ) ; return $ path ; }
Replaces predefined constants in path string to document and framework root
17,718
public function register ( $ eventType , callable $ filter ) { if ( ! isset ( $ this -> handlers [ $ eventType ] ) ) { $ this -> handlers [ $ eventType ] = [ ] ; } $ this -> handlers [ $ eventType ] [ ] = $ filter ; }
Registers a filter function .
17,719
public function start ( int $ maxRuntimeInSec = 60 * 15 ) : void { \ pcntl_signal ( SIGTERM , function ( ) { $ this -> shouldTerminate = true ; $ this -> logger -> debug ( 'Caught SIGTERM, worker goes into termination.' ) ; } ) ; $ this -> startedTime = \ time ( ) ; $ this -> logger -> info ( 'Worker started: ' . $ this -> name ) ; while ( ! $ this -> shouldTerminate || 0 < \ count ( $ this -> runningJobs ) ) { \ pcntl_signal_dispatch ( ) ; $ this -> checkRunningJobs ( ) ; if ( ! $ this -> shouldTerminate ) { if ( \ count ( $ this -> runningJobs ) < $ this -> maxJobs && null !== $ job = $ this -> queue -> dequeue ( ) ) { $ this -> handleDequeuedJob ( $ job ) ; } if ( \ time ( ) > $ this -> startedTime + $ maxRuntimeInSec ) { $ this -> shouldTerminate = true ; $ this -> logger -> debug ( 'Elapsed maximum runtime, worker goes into termination.' ) ; } } \ usleep ( 500000 ) ; } }
Starts polling to run jobs .
17,720
public function show ( ) { global $ config ; $ title = $ config [ 'title' ] ; $ msg = $ this -> getCode ( ) . ': Error on line ' . $ this -> getLine ( ) . ' in ' . $ this -> getFile ( ) . ': <b> "' . $ this -> getMessage ( ) . ' " </b> ' ; include Path :: sys ( ) . 'Exceptions' . DIRECTORY_SEPARATOR . 'index.php' ; exit ( ) ; }
This method displays the error message
17,721
public static function add ( array & $ array , string $ key , $ value , string $ delimiter = null ) { if ( null === static :: get ( $ array , $ key , null , $ delimiter ) ) { static :: set ( $ array , $ key , $ value , $ delimiter ) ; } }
Adds an element to the given array but only if it does not yet exist .
17,722
public static function collapse ( array $ array ) : array { $ results = [ ] ; foreach ( $ array as $ key => $ item ) { if ( is_array ( $ item ) ) { $ results = array_merge ( $ results , $ item ) ; continue ; } if ( is_int ( $ key ) ) { $ results [ ] = $ item ; continue ; } if ( ! array_key_exists ( $ key , $ results ) ) { $ results [ $ key ] = $ item ; } } return $ results ; }
Collapses an array of arrays into a single array . Not recursive ie . only the first dimension of arrays will be collapsed down .
17,723
public static function contains ( array $ haystack , $ needle , bool $ strict = true ) { foreach ( $ haystack as $ value ) { if ( ( ! $ strict && $ needle == $ value ) || $ needle === $ value ) { return true ; } if ( is_array ( $ value ) && static :: contains ( $ needle , $ value , $ strict ) ) { return true ; } } return false ; }
Checks whether the given value is contained within the given array . Equivalent of a recursive in_array . When you are sure you are dealing with a 1 - dimensional array use in_array instead to avoid the overhead .
17,724
public static function delimit ( array $ array , string $ prepend = '' , string $ delimiter = null ) { $ results = [ ] ; if ( null === $ delimiter ) { $ delimiter = static :: $ delimiter ; } foreach ( $ array as $ key => $ value ) { if ( is_array ( $ value ) && ! empty ( $ value ) ) { $ results = array_merge ( $ results , static :: delimit ( $ value , $ prepend . $ key . $ delimiter ) ) ; } else { $ results [ $ prepend . $ key ] = $ value ; } } return $ results ; }
Flattens a multi - dimensional array using the given delimiter .
17,725
public static function fetch ( array $ array , string $ key , string $ delimiter = null ) : array { $ results = [ ] ; if ( null === $ delimiter ) { $ delimiter = static :: $ delimiter ; } foreach ( explode ( $ delimiter , $ key ) as $ segment ) { $ results = [ ] ; foreach ( $ array as $ value ) { $ value = ( array ) $ value ; $ results [ ] = $ value [ $ segment ] ; } $ array = array_values ( $ results ) ; } return array_values ( $ results ) ; }
Fetches a flattened array of an element nested in the initial array .
17,726
public static function find ( array $ array , callable $ callback , $ default = null ) { foreach ( $ array as $ key => $ value ) { if ( $ callback ( $ value , $ key ) ) { return $ value ; } } return $ default ; }
Returns the first value which passes the given truth test .
17,727
public static function get ( array $ array , $ key = null , $ default = null , string $ delimiter = null ) { if ( ! isset ( $ key ) ) { return $ array ; } if ( ! isset ( $ delimiter ) ) { $ delimiter = static :: $ delimiter ; } $ segments = is_array ( $ key ) ? $ key : explode ( $ delimiter , $ key ) ; while ( $ segment = array_shift ( $ segments ) ) { if ( $ segment === '*' ) { return is_array ( $ array ) ? static :: pluck ( $ array , $ segments , $ delimiter ) : $ default ; } if ( isset ( $ array -> { $ segment } ) ) { $ array = $ array -> { $ segment } ; } elseif ( is_array ( $ array ) && array_key_exists ( $ segment , $ array ) ) { $ array = $ array [ $ segment ] ; } else { return $ default ; } } return $ array ; }
Returns a string delimited key from an array with a default value if the given key does not exist . If null is given instead of a key the whole initial array will be returned .
17,728
public static function has ( array $ array , string $ key , string $ delimiter = null ) { if ( null === $ delimiter ) { $ delimiter = static :: $ delimiter ; } foreach ( explode ( $ delimiter , $ key ) as $ segment ) { if ( ! is_array ( $ array ) || ! array_key_exists ( $ segment , $ array ) ) { return false ; } $ array = $ array [ $ segment ] ; } return true ; }
Checks whether the given string delimited key exists in the array .
17,729
public static function pull ( & $ array , string $ key , string $ delimiter = null ) { $ value = static :: get ( $ array , $ key , null , $ delimiter ) ; static :: remove ( $ array , $ key , $ delimiter ) ; return $ value ; }
Returns the value for a string delimited key from an array and then removes it .
17,730
public static function remove ( array & $ array , string $ key , string $ delimiter = null ) { if ( ! isset ( $ delimiter ) ) { $ delimiter = static :: $ delimiter ; } $ keys = explode ( $ delimiter , $ key ) ; while ( $ key = array_shift ( $ keys ) ) { if ( ! isset ( $ array [ $ key ] ) || ! is_array ( $ array [ $ key ] ) ) { return ; } $ array = & $ array [ $ key ] ; } unset ( $ array [ array_shift ( $ keys ) ] ) ; }
Removes a string delimited key from the given array .
17,731
protected function _sendRequest ( array $ parameters ) { $ this -> _curlInfo = [ ] ; $ parameters = array_merge ( static :: DEFAULT_REQUEST_PARAMS , $ parameters ) ; $ this -> _closeCurl ( ) ; $ this -> _initCurl ( $ parameters ) ; $ toFilePointer = null ; if ( isset ( $ parameters [ 'toFile' ] ) ) { $ toFilePointer = @ \ fopen ( $ parameters [ 'toFile' ] , 'wb' ) ; if ( ! $ toFilePointer ) { ( $ this -> _onError ) ( 'HTTPClient can not open file "' . $ parameters [ 'toFile' ] . '" for writing!' ) ; return false ; } \ curl_setopt ( $ this -> _curlHandle , CURLOPT_FILE , $ toFilePointer ) ; } do { $ response = \ curl_exec ( $ this -> _curlHandle ) ; } while ( false === $ response && 0 !== -- $ parameters [ 'attemptsMax' ] && false !== \ sleep ( $ parameters [ 'attemptsDelay' ] ) ) ; if ( null !== $ toFilePointer ) { \ fclose ( $ toFilePointer ) ; if ( false === $ response ) { \ unlink ( $ parameters [ 'toFile' ] ) ; } } $ error = @ \ curl_error ( $ this -> _curlHandle ) ; $ this -> _curlInfo = @ \ curl_getinfo ( $ this -> _curlHandle ) ; if ( ! empty ( $ error ) ) { ( $ this -> _onError ) ( $ error ) ; return false ; } if ( false === $ response ) { ( $ this -> _onError ) ( 'HTTPClient can not get a response from "' . $ parameters [ 'url' ] . '"!' ) ; return false ; } if ( null !== $ this -> _lastResponseToFile ) { \ file_put_contents ( $ this -> _lastResponseToFile , $ response ) ; } return $ response ; }
Runs the request and return the response .
17,732
public final function getCookies ( ) : array { if ( ! $ this -> getCookieFile ( ) ) { return [ ] ; } unset ( $ this -> _curlHandle ) ; $ text = \ file_get_contents ( $ this -> getCookieFile ( ) ) ; $ cookies = [ ] ; foreach ( \ explode ( "\n" , $ text ) as $ line ) { $ parts = explode ( "\t" , $ line ) ; if ( 7 === \ count ( $ parts ) ) { $ cookies [ $ parts [ 5 ] ] = $ parts [ 6 ] ; } } return $ cookies ; }
Gets the current cookies .
17,733
public function setLastResponseToFile ( ? string $ lastResponseToFile ) : Client { $ this -> _lastResponseToFile = $ lastResponseToFile ?? '' ; if ( '' === \ trim ( $ this -> _lastResponseToFile ) ) { $ this -> _lastResponseToFile = null ; } return $ this ; }
If here a valid file path is defined the last response is stored inside the file .
17,734
public function sendHead ( string $ url , array $ parameters = [ ] , array $ options = [ ] ) { $ options [ 'url' ] = $ this -> _buildUrl ( $ url , $ parameters ) ; $ options [ 'header' ] = true ; $ options [ 'nobody' ] = true ; return $ this -> _sendRequest ( $ options ) ; }
Executes a HEAD HTTP request to get all response headers .
17,735
public function sendGet ( string $ url , array $ parameters = [ ] , array $ options = [ ] ) { $ options [ 'url' ] = $ this -> _buildUrl ( $ url , $ parameters ) ; return $ this -> _sendRequest ( $ options ) ; }
Executes GET HTTP request .
17,736
public function sendPost ( string $ url , array $ data = [ ] , array $ options = [ ] ) { $ options [ 'url' ] = $ this -> _buildUrl ( $ url ) ; $ options [ 'post' ] = $ data ; return $ this -> _sendRequest ( $ options ) ; }
Executes a POST HTTP request .
17,737
public function sendDownload ( string $ url , string $ destinationFile , array $ options = [ ] ) { $ options [ 'url' ] = $ this -> _buildUrl ( $ url ) ; $ options [ 'toFile' ] = $ destinationFile ; return $ this -> _sendRequest ( $ options ) ; }
Downloads file to specified destination file .
17,738
public function paginate ( Model $ model , $ per_page = 15 , array $ filters = [ ] , array $ columns = [ '*' ] ) { $ this -> onlyTrashed ( $ model ) ; $ this -> model = $ this -> relation -> apply ( $ this -> model , $ this ) ; $ this -> model = $ this -> filter -> apply ( $ this -> model , $ this , $ filters ) ; return $ this -> model -> order ( ) -> paginate ( $ per_page , $ columns ) -> toArray ( ) ; }
Eager relations can be taken from request input Filters taken from request
17,739
public function setModelId ( $ id ) { if ( is_array ( $ id ) ) { $ this -> modelId = $ id ; } else { $ this -> modelId = [ $ id ] ; } if ( $ this -> model ) { $ model = ( is_object ( $ this -> model ) ) ? get_class ( $ this -> model ) : $ this -> model ; $ this -> model = new $ model ( $ id ) ; } return $ this ; }
Sets the model ID .
17,740
public function setModel ( $ model ) { if ( ! is_object ( $ model ) ) { $ this -> modelClass = $ model ; $ model = new $ model ( $ this -> modelId ) ; } else { $ this -> modelId = $ model -> ids ( ) ; $ this -> modelClass = get_class ( $ model ) ; } $ this -> model = $ model ; return $ this ; }
Sets the model for this route .
17,741
public function getFirstError ( ) { if ( ! $ this -> model ) { return false ; } $ errors = $ this -> model -> getErrors ( ) -> errors ( ) ; return ( count ( $ errors ) > 0 ) ? $ errors [ 0 ] : false ; }
Gets the first error off the error stack .
17,742
protected function modelValidationError ( array $ error ) { $ code = ( 'no_permission' == $ error [ 'error' ] ) ? 403 : 400 ; $ param = array_value ( $ error , 'params.field' ) ; return new InvalidRequest ( $ error [ 'message' ] , $ code , $ param ) ; }
Builds a validation error from a CRUD operation .
17,743
public function retrieveModel ( ) { if ( $ this -> model -> persisted ( ) ) { return ; } $ modelClass = $ this -> modelClass ; $ this -> model = $ modelClass :: find ( $ this -> modelId ) ; if ( ! $ this -> model ) { throw $ this -> modelNotFoundError ( ) ; } }
Retrieves the model associated on this class with the persisted version from the data layer .
17,744
protected function withString ( $ string , $ name = 'query' ) { if ( ! is_string ( $ string ) && ! method_exists ( $ string , '__toString' ) ) { throw new InvalidArgumentException ( 'Uri fragment must be a string' ) ; } $ string = ltrim ( ( string ) $ string , '#' ) ; $ clone = clone $ this ; $ clone -> $ name = $ this -> filterQuery ( $ string ) ; return $ clone ; }
withString function .
17,745
public function setAmount ( $ amount ) { if ( $ amount === null ) { $ this -> amount = 0 ; return $ this ; } if ( ! is_int ( $ amount ) ) { throw new InvalidArgumentException ( sprintf ( 'Amount must be an integer, "%s" given' , is_object ( $ amount ) ? get_class ( $ amount ) : gettype ( $ amount ) ) ) ; } $ this -> amount = $ amount ; return $ this ; }
Set the monetary value represented by this object
17,746
public function setCurrency ( $ currency ) { if ( $ currency ) { $ currency = strtoupper ( $ currency ) ; Currency :: getNumericCode ( $ currency ) ; $ this -> currency = $ currency ; } else { $ this -> currency = null ; } return $ this ; }
Set the currency of the monetary value represented by this object
17,747
public function compareTo ( MoneyInterface $ money ) { if ( $ this -> currency !== $ money -> getCurrency ( ) ) { throw new CurrencyMismatchException ( 'Operations between different currencies are not supported.' ) ; } if ( $ this -> amount == $ money -> getAmount ( ) ) { return 0 ; } return $ this -> amount < $ money -> getAmount ( ) ? - 1 : 1 ; }
Compares this object with another
17,748
public function add ( MoneyInterface $ money ) { if ( $ this -> currency !== $ money -> getCurrency ( ) ) { throw new CurrencyMismatchException ( 'Operations between different currencies are not supported' ) ; } $ this -> amount = $ this -> toInt ( $ this -> amount + $ money -> getAmount ( ) ) ; return $ this ; }
Add the monetary value of another MoneyInterface object to this object
17,749
public function multiply ( $ factor , $ roundingMode = PHP_ROUND_HALF_UP ) { if ( $ factor instanceof DecimalNumberInterface ) { $ factor = $ factor -> toFloat ( ) ; } $ this -> amount = $ this -> toInt ( round ( $ factor * $ this -> amount , 0 , $ roundingMode ) ) ; return $ this ; }
Multiply the monetary value of this object by a given factor
17,750
public function fromFloat ( $ amount , $ currency = null ) { if ( $ currency ) { $ this -> setCurrency ( $ currency ) ; } if ( ! is_float ( $ amount ) ) { throw new InvalidArgumentException ( sprintf ( 'Amount must be a float, %s given' , gettype ( $ amount ) ) ) ; } $ this -> amount = $ this -> toInt ( round ( $ this -> getSubUnit ( ) * round ( $ amount , $ this -> getFractionDigits ( ) , PHP_ROUND_HALF_UP ) , 0 , PHP_ROUND_HALF_UP ) ) ; return $ this ; }
Populate current amount from a given float value
17,751
public function newApp ( string $ app_type , ApplicationFactoryInterface $ app_factory ) : ApplicationInterface { return $ app_factory -> createApplication ( $ app_type , $ this -> fs ) ; }
Create new application
17,752
protected function _exception ( ) { $ url = '.' . $ this -> request -> src . '.' . $ this -> request -> controller . '.' . $ this -> request -> action ; if ( in_array ( $ url , $ this -> config [ 'user' ] [ 'security' ] [ 'spam' ] [ 'config' ] [ 'exception' ] ) ) { $ this -> _exception = true ; } return $ this -> _exception ; }
check if the url is a spam exception
17,753
protected function _ips ( ) { if ( $ this -> _cache -> isExist ( ) ) { $ this -> _ips = $ this -> _cache -> getCache ( ) ; } else { $ this -> _ips = [ $ this -> _ip => [ 'time' => time ( ) , 'number' => 1 ] ] ; } }
get the the list of IPs
17,754
protected function _updateIp ( $ time = 0 , $ number = 1 ) { $ this -> _ips [ $ this -> _ip ] = [ 'time' => $ time , 'number' => $ number ] ; $ this -> _cache -> setContent ( $ this -> _ips ) ; $ this -> _cache -> setCache ( ) ; }
update time and number attribute from IP
17,755
public function match ( $ input ) { $ noMatch = true ; foreach ( $ this -> matchers as $ matcher ) { if ( $ matcher -> noMatch ( ) ) { continue ; } if ( $ matcher -> match ( $ input ) ) { $ noMatch = false ; } if ( $ matcher -> matchFound ( ) ) { $ this -> matched [ ] = $ matcher -> matched ; $ this -> resetMatchers ( ) ; break ; } } if ( $ noMatch ) { return false ; } return true ; }
Attempts to match an input token with the patterns
17,756
public function matchArray ( array $ tokens , $ reset = true ) { if ( $ reset ) { $ this -> reset ( ) ; } foreach ( $ tokens as $ t ) { if ( ! $ this -> match ( $ t ) ) { return false ; } } return true ; }
Matches an array of tokens against the configured patterns
17,757
public function installCollections ( ) { $ collections = $ this -> mongoInstance -> listCollections ( ) ; foreach ( $ collections as $ collection ) { if ( $ collection -> getName ( ) == self :: collection ) { return true ; } } $ this -> mongoInstance -> createCollection ( self :: collection ) ; $ this -> mongoInstance -> createIndex ( self :: collection , new SingleIndex ( 'key' , 'key' , false , true ) ) ; $ this -> mongoInstance -> createIndex ( self :: collection , new SingleIndex ( 'ttl' , 'ttl' , false , false , false , 0 ) ) ; return true ; }
Installs the required mongo collection for cache storage and creates the required indexes .
17,758
public function getExpressionData ( ) { $ data = parent :: getExpressionData ( ) ; if ( $ this -> default !== null ) { $ data [ 0 ] [ 0 ] .= ' DEFAULT %s' ; $ data [ 0 ] [ 1 ] [ ] = $ this -> default ; $ data [ 0 ] [ 2 ] [ ] = self :: TYPE_VALUE ; } return $ data ; }
Adds default option .
17,759
public static function getKey ( $ callable ) { $ class = null ; $ method = null ; if ( is_string ( $ callable ) ) { $ method = $ callable ; } elseif ( is_array ( $ callable ) ) { $ class = is_object ( $ callable [ 0 ] ) ? get_class ( $ callable [ 0 ] ) : $ callable [ 0 ] ; $ method = $ callable [ 1 ] ; } elseif ( is_object ( $ callable ) ) { if ( $ callable instanceof \ ReflectionFunctionAbstract ) { if ( $ callable -> isClosure ( ) ) { return null ; } $ class = $ callable instanceof \ ReflectionMethod ? $ callable -> class : null ; $ method = $ callable -> name ; } else { if ( $ callable instanceof \ Closure ) { return null ; } $ class = get_class ( $ callable ) ; $ method = '__invoke' ; } } return strtolower ( ( $ class ? $ class . '::' : '' ) . $ method ) ; }
Return unique string key for given callable or null for closures .
17,760
public static function save ( $ message , $ logFile = 'static.log' , $ logDir = 'data/logs' ) { if ( $ logFile === null ) { return ; } $ logger = static :: getInstance ( $ logFile , $ logDir ) ; if ( is_object ( $ message ) && $ message instanceof LoggableObject ) { $ message = json_encode ( $ message -> acploLogMe ( ) ) ; } $ logger -> debug ( $ message ) ; }
Saves a message to a logfile
17,761
public static function getInstance ( $ logFile = 'static.log' , $ logDir = 'data/logs' ) { if ( static :: $ instance instanceof StaticLogger ) { return static :: $ instance ; } static :: $ instance = new self ( $ logFile , $ logDir ) ; return static :: $ instance ; }
Gets an instance of this logger and sets the log directory and filename
17,762
protected function verifySectionName ( $ section ) { $ this -> assertion -> notEmpty ( $ section , 'The name of the section must not be empty.' ) ; $ this -> assertion -> string ( $ section , 'The name of the section must be a string.' ) ; }
Verifies the validity of the section to be managed .
17,763
public function getContentByIds ( array $ identifiers ) { $ items = array ( ) ; foreach ( $ identifiers as $ id ) { $ items [ $ id ] = $ this -> getContentById ( $ id ) ; } return $ items ; }
Shall find the registry items corresponding to the provided list of identifiers .
17,764
public function loadConfig ( $ config = null ) : void { $ baseClass = Base :: getInstance ( ) ; $ this -> errorLevel = ( string ) $ baseClass -> Database -> MySQL -> errorLevel ; if ( \ is_null ( $ config ) ) { $ config = $ baseClass -> Database -> MySQL -> defaultConnection ; } if ( ! ( $ config instanceof AbstractConfig ) ) { throw new RuntimeException ( '$config must be an instance of MS\LightFramework\Config\AbstractConfig' ) ; } $ this -> databaseHost = ( string ) $ config -> databaseHost ; $ this -> databaseUser = ( string ) $ config -> databaseUser ; $ this -> databasePass = ( string ) $ config -> databasePass ; $ this -> databaseName = ( string ) $ config -> databaseName ; $ this -> connectionCharset = ( string ) $ config -> connectionCharset ; $ this -> connectionCollation = ( string ) $ config -> connectionCollation ; $ this -> openConnection ( ) ; $ this -> selectDatabase ( $ this -> databaseName ) ; $ this -> setConnectionCharset ( $ this -> connectionCharset ) ; $ this -> setConnectionCollation ( $ this -> connectionCollation ) ; }
Loads configuration opens new connection selects database and sets connection charset & collation .
17,765
public function openConnection ( ) : void { $ this -> closeConnection ( ) ; $ this -> currentLink = @ new \ mysqli ( $ this -> databaseHost , $ this -> databaseUser , $ this -> databasePass ) ; if ( ! $ this -> currentLink -> connect_error ) { $ this -> isConnected = true ; $ this -> connectionCount += 1 ; } else { $ this -> setError ( AbstractMySQL :: E_NO_CONNECTION , __CLASS__ ) ; } }
Opens new database connection .
17,766
public function closeConnection ( ) : void { if ( $ this -> isConnected ) { @ $ this -> currentLink -> close ( ) ; $ this -> isConnected = false ; $ this -> currentLink = null ; $ this -> currentDB = null ; $ this -> selectedDB = '' ; } }
Closes existing database connection .
17,767
public function selectDatabase ( string $ databaseName = '' ) : void { $ this -> selectedDB = $ databaseName ; $ this -> currentDB = $ this -> currentLink -> select_db ( $ databaseName ) ; if ( ! $ this -> currentDB ) { $ this -> setError ( AbstractMySQL :: E_NO_DB_SELECTED , __CLASS__ ) ; } }
Selects a database .
17,768
public function setConnectionCollation ( string $ collationName = '' ) : void { if ( $ collationName !== '' ) { $ this -> connectionCollation = $ collationName ; $ this -> execute ( 'SET SESSION collation_connection = ' . $ collationName ) ; } }
Sets connection s collation .
17,769
public static function getUser ( $ key = null ) { if ( null == $ key ) { return $ GLOBALS [ 'TSFE' ] -> fe_user -> user ; } else { return ( isset ( $ GLOBALS [ 'TSFE' ] -> fe_user -> user [ $ key ] ) ) ? $ GLOBALS [ 'TSFE' ] -> fe_user -> user [ $ key ] : false ; } }
Returns fe_user data
17,770
public static function hasRoleId ( $ role ) { return ( self :: isFeUser ( ) && self :: isAuthenticated ( ) && in_array ( $ role , $ GLOBALS [ 'TSFE' ] -> fe_user -> groupData [ 'uid' ] ) ) ; }
Checks whether fe_user is authenticated and has given role id
17,771
public static function database ( ) { $ args = func_get_args ( ) ; switch ( $ args [ 0 ] ) { case 'mysql' : return self :: mysql ( $ args [ 1 ] , $ args [ 2 ] , $ args [ 3 ] , $ args [ 4 ] , $ args [ 5 ] ) ; break ; default : break ; } }
configure database .
17,772
public static function mysql ( $ host , $ database , $ user , $ password , $ prefix = null ) { if ( is_null ( $ prefix ) ) { $ prefixing = 'false' ; $ prefix = 'ysf' ; } else { $ prefixing = 'true' ; } $ content = Database :: set ( 'mysql' , $ host , $ database , $ user , $ password , $ prefixing , $ prefix ) ; file_put_contents ( Application :: $ root . 'config/database.php' , $ content , 0 ) ; return true ; }
function to set Mysql server config params .
17,773
private function getFilePath ( ) { $ tmpDir = realpath ( $ this -> getContainer ( ) -> get ( 'kernel' ) -> getRootDir ( ) . '/../var/tmp/' ) ; $ fileName = '/' . str_replace ( ':' , '--' , $ this -> getName ( ) ) . '.sock' ; if ( ! file_exists ( $ tmpDir ) ) { mkdir ( $ tmpDir ) ; } return $ tmpDir . $ fileName ; }
Gets the file path holding the port number
17,774
private function executeSend ( InputInterface $ input , OutputInterface $ output ) { $ message = $ input -> getOption ( self :: OPTION_SEND ) ; $ output -> writeln ( sprintf ( self :: WELCOME_SEND , $ message , $ this -> getName ( ) ) ) ; $ port = file_get_contents ( $ this -> getFilePath ( ) ) ; $ pingSock = socket_create ( AF_INET , SOCK_DGRAM , SOL_UDP ) ; socket_sendto ( $ pingSock , $ message . PHP_EOL , strlen ( $ message ) , 0 , '127.0.0.1' , $ port ) ; }
Execute send mode with send option
17,775
public function callAction ( callable $ callable , ServerRequestInterface $ request , ResponseInterface $ response , array $ routeArguments ) { try { return call_user_func_array ( $ callable , $ this -> buildParams ( $ callable , $ request , $ routeArguments ) ) ; } catch ( Exception $ e ) { $ handler = $ this -> container -> getActionErrorHandler ( ) ; return $ handler ( $ e , $ request , $ response ) ; } }
Call a method in an Action class
17,776
protected function callHandler ( callable $ callable , ServerRequestInterface $ request , ResponseInterface $ response , array $ routeArguments ) { if ( $ callable instanceof Closure ) { array_unshift ( $ routeArguments , $ request , $ response ) ; $ result = call_user_func_array ( $ callable , $ routeArguments ) ; } else { if ( is_array ( $ callable ) && $ callable [ 0 ] instanceof Action \ ActionInterface ) { $ callable [ 0 ] -> setResponse ( $ response ) ; $ callable [ 0 ] -> setRequest ( $ request ) ; } $ result = $ this -> callAction ( $ callable , $ request , $ response , $ routeArguments ) ; $ action = $ callable [ 0 ] ; $ response = $ action -> getResponse ( ) ; } if ( ( $ result instanceof ResponseInterface ) ) { $ response = $ result ; } else { $ response = $ this -> buildResponse ( $ result , $ response , $ request ) ; } return $ response ; }
Call action with built params
17,777
public function get ( string $ key , $ default = null ) { $ k = $ this -> keyConvert ( $ key ) ; $ v = getenv ( $ k ) ; return $ v !== false ? $ v : $ default ; }
Fetches an environment variable .
17,778
public function has ( string $ key ) : bool { $ k = $ this -> keyConvert ( $ key ) ; return getenv ( $ k ) !== false ; }
Check if an environment var is set .
17,779
public function keyConvert ( string $ key ) : string { $ key = str_replace ( ConfigKey :: VALID_NON_ALPHANUM , '_' , $ key ) ; if ( ! ConfigKey :: validate ( $ key ) ) { throw new InvalidArgumentException ( 'Arg key contains invalid character(s).' ) ; } return $ key ; }
Replaces all legal non - alphanumeric chars with underscore .
17,780
public function getHeaderLines ( $ name ) { $ name = strtolower ( $ name ) ; if ( ! isset ( $ this -> headers [ $ name ] ) ) { return array ( ) ; } return $ this -> headers [ $ name ] [ 1 ] ; }
Provides value for specified header name . If header doesn t exists it will return empty array .
17,781
public function setHeader ( $ name , $ value , $ replace = true ) { $ lowercaseName = strtolower ( $ name ) ; if ( $ replace || ! isset ( $ this -> headers [ $ lowercaseName ] ) ) { $ this -> headers [ $ lowercaseName ] = array ( $ name , array ( $ value ) ) ; } else { $ this -> headers [ $ lowercaseName ] [ 1 ] [ ] .= $ value ; } $ this -> messageCache = null ; }
Adds or replace header with given name with given value .
17,782
public function isConnectionClose ( ) { $ connection = $ this -> getHeader ( 'connection' ) ; if ( $ this -> protocolVersion === '1.1' ) { return ( $ connection [ 0 ] === 'C' || $ connection [ 0 ] === 'c' ) ; } else { return ( $ connection [ 0 ] !== 'K' && $ connection [ 0 ] !== 'k' ) ; } }
Provides information is TCP connection should be terminated after sending this request .
17,783
protected function getHeadersAsText ( ) { $ headers = '' ; foreach ( $ this -> headers as $ header ) { foreach ( $ header [ 1 ] as $ headerValue ) { $ headers .= $ header [ 0 ] . ': ' . $ headerValue . "\r\n" ; } } return $ headers ; }
Returns all headers in text form to embed into HTTP message .
17,784
protected function filterThroughWhitelist ( $ address ) { $ whitelist = Arr :: path ( $ this -> config , 'whitelist.list' ) ; $ trapAddress = Arr :: path ( $ this -> config , 'whitelist.trap' ) ; if ( ! is_array ( $ whitelist ) ) { return $ address ; } list ( $ name , $ domain ) = explode ( '@' , $ address ) ; $ addressWhitelisted = in_array ( $ address , $ whitelist ) ; $ domainWhitelisted = in_array ( $ domain , $ whitelist ) ; $ whitelisted = ( $ addressWhitelisted or $ domainWhitelisted ) ; return $ whitelisted ? $ address : $ this -> injectIntoTrapAddress ( $ address ) ; }
Filter an email address through the domain and email address whitelists
17,785
protected function injectIntoTrapAddress ( $ address ) { $ trapAddress = Arr :: path ( $ this -> config , 'whitelist.trap' ) ; if ( ! $ trapAddress ) { throw new RuntimeException ( 'Email address not whitelisted but no email trap exists' ) ; } $ address = str_ireplace ( '@' , '+' , $ address ) ; list ( $ trapName , $ trapDomain ) = explode ( '@' , $ trapAddress ) ; return sprintf ( '%s+%s@%s' , $ trapName , $ address , $ trapDomain ) ; }
Return the whitelist trap address with the specified email injected as a suffix
17,786
public static function Tcgtt ( $ tcg1 , $ tcg2 , & $ tt1 , & $ tt2 ) { $ t77t = DJM77 + TTMTAI / DAYSEC ; if ( $ tcg1 > $ tcg2 ) { $ tt1 = $ tcg1 ; $ tt2 = $ tcg2 - ( ( $ tcg1 - DJM0 ) + ( $ tcg2 - $ t77t ) ) * ELG ; } else { $ tt1 = $ tcg1 - ( ( $ tcg2 - DJM0 ) + ( $ tcg1 - $ t77t ) ) * ELG ; $ tt2 = $ tcg2 ; } return 0 ; }
- - - - - - - - - i a u T c g t t - - - - - - - - -
17,787
private static function parametersToHeaders ( $ parameters ) { $ filtered = array_filter ( array_keys ( $ parameters ) , function ( $ key ) { return strpos ( $ key , 'HTTP_' ) === 0 ; } ) ; $ transformKey = function ( $ key ) { $ parts = explode ( '_' , $ key ) ; $ lowerCase = array_map ( 'strtolower' , array_slice ( $ parts , 1 ) ) ; $ firstUpper = array_map ( 'ucfirst' , $ lowerCase ) ; return implode ( '-' , $ firstUpper ) ; } ; return array_reduce ( $ filtered , function ( $ acc , $ key ) use ( $ parameters , $ transformKey ) { $ headerKey = $ transformKey ( $ key ) ; return array_merge ( $ acc , [ $ headerKey => $ parameters [ $ key ] ] ) ; } , [ ] ) ; }
Convert HTTP_ parameters to headers map .
17,788
private static function encapsulateFiles ( $ files ) { $ validFiles = array_filter ( $ files , function ( $ file ) { return $ file [ 'error' ] == UPLOAD_ERR_OK ; } ) ; return array_map ( function ( $ file ) { return new File ( $ file [ 'name' ] , $ file [ 'size' ] , $ file [ 'tmp_name' ] ) ; } , $ validFiles ) ; }
Encapsulate files into File objects .
17,789
public function createDefaults ( $ assocId ) { $ i = 1 ; $ data = array ( ) ; $ foreignModel = current ( Hash :: extract ( $ this -> getAssociated ( 'Parent' ) , 'conditions' ) ) ; foreach ( $ this -> defaults as $ entry ) { $ data [ $ this -> alias ] = $ entry ; $ data [ $ this -> alias ] [ 'foreign_key' ] = $ assocId ; $ data [ $ this -> alias ] [ 'foreign_model' ] = $ foreignModel ; $ data [ $ this -> alias ] [ 'position' ] = $ i ++ ; $ this -> create ( ) ; $ this -> save ( $ data ) ; } }
Creates default details entries for associated model s record .
17,790
public function getSection ( $ id , $ section = null , $ schema = false , $ format = true ) { $ foreignKey = $ this -> belongsTo [ $ this -> parentModel ] [ 'foreignKey' ] ; $ conditions = array ( "{$this->alias}.{$foreignKey}" => $ id ) ; if ( ! is_null ( $ section ) ) { $ conditions [ "{$this->alias}.field LIKE" ] = "$section.%" ; } $ fields = array ( "{$this->alias}.field" , "{$this->alias}.value" ) ; if ( true === $ schema ) { $ fields = array ( "{$this->alias}.field" , "{$this->alias}.input" , "{$this->alias}.data_type" , "{$this->alias}.label" ) ; } $ results = $ this -> find ( 'all' , array ( 'conditions' => $ conditions , 'fields' => $ fields , 'order' => array ( "{$this->alias}.position ASC" ) , 'recursive' => - 1 ) ) ; return $ this -> extractSection ( $ results , $ section , $ schema , $ format ) ; }
Gets detailed model record s associated details by section .
17,791
public function save ( $ data = null , $ validate = true , $ fieldList = array ( ) ) { if ( ! is_array ( $ validate ) ) { $ validate = compact ( 'validate' , 'fieldList' ) ; } $ defaults = array ( 'validate' => true , 'fieldList' => $ fieldList , 'callbacks' => true , 'bypass' => true ) ; $ options = array_merge ( $ defaults , $ validate ) ; if ( $ options [ 'bypass' ] ) { return true ; } return parent :: save ( $ data , $ options ) ; }
By - pass the save operation by default . This is a workaround so only the DetailableBehavior can save records after settings the required fields .
17,792
public function validateSection ( $ data , $ section ) { $ pass = true ; if ( ! empty ( $ this -> sectionValidation [ $ section ] ) ) { $ modelValidation = $ this -> validate ; $ this -> validate = $ this -> sectionValidation [ $ section ] ; $ this -> set ( $ data ) ; if ( ! $ this -> validates ( ) ) { $ pass = false ; } $ this -> validate = $ modelValidation ; } return $ pass ; }
Validates data for a given section .
17,793
public function getMbAssets ( $ wordpress = false ) { return $ wordpress ? $ this -> mbAssets -> get ( 'wordpress' ) : $ this -> mbAssets -> get ( 'plugin' ) ; }
Get either MbAsset from the plugin or from Wordpress
17,794
public function setMbAssets ( MbAsset $ mbAsset , $ wordpress = false ) { $ this -> mbAssets -> put ( $ wordpress ? 'wordpress' : 'plugin' , $ mbAsset ) ; return $ this ; }
Set either MbAsset to the plugin or to the Wordpress
17,795
public function setMbEvent ( MbEvent $ mbEvent , $ dispatch ) { if ( is_array ( $ dispatch ) ) { foreach ( $ dispatch as $ event ) { $ this -> setMbEvent ( $ mbEvent , $ event ) ; } } else { if ( ! $ this -> mbEvents -> has ( $ dispatch ) ) { $ this -> mbEvents -> put ( $ dispatch , new Collection ( ) ) ; } $ this -> mbEvents -> get ( $ dispatch ) -> push ( $ mbEvent ) ; } return $ this ; }
Set a MbEvent to a dispatcher type
17,796
protected function init ( ) { if ( ! defined ( 'ABSPATH' ) ) { die ( 'MocaBonita must be loaded along with Wordpress!' . PHP_EOL ) ; } $ timezone = get_option ( 'timezone_string' ) ; if ( ! empty ( $ timezone ) ) { date_default_timezone_set ( $ timezone ) ; } $ mbAudit = new MbAudit ( ) ; $ mbRequest = MbRequest :: capture ( ) ; $ mbResponse = MbResponse :: create ( ) ; $ mbRequest -> ajax ( ) ; $ mbRequest -> setBlogAdmin ( is_blog_admin ( ) ) ; $ mbAudit -> setRequest ( $ mbRequest ) ; $ mbResponse -> setMbRequest ( $ mbRequest ) ; $ mbResponse -> setMbAudit ( $ mbAudit ) ; $ this -> setPage ( $ mbRequest -> query ( 'page' ) ) ; $ this -> setAction ( $ mbRequest -> query ( 'action' , 'index' ) ) ; $ this -> setMbRequest ( $ mbRequest ) ; $ this -> setMbResponse ( $ mbResponse ) ; $ this -> setMbAudit ( $ mbAudit ) ; $ this -> mbAssets = new Collection ( [ 'plugin' => new MbAsset ( ) , 'wordpress' => new MbAsset ( ) , ] ) ; $ this -> mbEvents = new Collection ( ) ; $ this -> mbShortCodes = new Collection ( ) ; $ this -> mbPages = new Collection ( ) ; MbMigration :: enableWpdbConnection ( ) ; }
Function that s called when MocaBonita is started .
17,797
public function enableFlash ( $ session = null ) { if ( ! $ this -> getMbRequest ( ) -> hasSession ( ) ) { $ this -> enableSession ( $ session ) ; } $ this -> getMbRequest ( ) -> session ( ) -> getFlashBag ( ) ; return $ this ; }
Enable flash session
17,798
public static function plugin ( \ Closure $ pluginStructure , $ audit = false , $ tag = "plugins_loaded" ) { $ mocaBonita = self :: getInstance ( ) ; $ mocaBonita -> audit = ( bool ) $ audit ; if ( $ mocaBonita -> audit ) { MbWPActionHook :: addActionCallback ( 'plugins_loaded' , function ( ) use ( $ mocaBonita ) { try { MbDatabase :: enableQueryLog ( ) ; $ mocaBonita -> getMbAudit ( ) -> setMocaBonita ( $ mocaBonita ) ; $ mocaBonita -> getMbAudit ( ) -> setUser ( MbWpUser :: getCurrentUser ( true ) ) ; } catch ( \ Exception $ e ) { $ mocaBonita -> getMbResponse ( ) -> setContent ( $ e ) ; } } ) ; MbWPActionHook :: addActionCallback ( 'shutdown' , function ( ) use ( $ mocaBonita ) { try { $ mocaBonita -> getMbAudit ( ) -> run ( ) ; } catch ( \ Exception $ e ) { error_log ( $ e -> getMessage ( ) ) ; } finally { MbDatabase :: disableQueryLog ( ) ; } } ) ; } MbWPActionHook :: addActionCallback ( $ tag , function ( ) use ( $ pluginStructure , $ mocaBonita ) { try { call_user_func_array ( $ pluginStructure , [ $ mocaBonita ] ) ; $ mocaBonita -> runPlugin ( ) ; } catch ( \ Exception $ e ) { $ mocaBonita -> mbResponse -> setContent ( $ e ) ; } finally { $ mocaBonita -> runHookCurrentAction ( ) ; $ mocaBonita -> getMbAudit ( ) -> setResponseStatusCode ( $ mocaBonita -> mbResponse -> status ( ) ) ; $ mocaBonita -> getMbAudit ( ) -> setResponseHeader ( $ mocaBonita -> mbResponse -> headers -> all ( ) ) ; $ mocaBonita -> mbResponse -> sendHeaders ( ) ; } } ) ; }
Set the callback that has the plugin s structure
17,799
public static function active ( \ Closure $ active ) { $ mocaBonita = self :: getInstance ( ) ; register_activation_hook ( MbPath :: pBaseN ( ) , function ( ) use ( $ active , $ mocaBonita ) { try { MbMigration :: enablePdoConnection ( ) ; call_user_func_array ( $ active , [ $ mocaBonita ] ) ; } catch ( \ Exception $ e ) { deactivate_plugins ( basename ( MbPath :: pBaseN ( ) ) ) ; wp_die ( $ e -> getMessage ( ) ) ; } } ) ; }
Set the callback that will be called when the plugin is activated