idx
int64 0
60.3k
| question
stringlengths 101
6.21k
| target
stringlengths 7
803
|
|---|---|---|
4,900
|
public function getPublicDir ( ) { $ base = $ this -> getBaseDir ( ) ; $ public = Path :: join ( $ base , 'public' ) . DIRECTORY_SEPARATOR ; if ( file_exists ( $ public ) ) { return $ public ; } return $ base ; }
|
Get path to public directory
|
4,901
|
public function checkModuleExists ( $ dirname ) { if ( in_array ( $ dirname , [ 'mysite' , 'app' ] ) ) { return file_exists ( $ this -> getBaseDir ( ) . $ dirname ) ; } $ paths = [ "vendor/silverstripe/{$dirname}/" , "{$dirname}/" , ] ; foreach ( $ paths as $ path ) { $ checks = [ '_config' , '_config.php' ] ; foreach ( $ checks as $ check ) { if ( file_exists ( $ this -> getBaseDir ( ) . $ path . $ check ) ) { return true ; } } } return false ; }
|
Check that a module exists
|
4,902
|
public function isIIS ( $ fromVersion = 7 ) { $ webserver = $ this -> findWebserver ( ) ; if ( preg_match ( '#.*IIS/(?<version>[.\\d]+)$#' , $ webserver , $ matches ) ) { return version_compare ( $ matches [ 'version' ] , $ fromVersion , '>=' ) ; } return false ; }
|
Check if the web server is IIS and version greater than the given version .
|
4,903
|
public function findWebserver ( ) { if ( ! empty ( $ _SERVER [ 'SERVER_SIGNATURE' ] ) ) { $ webserver = $ _SERVER [ 'SERVER_SIGNATURE' ] ; } elseif ( ! empty ( $ _SERVER [ 'SERVER_SOFTWARE' ] ) ) { $ webserver = $ _SERVER [ 'SERVER_SOFTWARE' ] ; } else { return false ; } return strip_tags ( trim ( $ webserver ) ) ; }
|
Find the webserver software running on the PHP host .
|
4,904
|
public function set_stat ( $ name , $ value ) { Deprecation :: notice ( '5.0' , 'Use ->config()->set()' ) ; $ this -> config ( ) -> set ( $ name , $ value ) ; return $ this ; }
|
Update the config value for a given property
|
4,905
|
public function typeCorrectedFetchAll ( ) { if ( $ this -> columnMeta === null ) { $ columnCount = $ this -> statement -> columnCount ( ) ; $ this -> columnMeta = [ ] ; for ( $ i = 0 ; $ i < $ columnCount ; $ i ++ ) { $ this -> columnMeta [ $ i ] = $ this -> statement -> getColumnMeta ( $ i ) ; } } return array_map ( function ( $ rowArray ) { $ row = [ ] ; foreach ( $ this -> columnMeta as $ i => $ meta ) { if ( isset ( $ meta [ 'native_type' ] ) && isset ( self :: $ type_mapping [ $ meta [ 'native_type' ] ] ) ) { settype ( $ rowArray [ $ i ] , self :: $ type_mapping [ $ meta [ 'native_type' ] ] ) ; } $ row [ $ meta [ 'name' ] ] = $ rowArray [ $ i ] ; } return $ row ; } , $ this -> statement -> fetchAll ( PDO :: FETCH_NUM ) ) ; }
|
Fetch a record form the statement with its type data corrected Returns data as an array of maps
|
4,906
|
public static function filter_backtrace ( $ bt , $ ignoredFunctions = null ) { $ defaultIgnoredFunctions = array ( 'SilverStripe\\Logging\\Log::log' , 'SilverStripe\\Dev\\Backtrace::backtrace' , 'SilverStripe\\Dev\\Backtrace::filtered_backtrace' , 'Zend_Log_Writer_Abstract->write' , 'Zend_Log->log' , 'Zend_Log->__call' , 'Zend_Log->err' , 'SilverStripe\\Dev\\DebugView->writeTrace' , 'SilverStripe\\Dev\\CliDebugView->writeTrace' , 'SilverStripe\\Dev\\Debug::emailError' , 'SilverStripe\\Dev\\Debug::warningHandler' , 'SilverStripe\\Dev\\Debug::noticeHandler' , 'SilverStripe\\Dev\\Debug::fatalHandler' , 'errorHandler' , 'SilverStripe\\Dev\\Debug::showError' , 'SilverStripe\\Dev\\Debug::backtrace' , 'exceptionHandler' ) ; if ( $ ignoredFunctions ) { foreach ( $ ignoredFunctions as $ ignoredFunction ) { $ defaultIgnoredFunctions [ ] = $ ignoredFunction ; } } while ( $ bt && in_array ( self :: full_func_name ( $ bt [ 0 ] ) , $ defaultIgnoredFunctions ) ) { array_shift ( $ bt ) ; } $ ignoredArgs = static :: config ( ) -> get ( 'ignore_function_args' ) ; foreach ( $ bt as $ i => $ frame ) { $ match = false ; if ( ! empty ( $ bt [ $ i ] [ 'class' ] ) ) { foreach ( $ ignoredArgs as $ fnSpec ) { if ( is_array ( $ fnSpec ) && ( '*' == $ fnSpec [ 0 ] || $ bt [ $ i ] [ 'class' ] == $ fnSpec [ 0 ] ) && $ bt [ $ i ] [ 'function' ] == $ fnSpec [ 1 ] ) { $ match = true ; } } } else { if ( in_array ( $ bt [ $ i ] [ 'function' ] , $ ignoredArgs ) ) { $ match = true ; } } if ( $ match ) { foreach ( $ bt [ $ i ] [ 'args' ] as $ j => $ arg ) { $ bt [ $ i ] [ 'args' ] [ $ j ] = '<filtered>' ; } } } return $ bt ; }
|
Filter a backtrace so that it doesn t show the calls to the debugging system which is useless information .
|
4,907
|
public static function backtrace ( $ returnVal = false , $ ignoreAjax = false , $ ignoredFunctions = null ) { $ plainText = Director :: is_cli ( ) || ( Director :: is_ajax ( ) && ! $ ignoreAjax ) ; $ result = self :: get_rendered_backtrace ( debug_backtrace ( ) , $ plainText , $ ignoredFunctions ) ; if ( $ returnVal ) { return $ result ; } else { echo $ result ; return null ; } }
|
Render or return a backtrace from the given scope .
|
4,908
|
public static function full_func_name ( $ item , $ showArgs = false , $ argCharLimit = 10000 ) { $ funcName = '' ; if ( isset ( $ item [ 'class' ] ) ) { $ funcName .= $ item [ 'class' ] ; } if ( isset ( $ item [ 'type' ] ) ) { $ funcName .= $ item [ 'type' ] ; } if ( isset ( $ item [ 'function' ] ) ) { $ funcName .= $ item [ 'function' ] ; } if ( $ showArgs && isset ( $ item [ 'args' ] ) ) { $ args = array ( ) ; foreach ( $ item [ 'args' ] as $ arg ) { if ( ! is_object ( $ arg ) || method_exists ( $ arg , '__toString' ) ) { $ sarg = is_array ( $ arg ) ? 'Array' : strval ( $ arg ) ; $ args [ ] = ( strlen ( $ sarg ) > $ argCharLimit ) ? substr ( $ sarg , 0 , $ argCharLimit ) . '...' : $ sarg ; } else { $ args [ ] = get_class ( $ arg ) ; } } $ funcName .= "(" . implode ( ", " , $ args ) . ")" ; } return $ funcName ; }
|
Return the full function name . If showArgs is set to true a string representation of the arguments will be shown
|
4,909
|
public static function get_rendered_backtrace ( $ bt , $ plainText = false , $ ignoredFunctions = null ) { if ( empty ( $ bt ) ) { return '' ; } $ bt = self :: filter_backtrace ( $ bt , $ ignoredFunctions ) ; $ result = ( $ plainText ) ? '' : '<ul>' ; foreach ( $ bt as $ item ) { if ( $ plainText ) { $ result .= self :: full_func_name ( $ item , true ) . "\n" ; if ( isset ( $ item [ 'line' ] ) && isset ( $ item [ 'file' ] ) ) { $ result .= basename ( $ item [ 'file' ] ) . ":$item[line]\n" ; } $ result .= "\n" ; } else { if ( $ item [ 'function' ] == 'user_error' ) { $ name = $ item [ 'args' ] [ 0 ] ; } else { $ name = self :: full_func_name ( $ item , true ) ; } $ result .= "<li><b>" . htmlentities ( $ name , ENT_COMPAT , 'UTF-8' ) . "</b>\n<br />\n" ; $ result .= isset ( $ item [ 'file' ] ) ? htmlentities ( basename ( $ item [ 'file' ] ) , ENT_COMPAT , 'UTF-8' ) : '' ; $ result .= isset ( $ item [ 'line' ] ) ? ":$item[line]" : '' ; $ result .= "</li>\n" ; } } if ( ! $ plainText ) { $ result .= '</ul>' ; } return $ result ; }
|
Render a backtrace array into an appropriate plain - text or HTML string .
|
4,910
|
public function createRoot ( ) { $ instance = new CachedConfigCollection ( ) ; $ instance -> setNestFactory ( function ( $ collection ) { return DeltaConfigCollection :: createFromCollection ( $ collection , Config :: NO_DELTAS ) ; } ) ; if ( $ this -> cacheFactory ) { $ cache = $ this -> cacheFactory -> create ( CacheInterface :: class . '.configcache' , [ 'namespace' => 'configcache' ] ) ; $ instance -> setCache ( $ cache ) ; } $ instance -> setCollectionCreator ( function ( ) { return $ this -> createCore ( ) ; } ) ; return $ instance ; }
|
Create root application config . This will be an immutable cached config which conditionally generates a nested core config .
|
4,911
|
public function createCore ( ) { $ config = new MemoryConfigCollection ( ) ; $ config -> setMiddlewares ( [ new InheritanceMiddleware ( Config :: UNINHERITED ) , new ExtensionMiddleware ( Config :: EXCLUDE_EXTRA_SOURCES ) , ] ) ; $ config -> transform ( [ $ this -> buildStaticTransformer ( ) , $ this -> buildYamlTransformer ( ) ] ) ; return $ config ; }
|
Rebuild new uncached config which is mutable
|
4,912
|
public function reset ( ) { $ this -> tableNames = [ ] ; $ this -> databaseFields = [ ] ; $ this -> databaseIndexes = [ ] ; $ this -> defaultDatabaseIndexes = [ ] ; $ this -> compositeFields = [ ] ; }
|
Clear cached table names
|
4,913
|
public function tableName ( $ class ) { $ tables = $ this -> getTableNames ( ) ; $ class = ClassInfo :: class_name ( $ class ) ; if ( isset ( $ tables [ $ class ] ) ) { return Convert :: raw2sql ( $ tables [ $ class ] ) ; } return null ; }
|
Get table name for the given class .
|
4,914
|
public function fieldSpecs ( $ classOrInstance , $ options = 0 ) { $ class = ClassInfo :: class_name ( $ classOrInstance ) ; if ( ! is_int ( $ options ) ) { throw new InvalidArgumentException ( "Invalid options " . var_export ( $ options , true ) ) ; } $ uninherited = ( $ options & self :: UNINHERITED ) === self :: UNINHERITED ; $ dbOnly = ( $ options & self :: DB_ONLY ) === self :: DB_ONLY ; $ includeClass = ( $ options & self :: INCLUDE_CLASS ) === self :: INCLUDE_CLASS ; $ db = [ ] ; $ classes = $ uninherited ? [ $ class ] : ClassInfo :: ancestry ( $ class ) ; foreach ( $ classes as $ tableClass ) { if ( ! is_subclass_of ( $ tableClass , DataObject :: class ) ) { continue ; } $ fields = $ this -> databaseFields ( $ tableClass , false ) ; if ( ! $ dbOnly ) { $ compositeFields = $ this -> compositeFields ( $ tableClass , false ) ; $ fields = array_merge ( $ fields , $ compositeFields ) ; } foreach ( $ fields as $ name => $ specification ) { $ prefix = $ includeClass ? "{$tableClass}." : "" ; $ db [ $ name ] = $ prefix . $ specification ; } } return $ db ; }
|
Get all DB field specifications for a class including ancestors and composite fields .
|
4,915
|
public function fieldSpec ( $ classOrInstance , $ fieldName , $ options = 0 ) { $ specs = $ this -> fieldSpecs ( $ classOrInstance , $ options ) ; return isset ( $ specs [ $ fieldName ] ) ? $ specs [ $ fieldName ] : null ; }
|
Get specifications for a single class field
|
4,916
|
public function tableClass ( $ table ) { $ tables = $ this -> getTableNames ( ) ; $ class = array_search ( $ table , $ tables , true ) ; if ( $ class ) { return $ class ; } if ( preg_match ( '/^(?<class>.+)(_[^_]+)$/i' , $ table , $ matches ) ) { $ table = $ matches [ 'class' ] ; $ class = array_search ( $ table , $ tables , true ) ; if ( $ class ) { return $ class ; } } return null ; }
|
Find the class for the given table
|
4,917
|
protected function cacheTableNames ( ) { if ( $ this -> tableNames ) { return ; } $ this -> tableNames = [ ] ; foreach ( ClassInfo :: subclassesFor ( DataObject :: class ) as $ class ) { if ( $ class === DataObject :: class ) { continue ; } $ table = $ this -> buildTableName ( $ class ) ; $ conflict = array_search ( $ table , $ this -> tableNames , true ) ; if ( $ conflict ) { throw new LogicException ( "Multiple classes (\"{$class}\", \"{$conflict}\") map to the same table: \"{$table}\"" ) ; } $ this -> tableNames [ $ class ] = $ table ; } }
|
Cache all table names if necessary
|
4,918
|
protected function buildTableName ( $ class ) { $ table = Config :: inst ( ) -> get ( $ class , 'table_name' , Config :: UNINHERITED ) ; if ( $ table ) { return $ table ; } if ( strpos ( $ class , '\\' ) === false ) { return $ class ; } $ separator = DataObjectSchema :: config ( ) -> uninherited ( 'table_namespace_separator' ) ; $ table = str_replace ( '\\' , $ separator , trim ( $ class , '\\' ) ) ; if ( ! ClassInfo :: classImplements ( $ class , TestOnly :: class ) && $ this -> classHasTable ( $ class ) ) { DBSchemaManager :: showTableNameWarning ( $ table , $ class ) ; } return $ table ; }
|
Generate table name for a class .
|
4,919
|
public function databaseFields ( $ class , $ aggregated = true ) { $ class = ClassInfo :: class_name ( $ class ) ; if ( $ class === DataObject :: class ) { return [ ] ; } $ this -> cacheDatabaseFields ( $ class ) ; $ fields = $ this -> databaseFields [ $ class ] ; if ( ! $ aggregated ) { return $ fields ; } $ parentFields = $ this -> databaseFields ( get_parent_class ( $ class ) ) ; return array_merge ( $ fields , array_diff_key ( $ parentFields , $ fields ) ) ; }
|
Return the complete map of fields to specification on this object including fixed_fields . ID will be included on every table .
|
4,920
|
public function databaseField ( $ class , $ field , $ aggregated = true ) { $ fields = $ this -> databaseFields ( $ class , $ aggregated ) ; return isset ( $ fields [ $ field ] ) ? $ fields [ $ field ] : null ; }
|
Gets a single database field .
|
4,921
|
public function classHasTable ( $ class ) { if ( ! is_subclass_of ( $ class , DataObject :: class ) ) { return false ; } $ fields = $ this -> databaseFields ( $ class , false ) ; return ! empty ( $ fields ) ; }
|
Check if the given class has a table
|
4,922
|
public function compositeFields ( $ class , $ aggregated = true ) { $ class = ClassInfo :: class_name ( $ class ) ; if ( $ class === DataObject :: class ) { return [ ] ; } $ this -> cacheDatabaseFields ( $ class ) ; $ compositeFields = $ this -> compositeFields [ $ class ] ; if ( ! $ aggregated ) { return $ compositeFields ; } $ parentFields = $ this -> compositeFields ( get_parent_class ( $ class ) ) ; return array_merge ( $ compositeFields , array_diff_key ( $ parentFields , $ compositeFields ) ) ; }
|
Returns a list of all the composite if the given db field on the class is a composite field . Will check all applicable ancestor classes and aggregate results .
|
4,923
|
public function compositeField ( $ class , $ field , $ aggregated = true ) { $ fields = $ this -> compositeFields ( $ class , $ aggregated ) ; return isset ( $ fields [ $ field ] ) ? $ fields [ $ field ] : null ; }
|
Get a composite field for a class
|
4,924
|
protected function cacheDatabaseFields ( $ class ) { if ( isset ( $ this -> databaseFields [ $ class ] ) && isset ( $ this -> compositeFields [ $ class ] ) ) { return ; } $ compositeFields = array ( ) ; $ dbFields = array ( ) ; $ fixedFields = DataObject :: config ( ) -> uninherited ( 'fixed_fields' ) ; if ( get_parent_class ( $ class ) === DataObject :: class ) { $ dbFields = $ fixedFields ; } else { $ dbFields [ 'ID' ] = $ fixedFields [ 'ID' ] ; } $ db = Config :: inst ( ) -> get ( $ class , 'db' , Config :: UNINHERITED ) ? : array ( ) ; foreach ( $ db as $ fieldName => $ fieldSpec ) { $ fieldClass = strtok ( $ fieldSpec , '(' ) ; if ( singleton ( $ fieldClass ) instanceof DBComposite ) { $ compositeFields [ $ fieldName ] = $ fieldSpec ; } else { $ dbFields [ $ fieldName ] = $ fieldSpec ; } } $ hasOne = Config :: inst ( ) -> get ( $ class , 'has_one' , Config :: UNINHERITED ) ? : array ( ) ; foreach ( $ hasOne as $ fieldName => $ hasOneClass ) { if ( $ hasOneClass === DataObject :: class ) { $ compositeFields [ $ fieldName ] = 'PolymorphicForeignKey' ; } else { $ dbFields [ "{$fieldName}ID" ] = 'ForeignKey' ; } } foreach ( $ compositeFields as $ fieldName => $ fieldSpec ) { $ fieldObj = Injector :: inst ( ) -> create ( $ fieldSpec , $ fieldName ) ; $ fieldObj -> setTable ( $ class ) ; $ nestedFields = $ fieldObj -> compositeDatabaseFields ( ) ; foreach ( $ nestedFields as $ nestedName => $ nestedSpec ) { $ dbFields [ "{$fieldName}{$nestedName}" ] = $ nestedSpec ; } } if ( count ( $ dbFields ) < 2 ) { $ dbFields = [ ] ; } $ this -> databaseFields [ $ class ] = $ dbFields ; $ this -> compositeFields [ $ class ] = $ compositeFields ; }
|
Cache all database and composite fields for the given class . Will do nothing if already cached
|
4,925
|
protected function cacheDatabaseIndexes ( $ class ) { if ( ! array_key_exists ( $ class , $ this -> databaseIndexes ) ) { $ this -> databaseIndexes [ $ class ] = array_merge ( $ this -> buildSortDatabaseIndexes ( $ class ) , $ this -> cacheDefaultDatabaseIndexes ( $ class ) , $ this -> buildCustomDatabaseIndexes ( $ class ) ) ; } }
|
Cache all indexes for the given class . Will do nothing if already cached .
|
4,926
|
protected function cacheDefaultDatabaseIndexes ( $ class ) { if ( array_key_exists ( $ class , $ this -> defaultDatabaseIndexes ) ) { return $ this -> defaultDatabaseIndexes [ $ class ] ; } $ this -> defaultDatabaseIndexes [ $ class ] = [ ] ; $ fieldSpecs = $ this -> fieldSpecs ( $ class , self :: UNINHERITED ) ; foreach ( $ fieldSpecs as $ field => $ spec ) { $ fieldObj = Injector :: inst ( ) -> create ( $ spec , $ field ) ; if ( $ indexSpecs = $ fieldObj -> getIndexSpecs ( ) ) { $ this -> defaultDatabaseIndexes [ $ class ] [ $ field ] = $ indexSpecs ; } } return $ this -> defaultDatabaseIndexes [ $ class ] ; }
|
Get default database indexable field types
|
4,927
|
protected function buildCustomDatabaseIndexes ( $ class ) { $ indexes = [ ] ; $ classIndexes = Config :: inst ( ) -> get ( $ class , 'indexes' , Config :: UNINHERITED ) ? : [ ] ; foreach ( $ classIndexes as $ indexName => $ indexSpec ) { if ( array_key_exists ( $ indexName , $ indexes ) ) { throw new InvalidArgumentException ( sprintf ( 'Index named "%s" already exists on class %s' , $ indexName , $ class ) ) ; } if ( is_array ( $ indexSpec ) ) { if ( ! ArrayLib :: is_associative ( $ indexSpec ) ) { $ indexSpec = [ 'columns' => $ indexSpec , ] ; } if ( ! isset ( $ indexSpec [ 'type' ] ) ) { $ indexSpec [ 'type' ] = 'index' ; } if ( ! isset ( $ indexSpec [ 'columns' ] ) ) { $ indexSpec [ 'columns' ] = [ $ indexName ] ; } elseif ( ! is_array ( $ indexSpec [ 'columns' ] ) ) { throw new InvalidArgumentException ( sprintf ( 'Index %s on %s is not valid. columns should be an array %s given' , var_export ( $ indexName , true ) , var_export ( $ class , true ) , var_export ( $ indexSpec [ 'columns' ] , true ) ) ) ; } } else { $ indexSpec = [ 'type' => 'index' , 'columns' => [ $ indexName ] , ] ; } $ indexes [ $ indexName ] = $ indexSpec ; } return $ indexes ; }
|
Look for custom indexes declared on the class
|
4,928
|
public function manyManyComponent ( $ class , $ component ) { $ classes = ClassInfo :: ancestry ( $ class ) ; foreach ( $ classes as $ parentClass ) { $ otherManyMany = Config :: inst ( ) -> get ( $ parentClass , 'many_many' , Config :: UNINHERITED ) ; if ( isset ( $ otherManyMany [ $ component ] ) ) { return $ this -> parseManyManyComponent ( $ parentClass , $ component , $ otherManyMany [ $ component ] ) ; } $ belongsManyMany = Config :: inst ( ) -> get ( $ parentClass , 'belongs_many_many' , Config :: UNINHERITED ) ; if ( ! isset ( $ belongsManyMany [ $ component ] ) ) { continue ; } $ belongs = $ this -> parseBelongsManyManyComponent ( $ parentClass , $ component , $ belongsManyMany [ $ component ] ) ; $ otherManyMany = $ this -> manyManyComponent ( $ belongs [ 'childClass' ] , $ belongs [ 'relationName' ] ) ; return [ 'relationClass' => $ otherManyMany [ 'relationClass' ] , 'parentClass' => $ otherManyMany [ 'childClass' ] , 'childClass' => $ otherManyMany [ 'parentClass' ] , 'parentField' => $ otherManyMany [ 'childField' ] , 'childField' => $ otherManyMany [ 'parentField' ] , 'join' => $ otherManyMany [ 'join' ] , ] ; } return null ; }
|
Return information about a specific many_many component . Returns a numeric array . The first item in the array will be the class name of the relation .
|
4,929
|
protected function parseBelongsManyManyComponent ( $ parentClass , $ component , $ specification ) { $ childClass = $ specification ; $ relationName = null ; if ( strpos ( $ specification , '.' ) !== false ) { list ( $ childClass , $ relationName ) = explode ( '.' , $ specification , 2 ) ; } if ( ! class_exists ( $ childClass ) ) { throw new LogicException ( "belongs_many_many relation {$parentClass}.{$component} points to " . "{$childClass} which does not exist" ) ; } if ( ! $ relationName ) { $ relationName = $ this -> getManyManyInverseRelationship ( $ childClass , $ parentClass ) ; } if ( ! $ relationName ) { throw new LogicException ( "belongs_many_many relation {$parentClass}.{$component} points to " . "{$specification} without matching many_many" ) ; } return [ 'childClass' => $ childClass , 'relationName' => $ relationName , ] ; }
|
Parse a belongs_many_many component to extract class and relationship name
|
4,930
|
public function manyManyExtraFieldsForComponent ( $ class , $ component ) { $ extraFields = Config :: inst ( ) -> get ( $ class , 'many_many_extraFields' ) ; if ( isset ( $ extraFields [ $ component ] ) ) { return $ extraFields [ $ component ] ; } while ( $ class && ( $ class !== DataObject :: class ) ) { $ belongsManyMany = Config :: inst ( ) -> get ( $ class , 'belongs_many_many' , Config :: UNINHERITED ) ; if ( isset ( $ belongsManyMany [ $ component ] ) ) { $ belongs = $ this -> parseBelongsManyManyComponent ( $ class , $ component , $ belongsManyMany [ $ component ] ) ; return $ this -> manyManyExtraFieldsForComponent ( $ belongs [ 'childClass' ] , $ belongs [ 'relationName' ] ) ; } $ class = get_parent_class ( $ class ) ; } return null ; }
|
Return the many - to - many extra fields specification for a specific component .
|
4,931
|
public function hasManyComponent ( $ class , $ component , $ classOnly = true ) { $ hasMany = ( array ) Config :: inst ( ) -> get ( $ class , 'has_many' ) ; if ( ! isset ( $ hasMany [ $ component ] ) ) { return null ; } $ hasMany = $ hasMany [ $ component ] ; $ hasManyClass = strtok ( $ hasMany , '.' ) ; $ this -> checkRelationClass ( $ class , $ component , $ hasManyClass , 'has_many' ) ; return $ classOnly ? $ hasManyClass : $ hasMany ; }
|
Return data for a specific has_many component .
|
4,932
|
public function hasOneComponent ( $ class , $ component ) { $ hasOnes = Config :: forClass ( $ class ) -> get ( 'has_one' ) ; if ( ! isset ( $ hasOnes [ $ component ] ) ) { return null ; } $ relationClass = $ hasOnes [ $ component ] ; $ this -> checkRelationClass ( $ class , $ component , $ relationClass , 'has_one' ) ; return $ relationClass ; }
|
Return data for a specific has_one component .
|
4,933
|
public function belongsToComponent ( $ class , $ component , $ classOnly = true ) { $ belongsTo = ( array ) Config :: forClass ( $ class ) -> get ( 'belongs_to' ) ; if ( ! isset ( $ belongsTo [ $ component ] ) ) { return null ; } $ belongsTo = $ belongsTo [ $ component ] ; $ belongsToClass = strtok ( $ belongsTo , '.' ) ; $ this -> checkRelationClass ( $ class , $ component , $ belongsToClass , 'belongs_to' ) ; return $ classOnly ? $ belongsToClass : $ belongsTo ; }
|
Return data for a specific belongs_to component .
|
4,934
|
protected function getManyManyInverseRelationship ( $ childClass , $ parentClass ) { $ otherManyMany = Config :: inst ( ) -> get ( $ childClass , 'many_many' , Config :: UNINHERITED ) ; if ( ! $ otherManyMany ) { return null ; } foreach ( $ otherManyMany as $ inverseComponentName => $ manyManySpec ) { if ( $ manyManySpec === $ parentClass ) { return $ inverseComponentName ; } if ( is_array ( $ manyManySpec ) ) { $ toClass = $ this -> hasOneComponent ( $ manyManySpec [ 'through' ] , $ manyManySpec [ 'to' ] ) ; if ( $ toClass === $ parentClass ) { return $ inverseComponentName ; } } } return null ; }
|
Find a many_many on the child class that points back to this many_many
|
4,935
|
public function getRemoteJoinField ( $ class , $ component , $ type = 'has_many' , & $ polymorphic = false ) { if ( $ type === 'has_many' ) { $ remoteClass = $ this -> hasManyComponent ( $ class , $ component , false ) ; } else { $ remoteClass = $ this -> belongsToComponent ( $ class , $ component , false ) ; } if ( empty ( $ remoteClass ) ) { throw new Exception ( "Unknown $type component '$component' on class '$class'" ) ; } if ( ! ClassInfo :: exists ( strtok ( $ remoteClass , '.' ) ) ) { throw new Exception ( "Class '$remoteClass' not found, but used in $type component '$component' on class '$class'" ) ; } $ remoteField = null ; if ( strpos ( $ remoteClass , '.' ) !== false ) { list ( $ remoteClass , $ remoteField ) = explode ( '.' , $ remoteClass ) ; } $ remoteRelations = Config :: inst ( ) -> get ( $ remoteClass , 'has_one' ) ; if ( empty ( $ remoteField ) ) { $ remoteRelationsMap = array_flip ( $ remoteRelations ) ; foreach ( array_reverse ( ClassInfo :: ancestry ( $ class ) ) as $ ancestryClass ) { if ( array_key_exists ( $ ancestryClass , $ remoteRelationsMap ) ) { $ remoteField = $ remoteRelationsMap [ $ ancestryClass ] ; break ; } } } if ( empty ( $ remoteField ) ) { $ polymorphic = false ; $ message = "No has_one found on class '$remoteClass'" ; if ( $ type == 'has_many' ) { $ message .= ", the has_many relation from '$class' to '$remoteClass'" ; $ message .= " requires a has_one on '$remoteClass'" ; } throw new Exception ( $ message ) ; } if ( empty ( $ remoteRelations [ $ remoteField ] ) ) { throw new Exception ( "Missing expected has_one named '$remoteField' on class '$remoteClass' referenced by $type named '$component' on class {$class}" ) ; } if ( $ remoteRelations [ $ remoteField ] === DataObject :: class ) { $ polymorphic = true ; return $ remoteField ; } else { $ polymorphic = false ; return $ remoteField . 'ID' ; } }
|
Tries to find the database key on another object that is used to store a relationship to this class . If no join field can be found it defaults to ParentID .
|
4,936
|
protected function checkManyManyFieldClass ( $ parentClass , $ component , $ joinClass , $ specification , $ key ) { if ( empty ( $ specification [ $ key ] ) ) { throw new InvalidArgumentException ( "many_many relation {$parentClass}.{$component} has missing {$key} which " . "should be a has_one on class {$joinClass}" ) ; } $ relation = $ specification [ $ key ] ; $ relationClass = $ this -> hasOneComponent ( $ joinClass , $ relation ) ; if ( empty ( $ relationClass ) ) { throw new InvalidArgumentException ( "many_many through relation {$parentClass}.{$component} {$key} references a field name " . "{$joinClass}::{$relation} which is not a has_one" ) ; } if ( $ relationClass === DataObject :: class ) { if ( $ key === 'from' ) { return $ relationClass ; } throw new InvalidArgumentException ( "many_many through relation {$parentClass}.{$component} {$key} references a polymorphic field " . "{$joinClass}::{$relation} which is not supported" ) ; } $ field = $ this -> fieldSpec ( $ relationClass , $ joinClass ) ; if ( $ field ) { throw new InvalidArgumentException ( "many_many through relation {$parentClass}.{$component} {$key} class {$relationClass} " . " cannot have a db field of the same name of the join class {$joinClass}" ) ; } if ( $ key === 'from' && $ relationClass !== $ parentClass ) { throw new InvalidArgumentException ( "many_many through relation {$parentClass}.{$component} {$key} references a field name " . "{$joinClass}::{$relation} of type {$relationClass}; {$parentClass} expected" ) ; } return $ relationClass ; }
|
Validate the to or from field on a has_many mapping class
|
4,937
|
protected function checkRelationClass ( $ class , $ component , $ relationClass , $ type ) { if ( ! is_string ( $ component ) || is_numeric ( $ component ) ) { throw new InvalidArgumentException ( "{$class} has invalid {$type} relation name" ) ; } if ( ! is_string ( $ relationClass ) ) { throw new InvalidArgumentException ( "{$type} relation {$class}.{$component} is not a class name" ) ; } if ( ! class_exists ( $ relationClass ) ) { throw new InvalidArgumentException ( "{$type} relation {$class}.{$component} references class {$relationClass} which doesn't exist" ) ; } if ( $ type === 'has_one' ) { $ valid = is_a ( $ relationClass , DataObject :: class , true ) ; } else { $ valid = is_subclass_of ( $ relationClass , DataObject :: class , true ) ; } if ( ! $ valid ) { throw new InvalidArgumentException ( "{$type} relation {$class}.{$component} references class {$relationClass} " . " which is not a subclass of " . DataObject :: class ) ; } }
|
Validate a given class is valid for a relation
|
4,938
|
function construct ( $ matchrule , $ name , $ arguments = null ) { $ res = parent :: construct ( $ matchrule , $ name , $ arguments ) ; if ( ! isset ( $ res [ 'php' ] ) ) { $ res [ 'php' ] = '' ; } return $ res ; }
|
Override the function that constructs the result arrays to also prepare a php item in the array
|
4,939
|
public function setClosedBlocks ( $ closedBlocks ) { $ this -> closedBlocks = array ( ) ; foreach ( ( array ) $ closedBlocks as $ name => $ callable ) { $ this -> addClosedBlock ( $ name , $ callable ) ; } }
|
Set the closed blocks that the template parser should use
|
4,940
|
public function setOpenBlocks ( $ openBlocks ) { $ this -> openBlocks = array ( ) ; foreach ( ( array ) $ openBlocks as $ name => $ callable ) { $ this -> addOpenBlock ( $ name , $ callable ) ; } }
|
Set the open blocks that the template parser should use
|
4,941
|
protected function validateExtensionBlock ( $ name , $ callable , $ type ) { if ( ! is_string ( $ name ) ) { throw new InvalidArgumentException ( sprintf ( "Name argument for %s must be a string" , $ type ) ) ; } elseif ( ! is_callable ( $ callable ) ) { throw new InvalidArgumentException ( sprintf ( "Callable %s argument named '%s' is not callable" , $ type , $ name ) ) ; } }
|
Ensures that the arguments to addOpenBlock and addClosedBlock are valid
|
4,942
|
function CallArguments_Argument ( & $ res , $ sub ) { if ( ! empty ( $ res [ 'php' ] ) ) { $ res [ 'php' ] .= ', ' ; } $ res [ 'php' ] .= ( $ sub [ 'ArgumentMode' ] == 'default' ) ? $ sub [ 'string_php' ] : str_replace ( '$$FINAL' , 'XML_val' , $ sub [ 'php' ] ) ; }
|
Values are bare words in templates but strings in PHP . We rely on PHP s type conversion to back - convert strings to numbers when needed .
|
4,943
|
function ClosedBlock_Handle_Loop ( & $ res ) { if ( $ res [ 'ArgumentCount' ] > 1 ) { throw new SSTemplateParseException ( 'Either no or too many arguments in control block. Must be one ' . 'argument only.' , $ this ) ; } if ( $ res [ 'ArgumentCount' ] == 0 ) { $ on = '$scope->obj(\'Up\', null)->obj(\'Foo\', null)' ; } else { $ arg = $ res [ 'Arguments' ] [ 0 ] ; if ( $ arg [ 'ArgumentMode' ] == 'string' ) { throw new SSTemplateParseException ( 'Control block cant take string as argument.' , $ this ) ; } $ on = str_replace ( '$$FINAL' , 'obj' , ( $ arg [ 'ArgumentMode' ] == 'default' ) ? $ arg [ 'lookup_php' ] : $ arg [ 'php' ] ) ; } return $ on . '; $scope->pushScope(); while (($key = $scope->next()) !== false) {' . PHP_EOL . $ res [ 'Template' ] [ 'php' ] . PHP_EOL . '}; $scope->popScope(); ' ; }
|
This is an example of a block handler function . This one handles the loop tag .
|
4,944
|
function ClosedBlock_Handle_With ( & $ res ) { if ( $ res [ 'ArgumentCount' ] != 1 ) { throw new SSTemplateParseException ( 'Either no or too many arguments in with block. Must be one ' . 'argument only.' , $ this ) ; } $ arg = $ res [ 'Arguments' ] [ 0 ] ; if ( $ arg [ 'ArgumentMode' ] == 'string' ) { throw new SSTemplateParseException ( 'Control block cant take string as argument.' , $ this ) ; } $ on = str_replace ( '$$FINAL' , 'obj' , ( $ arg [ 'ArgumentMode' ] == 'default' ) ? $ arg [ 'lookup_php' ] : $ arg [ 'php' ] ) ; return $ on . '; $scope->pushScope();' . PHP_EOL . $ res [ 'Template' ] [ 'php' ] . PHP_EOL . '; $scope->popScope(); ' ; }
|
The closed block handler for with blocks
|
4,945
|
function Text__finalise ( & $ res ) { $ text = $ res [ 'text' ] ; $ text = stripslashes ( $ text ) ; $ text = addcslashes ( $ text , '\'\\' ) ; $ code = <<<'EOC'(\SilverStripe\View\SSViewer::getRewriteHashLinksDefault() ? \SilverStripe\Core\Convert::raw2att( preg_replace("/^(\\/)+/", "/", $_SERVER['REQUEST_URI'] ) ) : "")EOC ; $ text = preg_replace ( '/(<a[^>]+href *= *)"#/i' , '\\1"\' . ' . addcslashes ( $ code , '\\' ) . ' . \'#' , $ text ) ; $ res [ 'php' ] .= '$val .= \'' . $ text . '\';' . PHP_EOL ; }
|
We convert text
|
4,946
|
public function compileString ( $ string , $ templateName = "" , $ includeDebuggingComments = false , $ topTemplate = true ) { if ( ! trim ( $ string ) ) { $ code = '' ; } else { parent :: __construct ( $ string ) ; $ this -> includeDebuggingComments = $ includeDebuggingComments ; if ( substr ( $ string , 0 , 3 ) == pack ( "CCC" , 0xef , 0xbb , 0xbf ) ) { $ this -> pos = 3 ; } if ( $ topTemplate ) { $ result = $ this -> match_TopTemplate ( ) ; } else { $ result = $ this -> match_Template ( ) ; } if ( ! $ result ) { throw new SSTemplateParseException ( 'Unexpected problem parsing template' , $ this ) ; } $ code = $ result [ 'php' ] ; } if ( $ includeDebuggingComments && $ templateName && stripos ( $ code , "<?xml" ) === false ) { $ code = $ this -> includeDebuggingComments ( $ code , $ templateName ) ; } return $ code ; }
|
Compiles some passed template source code into the php code that will execute as per the template source .
|
4,947
|
protected function sessionEnvironment ( ) { if ( isset ( $ _GET [ 'isDev' ] ) ) { if ( isset ( $ _SESSION ) ) { unset ( $ _SESSION [ 'isTest' ] ) ; $ _SESSION [ 'isDev' ] = $ _GET [ 'isDev' ] ; } return self :: DEV ; } if ( isset ( $ _GET [ 'isTest' ] ) ) { if ( isset ( $ _SESSION ) ) { unset ( $ _SESSION [ 'isDev' ] ) ; $ _SESSION [ 'isTest' ] = $ _GET [ 'isTest' ] ; } return self :: TEST ; } if ( ! empty ( $ _SESSION [ 'isDev' ] ) ) { return self :: DEV ; } if ( ! empty ( $ _SESSION [ 'isTest' ] ) ) { return self :: TEST ; } return null ; }
|
Check or update any temporary environment specified in the session .
|
4,948
|
protected function bootConfigs ( ) { global $ project ; $ projectBefore = $ project ; $ config = ModuleManifest :: config ( ) ; $ this -> getModuleLoader ( ) -> getManifest ( ) -> activateConfig ( ) ; if ( $ project && $ project !== $ projectBefore ) { Deprecation :: notice ( '5.0' , '$project global is deprecated' ) ; $ config -> set ( 'project' , $ project ) ; } }
|
Include all _config . php files
|
4,949
|
protected function bootDatabaseEnvVars ( ) { $ databaseConfig = $ this -> getDatabaseConfig ( ) ; $ databaseConfig [ 'database' ] = $ this -> getDatabaseName ( ) ; DB :: setConfig ( $ databaseConfig ) ; }
|
Load default database configuration from environment variable
|
4,950
|
protected function validateDatabase ( ) { $ databaseConfig = DB :: getConfig ( ) ; if ( empty ( $ databaseConfig [ 'database' ] ) ) { $ this -> detectLegacyEnvironment ( ) ; $ this -> redirectToInstaller ( ) ; } }
|
Check that the database configuration is valid throwing an HTTPResponse_Exception if it s not
|
4,951
|
protected function detectLegacyEnvironment ( ) { if ( ! file_exists ( $ this -> basePath . '/_ss_environment.php' ) && ! file_exists ( dirname ( $ this -> basePath ) . '/_ss_environment.php' ) ) { return ; } $ dv = new DebugView ( ) ; $ body = $ dv -> renderHeader ( ) . $ dv -> renderInfo ( "Configuration Error" , Director :: absoluteBaseURL ( ) ) . $ dv -> renderParagraph ( 'You need to replace your _ss_environment.php file with a .env file, or with environment variables.<br><br>' . 'See the <a href="https://docs.silverstripe.org/en/4/getting_started/environment_management/">' . 'Environment Management</a> docs for more information.' ) . $ dv -> renderFooter ( ) ; $ response = new HTTPResponse ( $ body , 500 ) ; throw new HTTPResponse_Exception ( $ response ) ; }
|
Check if there s a legacy _ss_environment . php file
|
4,952
|
protected function redirectToInstaller ( ) { if ( ! file_exists ( Director :: publicFolder ( ) . '/install.php' ) ) { throw new HTTPResponse_Exception ( 'SilverStripe Framework requires database configuration defined via .env' , 500 ) ; } $ response = new HTTPResponse ( ) ; $ response -> redirect ( Director :: absoluteURL ( 'install.php' ) ) ; throw new HTTPResponse_Exception ( $ response ) ; }
|
If missing configuration redirect to install . php
|
4,953
|
protected function getDatabaseConfig ( ) { $ databaseConfig = [ "type" => Environment :: getEnv ( 'SS_DATABASE_CLASS' ) ? : 'MySQLDatabase' , "server" => Environment :: getEnv ( 'SS_DATABASE_SERVER' ) ? : 'localhost' , "username" => Environment :: getEnv ( 'SS_DATABASE_USERNAME' ) ? : null , "password" => Environment :: getEnv ( 'SS_DATABASE_PASSWORD' ) ? : null , ] ; $ dbPort = Environment :: getEnv ( 'SS_DATABASE_PORT' ) ; if ( $ dbPort ) { $ databaseConfig [ 'port' ] = $ dbPort ; } $ dbTZ = Environment :: getEnv ( 'SS_DATABASE_TIMEZONE' ) ; if ( $ dbTZ ) { $ databaseConfig [ 'timezone' ] = $ dbTZ ; } $ dbSchema = Environment :: getEnv ( 'SS_DATABASE_SCHEMA' ) ; if ( $ dbSchema ) { $ databaseConfig [ "schema" ] = $ dbSchema ; } $ dbMemory = Environment :: getEnv ( 'SS_DATABASE_MEMORY' ) ; if ( $ dbMemory ) { $ databaseConfig [ "memory" ] = $ dbMemory ; } DatabaseAdapterRegistry :: autoconfigure ( $ databaseConfig ) ; return $ databaseConfig ; }
|
Load database config from environment
|
4,954
|
protected function getDatabaseName ( ) { global $ database ; if ( ! empty ( $ database ) ) { return $ this -> getDatabasePrefix ( ) . $ database . $ this -> getDatabaseSuffix ( ) ; } global $ databaseConfig ; if ( ! empty ( $ databaseConfig [ 'database' ] ) ) { return $ databaseConfig [ 'database' ] ; } $ database = Environment :: getEnv ( 'SS_DATABASE_NAME' ) ; if ( $ database ) { return $ this -> getDatabasePrefix ( ) . $ database . $ this -> getDatabaseSuffix ( ) ; } $ chooseName = Environment :: getEnv ( 'SS_DATABASE_CHOOSE_NAME' ) ; if ( $ chooseName ) { $ loopCount = ( int ) $ chooseName ; $ databaseDir = $ this -> basePath ; for ( $ i = 0 ; $ i < $ loopCount - 1 ; $ i ++ ) { $ databaseDir = dirname ( $ databaseDir ) ; } $ database = str_replace ( '.' , '' , basename ( $ databaseDir ) ) ; $ prefix = $ this -> getDatabasePrefix ( ) ; if ( $ prefix ) { $ prefix = 'SS_' ; } else { $ prefix = '' ; $ database = 'SS_' . $ database ; } return $ prefix . $ database ; } return null ; }
|
Get name of database
|
4,955
|
protected function bootPHP ( ) { if ( $ this -> getEnvironment ( ) === self :: LIVE ) { error_reporting ( E_ALL & ~ ( E_DEPRECATED | E_STRICT | E_NOTICE ) ) ; } else { error_reporting ( E_ALL | E_STRICT ) ; } Environment :: increaseMemoryLimitTo ( '64M' ) ; if ( function_exists ( 'xdebug_enable' ) ) { $ current = ini_get ( 'xdebug.max_nesting_level' ) ; if ( ( int ) $ current < 200 ) { ini_set ( 'xdebug.max_nesting_level' , 200 ) ; } } mb_http_output ( 'UTF-8' ) ; mb_internal_encoding ( 'UTF-8' ) ; mb_regex_encoding ( 'UTF-8' ) ; gc_enable ( ) ; }
|
Initialise PHP with default variables
|
4,956
|
protected function bootManifests ( $ flush ) { $ this -> getClassLoader ( ) -> init ( $ this -> getIncludeTests ( ) , $ flush ) ; $ this -> getModuleLoader ( ) -> init ( $ this -> getIncludeTests ( ) , $ flush ) ; if ( $ flush ) { $ config = $ this -> getConfigLoader ( ) -> getManifest ( ) ; if ( $ config instanceof CachedConfigCollection ) { $ config -> setFlush ( true ) ; } } $ this -> getModuleLoader ( ) -> getManifest ( ) -> sort ( ) ; $ defaultSet = $ this -> getThemeResourceLoader ( ) -> getSet ( '$default' ) ; if ( $ defaultSet instanceof ThemeManifest ) { $ defaultSet -> setProject ( ModuleManifest :: config ( ) -> get ( 'project' ) ) ; $ defaultSet -> init ( $ this -> getIncludeTests ( ) , $ flush ) ; } }
|
Boot all manifests
|
4,957
|
protected function bootErrorHandling ( ) { $ errorHandler = Injector :: inst ( ) -> get ( ErrorHandler :: class ) ; $ errorHandler -> start ( ) ; $ errorLog = Environment :: getEnv ( 'SS_ERROR_LOG' ) ; if ( $ errorLog ) { $ logger = Injector :: inst ( ) -> get ( LoggerInterface :: class ) ; if ( $ logger instanceof Logger ) { $ logger -> pushHandler ( new StreamHandler ( $ this -> basePath . '/' . $ errorLog , Logger :: WARNING ) ) ; } else { user_error ( "SS_ERROR_LOG setting only works with Monolog, you are using another logger" , E_USER_WARNING ) ; } } }
|
Turn on error handling
|
4,958
|
public function renameTable ( $ oldTableName , $ newTableName ) { if ( ! $ this -> hasTable ( $ oldTableName ) ) { throw new LogicException ( 'Table ' . $ oldTableName . ' does not exist.' ) ; } return $ this -> query ( "ALTER TABLE \"$oldTableName\" RENAME \"$newTableName\"" ) ; }
|
Renames a table
|
4,959
|
protected function runTableCheckCommand ( $ sql ) { $ testResults = $ this -> query ( $ sql ) ; foreach ( $ testResults as $ testRecord ) { if ( strtolower ( $ testRecord [ 'Msg_text' ] ) != 'ok' ) { return false ; } } return true ; }
|
Helper function used by checkAndRepairTable .
|
4,960
|
public function renameField ( $ tableName , $ oldName , $ newName ) { $ fieldList = $ this -> fieldList ( $ tableName ) ; if ( array_key_exists ( $ oldName , $ fieldList ) ) { $ this -> query ( "ALTER TABLE \"$tableName\" CHANGE \"$oldName\" \"$newName\" " . $ fieldList [ $ oldName ] ) ; } }
|
Change the database column name of the given field .
|
4,961
|
public function createIndex ( $ tableName , $ indexName , $ indexSpec ) { $ this -> query ( "ALTER TABLE \"$tableName\" ADD " . $ this -> getIndexSqlDefinition ( $ indexName , $ indexSpec ) ) ; }
|
Create an index on a table .
|
4,962
|
protected function getIndexSqlDefinition ( $ indexName , $ indexSpec ) { if ( $ indexSpec [ 'type' ] == 'using' ) { return sprintf ( 'index "%s" using (%s)' , $ indexName , $ this -> implodeColumnList ( $ indexSpec [ 'columns' ] ) ) ; } else { return sprintf ( '%s "%s" (%s)' , $ indexSpec [ 'type' ] , $ indexName , $ this -> implodeColumnList ( $ indexSpec [ 'columns' ] ) ) ; } }
|
Generate SQL suitable for creating this index
|
4,963
|
public function varchar ( $ values ) { $ default = $ this -> defaultClause ( $ values ) ; $ charset = Config :: inst ( ) -> get ( 'SilverStripe\ORM\Connect\MySQLDatabase' , 'charset' ) ; $ collation = Config :: inst ( ) -> get ( 'SilverStripe\ORM\Connect\MySQLDatabase' , 'collation' ) ; return "varchar({$values['precision']}) character set {$charset} collate {$collation}{$default}" ; }
|
Return a varchar type - formatted string
|
4,964
|
public static function join ( ... $ parts ) { if ( count ( $ parts ) === 1 && is_array ( $ parts [ 0 ] ) ) { $ parts = $ parts [ 0 ] ; } $ parts = array_filter ( array_map ( 'trim' , $ parts ) ) ; $ fullPath = static :: normalise ( implode ( DIRECTORY_SEPARATOR , $ parts ) ) ; if ( strpos ( $ fullPath , '..' ) !== false ) { throw new InvalidArgumentException ( 'Can not collapse relative folders' ) ; } return $ fullPath ? : DIRECTORY_SEPARATOR ; }
|
Joins one or more paths normalising all separators to DIRECTORY_SEPARATOR
|
4,965
|
public function foreignIDFilter ( $ id = null ) { if ( $ id === null ) { $ id = $ this -> getForeignID ( ) ; } $ manyManyFilter = parent :: foreignIDFilter ( $ id ) ; $ query = SQLSelect :: create ( '"Group_Members"."GroupID"' , '"Group_Members"' , $ manyManyFilter ) ; $ groupIDs = $ query -> execute ( ) -> column ( ) ; $ allGroupIDs = [ ] ; while ( $ groupIDs ) { $ allGroupIDs = array_merge ( $ allGroupIDs , $ groupIDs ) ; $ groupIDs = DataObject :: get ( Group :: class ) -> byIDs ( $ groupIDs ) -> column ( "ParentID" ) ; $ groupIDs = array_filter ( $ groupIDs ) ; } if ( ! empty ( $ allGroupIDs ) ) { $ allGroupIDsPlaceholders = DB :: placeholders ( $ allGroupIDs ) ; return [ "\"Group\".\"ID\" IN ($allGroupIDsPlaceholders)" => $ allGroupIDs ] ; } return [ '"Group"."ID"' => 0 ] ; }
|
Link this group set to a specific member .
|
4,966
|
protected function canAddGroups ( $ itemIDs ) { if ( empty ( $ itemIDs ) ) { return true ; } $ member = $ this -> getMember ( ) ; return empty ( $ member ) || $ member -> onChangeGroups ( $ itemIDs ) ; }
|
Determine if the following groups IDs can be added
|
4,967
|
public function selector2xpath ( $ selector ) { $ parts = preg_split ( '/\\s+/' , $ selector ) ; $ xpath = "" ; foreach ( $ parts as $ part ) { if ( preg_match ( '/^([A-Za-z][A-Za-z0-9]*)/' , $ part , $ matches ) ) { $ xpath .= "//$matches[1]" ; } else { $ xpath .= "//*" ; } $ xfilters = array ( ) ; if ( preg_match ( '/#([^#.\[]+)/' , $ part , $ matches ) ) { $ xfilters [ ] = "@id='$matches[1]'" ; } if ( preg_match ( '/\.([^#.\[]+)/' , $ part , $ matches ) ) { $ xfilters [ ] = "contains(@class,'$matches[1]')" ; } if ( $ xfilters ) { $ xpath .= '[' . implode ( ',' , $ xfilters ) . ']' ; } } return $ xpath ; }
|
Converts a CSS selector into an equivalent xpath expression . Currently the selector engine only supports querying by tag id and class .
|
4,968
|
public function getSchemaDataDefaults ( ) { $ defaults = parent :: getSchemaDataDefaults ( ) ; $ defaults [ 'attributes' ] [ 'type' ] = $ this -> getUseButtonTag ( ) ? 'button' : 'submit' ; $ defaults [ 'data' ] [ 'icon' ] = $ this -> getIcon ( ) ; return $ defaults ; }
|
Add extra options to data
|
4,969
|
public static function get_closest_translation ( $ locale ) { $ pool = self :: getSources ( ) -> getKnownLocales ( ) ; if ( isset ( $ pool [ $ locale ] ) ) { return $ locale ; } $ localesData = static :: getData ( ) ; $ lang = $ localesData -> langFromLocale ( $ locale ) ; $ candidate = $ localesData -> localeFromLang ( $ lang ) ; if ( isset ( $ pool [ $ candidate ] ) ) { return $ candidate ; } return null ; }
|
Matches a given locale with the closest translation available in the system
|
4,970
|
public static function with_locale ( $ locale , $ callback ) { $ oldLocale = self :: $ current_locale ; static :: set_locale ( $ locale ) ; try { return $ callback ( ) ; } finally { static :: set_locale ( $ oldLocale ) ; } }
|
Temporarily set the locale while invoking a callback
|
4,971
|
public function setValue ( $ value , $ data = null ) { $ id = $ this -> getIsNullId ( ) ; if ( is_array ( $ data ) && array_key_exists ( $ id , $ data ) && $ data [ $ id ] ) { $ value = null ; } $ this -> valueField -> setValue ( $ value ) ; parent :: setValue ( $ value ) ; return $ this ; }
|
Value is sometimes an array and sometimes a single value so we need to handle both cases
|
4,972
|
public static function createTag ( $ tag , $ attributes , $ content = null ) { $ tag = strtolower ( $ tag ) ; $ preparedAttributes = '' ; foreach ( $ attributes as $ attributeKey => $ attributeValue ) { if ( strlen ( $ attributeValue ) > 0 ) { $ preparedAttributes .= sprintf ( ' %s="%s"' , $ attributeKey , Convert :: raw2att ( $ attributeValue ) ) ; } } if ( in_array ( $ tag , static :: config ( ) -> get ( 'void_elements' ) ) ) { if ( $ content ) { throw new InvalidArgumentException ( "Void element \"{$tag}\" cannot have content" ) ; } return "<{$tag}{$preparedAttributes} />" ; } return "<{$tag}{$preparedAttributes}>{$content}</{$tag}>" ; }
|
Construct and return HTML tag .
|
4,973
|
public function merge ( $ name , $ value ) { Config :: modify ( ) -> merge ( $ this -> class , $ name , $ value ) ; return $ this ; }
|
Merge a given config
|
4,974
|
public function set ( $ name , $ value ) { Config :: modify ( ) -> set ( $ this -> class , $ name , $ value ) ; return $ this ; }
|
Replace config value
|
4,975
|
public function output ( $ statusCode ) { if ( Director :: is_ajax ( ) ) { return $ this -> getTitle ( ) ; } $ renderer = Debug :: create_debug_view ( ) ; $ output = $ renderer -> renderHeader ( ) ; $ output .= $ renderer -> renderInfo ( "Website Error" , $ this -> getTitle ( ) , $ this -> getBody ( ) ) ; $ adminEmail = Email :: config ( ) -> get ( 'admin_email' ) ; if ( $ adminEmail ) { $ mailto = Email :: obfuscate ( $ adminEmail ) ; $ output .= $ renderer -> renderParagraph ( 'Contact an administrator: ' . $ mailto . '' ) ; } $ output .= $ renderer -> renderFooter ( ) ; return $ output ; }
|
Return the appropriate error content for the given status code
|
4,976
|
protected function getFormActions ( ) { $ actions = new FieldList ( ) ; if ( $ this -> record -> ID !== 0 ) { if ( $ this -> record -> canEdit ( ) ) { $ actions -> push ( FormAction :: create ( 'doSave' , _t ( 'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Save' , 'Save' ) ) -> setUseButtonTag ( true ) -> addExtraClass ( 'btn-primary font-icon-save' ) ) ; } if ( $ this -> record -> canDelete ( ) ) { $ actions -> push ( FormAction :: create ( 'doDelete' , _t ( 'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Delete' , 'Delete' ) ) -> setUseButtonTag ( true ) -> addExtraClass ( 'btn-outline-danger btn-hide-outline font-icon-trash-bin action--delete' ) ) ; } $ gridState = $ this -> getRequest ( ) -> requestVar ( 'gridState' ) ; $ this -> gridField -> getState ( false ) -> setValue ( $ gridState ) ; $ actions -> push ( HiddenField :: create ( 'gridState' , null , $ gridState ) ) ; $ actions -> push ( $ this -> getRightGroupField ( ) ) ; } else { $ actions -> push ( FormAction :: create ( 'doSave' , _t ( 'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.Create' , 'Create' ) ) -> setUseButtonTag ( true ) -> addExtraClass ( 'btn-primary font-icon-plus-thin' ) ) ; $ crumbs = $ this -> Breadcrumbs ( ) ; if ( $ crumbs && $ crumbs -> count ( ) >= 2 ) { $ oneLevelUp = $ crumbs -> offsetGet ( $ crumbs -> count ( ) - 2 ) ; $ text = sprintf ( "<a class=\"%s\" href=\"%s\">%s</a>" , "crumb btn btn-secondary cms-panel-link" , $ oneLevelUp -> Link , _t ( 'SilverStripe\\Forms\\GridField\\GridFieldDetailForm.CancelBtn' , 'Cancel' ) ) ; $ actions -> push ( new LiteralField ( 'cancelbutton' , $ text ) ) ; } } $ this -> extend ( 'updateFormActions' , $ actions ) ; return $ actions ; }
|
Build the set of form field actions for this DataObject
|
4,977
|
public function doPrevious ( $ data , $ form ) { $ this -> getToplevelController ( ) -> getResponse ( ) -> addHeader ( 'X-Pjax' , 'Content' ) ; $ link = $ this -> getEditLink ( $ this -> getPreviousRecordID ( ) ) ; return $ this -> redirect ( $ link ) ; }
|
Goes to the previous record
|
4,978
|
public function doNext ( $ data , $ form ) { $ this -> getToplevelController ( ) -> getResponse ( ) -> addHeader ( 'X-Pjax' , 'Content' ) ; $ link = $ this -> getEditLink ( $ this -> getNextRecordID ( ) ) ; return $ this -> redirect ( $ link ) ; }
|
Goes to the next record
|
4,979
|
public function doNew ( $ data , $ form ) { return $ this -> redirect ( Controller :: join_links ( $ this -> gridField -> Link ( 'item' ) , 'new' ) ) ; }
|
Creates a new record . If you re already creating a new record this forces the URL to change .
|
4,980
|
public function getEditLink ( $ id ) { return Controller :: join_links ( $ this -> gridField -> Link ( ) , 'item' , $ id , '?gridState=' . urlencode ( $ this -> gridField -> getState ( false ) -> Value ( ) ) ) ; }
|
Gets the edit link for a record
|
4,981
|
protected function redirectAfterSave ( $ isNewRecord ) { $ controller = $ this -> getToplevelController ( ) ; if ( $ isNewRecord ) { return $ controller -> redirect ( $ this -> Link ( ) ) ; } elseif ( $ this -> gridField -> getList ( ) -> byID ( $ this -> record -> ID ) ) { return $ this -> edit ( $ controller -> getRequest ( ) ) ; } else { $ url = $ controller -> getRequest ( ) -> getURL ( ) ; $ noActionURL = $ controller -> removeAction ( $ url ) ; $ controller -> getRequest ( ) -> addHeader ( 'X-Pjax' , 'Content' ) ; return $ controller -> redirect ( $ noActionURL , 302 ) ; } }
|
Response object for this request after a successful save
|
4,982
|
protected function saveFormIntoRecord ( $ data , $ form ) { $ list = $ this -> gridField -> getList ( ) ; if ( isset ( $ data [ 'ClassName' ] ) && $ data [ 'ClassName' ] != $ this -> record -> ClassName ) { $ newClassName = $ data [ 'ClassName' ] ; $ this -> record -> setClassName ( $ this -> record -> ClassName ) ; $ this -> record = $ this -> record -> newClassInstance ( $ newClassName ) ; } $ form -> saveInto ( $ this -> record ) ; $ this -> record -> write ( ) ; $ this -> extend ( 'onAfterSave' , $ this -> record ) ; $ extraData = $ this -> getExtraSavedData ( $ this -> record , $ list ) ; $ list -> add ( $ this -> record , $ extraData ) ; return $ this -> record ; }
|
Loads the given form data into the underlying dataobject and relation
|
4,983
|
public function getTemplates ( ) { $ templates = SSViewer :: get_templates_by_class ( $ this , '' , __CLASS__ ) ; if ( $ this -> getTemplate ( ) ) { array_unshift ( $ templates , $ this -> getTemplate ( ) ) ; } return $ templates ; }
|
Get list of templates to use
|
4,984
|
public static function get_enabled ( ) { if ( ! Director :: isDev ( ) ) { return false ; } if ( isset ( self :: $ enabled ) ) { return self :: $ enabled ; } return Environment :: getEnv ( 'SS_DEPRECATION_ENABLED' ) ? : true ; }
|
Determine if deprecation notices should be displayed
|
4,985
|
public static function restore_settings ( $ settings ) { self :: $ notice_level = $ settings [ 'level' ] ; self :: $ version = $ settings [ 'version' ] ; self :: $ module_version_overrides = $ settings [ 'moduleVersions' ] ; self :: $ enabled = $ settings [ 'enabled' ] ; }
|
Method for when testing . Restore all the current version settings from a variable
|
4,986
|
public function forTemplate ( $ field = null ) { $ class = get_class ( $ this -> object ) ; if ( $ field ) { return "<b>Debugging Information for {$class}->{$field}</b><br/>" . ( $ this -> object -> hasMethod ( $ field ) ? "Has method '$field'<br/>" : null ) . ( $ this -> object -> hasField ( $ field ) ? "Has field '$field'<br/>" : null ) ; } $ reflector = new ReflectionObject ( $ this -> object ) ; $ debug = "<b>Debugging Information: all methods available in '{$class}'</b><br/><ul>" ; foreach ( $ this -> object -> allMethodNames ( ) as $ method ) { if ( $ method [ 0 ] === strtoupper ( $ method [ 0 ] ) && $ method [ 0 ] != '_' ) { if ( $ reflector -> hasMethod ( $ method ) && $ method = $ reflector -> getMethod ( $ method ) ) { if ( $ method -> isPublic ( ) ) { $ debug .= "<li>\${$method->getName()}" ; if ( count ( $ method -> getParameters ( ) ) ) { $ debug .= ' <small>(' . implode ( ', ' , $ method -> getParameters ( ) ) . ')</small>' ; } $ debug .= '</li>' ; } } else { $ debug .= "<li>\$$method</li>" ; } } } $ debug .= '</ul>' ; if ( $ this -> object -> hasMethod ( 'toMap' ) ) { $ debug .= "<b>Debugging Information: all fields available in '{$class}'</b><br/><ul>" ; foreach ( $ this -> object -> toMap ( ) as $ field => $ value ) { $ debug .= "<li>\$$field</li>" ; } $ debug .= "</ul>" ; } if ( $ this -> object -> hasMethod ( 'data' ) && $ this -> object -> data ( ) != $ this -> object ) { $ debug .= ViewableData_Debugger :: create ( $ this -> object -> data ( ) ) -> forTemplate ( ) ; } return $ debug ; }
|
Return debugging information as XHTML . If a field name is passed it will show debugging information on that field otherwise it will show information on all methods and fields .
|
4,987
|
public function getTimeFormat ( ) { if ( $ this -> getHTML5 ( ) ) { $ this -> setTimeFormat ( DBTime :: ISO_TIME ) ; } if ( $ this -> timeFormat ) { return $ this -> timeFormat ; } return $ this -> getFrontendFormatter ( ) -> getPattern ( ) ; }
|
Get time format in CLDR standard format
|
4,988
|
protected function getInternalFormatter ( ) { $ formatter = IntlDateFormatter :: create ( i18n :: config ( ) -> uninherited ( 'default_locale' ) , IntlDateFormatter :: NONE , IntlDateFormatter :: MEDIUM , date_default_timezone_get ( ) ) ; $ formatter -> setLenient ( false ) ; $ formatter -> setPattern ( DBTime :: ISO_TIME ) ; return $ formatter ; }
|
Get a time formatter for the ISO 8601 format
|
4,989
|
protected function withTimezone ( $ timezone , $ callback ) { $ currentTimezone = date_default_timezone_get ( ) ; try { if ( $ timezone ) { date_default_timezone_set ( $ timezone ) ; } return $ callback ( ) ; } finally { if ( $ timezone ) { date_default_timezone_set ( $ currentTimezone ) ; } } }
|
Run a callback within a specific timezone
|
4,990
|
public function validate ( $ validator ) { $ this -> value = trim ( $ this -> value ) ; $ pattern = '^[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$' ; $ safePattern = str_replace ( '/' , '\\/' , $ pattern ) ; if ( $ this -> value && ! preg_match ( '/' . $ safePattern . '/i' , $ this -> value ) ) { $ validator -> validationError ( $ this -> name , _t ( 'SilverStripe\\Forms\\EmailField.VALIDATION' , 'Please enter an email address' ) , 'validation' ) ; return false ; } return true ; }
|
Validates for RFC 2822 compliant email addresses .
|
4,991
|
public function generatesecuretoken ( ) { $ generator = Injector :: inst ( ) -> create ( 'SilverStripe\\Security\\RandomGenerator' ) ; $ token = $ generator -> randomToken ( 'sha1' ) ; $ body = <<<TXTGenerated new token. Please add the following code to your YAML configuration:Security: token: $tokenTXT ; $ response = new HTTPResponse ( $ body ) ; return $ response -> addHeader ( 'Content-Type' , 'text/plain' ) ; }
|
Generate a secure token which can be used as a crypto key . Returns the token and suggests PHP configuration to set it .
|
4,992
|
public function getDisplayFields ( $ gridField ) { if ( ! $ this -> displayFields ) { return singleton ( $ gridField -> getModelClass ( ) ) -> summaryFields ( ) ; } return $ this -> displayFields ; }
|
Get the DisplayFields
|
4,993
|
protected function castValue ( $ gridField , $ fieldName , $ value ) { if ( array_key_exists ( $ fieldName , $ this -> fieldCasting ) ) { $ value = $ gridField -> getCastedValue ( $ value , $ this -> fieldCasting [ $ fieldName ] ) ; } elseif ( is_object ( $ value ) ) { if ( method_exists ( $ value , 'Nice' ) ) { $ value = Convert :: raw2xml ( $ value -> Nice ( ) ) ; } else { $ value = $ value -> forTemplate ( ) ; } } else { $ value = Convert :: raw2xml ( $ value ) ; } return $ value ; }
|
Casts a field to a string which is safe to insert into HTML
|
4,994
|
protected function escapeValue ( $ gridField , $ value ) { if ( ! $ escape = $ gridField -> FieldEscape ) { return $ value ; } foreach ( $ escape as $ search => $ replace ) { $ value = str_replace ( $ search , $ replace , $ value ) ; } return $ value ; }
|
Remove values from a value using FieldEscape setter
|
4,995
|
public function withOwner ( $ owner , callable $ callback , $ args = [ ] ) { try { $ this -> setOwner ( $ owner ) ; return $ callback ( ... $ args ) ; } finally { $ this -> clearOwner ( ) ; } }
|
Temporarily modify the owner . The original owner is ensured to be restored
|
4,996
|
public function setAuthenticatorClass ( $ class ) { $ this -> authenticatorClass = $ class ; $ fields = $ this -> Fields ( ) ; if ( ! $ fields ) { return $ this ; } $ authenticatorField = $ fields -> dataFieldByName ( 'AuthenticationMethod' ) ; if ( $ authenticatorField ) { $ authenticatorField -> setValue ( $ class ) ; } return $ this ; }
|
Set the authenticator class name to use
|
4,997
|
public function hit ( ) { if ( ! $ this -> getCache ( ) -> has ( $ this -> getIdentifier ( ) ) ) { $ ttl = $ this -> getDecay ( ) * 60 ; $ expiry = DBDatetime :: now ( ) -> getTimestamp ( ) + $ ttl ; $ this -> getCache ( ) -> set ( $ this -> getIdentifier ( ) . '-timer' , $ expiry , $ ttl ) ; } else { $ expiry = $ this -> getCache ( ) -> get ( $ this -> getIdentifier ( ) . '-timer' ) ; $ ttl = $ expiry - DBDatetime :: now ( ) -> getTimestamp ( ) ; } $ this -> getCache ( ) -> set ( $ this -> getIdentifier ( ) , $ this -> getNumAttempts ( ) + 1 , $ ttl ) ; return $ this ; }
|
Store a hit in the rate limit cache
|
4,998
|
public function getImportSpec ( ) { $ singleton = DataObject :: singleton ( $ this -> objectClass ) ; $ fields = ( array ) $ singleton -> fieldLabels ( false ) ; $ relations = array_merge ( $ singleton -> hasOne ( ) , $ singleton -> hasMany ( ) , $ singleton -> manyMany ( ) ) ; foreach ( $ relations as $ name => $ desc ) { if ( ! is_string ( $ desc ) ) { $ relations [ $ name ] = $ name ; } } return [ 'fields' => $ fields , 'relations' => $ relations , ] ; }
|
Get a specification of all available columns and relations on the used model . Useful for generation of spec documents for technical end users .
|
4,999
|
public function removeFilterOn ( $ fieldExpression ) { $ matched = false ; if ( is_array ( $ fieldExpression ) ) { reset ( $ fieldExpression ) ; $ fieldExpression = key ( $ fieldExpression ) ; } $ where = $ this -> query -> getWhere ( ) ; foreach ( $ where as $ i => $ condition ) { if ( $ condition instanceof SQLConditionGroup ) { $ predicate = $ condition -> conditionSQL ( $ parameters ) ; $ condition = array ( $ predicate => $ parameters ) ; } foreach ( $ condition as $ predicate => $ parameters ) { if ( strpos ( $ predicate , $ fieldExpression ) !== false ) { unset ( $ where [ $ i ] ) ; $ matched = true ; } break ; } } if ( $ matched ) { $ this -> query -> setWhere ( $ where ) ; } else { throw new InvalidArgumentException ( "Couldn't find $fieldExpression in the query filter." ) ; } return $ this ; }
|
Remove a filter from the query
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.