idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
12,200
public function setTheme ( string $ theme ) : FieldTypeInterface { $ this -> options [ 'theme' ] = $ theme ; foreach ( $ this -> repository -> all ( ) as $ field ) { $ field -> setTheme ( $ theme ) ; } foreach ( $ this -> repository ( ) -> getGroups ( ) as $ group ) { $ group -> setTheme ( $ theme ) ; } return $ this ; }
Set the form and attached fields theme .
12,201
public function handleRequest ( Request $ request ) : FormInterface { $ fields = $ this -> repository -> all ( ) ; $ this -> validator = $ this -> validation -> make ( $ request -> all ( ) , $ this -> getFormRules ( $ fields ) , $ this -> getFormMessages ( $ fields ) , $ this -> getFormPlaceholders ( $ fields ) ) ; $ data = $ this -> validator -> valid ( ) ; array_walk ( $ fields , function ( $ field ) use ( $ data ) { $ field -> setErrorMessageBag ( $ this -> errors ( ) ) ; $ field -> setValue ( Arr :: get ( $ data , $ field -> getName ( ) ) ) ; if ( ! is_null ( $ this -> dataClass ) && is_object ( $ this -> dataClass ) && $ field -> getOption ( 'mapped' ) ) { $ this -> dataMapper -> mapFromFieldToObject ( $ field , $ this -> dataClass ) ; } if ( $ this -> validator -> fails ( ) ) { if ( $ field -> error ( ) ) { $ field -> addAttribute ( 'class' , 'is-invalid' ) ; } else { $ field -> addAttribute ( 'class' , 'is-valid' ) ; } } else { if ( $ this -> getOption ( 'flush' , false ) ) { $ field [ 'flush' ] = true ; } } } ) ; return $ this ; }
Handle current request and start form data validation .
12,202
protected function getFormRules ( array $ fields ) { $ rules = [ ] ; foreach ( $ fields as $ field ) { $ rules [ $ field -> getName ( ) ] = $ field -> getOption ( 'rules' ) ; } return $ rules ; }
Get the list of form rules .
12,203
protected function getFormMessages ( array $ fields ) { $ messages = [ ] ; foreach ( $ fields as $ field ) { foreach ( $ field -> getOption ( 'messages' ) as $ attr => $ message ) { $ messages [ $ field -> getName ( ) . '.' . $ attr ] = $ message ; } } return $ messages ; }
Get the list of form fields messages .
12,204
public function error ( string $ name = '' , bool $ first = false ) { $ errors = $ this -> errors ( ) ; if ( empty ( $ name ) ) { return $ errors -> all ( ) ; } $ field = $ this -> repository -> getFieldByName ( $ name ) ; if ( $ first ) { return $ errors -> first ( $ field -> getName ( ) ) ; } return $ errors -> get ( $ field -> getName ( ) ) ; }
Return error messages for a specific field . By setting the second parameter to true a user can fetch the first error message only on the mentioned field .
12,205
public function render ( ) : string { $ view = $ this -> viewer -> make ( $ this -> getView ( ) , $ this -> getFormData ( ) ) ; $ this -> rendered = true ; return $ view -> render ( ) ; }
Render a form and returns its HTML structure .
12,206
public function setGroupView ( string $ view , string $ group = 'default' ) : FormInterface { if ( ! $ this -> repository ( ) -> hasGroup ( $ group ) ) { throw new DomainException ( 'You cannot change the view of an undefined form group.' ) ; } $ this -> repository ( ) -> getGroup ( $ group ) -> setView ( $ view ) ; return $ this ; }
Set form group view file .
12,207
public function getView ( bool $ prefixed = true ) : string { if ( $ prefixed ) { return $ this -> buildViewPath ( $ this -> getTheme ( ) , $ this -> view ) ; } return $ this -> view ; }
Return the view path instance used by the form .
12,208
protected function validateOptions ( array $ options ) { $ validated = [ ] ; foreach ( $ options as $ name => $ option ) { if ( ! in_array ( $ name , $ this -> getAllowedOptions ( ) ) ) { throw new DomainException ( 'The "' . $ name . '" option is not allowed on the provided form.' ) ; } $ validated [ $ name ] = $ option ; } return $ validated ; }
Validate form options .
12,209
protected function parseOptions ( array $ options ) { $ options [ 'attributes' ] = array_merge ( $ this -> getAttributes ( ) , $ options [ 'attributes' ] ) ; if ( isset ( $ options [ 'attributes' ] [ 'method' ] ) && 'post' === strtolower ( $ options [ 'attributes' ] [ 'method' ] ) ) { $ options [ 'nonce' ] = $ options [ 'nonce' ] ?? '_themosisnonce' ; $ options [ 'nonce_action' ] = $ options [ 'nonce_action' ] ?? 'form' ; $ options [ 'referer' ] = $ options [ 'referer' ] ?? true ; } if ( ! isset ( $ this -> options [ 'theme' ] ) ) { $ this -> setTheme ( 'themosis' ) ; } return $ options ; }
Parse form options and add some default parameters .
12,210
public function addAttribute ( string $ name , string $ value , $ overwrite = false ) : FieldTypeInterface { if ( isset ( $ this -> options [ 'attributes' ] [ $ name ] ) && ! $ overwrite ) { $ this -> options [ 'attributes' ] [ $ name ] .= ' ' . $ value ; } else { $ this -> options [ 'attributes' ] [ $ name ] = $ value ; } return $ this ; }
Add an attribute to the field .
12,211
protected function validateOptions ( array $ options , FieldTypeInterface $ field ) { $ parsed = [ ] ; foreach ( $ options as $ key => $ value ) { if ( ! in_array ( $ key , $ field -> getAllowedOptions ( ) , true ) ) { throw new \ DomainException ( 'The "' . $ key . '" option is not allowed on the provided field.' ) ; } $ parsed [ $ key ] = $ value ; } return $ parsed ; }
Validate the options used by a field instance .
12,212
public function add ( FieldTypeInterface $ field ) : FormBuilderInterface { $ opts = $ this -> validateOptions ( array_merge ( [ 'errors' => $ this -> form -> getOption ( 'errors' ) , 'theme' => $ this -> form -> getOption ( 'theme' ) ] , $ field -> getOptions ( ) ) , $ field ) ; $ field -> setLocale ( $ this -> form -> getLocale ( ) ) ; $ field -> setOptions ( $ opts ) ; $ field -> setForm ( $ this -> form ) ; $ field -> setViewFactory ( $ this -> form -> getViewer ( ) ) ; $ field -> setResourceTransformerFactory ( $ this -> form -> getResourceTransformerFactory ( ) ) ; if ( ! is_null ( $ this -> dataClass ) && is_object ( $ this -> dataClass ) && $ field -> getOption ( 'mapped' ) ) { $ this -> dataMapperManager -> mapFromObjectToField ( $ this -> dataClass , $ field ) ; } if ( $ this -> form -> repository ( ) -> hasGroup ( $ field -> getOption ( 'group' ) ) ) { $ section = $ this -> form -> repository ( ) -> getGroup ( $ field -> getOption ( 'group' ) ) ; } else { $ section = new Section ( $ field -> getOption ( 'group' ) ) ; } $ section -> setTheme ( $ this -> form -> getTheme ( ) ) ; $ section -> setView ( 'form.group' ) ; $ section -> addItem ( $ field ) ; $ this -> form -> repository ( ) -> addField ( $ field , $ section ) ; return $ this ; }
Add a field to the current form instance .
12,213
public function bootstrap ( Application $ app ) { $ uri = $ app -> make ( 'config' ) -> get ( 'app.url' , 'http://localhost' ) ; $ components = parse_url ( $ uri ) ; $ server = $ _SERVER ; if ( isset ( $ components [ 'path' ] ) ) { $ server = array_merge ( $ server , [ 'SCRIPT_FILENAME' => $ components [ 'path' ] , 'SCRIPT_NAME' => $ components [ 'path' ] ] ) ; } $ app -> instance ( 'request' , Request :: create ( $ uri , 'GET' , [ ] , [ ] , [ ] , $ server ) ) ; }
Setup the request for console application .
12,214
protected function registerUserField ( ) { $ this -> app -> bind ( 'themosis.user.field' , function ( $ app ) { $ viewFactory = $ app [ 'view' ] ; $ viewFactory -> addLocation ( __DIR__ . '/views' ) ; return new UserField ( new FieldsRepository ( ) , $ app [ 'action' ] , $ viewFactory , $ app [ 'validator' ] ) ; } ) ; }
Register the user field .
12,215
protected function createController ( ) { $ controller = Str :: studly ( class_basename ( $ this -> argument ( 'name' ) ) ) ; $ modelName = $ this -> qualifyClass ( $ this -> getNameInput ( ) ) ; $ this -> call ( 'make:controller' , [ 'name' => "{$controller}Controller" , '--model' => $ this -> option ( 'resource' ) ? $ modelName : null ] ) ; }
Create a controller for the model .
12,216
protected function parse ( array $ sizes ) { $ images = [ ] ; foreach ( $ sizes as $ slug => $ properties ) { list ( $ width , $ height , $ crop , $ label ) = $ this -> parseProperties ( $ properties , $ slug ) ; $ images [ $ slug ] = [ 'width' => $ width , 'height' => $ height , 'crop' => $ crop , 'label' => $ label ] ; } return $ images ; }
Parse the images sizes .
12,217
protected function parseProperties ( array $ properties , string $ slug ) { switch ( count ( $ properties ) ) { case 1 : return [ $ properties [ 0 ] , $ properties [ 0 ] , false , false ] ; break ; case 2 : return [ $ properties [ 0 ] , $ properties [ 1 ] , false , false ] ; break ; case 3 : return [ $ properties [ 0 ] , $ properties [ 1 ] , $ properties [ 2 ] , false ] ; break ; case 4 : default : $ label = ( is_bool ( $ properties [ 3 ] ) && true === $ properties [ 3 ] ) ? $ this -> label ( $ slug ) : $ properties [ 3 ] ; return [ $ properties [ 0 ] , $ properties [ 1 ] , $ properties [ 2 ] , $ label ] ; } }
Parse image properties .
12,218
public function addToDropDown ( array $ options ) { foreach ( $ this -> sizes as $ slug => $ props ) { if ( $ props [ 'label' ] && ! isset ( $ options [ $ slug ] ) ) { $ options [ $ slug ] = $ props [ 'label' ] ; } } return $ options ; }
Filter media size drop down options . Add user custom image sizes .
12,219
protected function getFreshApplicationRoutes ( ) { return tap ( $ this -> getFreshApplication ( ) [ 'router' ] -> getRoutes ( ) , function ( $ routes ) { $ routes -> refreshNameLookups ( ) ; $ routes -> refreshActionLookups ( ) ; } ) ; }
Boot a fresh copy of the application and retrieve its routes .
12,220
protected function getFreshApplication ( ) { return tap ( require $ this -> laravel -> bootstrapPath ( 'app.php' ) , function ( $ app ) { $ app -> make ( \ Illuminate \ Contracts \ Console \ Kernel :: class ) -> bootstrap ( ) ; } ) ; }
Return a fresh application instance .
12,221
protected function getOptions ( FieldTypeInterface $ field ) { $ options = parent :: getOptions ( $ field ) ; $ attachedFile = get_attached_file ( $ field -> getValue ( ) ) ; $ options [ 'media' ] = [ 'name' => wp_basename ( $ attachedFile ) , 'thumbnail' => wp_get_attachment_image_src ( $ field -> getValue ( ) , 'thumbnail' , true ) [ 0 ] , 'filesize' => round ( filesize ( $ attachedFile ) / 1024 ) . ' KB' ] ; return $ options ; }
Return media field options .
12,222
public static function toInternal ( array $ routeParams , $ scheme = false ) { if ( $ scheme ) { return Yii :: $ app -> getUrlManager ( ) -> internalCreateAbsoluteUrl ( $ routeParams ) ; } return Yii :: $ app -> getUrlManager ( ) -> internalCreateUrl ( $ routeParams ) ; }
This helper method will not concern any context informations
12,223
public static function toAjax ( $ route , array $ params = [ ] ) { $ routeParams = [ '/' . $ route ] ; foreach ( $ params as $ key => $ value ) { $ routeParams [ $ key ] = $ value ; } return static :: toInternal ( $ routeParams , true ) ; }
Create a link to use when point to an ajax script .
12,224
public function afterFind ( $ event ) { foreach ( $ this -> attributes as $ attribute ) { $ this -> owner -> { $ attribute } = $ this -> htmlEncode ( $ this -> owner -> { $ attribute } ) ; } }
Event will be triggered after find .
12,225
protected function timeToIso8601Duration ( $ time ) { $ units = array ( "Y" => 365 * 24 * 3600 , "D" => 24 * 3600 , "H" => 3600 , "M" => 60 , "S" => 1 , ) ; $ str = "P" ; $ istime = false ; foreach ( $ units as $ unitName => & $ unit ) { $ quot = intval ( $ time / $ unit ) ; $ time -= $ quot * $ unit ; $ unit = $ quot ; if ( $ unit > 0 ) { if ( ! $ istime && in_array ( $ unitName , array ( "H" , "M" , "S" ) ) ) { $ str .= "T" ; $ istime = true ; } $ str .= strval ( $ unit ) . $ unitName ; } } return $ str ; }
Convert time to iso date .
12,226
public static function has ( $ name ) { return ( self :: find ( ) -> where ( [ self :: getNameAttribute ( ) => $ name ] ) -> one ( ) ) ? true : false ; }
Check whether a config value exists or not
12,227
public static function get ( $ name , $ defaultValue = null ) { $ model = self :: find ( ) -> where ( [ self :: getNameAttribute ( ) => $ name ] ) -> asArray ( ) -> one ( ) ; if ( $ model ) { return $ model [ self :: getValueAttribute ( ) ] ; } return $ defaultValue ; }
Get the value of a config value
12,228
public static function remove ( $ name ) { $ model = self :: find ( ) -> where ( [ self :: getNameAttribute ( ) => $ name ] ) -> one ( ) ; if ( $ model ) { return ( bool ) $ model -> delete ( ) ; } return false ; }
Remove an existing config value
12,229
private function callActionCallable ( $ action , $ result ) { if ( isset ( $ this -> actionsCallable [ $ action ] ) && is_callable ( $ this -> actionsCallable [ $ action ] ) ) { call_user_func ( $ this -> actionsCallable [ $ action ] , $ result ) ; } }
call the action callable if available .
12,230
public function truncate ( $ length ) { $ this -> _text = StringHelper :: truncate ( $ this -> _text , $ length ) ; return $ this ; }
Truncate the string for a given lenth .
12,231
public function getViewPath ( ) { if ( $ this -> module instanceof Module ) { if ( $ this -> module -> useAppViewPath ) { return '@app/views/' . $ this -> module -> id . '/' . $ this -> id ; } elseif ( is_array ( $ this -> module -> viewMap ) ) { $ currentAction = $ this -> id . '/' . ( $ this -> action ? $ this -> action -> id : $ this -> defaultAction ) ; foreach ( $ this -> module -> viewMap as $ action => $ viewPath ) { if ( $ action === '*' ) { return $ viewPath . '/' . $ this -> id ; } elseif ( fnmatch ( $ action , $ currentAction ) ) { return $ viewPath ; } } } } return parent :: getViewPath ( ) ; }
Override the default Yii controller getViewPath method . To define the template folders in where the templates are located . Why? Basically some modules needs to put theyr templates inside of the client repository .
12,232
public function render ( $ view , $ params = [ ] ) { if ( ! empty ( $ this -> module -> context ) && empty ( $ this -> layout ) ) { return $ this -> renderPartial ( $ view , $ params ) ; } return parent :: render ( $ view , $ params ) ; }
If we are acting in the module context and the layout is empty we only should renderPartial the content .
12,233
public function beforeRun ( $ app ) { foreach ( $ app -> tags as $ name => $ config ) { TagParser :: inject ( $ name , $ config ) ; } foreach ( $ this -> getModules ( ) as $ id => $ module ) { foreach ( $ module -> urlRules as $ key => $ rule ) { if ( is_string ( $ key ) ) { $ this -> _urlRules [ $ key ] = $ rule ; } else { $ this -> _urlRules [ ] = $ rule ; } } foreach ( $ module -> apiRules as $ endpoint => $ rule ) { $ this -> _apiRules [ $ endpoint ] = $ rule ; } foreach ( $ module -> apis as $ alias => $ class ) { $ this -> _apis [ $ alias ] = [ 'class' => $ class , 'module' => $ module ] ; } foreach ( $ module -> tags as $ name => $ config ) { TagParser :: inject ( $ name , $ config ) ; } } }
Before bootstrap run process .
12,234
public function run ( $ app ) { if ( ! $ app -> request -> getIsConsoleRequest ( ) ) { if ( $ this -> hasModule ( 'admin' ) && $ app -> request -> isAdmin ) { $ app -> request -> csrfParam = '_csrf_admin' ; foreach ( $ this -> getModules ( ) as $ id => $ module ) { if ( $ module instanceof AdminModuleInterface ) { $ this -> _adminAssets = ArrayHelper :: merge ( $ module -> getAdminAssets ( ) , $ this -> _adminAssets ) ; if ( $ module -> getMenu ( ) ) { $ this -> _adminMenus [ $ module -> id ] = $ module -> getMenu ( ) ; } $ this -> _jsTranslations [ $ id ] = $ module -> getJsTranslationMessages ( ) ; } } $ app -> getModule ( 'admin' ) -> assets = $ this -> _adminAssets ; $ app -> getModule ( 'admin' ) -> controllerMap = $ this -> _apis ; $ app -> getModule ( 'admin' ) -> moduleMenus = $ this -> _adminMenus ; $ app -> getModule ( 'admin' ) -> setJsTranslations ( $ this -> _jsTranslations ) ; if ( $ app -> getModule ( 'admin' ) -> hasProperty ( 'apiDefintions' ) ) { $ app -> getModule ( 'admin' ) -> apiDefintions = $ this -> generateApiRuleDefintions ( $ this -> _apis , $ this -> _apiRules ) ; } $ this -> _urlRules = array_merge ( $ app -> getModule ( 'admin' ) -> urlRules , $ this -> _urlRules ) ; } } $ app -> getUrlManager ( ) -> addRules ( $ this -> _urlRules ) ; }
Invokes the bootstraping process .
12,235
public function getRatingValue ( ) { if ( $ this -> _ratingValue === null ) { return null ; } $ range = new RangeValue ( $ this -> _ratingValue ) ; $ range -> ensureRange ( $ this -> _worstRating ? : 0 , $ this -> _bestRating ? : 5 ) ; return $ this -> _ratingValue = $ range -> getValue ( ) ; }
Get Rating Value .
12,236
protected function setRenderTime ( $ time ) { $ merge = Yii :: $ app -> session -> get ( self :: ROBOTS_FILTER_SESSION_IDENTIFIER , [ ] ) ; Yii :: $ app -> session -> set ( self :: ROBOTS_FILTER_SESSION_IDENTIFIER , array_merge ( [ $ this -> getSessionKeyByOwner ( ) => $ time ] , $ merge ) ) ; }
Render Time Setter .
12,237
protected function getSessionKeyByOwner ( ) { if ( $ this -> sessionKey ) { return $ this -> sessionKey ; } if ( $ this -> owner instanceof Controller ) { return $ this -> owner -> module -> id ; } return 'generic' ; }
Get a specific key for the current robots filter session array .
12,238
public static function typeCast ( $ string ) { if ( is_numeric ( $ string ) ) { return static :: typeCastNumeric ( $ string ) ; } elseif ( is_array ( $ string ) ) { return ArrayHelper :: typeCast ( $ string ) ; } return $ string ; }
TypeCast a string to its specific types .
12,239
public static function typeCastNumeric ( $ value ) { if ( ! self :: isFloat ( $ value ) ) { return $ value ; } if ( intval ( $ value ) == $ value ) { return ( int ) $ value ; } return ( float ) $ value ; }
TypeCast a numeric value to float or integer .
12,240
public static function contains ( $ needle , $ haystack , $ strict = false ) { $ needles = ( array ) $ needle ; $ state = false ; foreach ( $ needles as $ item ) { $ state = ( strpos ( $ haystack , $ item ) !== false ) ; if ( $ strict && ! $ state ) { return false ; } if ( ! $ strict && $ state ) { return true ; } } return $ state ; }
Check whether a char or word exists in a string or not .
12,241
public static function minify ( $ content , array $ options = [ ] ) { $ min = preg_replace ( [ '/[\n\r]/' , '/\>[^\S ]+/s' , '/[^\S ]+\</s' , '/(\s)+/s' , ] , [ '' , '>' , '<' , '\\1' ] , trim ( $ content ) ) ; $ min = str_replace ( [ '> <' ] , [ '><' ] , $ min ) ; if ( ArrayHelper :: getValue ( $ options , 'comments' , false ) ) { $ min = preg_replace ( '/<!--(.*) , '' , $ min ) ; } return $ min ; }
Minify html content .
12,242
public static function highlightWord ( $ content , $ word , $ markup = '<b>%s</b>' ) { $ word = ( array ) $ word ; $ content = strip_tags ( $ content ) ; $ latest = null ; foreach ( $ word as $ needle ) { preg_match_all ( "/" . preg_quote ( $ needle , '/' ) . "+/i" , $ content , $ matches ) ; if ( is_array ( $ matches [ 0 ] ) && count ( $ matches [ 0 ] ) >= 1 ) { foreach ( $ matches [ 0 ] as $ match ) { if ( $ latest === $ match ) { continue ; } $ content = str_replace ( $ match , sprintf ( $ markup , $ match ) , $ content ) ; $ latest = $ match ; } } } return $ content ; }
Highlight a word within a content .
12,243
public static function mb_str_split ( $ string , $ length = 1 ) { $ array = [ ] ; $ stringLength = mb_strlen ( $ string , 'UTF-8' ) ; for ( $ i = 0 ; $ i < $ stringLength ; $ i += $ length ) { $ array [ ] = mb_substr ( $ string , $ i , $ length , 'UTF-8' ) ; } return $ array ; }
Multibyte - safe str_split funciton .
12,244
public function setAttendee ( $ attendee ) { ObjectHelper :: isInstanceOf ( $ attendee , [ Organization :: class , PersonInterface :: class ] ) ; $ this -> _attendee = $ attendee ; return $ this ; }
A person or organization attending the event . Supersedes attendees .
12,245
public function setComposer ( $ composer ) { ObjectHelper :: isInstanceOf ( $ author , [ Organization :: class , PersonInterface :: class ] ) ; $ this -> _composer = $ composer ; return $ this ; }
The person or organization who wrote a composition or who is the composer of a work performed at some event .
12,246
public function setContributor ( $ contributor ) { ObjectHelper :: isInstanceOf ( $ contributor , [ Organization :: class , PersonInterface :: class ] ) ; $ this -> _contributor = $ contributor ; return $ this ; }
A secondary contributor to the CreativeWork or Event .
12,247
public function setOrganizer ( $ organizer ) { ObjectHelper :: isInstanceOf ( $ organizer , [ Organization :: class , PersonInterface :: class ] ) ; $ this -> _organizer = $ organizer ; return $ this ; }
An organizer of an Event .
12,248
public function setTranslator ( $ translator ) { ObjectHelper :: isInstanceOf ( $ translator , [ Organization :: class , PersonInterface :: class ] ) ; $ this -> _translator = $ translator ; return $ this ; }
Organization or person who adapts a creative work to different languages regional differences and technical requirements of a target market or that translates during some event .
12,249
public function run ( $ app ) { foreach ( $ app -> getApplicationModules ( ) as $ id => $ module ) { $ folder = $ module -> basePath . DIRECTORY_SEPARATOR . 'commands' ; if ( file_exists ( $ folder ) && is_dir ( $ folder ) ) { foreach ( FileHelper :: findFiles ( $ folder ) as $ file ) { $ module -> controllerNamespace = $ module -> namespace . '\commands' ; $ className = '\\' . $ module -> getNamespace ( ) . '\\commands\\' . pathinfo ( $ file , PATHINFO_FILENAME ) ; $ command = str_replace ( '-controller' , '' , $ module -> id . '/' . Inflector :: camel2id ( pathinfo ( $ file , PATHINFO_FILENAME ) ) ) ; Yii :: $ app -> controllerMap [ $ command ] = [ 'class' => $ className ] ; } } } }
The run method must be implemented by defintion .
12,250
public function actionConfigInfo ( ) { $ this -> outputInfo ( "dev config file: " . Yii :: getAlias ( $ this -> configFile ) ) ; $ config = $ this -> readConfig ( ) ; if ( ! $ config ) { return $ this -> outputError ( "Unable to open config file." ) ; } foreach ( $ config as $ key => $ value ) { $ this -> output ( "{$key} => " . VarDumper :: dumpAsString ( $ value ) ) ; } }
Display config data and location .
12,251
protected function readConfig ( ) { $ data = FileHelper :: getFileContent ( $ this -> configFile ) ; if ( $ data ) { return Json :: decode ( $ data ) ; } return false ; }
Read entire config and return as array .
12,252
protected function getConfig ( $ key , $ defaultValue = null ) { $ config = $ this -> readConfig ( ) ; return isset ( $ config [ $ key ] ) ? $ config [ $ key ] : $ defaultValue ; }
Get a specific value for a given key .
12,253
protected function saveConfig ( $ key , $ value ) { $ content = $ this -> readConfig ( ) ; if ( ! $ content ) { $ content = [ ] ; } $ content [ $ key ] = $ value ; $ save = FileHelper :: writeFile ( $ this -> configFile , Json :: encode ( $ content ) ) ; if ( ! $ save ) { return $ this -> outputError ( "Unable to find config file " . $ this -> configFile . ". Please create and provide Permissions." ) ; } return $ value ; }
Save a value in the config for a given key .
12,254
public function init ( ) { parent :: init ( ) ; if ( $ this -> autoRegisterCsrf && Yii :: $ app -> request -> enableCsrfValidation ) { $ this -> registerCsrfMetaTags ( ) ; } }
Init view object . Implements auto register csrf meta tokens .
12,255
public function getAssetUrl ( $ assetName ) { $ assetName = ltrim ( $ assetName , '\\' ) ; if ( ! isset ( $ this -> assetBundles [ $ assetName ] ) ) { throw new Exception ( "The AssetBundle '$assetName' is not registered." ) ; } return $ this -> assetBundles [ $ assetName ] -> baseUrl ; }
Get the url source for an asset .
12,256
public function setEmail ( $ email ) { $ validator = new EmailValidator ( ) ; if ( $ validator -> validate ( $ email ) ) { $ this -> _email = $ email ; } else { $ this -> _email = false ; } }
Setter method for e - mail .
12,257
public function actionIndex ( ) { $ error = false ; @ chdir ( Yii :: getAlias ( '@app' ) ) ; $ this -> output ( 'The directory the health commands is applying to: ' . Yii :: getAlias ( '@app' ) ) ; foreach ( $ this -> folders as $ folder => $ writable ) { $ mode = ( $ writable ) ? 0777 : 0775 ; if ( ! file_exists ( $ folder ) ) { if ( FileHelper :: createDirectory ( $ folder , $ mode ) ) { $ this -> outputSuccess ( "$folder: successfully created directory" ) ; } else { $ error = true ; $ this -> outputError ( "$folder: unable to create directory" ) ; } } else { $ this -> outputInfo ( "$folder: directory exists already" ) ; } if ( $ writable && ! is_writable ( $ folder ) ) { $ this -> outputInfo ( "$folder: is not writeable, try to set mode '$mode'." ) ; @ chmod ( $ folder , $ mode ) ; } if ( $ writable ) { if ( ! is_writable ( $ folder ) ) { $ error = true ; $ this -> outputError ( "$folder: is not writable, please change permissions." ) ; } } } foreach ( $ this -> files as $ file ) { if ( file_exists ( $ file ) ) { $ this -> outputInfo ( "$file: file exists." ) ; } else { $ error = true ; $ this -> outputError ( "$file: file does not exists!" ) ; } } return $ error ? $ this -> outputError ( 'Health check found errors!' ) : $ this -> outputSuccess ( 'O.K.' ) ; }
Create all required directories an check whether they are writeable or not .
12,258
public static function addGraph ( $ data ) { self :: registerView ( ) ; if ( is_scalar ( $ data ) ) { throw new Exception ( "Data must be either an array or an object of type luya\web\jsonld\BaseThing." ) ; } Yii :: $ app -> view -> params [ '@context' ] = 'https://schema.org' ; Yii :: $ app -> view -> params [ '@graph' ] [ ] = $ data ; return $ data ; }
Register graph data .
12,259
protected static function registerView ( ) { if ( self :: $ _view === null ) { Yii :: $ app -> view -> on ( View :: EVENT_BEGIN_BODY , function ( $ event ) { echo '<script type="application/ld+json">' . Json :: encode ( $ event -> sender -> params ) . '</script>' ; } ) ; self :: $ _view = true ; } }
Register the view file an observe the event which then reads the data from
12,260
public function validateAttribute ( $ model , $ attribute ) { $ value = $ model -> $ attribute ; if ( ! is_numeric ( $ value ) && ! is_float ( $ value ) ) { return $ model -> addError ( $ attribute , Yii :: t ( 'luya' , $ this -> message , [ 'attribute' => $ model -> getAttributeLabel ( $ attribute ) ] ) ) ; } }
Validate the value if is_numeric or if not is_float .
12,261
public function parse ( $ value , $ sub ) { return Html :: a ( empty ( $ sub ) ? $ value : $ sub , 'tel:' . $ this -> ensureNumber ( $ value ) ) ; }
Generate the Tel Tag .
12,262
public function setHref ( $ href ) { if ( StringHelper :: startsWith ( $ href , '//' ) ) { $ this -> _href = Url :: base ( true ) . str_replace ( '//' , '/' , $ href ) ; } else { $ this -> _href = Url :: ensureHttp ( $ href ) ; } }
Set the href value for an external link resource .
12,263
public static function isJson ( $ value ) { if ( ! is_scalar ( $ value ) ) { return false ; } $ firstChar = substr ( $ value , 0 , 1 ) ; if ( $ firstChar !== '{' && $ firstChar !== '[' ) { return false ; } $ json_check = json_decode ( $ value ) ; return json_last_error ( ) === JSON_ERROR_NONE ; }
Checks if a string is a json or not .
12,264
public function actionUpdate ( ) { foreach ( $ this -> repos as $ repo ) { $ this -> rebaseRepo ( $ repo , $ this -> getFilesystemRepoPath ( $ repo ) ) ; } foreach ( $ this -> getConfig ( self :: CONFIG_VAR_CUSTOMCLONES , [ ] ) as $ repo => $ path ) { $ this -> rebaseRepo ( $ repo , $ path ) ; } }
Update all repos to master branch from upstream .
12,265
public function actionRemove ( $ repo ) { FileHelper :: removeDirectory ( $ this -> getFilesystemRepoPath ( $ repo ) ) ; $ clones = $ this -> getConfig ( self :: CONFIG_VAR_CUSTOMCLONES , [ ] ) ; if ( isset ( $ clones [ $ repo ] ) ) { unset ( $ clones [ $ repo ] ) ; $ this -> saveConfig ( self :: CONFIG_VAR_CUSTOMCLONES , $ clones ) ; } return $ this -> outputSuccess ( "Removed repo {$repo}." ) ; }
Remove a given repo from filesystem .
12,266
public static function on ( $ name , $ value , $ prepend = false ) { $ object = new HookEvent ( [ 'handler' => $ value ] ) ; if ( $ prepend ) { array_unshift ( static :: $ _hooks [ $ name ] , $ object ) ; } else { static :: $ _hooks [ $ name ] [ ] = $ object ; } }
Register a hook listener .
12,267
public static function string ( $ name ) { $ buffer = [ ] ; foreach ( self :: trigger ( $ name ) as $ hook ) { $ buffer [ ] = $ hook -> output ; } return implode ( "" , $ buffer ) ; }
Get the string output of the hooks .
12,268
public static function iterate ( $ name ) { $ buffer = [ ] ; foreach ( self :: trigger ( $ name ) as $ hook ) { $ buffer = array_merge ( $ buffer , $ hook -> getIterations ( ) ) ; } return $ buffer ; }
Get the array output of iteration hooks .
12,269
public function parse ( $ value , $ sub ) { if ( substr ( $ value , 0 , 2 ) == '//' ) { $ value = StringHelper :: replaceFirst ( '//' , Url :: base ( true ) . '/' , $ value ) ; $ external = false ; } else { $ external = true ; } $ value = Url :: ensureHttp ( $ value ) ; $ label = empty ( $ sub ) ? $ value : $ sub ; return Html :: a ( $ label , $ value , [ 'class' => $ external ? 'link-external' : 'link-internal' , 'target' => $ external ? '_blank' : null ] ) ; }
Generate the Link Tag .
12,270
public function renderReadme ( $ folders , $ name , $ ns ) { return $ this -> view -> render ( '@luya/console/commands/views/module/readme.php' , [ 'folders' => $ folders , 'name' => $ name , 'humanName' => $ this -> humanizeName ( $ name ) , 'ns' => $ ns , 'luyaText' => $ this -> getGeneratorText ( 'module/create' ) , ] ) ; }
Render the readme template .
12,271
public function isHostAllowed ( $ allowedHosts ) { $ currentHost = $ this -> request -> hostName ; $ rules = ( array ) $ allowedHosts ; foreach ( $ rules as $ allowedHost ) { if ( StringHelper :: matchWildcard ( $ allowedHost , $ currentHost ) ) { return true ; } } return false ; }
Checks if the current request name against the allowedHosts list .
12,272
public function getKeys ( ) { if ( $ this -> _keys === null ) { $ this -> _keys = $ this -> getResolvedPathInfo ( $ this -> request ) -> resolvedValues ; } return $ this -> _keys ; }
Resolves the current key and value objects based on the current pathInto and pattern from Request component .
12,273
public function getKey ( $ key , $ defaultValue = false ) { $ this -> getKeys ( ) ; return isset ( $ this -> _keys [ $ key ] ) ? $ this -> _keys [ $ key ] : $ defaultValue ; }
Get value from the composition array for the provided key if the key does not existing the default value will be return . The standard value of the defaultValue is false so if nothing defined and the could not be found the return value is false .
12,274
public function createRouteEnsure ( array $ overrideKeys = [ ] ) { if ( isset ( $ overrideKeys [ 'langShortCode' ] ) ) { $ langShortCode = $ overrideKeys [ 'langShortCode' ] ; } else { $ langShortCode = $ this -> langShortCode ; } return $ this -> hidden || ( ! $ this -> hidden && $ langShortCode == $ this -> defaultLangShortCode && $ this -> hideDefaultPrefixOnly ) ? '' : $ this -> createRoute ( $ overrideKeys ) ; }
Create a route but ensures if composition is hidden anyhow .
12,275
public function getIsCli ( ) { if ( $ this -> _isCli === null ) { $ this -> _isCli = $ this -> getSapiName ( ) === 'cli' ; } return $ this -> _isCli ; }
Getter method whether current request is cli or not .
12,276
public function getConfigArray ( ) { if ( $ this -> _configArray === null ) { if ( ! file_exists ( $ this -> configFile ) ) { if ( ! $ this -> getIsCli ( ) ) { throw new Exception ( "Unable to load the config file '" . $ this -> configFile . "'." ) ; } $ config = [ 'id' => 'consoleapp' , 'basePath' => dirname ( __DIR__ ) ] ; } else { $ config = require $ this -> configFile ; } if ( ! is_array ( $ config ) ) { throw new Exception ( "config file '" . $ this -> configFile . "' found but no array returning." ) ; } if ( ! empty ( $ this -> prependConfigArray ( ) ) ) { $ config = ArrayHelper :: merge ( $ config , $ this -> prependConfigArray ( ) ) ; } $ this -> _configArray = $ config ; } return $ this -> _configArray ; }
Get the config array from the configFile path with the predefined values .
12,277
public function applicationConsole ( ) { $ this -> setIsCli ( true ) ; $ config = $ this -> getConfigArray ( ) ; $ config [ 'defaultRoute' ] = 'help' ; if ( isset ( $ config [ 'components' ] ) ) { if ( isset ( $ config [ 'components' ] [ 'composition' ] ) ) { unset ( $ config [ 'components' ] [ 'composition' ] ) ; } } $ this -> includeYii ( ) ; $ baseUrl = null ; if ( isset ( $ config [ 'consoleBaseUrl' ] ) ) { $ baseUrl = $ config [ 'consoleBaseUrl' ] ; } elseif ( isset ( $ config [ 'consoleHostInfo' ] ) ) { $ baseUrl = '/' ; } $ mergedConfig = ArrayHelper :: merge ( $ config , [ 'bootstrap' => [ 'luya\console\Bootstrap' ] , 'components' => [ 'urlManager' => [ 'class' => 'yii\web\UrlManager' , 'enablePrettyUrl' => true , 'showScriptName' => false , 'baseUrl' => $ baseUrl , 'hostInfo' => isset ( $ config [ 'consoleHostInfo' ] ) ? $ config [ 'consoleHostInfo' ] : null , ] , ] , ] ) ; $ this -> app = new ConsoleApplication ( $ mergedConfig ) ; if ( ! $ this -> mockOnly ) { exit ( $ this -> app -> run ( ) ) ; } }
Run Cli - Application based on the provided config file .
12,278
public function applicationWeb ( ) { $ config = $ this -> getConfigArray ( ) ; $ this -> includeYii ( ) ; $ mergedConfig = ArrayHelper :: merge ( $ config , [ 'bootstrap' => [ 'luya\web\Bootstrap' ] ] ) ; $ this -> app = new WebApplication ( $ mergedConfig ) ; if ( ! $ this -> mockOnly ) { return $ this -> app -> run ( ) ; } }
Run Web - Application based on the provided config file .
12,279
private function includeYii ( ) { if ( file_exists ( $ this -> _baseYiiFile ) ) { defined ( 'LUYA_YII_VENDOR' ) ? : define ( 'LUYA_YII_VENDOR' , dirname ( $ this -> _baseYiiFile ) ) ; $ baseYiiFolder = LUYA_YII_VENDOR . DIRECTORY_SEPARATOR ; $ luyaYiiFile = $ this -> getCoreBasePath ( ) . DIRECTORY_SEPARATOR . 'Yii.php' ; if ( file_exists ( $ luyaYiiFile ) ) { require_once ( $ baseYiiFolder . 'BaseYii.php' ) ; require_once ( $ luyaYiiFile ) ; } else { require_once ( $ baseYiiFolder . 'Yii.php' ) ; } Yii :: setAlias ( '@luya' , $ this -> getCoreBasePath ( ) ) ; return true ; } throw new Exception ( "YiiBase file does not exits '" . $ this -> _baseYiiFile . "'." ) ; }
Helper method to check whether the provided Yii Base file exists if yes include and return the file .
12,280
public function getViewPath ( ) { if ( ! $ this -> useAppViewPath ) { return parent :: getViewPath ( ) ; } $ class = new ReflectionClass ( $ this ) ; return '@app/views/widgets/' . Inflector :: camel2id ( $ class -> getShortName ( ) ) ; }
Find view paths in application folder .
12,281
public function getPrev ( ) { return self :: find ( ) -> where ( [ '<' , 'id' , $ this -> id ] ) -> orderBy ( [ 'id' => SORT_DESC ] ) -> limit ( 1 ) -> one ( ) ; }
Get the previous record of a current id
12,282
public function init ( ) { parent :: init ( ) ; Yii :: trace ( 'initialize LUYA Application' , __METHOD__ ) ; $ this -> setLocale ( $ this -> language ) ; }
Add trace info to luya application trait
12,283
public function getPackageInstaller ( ) { $ file = Yii :: getAlias ( '@vendor/luyadev/installer.php' ) ; $ data = is_file ( $ file ) ? include $ file : [ ] ; return new PackageInstaller ( $ data ) ; }
Get the package Installer
12,284
public function getApplicationModules ( ) { $ modules = [ ] ; foreach ( $ this -> getModules ( ) as $ id => $ obj ) { if ( $ obj instanceof Module ) { $ modules [ $ id ] = $ obj ; } } return $ modules ; }
Get an array with all modules which are an instance of the luya \ base \ Module .
12,285
public function getFrontendModules ( ) { $ modules = [ ] ; foreach ( $ this -> getModules ( ) as $ id => $ obj ) { if ( $ obj instanceof Module && ! $ obj instanceof AdminModuleInterface && ! $ obj instanceof CoreModuleInterface ) { $ modules [ $ id ] = $ obj ; } } return $ modules ; }
Return a list with all registered frontend modules except luya and cms . This is needed in the module block .
12,286
public function getAdminModules ( ) { $ modules = [ ] ; foreach ( $ this -> getModules ( ) as $ id => $ obj ) { if ( $ obj instanceof Module && $ obj instanceof AdminModuleInterface ) { $ modules [ $ id ] = $ obj ; } } return $ modules ; }
Return all Admin Module Interface implementing modules .
12,287
public function init ( ) { $ path = Yii :: getAlias ( $ this -> configFile ) ; if ( file_exists ( $ path ) ) { $ config = ( include ( $ path ) ) ; foreach ( $ config as $ name => $ closure ) { if ( is_array ( $ closure ) ) { $ this -> addElement ( $ name , $ closure [ 0 ] , $ closure [ 1 ] ) ; } else { $ this -> addElement ( $ name , $ closure ) ; } } } }
Yii intializer is loading the default elements . php if existing .
12,288
public function addElement ( $ name , $ closure , $ mockedArgs = [ ] ) { $ this -> _elements [ $ name ] = $ closure ; $ this -> mockArgs ( $ name , $ mockedArgs ) ; }
Add an element with a closure to the elements array .
12,289
public function getElement ( $ name , array $ params = [ ] ) { if ( ! array_key_exists ( $ name , $ this -> _elements ) ) { throw new Exception ( "The requested element '$name' does not exist in the list. You may register the element first with `addElement(name, closure)`." ) ; } return call_user_func_array ( $ this -> _elements [ $ name ] , $ params ) ; }
Renders the closure for the given name and returns the content .
12,290
public function getMockedArgValue ( $ elementName , $ argName ) { if ( isset ( $ this -> _mockedArguments [ $ elementName ] ) && isset ( $ this -> _mockedArguments [ $ elementName ] [ $ argName ] ) ) { $ response = $ this -> _mockedArguments [ $ elementName ] [ $ argName ] ; if ( is_callable ( $ response ) ) { $ response = call_user_func ( $ response ) ; } return $ response ; } return false ; }
Find the mocked value for an element argument .
12,291
public function render ( $ file , array $ args = [ ] ) { $ view = new View ( ) ; $ view -> autoRegisterCsrf = false ; return $ view -> renderPhpFile ( rtrim ( $ this -> getFolder ( ) , DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR . FileHelper :: ensureExtension ( $ file , 'php' ) , $ args ) ; }
Method to render twig files with theyr specific arguments can be used inside the element closure depending on where the closure was registered . Otherwhise the use of the element variable must be provided .
12,292
public function resolveGetterMethods ( ) { $ resolved = [ ] ; $ methods = get_class_methods ( $ this ) ; if ( ! $ methods ) { return [ ] ; } foreach ( $ methods as $ method ) { if ( StringHelper :: startsWith ( $ method , 'get' , true ) ) { $ resolved [ ] = lcfirst ( StringHelper :: replaceFirst ( 'get' , '' , $ method ) ) ; } } asort ( $ resolved ) ; return $ resolved ; }
Find all getter methods .
12,293
private function removeEmptyValues ( array $ haystack ) { foreach ( $ haystack as $ key => $ value ) { if ( is_array ( $ value ) ) { $ haystack [ $ key ] = $ this -> removeEmptyValues ( $ value ) ; } if ( $ value === null || $ value == '' ) { unset ( $ haystack [ $ key ] ) ; } } return $ haystack ; }
Cleanup array from null values .
12,294
public function beforeInsert ( $ event ) { foreach ( $ this -> insert as $ field ) { $ event -> sender -> $ field = time ( ) ; } }
Insert the timestamp for all provided fields .
12,295
public function beforeUpdate ( $ event ) { foreach ( $ this -> update as $ field ) { $ event -> sender -> $ field = time ( ) ; } }
Update the timestamp for all provided fields .
12,296
public static function csv ( $ filename , array $ options = [ ] ) { $ filename = Yii :: getAlias ( $ filename ) ; if ( FileHelper :: getFileInfo ( $ filename ) -> extension ) { $ resource = fopen ( $ filename , 'r' ) ; } else { $ resource = fopen ( 'php://memory' , 'rw' ) ; fwrite ( $ resource , $ filename ) ; rewind ( $ resource ) ; } $ data = [ ] ; while ( ( $ row = fgetcsv ( $ resource , 0 , ArrayHelper :: getValue ( $ options , 'delimiter' , ',' ) , ArrayHelper :: getValue ( $ options , 'enclosure' , '"' ) ) ) !== false ) { $ data [ ] = $ row ; } fclose ( $ resource ) ; $ fields = ArrayHelper :: getValue ( $ options , 'fields' , false ) ; if ( $ fields && is_array ( $ fields ) ) { $ filteredData = [ ] ; foreach ( $ fields as $ fieldColumn ) { if ( ! is_numeric ( $ fieldColumn ) ) { $ fieldColumn = array_search ( $ fieldColumn , $ data [ 0 ] ) ; } foreach ( $ data as $ key => $ rowValue ) { if ( array_key_exists ( $ fieldColumn , $ rowValue ) ) { $ filteredData [ $ key ] [ ] = $ rowValue [ $ fieldColumn ] ; } } } $ data = $ filteredData ; unset ( $ filteredData ) ; } if ( ArrayHelper :: getValue ( $ options , 'removeHeader' , false ) ) { unset ( $ data [ 0 ] ) ; $ data = array_values ( $ data ) ; } return $ data ; }
Import a CSV from a string or filename and return array .
12,297
public function extractModules ( $ app ) { if ( $ this -> _modules === null ) { foreach ( $ app -> getModules ( ) as $ id => $ obj ) { $ moduleObject = Yii :: $ app -> getModule ( $ id ) ; if ( $ moduleObject instanceof \ luya \ base \ Module ) { $ this -> _modules [ $ id ] = $ moduleObject ; } } if ( $ this -> _modules === null ) { $ this -> _modules = [ ] ; } } }
Extract and load all modules from the Application - Object .
12,298
protected function addToDirectory ( $ path , $ folderName , $ ns , $ module ) { if ( file_exists ( $ path ) ) { $ this -> _dirs [ $ folderName ] [ ] = [ 'ns' => $ ns , 'module' => $ module , 'folderPath' => $ path . DIRECTORY_SEPARATOR , 'files' => $ this -> scanDirectoryFiles ( $ path , $ ns , $ module ) , ] ; } }
Add a given directory to the list of folders .
12,299
protected function scanDirectoryFiles ( $ path , $ ns , $ module ) { $ files = [ ] ; foreach ( scandir ( $ path ) as $ file ) { if ( substr ( $ file , 0 , 1 ) !== '.' ) { $ files [ ] = [ 'file' => $ file , 'module' => $ module , 'ns' => $ ns . '\\' . pathinfo ( $ file , PATHINFO_FILENAME ) , ] ; } } return $ files ; }
Scan a given directory path and return an array with namespace module and file .