idx
int64 0
60.3k
| question
stringlengths 101
6.21k
| target
stringlengths 7
803
|
|---|---|---|
4,100
|
public static function add_extension ( $ classOrExtension , $ extension = null ) { if ( $ extension ) { $ class = $ classOrExtension ; } else { $ class = get_called_class ( ) ; $ extension = $ classOrExtension ; } if ( ! preg_match ( '/^([^(]*)/' , $ extension , $ matches ) ) { return false ; } $ extensionClass = $ matches [ 1 ] ; if ( ! class_exists ( $ extensionClass ) ) { user_error ( sprintf ( 'Object::add_extension() - Can\'t find extension class for "%s"' , $ extensionClass ) , E_USER_ERROR ) ; } if ( ! is_subclass_of ( $ extensionClass , 'SilverStripe\\Core\\Extension' ) ) { user_error ( sprintf ( 'Object::add_extension() - Extension "%s" is not a subclass of Extension' , $ extensionClass ) , E_USER_ERROR ) ; } $ subclasses = ClassInfo :: subclassesFor ( $ class ) ; $ subclasses [ ] = $ class ; if ( $ subclasses ) { foreach ( $ subclasses as $ subclass ) { unset ( self :: $ extra_methods [ $ subclass ] ) ; } } Config :: modify ( ) -> merge ( $ class , 'extensions' , array ( $ extension ) ) ; Injector :: inst ( ) -> unregisterNamedObject ( $ class ) ; return true ; }
|
Add an extension to a specific class .
|
4,101
|
public static function get_extra_config_sources ( $ class = null ) { if ( ! $ class ) { $ class = get_called_class ( ) ; } if ( in_array ( $ class , self :: $ unextendable_classes ) ) { return null ; } $ sources = null ; $ extensions = Config :: inst ( ) -> get ( $ class , 'extensions' , Config :: EXCLUDE_EXTRA_SOURCES | Config :: UNINHERITED ) ; if ( ! $ extensions ) { return null ; } $ sources = array ( ) ; foreach ( $ extensions as $ extension ) { list ( $ extensionClass , $ extensionArgs ) = ClassInfo :: parse_class_spec ( $ extension ) ; $ extensionClass = strtok ( $ extensionClass , '.' ) ; $ sources [ ] = $ extensionClass ; if ( ! class_exists ( $ extensionClass ) ) { throw new InvalidArgumentException ( "$class references nonexistent $extensionClass in \$extensions" ) ; } call_user_func ( array ( $ extensionClass , 'add_to_class' ) , $ class , $ extensionClass , $ extensionArgs ) ; foreach ( array_reverse ( ClassInfo :: ancestry ( $ extensionClass ) ) as $ extensionClassParent ) { if ( ClassInfo :: has_method_from ( $ extensionClassParent , 'get_extra_config' , $ extensionClassParent ) ) { $ extras = $ extensionClassParent :: get_extra_config ( $ class , $ extensionClass , $ extensionArgs ) ; if ( $ extras ) { $ sources [ ] = $ extras ; } } } } return $ sources ; }
|
Get extra config sources for this class
|
4,102
|
public function extend ( $ method , & $ a1 = null , & $ a2 = null , & $ a3 = null , & $ a4 = null , & $ a5 = null , & $ a6 = null , & $ a7 = null ) { $ values = array ( ) ; if ( ! empty ( $ this -> beforeExtendCallbacks [ $ method ] ) ) { foreach ( array_reverse ( $ this -> beforeExtendCallbacks [ $ method ] ) as $ callback ) { $ value = call_user_func_array ( $ callback , array ( & $ a1 , & $ a2 , & $ a3 , & $ a4 , & $ a5 , & $ a6 , & $ a7 ) ) ; if ( $ value !== null ) { $ values [ ] = $ value ; } } $ this -> beforeExtendCallbacks [ $ method ] = array ( ) ; } foreach ( $ this -> getExtensionInstances ( ) as $ instance ) { if ( method_exists ( $ instance , $ method ) ) { try { $ instance -> setOwner ( $ this ) ; $ value = $ instance -> $ method ( $ a1 , $ a2 , $ a3 , $ a4 , $ a5 , $ a6 , $ a7 ) ; } finally { $ instance -> clearOwner ( ) ; } if ( $ value !== null ) { $ values [ ] = $ value ; } } } if ( ! empty ( $ this -> afterExtendCallbacks [ $ method ] ) ) { foreach ( array_reverse ( $ this -> afterExtendCallbacks [ $ method ] ) as $ callback ) { $ value = call_user_func_array ( $ callback , array ( & $ a1 , & $ a2 , & $ a3 , & $ a4 , & $ a5 , & $ a6 , & $ a7 ) ) ; if ( $ value !== null ) { $ values [ ] = $ value ; } } $ this -> afterExtendCallbacks [ $ method ] = array ( ) ; } return $ values ; }
|
Run the given function on all of this object s extensions . Note that this method originally returned void so if you wanted to return results you re hosed
|
4,103
|
public function getExtensionInstance ( $ extension ) { $ instances = $ this -> getExtensionInstances ( ) ; if ( array_key_exists ( $ extension , $ instances ) ) { return $ instances [ $ extension ] ; } foreach ( $ instances as $ instance ) { if ( is_a ( $ instance , $ extension ) ) { return $ instance ; } } return null ; }
|
Get an extension instance attached to this object by name .
|
4,104
|
protected function getFormFields ( ) { $ fields = FieldList :: create ( ) ; $ controller = $ this -> getController ( ) ; $ backURL = $ controller -> getBackURL ( ) ? : $ controller -> getReturnReferer ( ) ; if ( ! $ backURL || Director :: makeRelative ( $ backURL ) === $ controller -> getRequest ( ) -> getURL ( ) ) { $ backURL = Director :: baseURL ( ) ; } $ fields -> push ( HiddenField :: create ( 'BackURL' , 'BackURL' , $ backURL ) ) ; return $ fields ; }
|
Build the FieldList for the logout form
|
4,105
|
public static function filename2url ( $ filename ) { $ filename = realpath ( $ filename ) ; if ( ! $ filename ) { return null ; } $ base = realpath ( BASE_PATH ) ; $ baseLength = strlen ( $ base ) ; if ( substr ( $ filename , 0 , $ baseLength ) !== $ base ) { return null ; } $ relativePath = ltrim ( substr ( $ filename , $ baseLength ) , '/\\' ) ; return Director :: absoluteURL ( $ relativePath ) ; }
|
Turns a local system filename into a URL by comparing it to the script filename .
|
4,106
|
public static function absoluteURLs ( $ html ) { $ html = str_replace ( '$CurrentPageURL' , Controller :: curr ( ) -> getRequest ( ) -> getURL ( ) , $ html ) ; return HTTP :: urlRewriter ( $ html , function ( $ url ) { if ( preg_match ( '/^\w+:/' , $ url ) ) { return $ url ; } return Director :: absoluteURL ( $ url , true ) ; } ) ; }
|
Turn all relative URLs in the content to absolute URLs .
|
4,107
|
public static function urlRewriter ( $ content , $ code ) { if ( ! is_callable ( $ code ) ) { throw new InvalidArgumentException ( 'HTTP::urlRewriter expects a callable as the second parameter' ) ; } $ attribs = [ "src" , "background" , "a" => "href" , "link" => "href" , "base" => "href" ] ; $ regExps = [ ] ; foreach ( $ attribs as $ tag => $ attrib ) { if ( ! is_numeric ( $ tag ) ) { $ tagPrefix = "$tag " ; } else { $ tagPrefix = "" ; } $ regExps [ ] = "/(<{$tagPrefix}[^>]*$attrib *= *\")([^\"]*)(\")/i" ; $ regExps [ ] = "/(<{$tagPrefix}[^>]*$attrib *= *')([^']*)(')/i" ; $ regExps [ ] = "/(<{$tagPrefix}[^>]*$attrib *= *)([^\"' ]*)( )/i" ; } $ styles = [ 'background-image' , 'background' , 'list-style-image' , 'list-style' , 'content' ] ; foreach ( $ styles as $ style ) { $ regExps [ ] = "/($style:[^;]*url *\\(\")([^\"]+)(\"\\))/i" ; $ regExps [ ] = "/($style:[^;]*url *\\(')([^']+)('\\))/i" ; $ regExps [ ] = "/($style:[^;]*url *\\()([^\"\\)')]+)(\\))/i" ; } $ callback = function ( $ matches ) use ( $ code ) { $ URL = Convert :: xml2raw ( $ matches [ 2 ] ) ; $ rewritten = $ code ( $ URL ) ; return $ matches [ 1 ] . Convert :: raw2xml ( $ rewritten ) . $ matches [ 3 ] ; } ; foreach ( $ regExps as $ regExp ) { $ content = preg_replace_callback ( $ regExp , $ callback , $ content ) ; } return $ content ; }
|
Rewrite all the URLs in the given content evaluating the given string as PHP code .
|
4,108
|
public static function findByTagAndAttribute ( $ content , $ attributes ) { $ regexes = [ ] ; foreach ( $ attributes as $ tag => $ attribute ) { $ regexes [ ] = "/<{$tag} [^>]*$attribute *= *([\"'])(.*?)\\1[^>]*>/i" ; $ regexes [ ] = "/<{$tag} [^>]*$attribute *= *([^ \"'>]+)/i" ; } $ result = [ ] ; if ( $ regexes ) { foreach ( $ regexes as $ regex ) { if ( preg_match_all ( $ regex , $ content , $ matches ) ) { $ result = array_merge_recursive ( $ result , ( isset ( $ matches [ 2 ] ) ? $ matches [ 2 ] : $ matches [ 1 ] ) ) ; } } } return count ( $ result ) ? $ result : null ; }
|
Search for all tags with a specific attribute then return the value of that attribute in a flat array .
|
4,109
|
public static function get_mime_type ( $ filename ) { $ path = BASE_PATH . DIRECTORY_SEPARATOR . $ filename ; if ( class_exists ( 'finfo' ) && file_exists ( $ path ) ) { $ finfo = new finfo ( FILEINFO_MIME_TYPE ) ; return $ finfo -> file ( $ path ) ; } $ ext = strtolower ( File :: get_file_extension ( $ filename ) ) ; $ mimeTypes = HTTP :: config ( ) -> uninherited ( 'MimeTypes' ) ; if ( ! isset ( $ mimeTypes [ $ ext ] ) ) { return 'application/unknown' ; } return $ mimeTypes [ $ ext ] ; }
|
Get the MIME type based on a file s extension . If the finfo class exists in PHP and the file exists relative to the project root then use that extension otherwise fallback to a list of commonly known MIME types .
|
4,110
|
public static function set_cache_age ( $ age ) { Deprecation :: notice ( '5.0' , 'Use HTTPCacheControlMiddleware::singleton()->setMaxAge($age) instead' ) ; self :: $ cache_age = $ age ; HTTPCacheControlMiddleware :: singleton ( ) -> setMaxAge ( $ age ) ; }
|
Set the maximum age of this page in web caches in seconds .
|
4,111
|
public static function augmentState ( HTTPRequest $ request , HTTPResponse $ response ) { $ config = Config :: forClass ( HTTP :: class ) ; if ( $ config -> get ( 'ignoreDeprecatedCaching' ) ) { return ; } $ cacheControlMiddleware = HTTPCacheControlMiddleware :: singleton ( ) ; if ( $ config -> get ( 'disable_http_cache' ) ) { Deprecation :: notice ( '5.0' , 'Use HTTPCacheControlMiddleware.defaultState/.defaultForcingLevel instead' ) ; $ cacheControlMiddleware -> disableCache ( ) ; } if ( ! $ config -> get ( 'cache_ajax_requests' ) && Director :: is_ajax ( ) ) { Deprecation :: notice ( '5.0' , 'HTTP.cache_ajax_requests config is deprecated. Use HTTPCacheControlMiddleware::disableCache() instead' ) ; $ cacheControlMiddleware -> disableCache ( ) ; } $ configVary = $ config -> get ( 'vary' ) ; if ( $ configVary ) { Deprecation :: notice ( '5.0' , 'Use HTTPCacheControlMiddleware.defaultVary instead' ) ; $ cacheControlMiddleware -> addVary ( $ configVary ) ; } $ configCacheControl = $ config -> get ( 'cache_control' ) ; if ( $ configCacheControl ) { Deprecation :: notice ( '5.0' , 'Use HTTPCacheControlMiddleware API instead' ) ; $ supportedDirectives = [ 'max-age' , 'no-cache' , 'no-store' , 'must-revalidate' ] ; if ( $ foundUnsupported = array_diff ( array_keys ( $ configCacheControl ) , $ supportedDirectives ) ) { throw new \ LogicException ( 'Found unsupported legacy directives in HTTP.cache_control: ' . implode ( ', ' , $ foundUnsupported ) . '. Please use HTTPCacheControlMiddleware API instead' ) ; } if ( isset ( $ configCacheControl [ 'max-age' ] ) ) { $ cacheControlMiddleware -> setMaxAge ( $ configCacheControl [ 'max-age' ] ) ; } if ( isset ( $ configCacheControl [ 'no-cache' ] ) ) { $ cacheControlMiddleware -> setNoCache ( ( bool ) $ configCacheControl [ 'no-cache' ] ) ; } if ( isset ( $ configCacheControl [ 'no-store' ] ) ) { $ cacheControlMiddleware -> setNoStore ( ( bool ) $ configCacheControl [ 'no-store' ] ) ; } if ( isset ( $ configCacheControl [ 'must-revalidate' ] ) ) { $ cacheControlMiddleware -> setMustRevalidate ( ( bool ) $ configCacheControl [ 'must-revalidate' ] ) ; } } if ( self :: $ modification_date ) { Deprecation :: notice ( '5.0' , 'Use HTTPCacheControlMiddleware::registerModificationDate() instead' ) ; $ cacheControlMiddleware -> registerModificationDate ( self :: $ modification_date ) ; } if ( self :: $ etag && ! $ cacheControlMiddleware -> hasDirective ( 'no-store' ) && ! $ response -> getHeader ( 'ETag' ) ) { Deprecation :: notice ( '5.0' , 'Etag should not be set explicitly' ) ; $ response -> addHeader ( 'ETag' , self :: $ etag ) ; } }
|
Ensure that all deprecated HTTP cache settings are respected
|
4,112
|
protected function applyOne ( DataQuery $ query ) { $ this -> model = $ query -> applyRelation ( $ this -> relation ) ; $ predicate = sprintf ( "%s %s ?" , $ this -> getDbName ( ) , $ this -> getOperator ( ) ) ; $ clause = [ $ predicate => $ this -> getDbFormattedValue ( ) ] ; return $ this -> aggregate ? $ this -> applyAggregate ( $ query , $ clause ) : $ query -> where ( $ clause ) ; }
|
Applies a comparison filter to the query Handles SQL escaping for both numeric and string values
|
4,113
|
public function dataClass ( ) { if ( $ this -> dataClass ) { return $ this -> dataClass ; } if ( count ( $ this -> items ) > 0 ) { return get_class ( $ this -> items [ 0 ] ) ; } return null ; }
|
Return the class of items in this list by looking at the first item inside it .
|
4,114
|
public function toNestedArray ( ) { $ result = [ ] ; foreach ( $ this -> items as $ item ) { if ( is_object ( $ item ) ) { if ( method_exists ( $ item , 'toMap' ) ) { $ result [ ] = $ item -> toMap ( ) ; } else { $ result [ ] = ( array ) $ item ; } } else { $ result [ ] = $ item ; } } return $ result ; }
|
Return this list as an array and every object it as an sub array as well
|
4,115
|
public function limit ( $ length , $ offset = 0 ) { if ( ! is_numeric ( $ length ) || ! is_numeric ( $ offset ) ) { Deprecation :: notice ( '4.3' , 'Arguments to ArrayList::limit() should be numeric' ) ; } if ( $ length < 0 || $ offset < 0 ) { Deprecation :: notice ( '4.3' , 'Arguments to ArrayList::limit() should be positive' ) ; } if ( ! $ length ) { if ( $ length === 0 ) { Deprecation :: notice ( '4.3' , "limit(0) is deprecated in SS4. In SS5 a limit of 0 will instead return no records." ) ; } $ length = count ( $ this -> items ) ; } $ list = clone $ this ; $ list -> items = array_slice ( $ this -> items , $ offset , $ length ) ; return $ list ; }
|
Get a sub - range of this dataobjectset as an array
|
4,116
|
public function remove ( $ item ) { $ renumberKeys = false ; foreach ( $ this -> items as $ key => $ value ) { if ( $ item === $ value ) { $ renumberKeys = true ; unset ( $ this -> items [ $ key ] ) ; } } if ( $ renumberKeys ) { $ this -> items = array_values ( $ this -> items ) ; } }
|
Remove this item from this list
|
4,117
|
public function replace ( $ item , $ with ) { foreach ( $ this -> items as $ key => $ candidate ) { if ( $ candidate === $ item ) { $ this -> items [ $ key ] = $ with ; return ; } } }
|
Replaces an item in this list with another item .
|
4,118
|
public function removeDuplicates ( $ field = 'ID' ) { $ seen = [ ] ; $ renumberKeys = false ; foreach ( $ this -> items as $ key => $ item ) { $ value = $ this -> extractValue ( $ item , $ field ) ; if ( array_key_exists ( $ value , $ seen ) ) { $ renumberKeys = true ; unset ( $ this -> items [ $ key ] ) ; } $ seen [ $ value ] = true ; } if ( $ renumberKeys ) { $ this -> items = array_values ( $ this -> items ) ; } return $ this ; }
|
Removes items from this list which have a duplicate value for a certain field . This is especially useful when combining lists .
|
4,119
|
public function find ( $ key , $ value ) { foreach ( $ this -> items as $ item ) { if ( $ this -> extractValue ( $ item , $ key ) == $ value ) { return $ item ; } } return null ; }
|
Find the first item of this list where the given key = value
|
4,120
|
public function column ( $ colName = 'ID' ) { $ result = [ ] ; foreach ( $ this -> items as $ item ) { $ result [ ] = $ this -> extractValue ( $ item , $ colName ) ; } return $ result ; }
|
Returns an array of a single field value for all items in the list .
|
4,121
|
public function sort ( ) { $ args = func_get_args ( ) ; if ( count ( $ args ) == 0 ) { return $ this ; } if ( count ( $ args ) > 2 ) { throw new InvalidArgumentException ( 'This method takes zero, one or two arguments' ) ; } $ columnsToSort = [ ] ; if ( count ( $ args ) == 1 && is_string ( $ args [ 0 ] ) ) { list ( $ column , $ direction ) = $ this -> parseSortColumn ( $ args [ 0 ] ) ; $ columnsToSort [ $ column ] = $ direction ; } elseif ( count ( $ args ) == 2 ) { list ( $ column , $ direction ) = $ this -> parseSortColumn ( $ args [ 0 ] , $ args [ 1 ] ) ; $ columnsToSort [ $ column ] = $ direction ; } elseif ( is_array ( $ args [ 0 ] ) ) { foreach ( $ args [ 0 ] as $ key => $ value ) { list ( $ column , $ direction ) = $ this -> parseSortColumn ( $ key , $ value ) ; $ columnsToSort [ $ column ] = $ direction ; } } else { throw new InvalidArgumentException ( "Bad arguments passed to sort()" ) ; } $ originalKeys = array_keys ( $ this -> items ) ; $ multisortArgs = [ ] ; $ values = [ ] ; $ firstRun = true ; foreach ( $ columnsToSort as $ column => $ direction ) { $ values [ $ column ] = [ ] ; $ sortDirection [ $ column ] = $ direction ; foreach ( $ this -> items as $ index => $ item ) { $ values [ $ column ] [ ] = strtolower ( $ this -> extractValue ( $ item , $ column ) ) ; } $ multisortArgs [ ] = & $ values [ $ column ] ; $ multisortArgs [ ] = & $ sortDirection [ $ column ] ; if ( $ firstRun ) { $ multisortArgs [ ] = SORT_REGULAR ; } $ firstRun = false ; } $ multisortArgs [ ] = & $ originalKeys ; $ list = clone $ this ; $ multisortArgs [ ] = & $ list -> items ; call_user_func_array ( 'array_multisort' , $ multisortArgs ) ; return $ list ; }
|
Sorts this list by one or more fields . You can either pass in a single field name and direction or a map of field names to sort directions .
|
4,122
|
public function canFilterBy ( $ by ) { if ( empty ( $ this -> items ) ) { return false ; } $ firstRecord = $ this -> first ( ) ; return array_key_exists ( $ by , $ firstRecord ) ; }
|
Returns true if the given column can be used to filter the records .
|
4,123
|
public function filter ( ) { $ keepUs = call_user_func_array ( [ $ this , 'normaliseFilterArgs' ] , func_get_args ( ) ) ; $ itemsToKeep = [ ] ; foreach ( $ this -> items as $ item ) { $ keepItem = true ; foreach ( $ keepUs as $ column => $ value ) { if ( ( is_array ( $ value ) && ! in_array ( $ this -> extractValue ( $ item , $ column ) , $ value ) ) || ( ! is_array ( $ value ) && $ this -> extractValue ( $ item , $ column ) != $ value ) ) { $ keepItem = false ; break ; } } if ( $ keepItem ) { $ itemsToKeep [ ] = $ item ; } } $ list = clone $ this ; $ list -> items = $ itemsToKeep ; return $ list ; }
|
Filter the list to include items with these charactaristics
|
4,124
|
public function filterAny ( ) { $ keepUs = $ this -> normaliseFilterArgs ( ... func_get_args ( ) ) ; $ itemsToKeep = [ ] ; foreach ( $ this -> items as $ item ) { foreach ( $ keepUs as $ column => $ value ) { $ extractedValue = $ this -> extractValue ( $ item , $ column ) ; $ matches = is_array ( $ value ) ? in_array ( $ extractedValue , $ value ) : $ extractedValue == $ value ; if ( $ matches ) { $ itemsToKeep [ ] = $ item ; break ; } } } $ list = clone $ this ; $ list -> items = array_unique ( $ itemsToKeep , SORT_REGULAR ) ; return $ list ; }
|
Return a copy of this list which contains items matching any of these charactaristics .
|
4,125
|
public function exclude ( ) { $ removeUs = $ this -> normaliseFilterArgs ( ... func_get_args ( ) ) ; $ hitsRequiredToRemove = count ( $ removeUs ) ; $ matches = [ ] ; foreach ( $ removeUs as $ column => $ excludeValue ) { foreach ( $ this -> items as $ key => $ item ) { if ( ! is_array ( $ excludeValue ) && $ this -> extractValue ( $ item , $ column ) == $ excludeValue ) { $ matches [ $ key ] = isset ( $ matches [ $ key ] ) ? $ matches [ $ key ] + 1 : 1 ; } elseif ( is_array ( $ excludeValue ) && in_array ( $ this -> extractValue ( $ item , $ column ) , $ excludeValue ) ) { $ matches [ $ key ] = isset ( $ matches [ $ key ] ) ? $ matches [ $ key ] + 1 : 1 ; } } } $ keysToRemove = array_keys ( $ matches , $ hitsRequiredToRemove ) ; $ itemsToKeep = [ ] ; foreach ( $ this -> items as $ key => $ value ) { if ( ! in_array ( $ key , $ keysToRemove ) ) { $ itemsToKeep [ ] = $ value ; } } $ list = clone $ this ; $ list -> items = $ itemsToKeep ; return $ list ; }
|
Exclude the list to not contain items with these charactaristics
|
4,126
|
public function changeToList ( RelationList $ list ) { foreach ( $ this -> items as $ key => $ item ) { $ list -> add ( $ item , $ this -> extraFields [ $ key ] ) ; } }
|
Save all the items in this list into the RelationList
|
4,127
|
public function push ( $ item , $ extraFields = null ) { if ( ( is_object ( $ item ) && ! $ item instanceof $ this -> dataClass ) || ( ! is_object ( $ item ) && ! is_numeric ( $ item ) ) ) { throw new InvalidArgumentException ( "UnsavedRelationList::add() expecting a $this->dataClass object, or ID value" , E_USER_ERROR ) ; } if ( is_object ( $ item ) && $ item -> ID ) { $ item = $ item -> ID ; } $ this -> extraFields [ ] = $ extraFields ; parent :: push ( $ item ) ; }
|
Pushes an item onto the end of this list .
|
4,128
|
public function toArray ( ) { $ items = array ( ) ; foreach ( $ this -> items as $ key => $ item ) { if ( is_numeric ( $ item ) ) { $ item = DataObject :: get_by_id ( $ this -> dataClass , $ item ) ; } if ( ! empty ( $ this -> extraFields [ $ key ] ) ) { $ item -> update ( $ this -> extraFields [ $ key ] ) ; } $ items [ ] = $ item ; } return $ items ; }
|
Return an array of the actual items that this relation contains at this stage . This is when the query is actually executed .
|
4,129
|
public function first ( ) { $ item = reset ( $ this -> items ) ; if ( is_numeric ( $ item ) ) { $ item = DataObject :: get_by_id ( $ this -> dataClass , $ item ) ; } if ( ! empty ( $ this -> extraFields [ key ( $ this -> items ) ] ) ) { $ item -> update ( $ this -> extraFields [ key ( $ this -> items ) ] ) ; } return $ item ; }
|
Returns the first item in the list
|
4,130
|
public function last ( ) { $ item = end ( $ this -> items ) ; if ( ! empty ( $ this -> extraFields [ key ( $ this -> items ) ] ) ) { $ item -> update ( $ this -> extraFields [ key ( $ this -> items ) ] ) ; } return $ item ; }
|
Returns the last item in the list
|
4,131
|
public function forForeignID ( $ id ) { $ singleton = DataObject :: singleton ( $ this -> baseClass ) ; $ relation = $ singleton -> { $ this -> relationName } ( $ id ) ; return $ relation ; }
|
Returns a copy of this list with the relationship linked to the given foreign ID .
|
4,132
|
protected function getPaginator ( $ gridField ) { $ paginator = $ gridField -> getConfig ( ) -> getComponentByType ( GridFieldPaginator :: class ) ; if ( ! $ paginator && GridFieldPageCount :: config ( ) -> uninherited ( 'require_paginator' ) ) { throw new LogicException ( static :: class . " relies on a GridFieldPaginator to be added " . "to the same GridField, but none are present." ) ; } return $ paginator ; }
|
Retrieves an instance of a GridFieldPaginator attached to the same control
|
4,133
|
public function getBaseClass ( ) { if ( $ this -> baseClass ) { return $ this -> baseClass ; } $ schema = DataObject :: getSchema ( ) ; if ( $ this -> record ) { return $ schema -> baseDataClass ( $ this -> record ) ; } $ tableClass = $ schema -> tableClass ( $ this -> getTable ( ) ) ; if ( $ tableClass && ( $ baseClass = $ schema -> baseDataClass ( $ tableClass ) ) ) { return $ baseClass ; } return DataObject :: class ; }
|
Get the base dataclass for the list of subclasses
|
4,134
|
public function getShortName ( ) { $ value = $ this -> getValue ( ) ; if ( empty ( $ value ) || ! ClassInfo :: exists ( $ value ) ) { return null ; } return ClassInfo :: shortName ( $ value ) ; }
|
Get the base name of the current class Useful as a non - fully qualified CSS Class name in templates .
|
4,135
|
public function getEnum ( ) { $ classNames = ClassInfo :: subclassesFor ( $ this -> getBaseClass ( ) ) ; $ dataobject = strtolower ( DataObject :: class ) ; unset ( $ classNames [ $ dataobject ] ) ; return array_values ( $ classNames ) ; }
|
Get list of classnames that should be selectable
|
4,136
|
public static function name_to_label ( $ fieldName ) { if ( strpos ( $ fieldName , '.' ) !== false ) { $ parts = explode ( '.' , $ fieldName ) ; $ label = implode ( array_map ( 'ucfirst' , $ parts ) ) ; } else { $ label = $ fieldName ; } $ labelWithSpaces = preg_replace_callback ( '/([A-Z])([a-z]+)/' , function ( $ matches ) { return ' ' . strtolower ( $ matches [ 1 ] ) . $ matches [ 2 ] ; } , $ label ) ; $ labelWithSpaces = preg_replace ( '/([a-z])([A-Z]+)$/' , '$1 $2' , $ labelWithSpaces ) ; return ucfirst ( trim ( $ labelWithSpaces ) ) ; }
|
Takes a field name and converts camelcase to spaced words . Also resolves combined field names with dot syntax to spaced words .
|
4,137
|
public function Link ( $ action = null ) { if ( ! $ this -> form ) { throw new LogicException ( 'Field must be associated with a form to call Link(). Please use $field->setForm($form);' ) ; } $ link = Controller :: join_links ( $ this -> form -> FormAction ( ) , 'field/' . $ this -> name , $ action ) ; $ this -> extend ( 'updateLink' , $ link , $ action ) ; return $ link ; }
|
Return a link to this field
|
4,138
|
public function getAttributes ( ) { $ attributes = array ( 'type' => $ this -> getInputType ( ) , 'name' => $ this -> getName ( ) , 'value' => $ this -> Value ( ) , 'class' => $ this -> extraClass ( ) , 'id' => $ this -> ID ( ) , 'disabled' => $ this -> isDisabled ( ) , 'readonly' => $ this -> isReadonly ( ) , 'autofocus' => $ this -> isAutofocus ( ) ) ; if ( $ this -> Required ( ) ) { $ attributes [ 'required' ] = 'required' ; $ attributes [ 'aria-required' ] = 'true' ; } $ attributes = array_merge ( $ attributes , $ this -> attributes ) ; $ this -> extend ( 'updateAttributes' , $ attributes ) ; return $ attributes ; }
|
Allows customization through an updateAttributes hook on the base class . Existing attributes are passed in as the first argument and can be manipulated but any attributes added through a subclass implementation won t be included .
|
4,139
|
public function Field ( $ properties = array ( ) ) { $ context = $ this ; $ this -> extend ( 'onBeforeRender' , $ context , $ properties ) ; if ( count ( $ properties ) ) { $ context = $ context -> customise ( $ properties ) ; } $ result = $ context -> renderWith ( $ this -> getTemplates ( ) ) ; if ( is_string ( $ result ) ) { $ result = trim ( $ result ) ; } elseif ( $ result instanceof DBField ) { $ result -> setValue ( trim ( $ result -> getValue ( ) ) ) ; } return $ result ; }
|
Returns the form field .
|
4,140
|
public function FieldHolder ( $ properties = array ( ) ) { $ context = $ this ; if ( count ( $ properties ) ) { $ context = $ this -> customise ( $ properties ) ; } return $ context -> renderWith ( $ this -> getFieldHolderTemplates ( ) ) ; }
|
Returns a field holder for this field .
|
4,141
|
protected function _templates ( $ customTemplate = null , $ customTemplateSuffix = null ) { $ templates = SSViewer :: get_templates_by_class ( static :: class , $ customTemplateSuffix , __CLASS__ ) ; if ( $ customTemplate ) { array_unshift ( $ templates , $ customTemplate ) ; } return $ templates ; }
|
Generate an array of class name strings to use for rendering this form field into HTML .
|
4,142
|
public function performReadonlyTransformation ( ) { $ readonlyClassName = static :: class . '_Readonly' ; if ( ClassInfo :: exists ( $ readonlyClassName ) ) { $ clone = $ this -> castedCopy ( $ readonlyClassName ) ; } else { $ clone = $ this -> castedCopy ( ReadonlyField :: class ) ; } $ clone -> setReadonly ( true ) ; return $ clone ; }
|
Returns a read - only version of this field .
|
4,143
|
public function performDisabledTransformation ( ) { $ disabledClassName = static :: class . '_Disabled' ; if ( ClassInfo :: exists ( $ disabledClassName ) ) { $ clone = $ this -> castedCopy ( $ disabledClassName ) ; } else { $ clone = clone $ this ; } $ clone -> setDisabled ( true ) ; return $ clone ; }
|
Return a disabled version of this field .
|
4,144
|
public function hasClass ( $ class ) { $ classes = explode ( ' ' , strtolower ( $ this -> extraClass ( ) ) ) ; return in_array ( strtolower ( trim ( $ class ) ) , $ classes ) ; }
|
Returns whether the current field has the given class added
|
4,145
|
public function castedCopy ( $ classOrCopy ) { $ field = $ classOrCopy ; if ( ! is_object ( $ field ) ) { $ field = $ classOrCopy :: create ( $ this -> name ) ; } $ field -> setValue ( $ this -> value ) -> setForm ( $ this -> form ) -> setTitle ( $ this -> Title ( ) ) -> setLeftTitle ( $ this -> LeftTitle ( ) ) -> setRightTitle ( $ this -> RightTitle ( ) ) -> addExtraClass ( $ this -> extraClass ) -> setDescription ( $ this -> getDescription ( ) ) ; foreach ( $ this -> attributes as $ attributeKey => $ attributeValue ) { $ field -> setAttribute ( $ attributeKey , $ attributeValue ) ; } return $ field ; }
|
Returns another instance of this field but cast to a different class . The logic tries to retain all of the instance properties and may be overloaded by subclasses to set additional ones .
|
4,146
|
public function getSchemaData ( ) { $ defaults = $ this -> getSchemaDataDefaults ( ) ; return array_replace_recursive ( $ defaults , array_intersect_key ( $ this -> schemaData , $ defaults ) ) ; }
|
Gets the schema data used to render the FormField on the front - end .
|
4,147
|
public function getSchemaState ( ) { $ defaults = $ this -> getSchemaStateDefaults ( ) ; return array_merge ( $ defaults , array_intersect_key ( $ this -> schemaState , $ defaults ) ) ; }
|
Gets the schema state used to render the FormField on the front - end .
|
4,148
|
public function getPageStart ( ) { $ request = $ this -> getRequest ( ) ; if ( $ this -> pageStart === null ) { if ( $ request && isset ( $ request [ $ this -> getPaginationGetVar ( ) ] ) && $ request [ $ this -> getPaginationGetVar ( ) ] > 0 ) { $ this -> pageStart = ( int ) $ request [ $ this -> getPaginationGetVar ( ) ] ; } else { $ this -> pageStart = 0 ; } } return $ this -> pageStart ; }
|
Returns the offset of the item the current page starts at .
|
4,149
|
public function getTotalItems ( ) { if ( $ this -> totalItems === null ) { $ this -> totalItems = count ( $ this -> list ) ; } return $ this -> totalItems ; }
|
Returns the total number of items in the unpaginated list .
|
4,150
|
public function setPaginationFromQuery ( SQLSelect $ query ) { if ( $ limit = $ query -> getLimit ( ) ) { $ this -> setPageLength ( $ limit [ 'limit' ] ) ; $ this -> setPageStart ( $ limit [ 'start' ] ) ; $ this -> setTotalItems ( $ query -> unlimitedRowCount ( ) ) ; } return $ this ; }
|
Sets the page length page start and total items from a query object s limit offset and unlimited count . The query MUST have a limit clause .
|
4,151
|
public function Pages ( $ max = null ) { $ result = new ArrayList ( ) ; if ( $ max ) { $ start = ( $ this -> CurrentPage ( ) - floor ( $ max / 2 ) ) - 1 ; $ end = $ this -> CurrentPage ( ) + floor ( $ max / 2 ) ; if ( $ start < 0 ) { $ start = 0 ; $ end = $ max ; } if ( $ end > $ this -> TotalPages ( ) ) { $ end = $ this -> TotalPages ( ) ; $ start = max ( 0 , $ end - $ max ) ; } } else { $ start = 0 ; $ end = $ this -> TotalPages ( ) ; } for ( $ i = $ start ; $ i < $ end ; $ i ++ ) { $ result -> push ( new ArrayData ( array ( 'PageNum' => $ i + 1 , 'Link' => HTTP :: setGetVar ( $ this -> getPaginationGetVar ( ) , $ i * $ this -> getPageLength ( ) , ( $ this -> request instanceof HTTPRequest ) ? $ this -> request -> getURL ( true ) : null ) , 'CurrentBool' => $ this -> CurrentPage ( ) == ( $ i + 1 ) ) ) ) ; } return $ result ; }
|
Returns a set of links to all the pages in the list . This is useful for basic pagination .
|
4,152
|
public function PaginationSummary ( $ context = 4 ) { $ result = new ArrayList ( ) ; $ current = $ this -> CurrentPage ( ) ; $ total = $ this -> TotalPages ( ) ; if ( $ context % 2 ) { $ context -- ; } if ( $ current == 1 || $ current == $ total ) { $ offset = $ context ; } else { $ offset = floor ( $ context / 2 ) ; } $ left = max ( $ current - $ offset , 1 ) ; $ right = min ( $ current + $ offset , $ total ) ; $ range = range ( $ current - $ offset , $ current + $ offset ) ; if ( $ left + $ context > $ total ) { $ left = $ total - $ context ; } for ( $ i = 0 ; $ i < $ total ; $ i ++ ) { $ link = HTTP :: setGetVar ( $ this -> getPaginationGetVar ( ) , $ i * $ this -> getPageLength ( ) , ( $ this -> request instanceof HTTPRequest ) ? $ this -> request -> getURL ( true ) : null ) ; $ num = $ i + 1 ; $ emptyRange = $ num != 1 && $ num != $ total && ( $ num == $ left - 1 || $ num == $ right + 1 ) ; if ( $ emptyRange ) { $ result -> push ( new ArrayData ( array ( 'PageNum' => null , 'Link' => null , 'CurrentBool' => false ) ) ) ; } elseif ( $ num == 1 || $ num == $ total || in_array ( $ num , $ range ) ) { $ result -> push ( new ArrayData ( array ( 'PageNum' => $ num , 'Link' => $ link , 'CurrentBool' => $ current == $ num ) ) ) ; } } return $ result ; }
|
Returns a summarised pagination which limits the number of pages shown around the current page for visually balanced .
|
4,153
|
public function LastItem ( ) { $ pageLength = $ this -> getPageLength ( ) ; if ( ! $ pageLength ) { return $ this -> getTotalItems ( ) ; } elseif ( $ start = $ this -> getPageStart ( ) ) { return min ( $ start + $ pageLength , $ this -> getTotalItems ( ) ) ; } else { return min ( $ pageLength , $ this -> getTotalItems ( ) ) ; } }
|
Returns the number of the last item being displayed on this page .
|
4,154
|
public function FirstLink ( ) { return HTTP :: setGetVar ( $ this -> getPaginationGetVar ( ) , 0 , ( $ this -> request instanceof HTTPRequest ) ? $ this -> request -> getURL ( true ) : null ) ; }
|
Returns a link to the first page .
|
4,155
|
public function LastLink ( ) { return HTTP :: setGetVar ( $ this -> getPaginationGetVar ( ) , ( $ this -> TotalPages ( ) - 1 ) * $ this -> getPageLength ( ) , ( $ this -> request instanceof HTTPRequest ) ? $ this -> request -> getURL ( true ) : null ) ; }
|
Returns a link to the last page .
|
4,156
|
public function NextLink ( ) { if ( $ this -> NotLastPage ( ) ) { return HTTP :: setGetVar ( $ this -> getPaginationGetVar ( ) , $ this -> getPageStart ( ) + $ this -> getPageLength ( ) , ( $ this -> request instanceof HTTPRequest ) ? $ this -> request -> getURL ( true ) : null ) ; } }
|
Returns a link to the next page if there is another page after the current one .
|
4,157
|
public function PrevLink ( ) { if ( $ this -> NotFirstPage ( ) ) { return HTTP :: setGetVar ( $ this -> getPaginationGetVar ( ) , $ this -> getPageStart ( ) - $ this -> getPageLength ( ) , ( $ this -> request instanceof HTTPRequest ) ? $ this -> request -> getURL ( true ) : null ) ; } }
|
Returns a link to the previous page if the first page is not currently active .
|
4,158
|
public static function addManyManyRelationshipFields ( FieldList & $ fields , $ relationship , $ overrideFieldClass , $ tabbed , DataObject $ dataObject ) { if ( $ tabbed ) { $ fields -> findOrMakeTab ( "Root.$relationship" , $ dataObject -> fieldLabel ( $ relationship ) ) ; } $ fieldClass = $ overrideFieldClass ? : GridField :: class ; $ grid = Injector :: inst ( ) -> create ( $ fieldClass , $ relationship , $ dataObject -> fieldLabel ( $ relationship ) , $ dataObject -> $ relationship ( ) , GridFieldConfig_RelationEditor :: create ( ) ) ; if ( $ tabbed ) { $ fields -> addFieldToTab ( "Root.$relationship" , $ grid ) ; } else { $ fields -> push ( $ grid ) ; } }
|
Adds the default many - many relation fields for the relationship provided .
|
4,159
|
public function register ( $ shortcode , $ callback ) { if ( is_callable ( $ callback ) ) { $ this -> shortcodes [ $ shortcode ] = $ callback ; } else { throw new InvalidArgumentException ( "Callback is not callable" ) ; } return $ this ; }
|
Register a shortcode and attach it to a PHP callback .
|
4,160
|
public function callShortcode ( $ tag , $ attributes , $ content , $ extra = array ( ) ) { if ( ! $ tag || ! isset ( $ this -> shortcodes [ $ tag ] ) ) { return false ; } return call_user_func ( $ this -> shortcodes [ $ tag ] , $ attributes , $ content , $ this , $ tag , $ extra ) ; }
|
Call a shortcode and return its replacement text Returns false if the shortcode isn t registered
|
4,161
|
protected function replaceTagsWithText ( $ content , $ tags , $ generator ) { $ str = '' ; $ li = null ; $ i = count ( $ tags ) ; while ( $ i -- ) { if ( $ li === null ) { $ tail = substr ( $ content , $ tags [ $ i ] [ 'e' ] ) ; } else { $ tail = substr ( $ content , $ tags [ $ i ] [ 'e' ] , $ li - $ tags [ $ i ] [ 'e' ] ) ; } if ( $ tags [ $ i ] [ 'escaped' ] ) { $ str = substr ( $ content , $ tags [ $ i ] [ 's' ] + 1 , $ tags [ $ i ] [ 'e' ] - $ tags [ $ i ] [ 's' ] - 2 ) . $ tail . $ str ; } else { $ str = $ generator ( $ i , $ tags [ $ i ] ) . $ tail . $ str ; } $ li = $ tags [ $ i ] [ 's' ] ; } return substr ( $ content , 0 , $ tags [ 0 ] [ 's' ] ) . $ str ; }
|
Replaces the shortcode tags extracted by extractTags with HTML element markers so that we can parse the resulting string as HTML and easily mutate the shortcodes in the DOM
|
4,162
|
protected function replaceAttributeTagsWithContent ( $ htmlvalue ) { $ attributes = $ htmlvalue -> query ( '//@*[contains(.,"[")][contains(.,"]")]' ) ; $ parser = $ this ; for ( $ i = 0 ; $ i < $ attributes -> length ; $ i ++ ) { $ node = $ attributes -> item ( $ i ) ; $ tags = $ this -> extractTags ( $ node -> nodeValue ) ; $ extra = array ( 'node' => $ node , 'element' => $ node -> ownerElement ) ; if ( $ tags ) { $ node -> nodeValue = $ this -> replaceTagsWithText ( htmlspecialchars ( $ node -> nodeValue ) , $ tags , function ( $ idx , $ tag ) use ( $ parser , $ extra ) { return $ parser -> getShortcodeReplacementText ( $ tag , $ extra , false ) ; } ) ; } } }
|
Replace the shortcodes in attribute values with the calculated content
|
4,163
|
protected function replaceElementTagsWithMarkers ( $ content ) { $ tags = $ this -> extractTags ( $ content ) ; if ( $ tags ) { $ markerClass = self :: $ marker_class ; $ content = $ this -> replaceTagsWithText ( $ content , $ tags , function ( $ idx , $ tag ) use ( $ markerClass ) { return '<img class="' . $ markerClass . '" data-tagid="' . $ idx . '" />' ; } ) ; } return array ( $ content , $ tags ) ; }
|
Replace the element - scoped tags with markers
|
4,164
|
protected function moveMarkerToCompliantHome ( $ node , $ parent , $ location ) { if ( $ location == self :: BEFORE ) { if ( isset ( $ parent -> parentNode ) ) { $ parent -> parentNode -> insertBefore ( $ node , $ parent ) ; } } elseif ( $ location == self :: AFTER ) { $ this -> insertAfter ( $ node , $ parent ) ; } elseif ( $ location == self :: SPLIT ) { $ at = $ node ; $ splitee = $ node -> parentNode ; while ( $ splitee !== $ parent -> parentNode ) { $ spliter = $ splitee -> cloneNode ( false ) ; $ this -> insertAfter ( $ spliter , $ splitee ) ; while ( $ at -> nextSibling ) { $ spliter -> appendChild ( $ at -> nextSibling ) ; } $ at = $ splitee ; $ splitee = $ splitee -> parentNode ; } $ this -> insertAfter ( $ node , $ parent ) ; } elseif ( $ location == self :: INLINE ) { if ( in_array ( strtolower ( $ node -> tagName ) , self :: $ block_level_elements ) ) { user_error ( 'Requested to insert block tag ' . $ node -> tagName . ' inline - probably this will break HTML compliance' , E_USER_WARNING ) ; } } else { user_error ( 'Unknown value for $location argument ' . $ location , E_USER_ERROR ) ; } }
|
Given a node with represents a shortcode marker and a location string mutates the DOM to put the marker in the compliant location
|
4,165
|
protected function replaceMarkerWithContent ( $ node , $ tag ) { $ content = $ this -> getShortcodeReplacementText ( $ tag ) ; if ( $ content ) { $ parsed = HTMLValue :: create ( $ content ) ; $ body = $ parsed -> getBody ( ) ; if ( $ body ) { $ this -> insertListAfter ( $ body -> childNodes , $ node ) ; } } $ this -> removeNode ( $ node ) ; }
|
Given a node with represents a shortcode marker and some information about the shortcode call the shortcode handler & replace the marker with the actual content
|
4,166
|
public function parse ( $ content ) { $ this -> extend ( 'onBeforeParse' , $ content ) ; $ continue = true ; if ( ! $ this -> shortcodes ) { $ continue = false ; } elseif ( ! trim ( $ content ) ) { $ continue = false ; } elseif ( strpos ( $ content , '[' ) === false ) { $ continue = false ; } if ( $ continue ) { list ( $ content , $ tags ) = $ this -> replaceElementTagsWithMarkers ( $ content ) ; $ htmlvalue = Injector :: inst ( ) -> create ( 'HTMLValue' , $ content ) ; if ( ! $ htmlvalue -> isValid ( ) ) { if ( self :: $ error_behavior == self :: ERROR ) { user_error ( 'Couldn\'t decode HTML when processing short codes' , E_USER_ERROR ) ; } else { $ continue = false ; } } } if ( $ continue ) { $ this -> replaceAttributeTagsWithContent ( $ htmlvalue ) ; $ shortcodes = $ htmlvalue -> query ( '//img[@class="' . self :: $ marker_class . '"]' ) ; $ parents = $ this -> findParentsForMarkers ( $ shortcodes ) ; foreach ( $ shortcodes as $ shortcode ) { $ tag = $ tags [ $ shortcode -> getAttribute ( 'data-tagid' ) ] ; $ parent = $ parents [ $ shortcode -> getAttribute ( 'data-parentid' ) ] ; $ class = null ; if ( ! empty ( $ tag [ 'attrs' ] [ 'location' ] ) ) { $ class = $ tag [ 'attrs' ] [ 'location' ] ; } elseif ( ! empty ( $ tag [ 'attrs' ] [ 'class' ] ) ) { $ class = $ tag [ 'attrs' ] [ 'class' ] ; } $ location = self :: INLINE ; if ( $ class == 'left' || $ class == 'right' ) { $ location = self :: BEFORE ; } if ( ! $ parent ) { if ( $ location !== self :: INLINE ) { user_error ( "Parent block for shortcode couldn't be found, but location wasn't INLINE" , E_USER_ERROR ) ; } } else { $ this -> moveMarkerToCompliantHome ( $ shortcode , $ parent , $ location ) ; } $ this -> replaceMarkerWithContent ( $ shortcode , $ tag ) ; } $ content = $ htmlvalue -> getContent ( ) ; $ parser = $ this ; $ content = preg_replace_callback ( '/<img[^>]+class="' . preg_quote ( self :: $ marker_class ) . '"[^>]+data-tagid="([^"]+)"[^>]*>/i' , function ( $ matches ) use ( $ tags , $ parser ) { $ tag = $ tags [ $ matches [ 1 ] ] ; return $ parser -> getShortcodeReplacementText ( $ tag ) ; } , $ content ) ; } $ this -> extend ( 'onAfterParse' , $ content ) ; return $ content ; }
|
Parse a string and replace any registered shortcodes within it with the result of the mapped callback .
|
4,167
|
public function getField ( $ field ) { $ value = $ this -> array [ $ field ] ; if ( is_object ( $ value ) && ! $ value instanceof ViewableData ) { return new ArrayData ( $ value ) ; } elseif ( ArrayLib :: is_associative ( $ value ) ) { return new ArrayData ( $ value ) ; } else { return $ value ; } }
|
Gets a field from this object .
|
4,168
|
public static function array_to_object ( $ arr = null ) { $ obj = new stdClass ( ) ; if ( $ arr ) { foreach ( $ arr as $ name => $ value ) { $ obj -> $ name = $ value ; } } return $ obj ; }
|
Converts an associative array to a simple object
|
4,169
|
public function getParser ( ) { if ( ! $ this -> parser ) { $ this -> parser = ( new ParserFactory ) -> create ( ParserFactory :: PREFER_PHP7 ) ; } return $ this -> parser ; }
|
Get or create active parser
|
4,170
|
public function getTraverser ( ) { if ( ! $ this -> traverser ) { $ this -> traverser = new NodeTraverser ; $ this -> traverser -> addVisitor ( new NameResolver ) ; $ this -> traverser -> addVisitor ( $ this -> getVisitor ( ) ) ; } return $ this -> traverser ; }
|
Get node traverser for parsing class files
|
4,171
|
public function getItemPath ( $ name ) { $ lowerName = strtolower ( $ name ) ; foreach ( [ $ this -> classes , $ this -> interfaces , $ this -> traits , ] as $ source ) { if ( isset ( $ source [ $ lowerName ] ) && file_exists ( $ source [ $ lowerName ] ) ) { return $ source [ $ lowerName ] ; } } return null ; }
|
Returns the file path to a class or interface if it exists in the manifest .
|
4,172
|
public function getItemName ( $ name ) { $ lowerName = strtolower ( $ name ) ; foreach ( [ $ this -> classNames , $ this -> interfaceNames , $ this -> traitNames , ] as $ source ) { if ( isset ( $ source [ $ lowerName ] ) ) { return $ source [ $ lowerName ] ; } } return null ; }
|
Return correct case name
|
4,173
|
public function getImplementorsOf ( $ interface ) { $ lowerInterface = strtolower ( $ interface ) ; if ( array_key_exists ( $ lowerInterface , $ this -> implementors ) ) { return $ this -> implementors [ $ lowerInterface ] ; } else { return array ( ) ; } }
|
Returns an array containing the class names that implement a certain interface .
|
4,174
|
public function regenerate ( $ includeTests ) { $ this -> loadState ( [ ] ) ; $ this -> roots = [ ] ; $ this -> children = [ ] ; $ finder = new ManifestFileFinder ( ) ; $ finder -> setOptions ( array ( 'name_regex' => '/^[^_].*\\.php$/' , 'ignore_files' => array ( 'index.php' , 'cli-script.php' ) , 'ignore_tests' => ! $ includeTests , 'file_callback' => function ( $ basename , $ pathname , $ depth ) use ( $ includeTests , $ finder ) { $ this -> handleFile ( $ basename , $ pathname , $ includeTests ) ; } , ) ) ; $ finder -> find ( $ this -> base ) ; foreach ( $ this -> roots as $ root ) { $ this -> coalesceDescendants ( $ root ) ; } if ( $ this -> cache ) { $ data = $ this -> getState ( ) ; $ this -> cache -> set ( $ this -> cacheKey , $ data ) ; } }
|
Completely regenerates the manifest file .
|
4,175
|
protected function coalesceDescendants ( $ class ) { $ lowerClass = strtolower ( $ class ) ; if ( empty ( $ this -> children [ $ lowerClass ] ) ) { return [ ] ; } $ this -> descendants [ $ lowerClass ] = $ this -> children [ $ lowerClass ] ; foreach ( $ this -> children [ $ lowerClass ] as $ childClass ) { $ this -> descendants [ $ lowerClass ] = array_merge ( $ this -> descendants [ $ lowerClass ] , $ this -> coalesceDescendants ( $ childClass ) ) ; } return $ this -> descendants [ $ lowerClass ] ; }
|
Recursively coalesces direct child information into full descendant information .
|
4,176
|
protected function loadState ( $ data ) { $ success = true ; foreach ( $ this -> serialisedProperties as $ property ) { if ( ! isset ( $ data [ $ property ] ) || ! is_array ( $ data [ $ property ] ) ) { $ success = false ; $ value = [ ] ; } else { $ value = $ data [ $ property ] ; } $ this -> $ property = $ value ; } return $ success ; }
|
Reload state from given cache data
|
4,177
|
protected function getState ( ) { $ data = [ ] ; foreach ( $ this -> serialisedProperties as $ property ) { $ data [ $ property ] = $ this -> $ property ; } return $ data ; }
|
Load current state into an array of data
|
4,178
|
protected function validateItemCache ( $ data ) { if ( ! $ data || ! is_array ( $ data ) ) { return false ; } foreach ( [ 'classes' , 'interfaces' , 'traits' ] as $ key ) { if ( ! isset ( $ data [ $ key ] ) ) { return false ; } if ( ! is_array ( $ data [ $ key ] ) ) { return false ; } $ array = $ data [ $ key ] ; if ( ! empty ( $ array ) && is_numeric ( key ( $ array ) ) ) { return false ; } } return true ; }
|
Verify that cached data is valid for a single item
|
4,179
|
public function getDocument ( ) { if ( ! $ this -> valid ) { return false ; } elseif ( $ this -> document ) { return $ this -> document ; } else { $ this -> document = new DOMDocument ( '1.0' , 'UTF-8' ) ; $ this -> document -> strictErrorChecking = false ; $ this -> document -> formatOutput = false ; return $ this -> document ; } }
|
Get the DOMDocument for the passed content
|
4,180
|
public function getModelClass ( ) { if ( $ this -> modelClassName ) { return $ this -> modelClassName ; } $ list = $ this -> list ; if ( $ list && $ list -> hasMethod ( 'dataClass' ) ) { $ class = $ list -> dataClass ( ) ; if ( $ class ) { return $ class ; } } throw new LogicException ( 'GridField doesn\'t have a modelClassName, so it doesn\'t know the columns of this grid.' ) ; }
|
Returns a data class that is a DataObject type that this GridField should look like .
|
4,181
|
public function performReadonlyTransformation ( ) { $ copy = clone $ this ; $ copy -> setReadonly ( true ) ; $ copyConfig = $ copy -> getConfig ( ) ; $ allowedComponents = $ this -> getReadonlyComponents ( ) ; foreach ( $ this -> getConfig ( ) -> getComponents ( ) as $ component ) { if ( ! in_array ( get_class ( $ component ) , $ allowedComponents ) ) { $ copyConfig -> removeComponent ( $ component ) ; } } if ( ! $ copyConfig -> getComponentByType ( GridFieldViewButton :: class ) ) { $ copyConfig -> addComponent ( new GridFieldViewButton ) ; } return $ copy ; }
|
Custom Readonly transformation to remove actions which shouldn t be present for a readonly state .
|
4,182
|
public function getColumns ( ) { $ columns = array ( ) ; foreach ( $ this -> getComponents ( ) as $ item ) { if ( $ item instanceof GridField_ColumnProvider ) { $ item -> augmentColumns ( $ this , $ columns ) ; } } return $ columns ; }
|
Get the columns of this GridField they are provided by attached GridField_ColumnProvider .
|
4,183
|
public function getColumnContent ( $ record , $ column ) { if ( ! $ this -> columnDispatch ) { $ this -> buildColumnDispatch ( ) ; } if ( ! empty ( $ this -> columnDispatch [ $ column ] ) ) { $ content = '' ; foreach ( $ this -> columnDispatch [ $ column ] as $ handler ) { $ content .= $ handler -> getColumnContent ( $ this , $ record , $ column ) ; } return $ content ; } else { throw new InvalidArgumentException ( sprintf ( 'Bad column "%s"' , $ column ) ) ; } }
|
Get the value from a column .
|
4,184
|
public function addDataFields ( $ fields ) { if ( $ this -> customDataFields ) { $ this -> customDataFields = array_merge ( $ this -> customDataFields , $ fields ) ; } else { $ this -> customDataFields = $ fields ; } }
|
Add additional calculated data fields to be used on this GridField
|
4,185
|
public function getDataFieldValue ( $ record , $ fieldName ) { if ( isset ( $ this -> customDataFields [ $ fieldName ] ) ) { $ callback = $ this -> customDataFields [ $ fieldName ] ; return $ callback ( $ record ) ; } if ( $ record -> hasMethod ( 'relField' ) ) { return $ record -> relField ( $ fieldName ) ; } if ( $ record -> hasMethod ( $ fieldName ) ) { return $ record -> $ fieldName ( ) ; } return $ record -> $ fieldName ; }
|
Get the value of a named field on the given record .
|
4,186
|
public function getColumnAttributes ( $ record , $ column ) { if ( ! $ this -> columnDispatch ) { $ this -> buildColumnDispatch ( ) ; } if ( ! empty ( $ this -> columnDispatch [ $ column ] ) ) { $ attributes = array ( ) ; foreach ( $ this -> columnDispatch [ $ column ] as $ handler ) { $ columnAttributes = $ handler -> getColumnAttributes ( $ this , $ record , $ column ) ; if ( is_array ( $ columnAttributes ) ) { $ attributes = array_merge ( $ attributes , $ columnAttributes ) ; continue ; } throw new LogicException ( sprintf ( 'Non-array response from %s::getColumnAttributes().' , get_class ( $ handler ) ) ) ; } return $ attributes ; } throw new InvalidArgumentException ( sprintf ( 'Bad column "%s"' , $ column ) ) ; }
|
Get extra columns attributes used as HTML attributes .
|
4,187
|
public function getColumnMetadata ( $ column ) { if ( ! $ this -> columnDispatch ) { $ this -> buildColumnDispatch ( ) ; } if ( ! empty ( $ this -> columnDispatch [ $ column ] ) ) { $ metaData = array ( ) ; foreach ( $ this -> columnDispatch [ $ column ] as $ handler ) { $ columnMetaData = $ handler -> getColumnMetadata ( $ this , $ column ) ; if ( is_array ( $ columnMetaData ) ) { $ metaData = array_merge ( $ metaData , $ columnMetaData ) ; continue ; } throw new LogicException ( sprintf ( 'Non-array response from %s::getColumnMetadata().' , get_class ( $ handler ) ) ) ; } return $ metaData ; } throw new InvalidArgumentException ( sprintf ( 'Bad column "%s"' , $ column ) ) ; }
|
Get metadata for a column .
|
4,188
|
protected function buildColumnDispatch ( ) { $ this -> columnDispatch = array ( ) ; foreach ( $ this -> getComponents ( ) as $ item ) { if ( $ item instanceof GridField_ColumnProvider ) { $ columns = $ item -> getColumnsHandled ( $ this ) ; foreach ( $ columns as $ column ) { $ this -> columnDispatch [ $ column ] [ ] = $ item ; } } } }
|
Build an columnDispatch that maps a GridField_ColumnProvider to a column for reference later .
|
4,189
|
public function gridFieldAlterAction ( $ data , $ form , HTTPRequest $ request ) { $ data = $ request -> requestVars ( ) ; $ token = $ this -> getForm ( ) -> getSecurityToken ( ) ; if ( ! $ token -> checkRequest ( $ request ) ) { $ this -> httpError ( 400 , _t ( "SilverStripe\\Forms\\Form.CSRF_FAILED_MESSAGE" , "There seems to have been a technical problem. Please click the back button, " . "refresh your browser, and try again." ) ) ; } $ name = $ this -> getName ( ) ; $ fieldData = null ; if ( isset ( $ data [ $ name ] ) ) { $ fieldData = $ data [ $ name ] ; } $ state = $ this -> getState ( false ) ; if ( isset ( $ fieldData [ 'GridState' ] ) ) { $ state -> setValue ( $ fieldData [ 'GridState' ] ) ; } $ store = Injector :: inst ( ) -> create ( StateStore :: class . '.' . $ this -> getName ( ) ) ; foreach ( $ data as $ dataKey => $ dataValue ) { if ( preg_match ( '/^action_gridFieldAlterAction\?StateID=(.*)/' , $ dataKey , $ matches ) ) { $ stateChange = $ store -> load ( $ matches [ 1 ] ) ; $ actionName = $ stateChange [ 'actionName' ] ; $ arguments = array ( ) ; if ( isset ( $ stateChange [ 'args' ] ) ) { $ arguments = $ stateChange [ 'args' ] ; } ; $ html = $ this -> handleAlterAction ( $ actionName , $ arguments , $ data ) ; if ( $ html ) { return $ html ; } } } if ( $ request -> getHeader ( 'X-Pjax' ) === 'CurrentField' ) { if ( $ this -> getState ( ) -> Readonly === true ) { $ this -> performDisabledTransformation ( ) ; } return $ this -> FieldHolder ( ) ; } return $ form -> forTemplate ( ) ; }
|
This is the action that gets executed when a GridField_AlterAction gets clicked .
|
4,190
|
public function handleRequest ( HTTPRequest $ request ) { if ( $ this -> brokenOnConstruct ) { user_error ( sprintf ( "parent::__construct() needs to be called on %s::__construct()" , __CLASS__ ) , E_USER_WARNING ) ; } $ this -> setRequest ( $ request ) ; $ fieldData = $ this -> getRequest ( ) -> requestVar ( $ this -> getName ( ) ) ; if ( $ fieldData && isset ( $ fieldData [ 'GridState' ] ) ) { $ this -> getState ( false ) -> setValue ( $ fieldData [ 'GridState' ] ) ; } foreach ( $ this -> getComponents ( ) as $ component ) { if ( $ component instanceof GridField_URLHandler && $ urlHandlers = $ component -> getURLHandlers ( $ this ) ) { foreach ( $ urlHandlers as $ rule => $ action ) { if ( $ params = $ request -> match ( $ rule , true ) ) { if ( $ action [ 0 ] == '$' ) { $ action = $ params [ substr ( $ action , 1 ) ] ; } if ( ! method_exists ( $ component , 'checkAccessAction' ) || $ component -> checkAccessAction ( $ action ) ) { if ( ! $ action ) { $ action = "index" ; } if ( ! is_string ( $ action ) ) { throw new LogicException ( sprintf ( 'Non-string method name: %s' , var_export ( $ action , true ) ) ) ; } try { $ result = $ component -> $ action ( $ this , $ request ) ; } catch ( HTTPResponse_Exception $ responseException ) { $ result = $ responseException -> getResponse ( ) ; } if ( $ result instanceof HTTPResponse && $ result -> isError ( ) ) { return $ result ; } if ( $ this !== $ result && ! $ request -> isEmptyPattern ( $ rule ) && ( $ result instanceof RequestHandler || $ result instanceof HasRequestHandler ) ) { if ( $ result instanceof HasRequestHandler ) { $ result = $ result -> getRequestHandler ( ) ; } $ returnValue = $ result -> handleRequest ( $ request ) ; if ( is_array ( $ returnValue ) ) { throw new LogicException ( 'GridField_URLHandler handlers can\'t return arrays' ) ; } return $ returnValue ; } if ( $ request -> allParsed ( ) ) { return $ result ; } return $ this -> httpError ( 404 , sprintf ( 'I can\'t handle sub-URLs of a %s object.' , get_class ( $ result ) ) ) ; } } } } } return parent :: handleRequest ( $ request ) ; }
|
Custom request handler that will check component handlers before proceeding to the default implementation .
|
4,191
|
public static function setDefaultAdmin ( $ username , $ password ) { if ( static :: hasDefaultAdmin ( ) ) { throw new BadMethodCallException ( "Default admin already exists. Use clearDefaultAdmin() first." ) ; } if ( empty ( $ username ) || empty ( $ password ) ) { throw new InvalidArgumentException ( "Default admin username / password cannot be empty" ) ; } static :: $ default_username = $ username ; static :: $ default_password = $ password ; static :: $ has_default_admin = true ; }
|
Set the default admin credentials
|
4,192
|
public static function hasDefaultAdmin ( ) { if ( ! isset ( static :: $ has_default_admin ) ) { return ! empty ( Environment :: getEnv ( 'SS_DEFAULT_ADMIN_USERNAME' ) ) && ! empty ( Environment :: getEnv ( 'SS_DEFAULT_ADMIN_PASSWORD' ) ) ; } return static :: $ has_default_admin ; }
|
Check if there is a default admin
|
4,193
|
public function findOrCreateAdmin ( $ email , $ name = null ) { $ this -> extend ( 'beforeFindOrCreateAdmin' , $ email , $ name ) ; $ admin = Member :: get ( ) -> filter ( 'Email' , $ email ) -> first ( ) ; $ adminGroup = $ this -> findOrCreateAdminGroup ( ) ; if ( $ admin ) { $ inGroup = $ admin -> inGroup ( $ adminGroup ) ; } else { $ inGroup = false ; $ admin = Member :: create ( ) ; $ admin -> FirstName = $ name ? : $ email ; $ admin -> Email = $ email ; $ admin -> PasswordEncryption = 'none' ; $ admin -> write ( ) ; } if ( ! $ inGroup ) { $ adminGroup -> DirectMembers ( ) -> add ( $ admin ) ; } $ this -> extend ( 'afterFindOrCreateAdmin' , $ admin ) ; return $ admin ; }
|
Find or create a Member with admin permissions
|
4,194
|
protected function findOrCreateAdminGroup ( ) { $ adminGroup = Permission :: get_groups_by_permission ( 'ADMIN' ) -> first ( ) ; if ( $ adminGroup ) { return $ adminGroup ; } Group :: singleton ( ) -> requireDefaultRecords ( ) ; $ adminGroup = Permission :: get_groups_by_permission ( 'ADMIN' ) -> first ( ) ; if ( $ adminGroup ) { return $ adminGroup ; } $ adminGroup = Group :: create ( ) ; $ adminGroup -> Code = 'administrators' ; $ adminGroup -> Title = _t ( 'SilverStripe\\Security\\Group.DefaultGroupTitleAdministrators' , 'Administrators' ) ; $ adminGroup -> Sort = 0 ; $ adminGroup -> write ( ) ; Permission :: grant ( $ adminGroup -> ID , 'ADMIN' ) ; return $ adminGroup ; }
|
Ensure a Group exists with admin permission
|
4,195
|
public function redirectToLostPassword ( ) { $ lostPasswordLink = Security :: singleton ( ) -> Link ( 'lostpassword' ) ; return $ this -> redirect ( $ this -> addBackURLParam ( $ lostPasswordLink ) ) ; }
|
Redirect to password recovery form
|
4,196
|
public function forgotPassword ( $ data , $ form ) { $ dataValidation = $ this -> validateForgotPasswordData ( $ data , $ form ) ; if ( $ dataValidation instanceof HTTPResponse ) { return $ dataValidation ; } $ member = $ this -> getMemberFromData ( $ data ) ; $ results = $ this -> extend ( 'forgotPassword' , $ member ) ; if ( $ results && is_array ( $ results ) && in_array ( false , $ results , true ) ) { return $ this -> redirectToLostPassword ( ) ; } if ( $ member ) { $ token = $ member -> generateAutologinTokenAndStoreHash ( ) ; $ this -> sendEmail ( $ member , $ token ) ; } return $ this -> redirectToSuccess ( $ data ) ; }
|
Forgot password form handler method . Called when the user clicks on I ve lost my password . Extensions can use the forgotPassword method to veto executing the logic by returning FALSE . In this case the user will be redirected back to the form without further action . It is recommended to set a message in the form detailing why the action was denied .
|
4,197
|
protected function validateForgotPasswordData ( array $ data , LostPasswordForm $ form ) { if ( empty ( $ data [ 'Email' ] ) ) { $ form -> sessionMessage ( _t ( 'SilverStripe\\Security\\Member.ENTEREMAIL' , 'Please enter an email address to get a password reset link.' ) , 'bad' ) ; return $ this -> redirectToLostPassword ( ) ; } }
|
Ensure that the user has provided an email address . Note that the Email key is specific to this implementation but child classes can override this method to use another unique identifier field for validation .
|
4,198
|
protected function getMemberFromData ( array $ data ) { if ( ! empty ( $ data [ 'Email' ] ) ) { $ uniqueIdentifier = Member :: config ( ) -> get ( 'unique_identifier_field' ) ; return Member :: get ( ) -> filter ( [ $ uniqueIdentifier => $ data [ 'Email' ] ] ) -> first ( ) ; } }
|
Load an existing Member from the provided data
|
4,199
|
protected function sendEmail ( $ member , $ token ) { $ email = Email :: create ( ) -> setHTMLTemplate ( 'SilverStripe\\Control\\Email\\ForgotPasswordEmail' ) -> setData ( $ member ) -> setSubject ( _t ( 'SilverStripe\\Security\\Member.SUBJECTPASSWORDRESET' , "Your password reset link" , 'Email subject' ) ) -> addData ( 'PasswordResetLink' , Security :: getPasswordResetLink ( $ member , $ token ) ) -> setTo ( $ member -> Email ) ; return $ email -> send ( ) ; }
|
Send the email to the member that requested a reset link
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.