idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
4,500
protected function previewWrite ( $ sql ) { if ( isset ( $ _REQUEST [ 'previewwrite' ] ) && Director :: isDev ( ) && $ this -> connector -> isQueryMutable ( $ sql ) ) { Debug :: message ( "Will execute: $sql" ) ; return true ; } else { return false ; } }
Determines if the query should be previewed and thus interrupted silently . If so this function also displays the query via the debuging system . Subclasess should respect the results of this call for each query and not execute any queries that generate a true response .
4,501
protected function benchmarkQuery ( $ sql , $ callback , $ parameters = array ( ) ) { if ( isset ( $ _REQUEST [ 'showqueries' ] ) && Director :: isDev ( ) ) { $ this -> queryCount ++ ; $ starttime = microtime ( true ) ; $ result = $ callback ( $ sql ) ; $ endtime = round ( microtime ( true ) - $ starttime , 4 ) ; if ( in_array ( strtolower ( $ _REQUEST [ 'showqueries' ] ) , [ 'inline' , 'backtrace' ] ) ) { $ sql = DB :: inline_parameters ( $ sql , $ parameters ) ; } $ queryCount = sprintf ( "%04d" , $ this -> queryCount ) ; Debug :: message ( "\n$queryCount: $sql\n{$endtime}s\n" , false ) ; if ( $ _REQUEST [ 'showqueries' ] === 'backtrace' ) { Backtrace :: backtrace ( ) ; } return $ result ; } else { return $ callback ( $ sql ) ; } }
Allows the display and benchmarking of queries as they are being run
4,502
protected function escapeColumnKeys ( $ fieldValues ) { $ out = array ( ) ; foreach ( $ fieldValues as $ field => $ value ) { $ out [ $ this -> escapeIdentifier ( $ field ) ] = $ value ; } return $ out ; }
Escapes unquoted columns keys in an associative array
4,503
public function clearAllData ( ) { $ tables = $ this -> getSchemaManager ( ) -> tableList ( ) ; foreach ( $ tables as $ table ) { $ this -> clearTable ( $ table ) ; } }
Clear all data out of the database
4,504
public function connect ( $ parameters ) { if ( empty ( $ parameters [ 'driver' ] ) ) { $ parameters [ 'driver' ] = $ this -> getDatabaseServer ( ) ; } $ this -> connector -> connect ( $ parameters ) ; if ( ! empty ( $ parameters [ 'database' ] ) ) { $ this -> selectDatabase ( $ parameters [ 'database' ] , false , false ) ; } }
Instruct the database to generate a live connection
4,505
public function selectDatabase ( $ name , $ create = false , $ errorLevel = E_USER_ERROR ) { $ canConnect = Config :: inst ( ) -> get ( static :: class , 'optimistic_connect' ) || $ this -> schemaManager -> databaseExists ( $ name ) ; if ( $ canConnect ) { return $ this -> connector -> selectDatabase ( $ name ) ; } if ( ! $ create ) { if ( $ errorLevel !== false ) { user_error ( "Attempted to connect to non-existing database \"$name\"" , $ errorLevel ) ; } $ this -> connector -> unloadDatabase ( ) ; return false ; } $ this -> schemaManager -> createDatabase ( $ name ) ; return $ this -> connector -> selectDatabase ( $ name ) ; }
Change the connection to the specified database optionally creating the database if it doesn t exist in the current schema .
4,506
public function dropSelectedDatabase ( ) { $ databaseName = $ this -> connector -> getSelectedDatabase ( ) ; if ( $ databaseName ) { $ this -> connector -> unloadDatabase ( ) ; $ this -> schemaManager -> dropDatabase ( $ databaseName ) ; } }
Drop the database that this object is currently connected to . Use with caution .
4,507
protected function getRedirect ( HTTPRequest $ request ) { if ( ! $ this -> isEnabled ( ) ) { return null ; } $ host = $ request -> getHost ( ) ; $ scheme = $ request -> getScheme ( ) ; if ( $ this -> requiresSSL ( $ request ) ) { $ scheme = 'https' ; $ host = $ this -> getForceSSLDomain ( ) ? : $ host ; } if ( $ this -> getForceWWW ( ) && strpos ( $ host , 'www.' ) !== 0 ) { $ host = "www.{$host}" ; } if ( $ request -> getScheme ( ) === $ scheme && $ request -> getHost ( ) === $ host ) { return null ; } return $ this -> redirectToScheme ( $ request , $ scheme , $ host ) ; }
Given request object determine if we should redirect .
4,508
public function throwRedirectIfNeeded ( HTTPRequest $ request = null ) { $ request = $ this -> getOrValidateRequest ( $ request ) ; if ( ! $ request ) { return ; } $ response = $ this -> getRedirect ( $ request ) ; if ( $ response ) { throw new HTTPResponse_Exception ( $ response ) ; } }
Handles redirection to canonical urls outside of the main middleware chain using HTTPResponseException . Will not do anything if a current HTTPRequest isn t available
4,509
protected function getOrValidateRequest ( HTTPRequest $ request = null ) { if ( $ request instanceof HTTPRequest ) { return $ request ; } if ( Injector :: inst ( ) -> has ( HTTPRequest :: class ) ) { return Injector :: inst ( ) -> get ( HTTPRequest :: class ) ; } return null ; }
Return a valid request if one is available or null if none is available
4,510
protected function requiresSSL ( HTTPRequest $ request ) { if ( ! $ this -> getForceSSL ( ) ) { return false ; } if ( $ request -> getScheme ( ) === 'https' ) { return false ; } $ patterns = $ this -> getForceSSLPatterns ( ) ; if ( ! $ patterns ) { return true ; } $ relativeURL = $ request -> getURL ( true ) ; foreach ( $ patterns as $ pattern ) { if ( preg_match ( $ pattern , $ relativeURL ) ) { return true ; } } return false ; }
Check if a redirect for SSL is necessary
4,511
protected function isEnabled ( ) { if ( ! $ this -> getForceWWW ( ) && ! $ this -> getForceSSL ( ) ) { return false ; } $ enabledEnvs = $ this -> getEnabledEnvs ( ) ; if ( is_bool ( $ enabledEnvs ) ) { return $ enabledEnvs ; } if ( Director :: is_cli ( ) && ! in_array ( 'cli' , $ enabledEnvs ) ) { return false ; } return empty ( $ enabledEnvs ) || in_array ( Director :: get_environment_type ( ) , $ enabledEnvs ) ; }
Ensure this middleware is enabled
4,512
protected function hasBasicAuthPrompt ( HTTPResponse $ response = null ) { if ( ! $ response ) { return false ; } return ( $ response -> getStatusCode ( ) === 401 && $ response -> getHeader ( 'WWW-Authenticate' ) ) ; }
Determine whether the executed middlewares have added a basic authentication prompt
4,513
protected function redirectToScheme ( HTTPRequest $ request , $ scheme , $ host = null ) { if ( ! $ host ) { $ host = $ request -> getHost ( ) ; } $ url = Controller :: join_links ( "{$scheme}://{$host}" , Director :: baseURL ( ) , $ request -> getURL ( true ) ) ; $ response = HTTPResponse :: create ( ) ; $ response -> redirect ( $ url , $ this -> getRedirectType ( ) ) ; return $ response ; }
Redirect the current URL to the specified HTTP scheme
4,514
protected function getRuleForElement ( $ tag ) { if ( isset ( $ this -> elements [ $ tag ] ) ) { return $ this -> elements [ $ tag ] ; } foreach ( $ this -> elementPatterns as $ element ) { if ( preg_match ( $ element -> pattern , $ tag ) ) { return $ element ; } } return null ; }
Given an element tag return the rule structure for that element
4,515
protected function getRuleForAttribute ( $ elementRule , $ name ) { if ( isset ( $ elementRule -> attributes [ $ name ] ) ) { return $ elementRule -> attributes [ $ name ] ; } foreach ( $ elementRule -> attributePatterns as $ attribute ) { if ( preg_match ( $ attribute -> pattern , $ name ) ) { return $ attribute ; } } return null ; }
Given an attribute name return the rule structure for that attribute
4,516
protected function elementMatchesRule ( $ element , $ rule = null ) { if ( ! $ rule ) { return false ; } if ( $ rule -> attributesRequired ) { $ hasMatch = false ; foreach ( $ rule -> attributesRequired as $ attr ) { if ( $ element -> getAttribute ( $ attr ) ) { $ hasMatch = true ; break ; } } if ( ! $ hasMatch ) { return false ; } } if ( $ rule -> removeEmpty && ! $ element -> firstChild ) { return false ; } return true ; }
Given a DOMElement and an element rule check if that element passes the rule
4,517
protected function attributeMatchesRule ( $ attr , $ rule = null ) { if ( ! $ rule ) { return false ; } if ( isset ( $ rule -> validValues ) && ! in_array ( $ attr -> value , $ rule -> validValues ) ) { return false ; } return true ; }
Given a DOMAttr and an attribute rule check if that attribute passes the rule
4,518
public function getRelativePath ( ) { $ parent = $ this -> module -> getRelativePath ( ) ; if ( ! $ parent ) { return $ this -> relativePath ; } return Path :: join ( $ parent , $ this -> relativePath ) ; }
Get the path of this resource relative to the base path .
4,519
public function get ( $ name , $ includeUnsent = true ) { $ cookies = $ includeUnsent ? $ this -> current : $ this -> existing ; if ( isset ( $ cookies [ $ name ] ) ) { return $ cookies [ $ name ] ; } $ safeName = str_replace ( '.' , '_' , $ name ) ; if ( isset ( $ cookies [ $ safeName ] ) ) { return $ cookies [ $ safeName ] ; } return null ; }
Get the cookie value by name
4,520
public function forceExpiry ( $ name , $ path = null , $ domain = null , $ secure = false , $ httpOnly = true ) { $ this -> set ( $ name , false , - 1 , $ path , $ domain , $ secure , $ httpOnly ) ; }
Force the expiry of a cookie by name
4,521
protected function outputCookie ( $ name , $ value , $ expiry = 90 , $ path = null , $ domain = null , $ secure = false , $ httpOnly = true ) { if ( ! headers_sent ( $ file , $ line ) ) { return setcookie ( $ name , $ value , $ expiry , $ path , $ domain , $ secure , $ httpOnly ) ; } if ( Cookie :: config ( ) -> uninherited ( 'report_errors' ) ) { throw new LogicException ( "Cookie '$name' can't be set. The site started outputting content at line $line in $file" ) ; } return false ; }
The function that actually sets the cookie using PHP
4,522
public function Field ( $ properties = array ( ) ) { if ( $ this -> value ) { $ val = Convert :: raw2xml ( $ this -> value ) ; $ val = DBCurrency :: config ( ) -> get ( 'currency_symbol' ) . number_format ( preg_replace ( '/[^0-9.-]/' , '' , $ val ) , 2 ) ; $ valforInput = Convert :: raw2att ( $ val ) ; } else { $ valforInput = '' ; } return "<input class=\"text\" type=\"text\" disabled=\"disabled\"" . " name=\"" . $ this -> name . "\" value=\"" . $ valforInput . "\" />" ; }
Overloaded to display the correctly formatted value for this data type
4,523
public static function cleanHTML ( $ content , $ cleaner = null ) { if ( ! $ cleaner ) { if ( self :: $ html_cleaner_class && class_exists ( self :: $ html_cleaner_class ) ) { $ cleaner = Injector :: inst ( ) -> create ( self :: $ html_cleaner_class ) ; } else { $ cleaner = HTMLCleaner :: inst ( ) ; } } if ( $ cleaner ) { $ content = $ cleaner -> cleanHTML ( $ content ) ; } else { $ doc = HTMLValue :: create ( $ content ) ; $ content = $ doc -> getContent ( ) ; } $ content = preg_replace ( '/<(ins|del)[^>]*\/>/' , '' , $ content ) ; return $ content ; }
Attempt to clean invalid HTML which messes up diffs . This cleans code if possible using an instance of HTMLCleaner
4,524
public function addRow ( $ data = null ) { if ( ( $ current = $ this -> currentRow ( ) ) && $ current -> isEmpty ( ) ) { array_pop ( $ this -> rows ) ; } if ( $ data instanceof SQLAssignmentRow ) { $ this -> rows [ ] = $ data ; } else { $ this -> rows [ ] = new SQLAssignmentRow ( $ data ) ; } return $ this ; }
Appends a new row to insert
4,525
public function getColumns ( ) { $ columns = array ( ) ; foreach ( $ this -> getRows ( ) as $ row ) { $ columns = array_merge ( $ columns , $ row -> getColumns ( ) ) ; } return array_unique ( $ columns ) ; }
Returns the list of distinct column names used in this insert
4,526
public function currentRow ( $ create = false ) { $ current = end ( $ this -> rows ) ; if ( $ create && ! $ current ) { $ this -> rows [ ] = $ current = new SQLAssignmentRow ( ) ; } return $ current ; }
Returns the currently set row
4,527
public function getDateFormat ( ) { if ( $ this -> getHTML5 ( ) ) { return DBDate :: ISO_DATE ; } if ( $ this -> dateFormat ) { return $ this -> dateFormat ; } return $ this -> getFrontendFormatter ( ) -> getPattern ( ) ; }
Get date format in CLDR standard format
4,528
public function setFilterFunction ( $ callback ) { if ( ! is_callable ( $ callback , true ) ) { throw new InvalidArgumentException ( 'TreeDropdownField->setFilterCallback(): not passed a valid callback' ) ; } $ this -> filterCallback = $ callback ; return $ this ; }
Set a callback used to filter the values of the tree before displaying to the user .
4,529
public function setDisableFunction ( $ callback ) { if ( ! is_callable ( $ callback , true ) ) { throw new InvalidArgumentException ( 'TreeDropdownField->setDisableFunction(): not passed a valid callback' ) ; } $ this -> disableCallback = $ callback ; return $ this ; }
Set a callback used to disable checkboxes for some items in the tree
4,530
public function setSearchFunction ( $ callback ) { if ( ! is_callable ( $ callback , true ) ) { throw new InvalidArgumentException ( 'TreeDropdownField->setSearchFunction(): not passed a valid callback' ) ; } $ this -> searchCallback = $ callback ; return $ this ; }
Set a callback used to search the hierarchy globally even before applying the filter .
4,531
public function filterMarking ( $ node ) { $ callback = $ this -> getFilterFunction ( ) ; if ( $ callback && ! call_user_func ( $ callback , $ node ) ) { return false ; } if ( $ this -> search ) { return isset ( $ this -> searchIds [ $ node -> ID ] ) && $ this -> searchIds [ $ node -> ID ] ? true : false ; } return true ; }
Marking public function for the tree which combines different filters sensibly . If a filter function has been set that will be called . And if search text is set filter on that too . Return true if all applicable conditions are true false otherwise .
4,532
protected function flattenChildrenArray ( $ children , $ parentTitles = [ ] ) { $ output = [ ] ; foreach ( $ children as $ child ) { $ childTitles = array_merge ( $ parentTitles , [ $ child [ 'title' ] ] ) ; $ grandChildren = $ child [ 'children' ] ; $ contextString = implode ( '/' , $ parentTitles ) ; $ child [ 'contextString' ] = ( $ contextString !== '' ) ? $ contextString . '/' : '' ; unset ( $ child [ 'children' ] ) ; if ( ! $ this -> search || in_array ( $ child [ 'id' ] , $ this -> realSearchIds ) ) { $ output [ ] = $ child ; } $ output = array_merge ( $ output , $ this -> flattenChildrenArray ( $ grandChildren , $ childTitles ) ) ; } return $ output ; }
Flattens a given list of children array items so the data is no longer structured in a hierarchy
4,533
protected function getSearchResults ( ) { $ callback = $ this -> getSearchFunction ( ) ; if ( $ callback ) { return call_user_func ( $ callback , $ this -> getSourceObject ( ) , $ this -> getLabelField ( ) , $ this -> search ) ; } $ sourceObject = $ this -> getSourceObject ( ) ; $ filters = array ( ) ; $ sourceObjectInstance = DataObject :: singleton ( $ sourceObject ) ; $ candidates = array_unique ( [ $ this -> getLabelField ( ) , $ this -> getTitleField ( ) , 'Title' , 'Name' ] ) ; foreach ( $ candidates as $ candidate ) { if ( $ sourceObjectInstance -> hasDatabaseField ( $ candidate ) ) { $ filters [ "{$candidate}:PartialMatch" ] = $ this -> search ; } } if ( empty ( $ filters ) ) { throw new InvalidArgumentException ( sprintf ( 'Cannot query by %s.%s, not a valid database column' , $ sourceObject , $ this -> getTitleField ( ) ) ) ; } return DataObject :: get ( $ this -> getSourceObject ( ) ) -> filterAny ( $ filters ) ; }
Get the DataObjects that matches the searched parameter .
4,534
protected function getCacheKey ( ) { $ target = $ this -> getSourceObject ( ) ; if ( ! isset ( self :: $ cacheKeyCache [ $ target ] ) ) { self :: $ cacheKeyCache [ $ target ] = DataList :: create ( $ target ) -> max ( 'LastEdited' ) ; } return self :: $ cacheKeyCache [ $ target ] ; }
Ensure cache is keyed by last modified datetime of the underlying list . Caches the key for the respective underlying list types since it doesn t need to query again .
4,535
public function writeToManipulation ( & $ manipulation ) { foreach ( $ this -> compositeDatabaseFields ( ) as $ field => $ spec ) { $ fieldObject = $ this -> dbObject ( $ field ) ; $ fieldObject -> writeToManipulation ( $ manipulation ) ; } }
Write all nested fields into a manipulation
4,536
public function isChanged ( ) { if ( ! ( $ this -> record instanceof DataObject ) ) { return $ this -> isChanged ; } foreach ( $ this -> compositeDatabaseFields ( ) as $ field => $ spec ) { $ key = $ this -> getName ( ) . $ field ; if ( $ this -> record -> isChanged ( $ key ) ) { return true ; } } return false ; }
Returns true if this composite field has changed . For fields bound to a DataObject this will be cleared when the DataObject is written .
4,537
public function exists ( ) { foreach ( $ this -> compositeDatabaseFields ( ) as $ field => $ spec ) { $ fieldObject = $ this -> dbObject ( $ field ) ; if ( ! $ fieldObject -> exists ( ) ) { return false ; } } return true ; }
Composite field defaults to exists only if all fields have values
4,538
public function getField ( $ field ) { $ fields = $ this -> compositeDatabaseFields ( ) ; if ( ! isset ( $ fields [ $ field ] ) ) { return null ; } if ( $ this -> record instanceof DataObject ) { $ key = $ this -> getName ( ) . $ field ; return $ this -> record -> getField ( $ key ) ; } if ( isset ( $ this -> record [ $ field ] ) ) { return $ this -> record [ $ field ] ; } return null ; }
get value of a single composite field
4,539
public function setField ( $ field , $ value , $ markChanged = true ) { $ this -> objCacheClear ( ) ; if ( ! $ this -> hasField ( $ field ) ) { parent :: setField ( $ field , $ value ) ; return $ this ; } if ( $ markChanged ) { $ this -> isChanged = true ; } if ( $ this -> record instanceof DataObject ) { $ key = $ this -> getName ( ) . $ field ; $ this -> record -> setField ( $ key , $ value ) ; return $ this ; } $ this -> record [ $ field ] = $ value ; return $ this ; }
Set value of a single composite field
4,540
public function dbObject ( $ field ) { $ fields = $ this -> compositeDatabaseFields ( ) ; if ( ! isset ( $ fields [ $ field ] ) ) { return null ; } $ key = $ this -> getName ( ) . $ field ; $ spec = $ fields [ $ field ] ; $ fieldObject = Injector :: inst ( ) -> create ( $ spec , $ key ) ; $ fieldObject -> setValue ( $ this -> getField ( $ field ) , null , false ) ; return $ fieldObject ; }
Get a db object for the named field
4,541
protected function getItemRequestHandler ( $ gridField , $ record , $ requestHandler ) { $ class = $ this -> getItemRequestClass ( ) ; $ assignedClass = $ this -> itemRequestClass ; $ this -> extend ( 'updateItemRequestClass' , $ class , $ gridField , $ record , $ requestHandler , $ assignedClass ) ; $ handler = Injector :: inst ( ) -> createWithArgs ( $ class , array ( $ gridField , $ this , $ record , $ requestHandler , $ this -> name ) ) ; if ( $ template = $ this -> getTemplate ( ) ) { $ handler -> setTemplate ( $ template ) ; } $ this -> extend ( 'updateItemRequestHandler' , $ handler ) ; return $ handler ; }
Build a request handler for the given record
4,542
public function duplicate ( $ doWrite = true , $ relations = null ) { if ( is_string ( $ relations ) || $ relations === true ) { if ( $ relations === true ) { $ relations = 'many_many' ; } Deprecation :: notice ( '5.0' , 'Use cascade_duplicates config instead of providing a string to duplicate()' ) ; $ relations = array_keys ( $ this -> config ( ) -> get ( $ relations ) ) ? : [ ] ; } if ( $ relations === null ) { $ relations = $ this -> config ( ) -> get ( 'cascade_duplicates' ) ; if ( is_array ( $ relations ) ) { $ relations = array_unique ( $ relations ) ; } } $ map = $ this -> toMap ( ) ; unset ( $ map [ 'Created' ] ) ; $ clone = Injector :: inst ( ) -> create ( static :: class , $ map , false , $ this -> getSourceQueryParams ( ) ) ; $ clone -> ID = 0 ; $ clone -> invokeWithExtensions ( 'onBeforeDuplicate' , $ this , $ doWrite , $ relations ) ; if ( $ relations ) { $ this -> duplicateRelations ( $ this , $ clone , $ relations ) ; } if ( $ doWrite ) { $ clone -> write ( ) ; } $ clone -> invokeWithExtensions ( 'onAfterDuplicate' , $ this , $ doWrite , $ relations ) ; return $ clone ; }
Create a duplicate of this node . Can duplicate many_many relations
4,543
protected function duplicateRelations ( $ sourceObject , $ destinationObject , $ relations ) { $ manyMany = $ sourceObject -> manyMany ( ) ; $ hasMany = $ sourceObject -> hasMany ( ) ; $ hasOne = $ sourceObject -> hasOne ( ) ; $ belongsTo = $ sourceObject -> belongsTo ( ) ; foreach ( $ relations as $ relation ) { switch ( true ) { case array_key_exists ( $ relation , $ manyMany ) : { $ this -> duplicateManyManyRelation ( $ sourceObject , $ destinationObject , $ relation ) ; break ; } case array_key_exists ( $ relation , $ hasMany ) : { $ this -> duplicateHasManyRelation ( $ sourceObject , $ destinationObject , $ relation ) ; break ; } case array_key_exists ( $ relation , $ hasOne ) : { $ this -> duplicateHasOneRelation ( $ sourceObject , $ destinationObject , $ relation ) ; break ; } case array_key_exists ( $ relation , $ belongsTo ) : { $ this -> duplicateBelongsToRelation ( $ sourceObject , $ destinationObject , $ relation ) ; break ; } default : { $ sourceType = get_class ( $ sourceObject ) ; throw new InvalidArgumentException ( "Cannot duplicate unknown relation {$relation} on parent type {$sourceType}" ) ; } } } }
Copies the given relations from this object to the destination
4,544
protected function duplicateManyManyRelations ( $ sourceObject , $ destinationObject , $ filter ) { Deprecation :: notice ( '5.0' , 'Use duplicateRelations() instead' ) ; if ( $ filter === 'many_many' || $ filter === 'belongs_many_many' ) { $ relations = $ sourceObject -> config ( ) -> get ( $ filter ) ; } elseif ( $ filter === true ) { $ relations = $ sourceObject -> manyMany ( ) ; } else { throw new InvalidArgumentException ( "Invalid many_many duplication filter" ) ; } foreach ( $ relations as $ manyManyName => $ type ) { $ this -> duplicateManyManyRelation ( $ sourceObject , $ destinationObject , $ manyManyName ) ; } }
Copies the many_many and belongs_many_many relations from one object to another instance of the name of object .
4,545
public function update ( $ data ) { foreach ( $ data as $ key => $ value ) { if ( strpos ( $ key , '.' ) !== false ) { $ relations = explode ( '.' , $ key ) ; $ fieldName = array_pop ( $ relations ) ; $ relObj = $ this ; $ relation = null ; foreach ( $ relations as $ i => $ relation ) { if ( $ relObj -> $ relation ( ) instanceof DataObject ) { $ parentObj = $ relObj ; $ relObj = $ relObj -> $ relation ( ) ; if ( $ i < sizeof ( $ relations ) - 1 && ! $ relObj -> ID || ( ! $ relObj -> ID && $ parentObj !== $ this ) ) { $ relObj -> write ( ) ; $ relatedFieldName = $ relation . "ID" ; $ parentObj -> $ relatedFieldName = $ relObj -> ID ; $ parentObj -> write ( ) ; } } else { user_error ( "DataObject::update(): Can't traverse relationship '$relation'," . "it has to be a has_one relationship or return a single DataObject" , E_USER_NOTICE ) ; $ relObj = null ; break ; } } if ( $ relObj ) { $ relObj -> $ fieldName = $ value ; $ relObj -> write ( ) ; $ relatedFieldName = $ relation . "ID" ; $ this -> $ relatedFieldName = $ relObj -> ID ; $ relObj -> flushCache ( ) ; } else { $ class = static :: class ; user_error ( "Couldn't follow dot syntax '{$key}' on '{$class}' object" , E_USER_WARNING ) ; } } else { $ this -> $ key = $ value ; } } return $ this ; }
Update a number of fields on this object given a map of the desired changes .
4,546
public function merge ( $ rightObj , $ priority = 'right' , $ includeRelations = true , $ overwriteWithEmpty = false ) { $ leftObj = $ this ; if ( $ leftObj -> ClassName != $ rightObj -> ClassName ) { user_error ( "DataObject->merge(): Invalid object class '{$rightObj->ClassName}' (expected '{$leftObj->ClassName}')." , E_USER_WARNING ) ; return false ; } if ( ! $ rightObj -> ID ) { user_error ( "DataObject->merge(): Please write your merged-in object to the database before merging, to make sure all relations are transferred properly.')." , E_USER_WARNING ) ; return false ; } $ rightData = DataObject :: getSchema ( ) -> fieldSpecs ( get_class ( $ rightObj ) ) ; foreach ( $ rightData as $ key => $ rightSpec ) { if ( $ key === 'ID' ) { continue ; } if ( $ rightSpec === 'ForeignKey' && ! $ includeRelations ) { continue ; } if ( $ priority == 'left' && $ leftObj -> { $ key } !== $ rightObj -> { $ key } ) { continue ; } if ( $ priority == 'right' && ! $ overwriteWithEmpty && empty ( $ rightObj -> { $ key } ) ) { continue ; } $ leftObj -> { $ key } = $ rightObj -> { $ key } ; } if ( $ includeRelations ) { if ( $ manyMany = $ this -> manyMany ( ) ) { foreach ( $ manyMany as $ relationship => $ class ) { $ leftComponents = $ leftObj -> getManyManyComponents ( $ relationship ) ; $ rightComponents = $ rightObj -> getManyManyComponents ( $ relationship ) ; if ( $ rightComponents && $ rightComponents -> exists ( ) ) { $ leftComponents -> addMany ( $ rightComponents -> column ( 'ID' ) ) ; } $ leftComponents -> write ( ) ; } } if ( $ hasMany = $ this -> hasMany ( ) ) { foreach ( $ hasMany as $ relationship => $ class ) { $ leftComponents = $ leftObj -> getComponents ( $ relationship ) ; $ rightComponents = $ rightObj -> getComponents ( $ relationship ) ; if ( $ rightComponents && $ rightComponents -> exists ( ) ) { $ leftComponents -> addMany ( $ rightComponents -> column ( 'ID' ) ) ; } $ leftComponents -> write ( ) ; } } } return true ; }
Merges data and relations from another object of same class without conflict resolution . Allows to specify which dataset takes priority in case its not empty . has_one - relations are just transferred with priority right . has_many and many_many - relations are added regardless of priority .
4,547
public function forceChange ( ) { $ this -> loadLazyFields ( ) ; foreach ( array_keys ( static :: getSchema ( ) -> fieldSpecs ( static :: class ) ) as $ fieldName ) { if ( ! isset ( $ this -> record [ $ fieldName ] ) ) { $ this -> record [ $ fieldName ] = null ; } } $ this -> changeForced = true ; return $ this ; }
Forces the record to think that all its data has changed . Doesn t write to the database . Force - change preseved until next write . Existing CHANGE_VALUE or CHANGE_STRICT values are preserved .
4,548
protected function validateWrite ( ) { if ( $ this -> ObsoleteClassName ) { return new ValidationException ( "Object is of class '{$this->ObsoleteClassName}' which doesn't exist - " . "you need to change the ClassName before you can write it" ) ; } if ( DataObject :: config ( ) -> uninherited ( 'validation_enabled' ) ) { $ result = $ this -> validate ( ) ; if ( ! $ result -> isValid ( ) ) { return new ValidationException ( $ result ) ; } } return null ; }
Determine validation of this object prior to write
4,549
protected function preWrite ( ) { if ( $ writeException = $ this -> validateWrite ( ) ) { $ this -> invokeWithExtensions ( 'onAfterSkippedWrite' ) ; throw $ writeException ; } $ this -> brokenOnWrite = true ; $ this -> onBeforeWrite ( ) ; if ( $ this -> brokenOnWrite ) { user_error ( static :: class . " has a broken onBeforeWrite() function." . " Make sure that you call parent::onBeforeWrite()." , E_USER_ERROR ) ; } }
Prepare an object prior to write
4,550
protected function updateChanges ( $ forceChanges = false ) { if ( $ forceChanges ) { foreach ( $ this -> record as $ field => $ value ) { $ this -> changed [ $ field ] = static :: CHANGE_VALUE ; } return true ; } return $ this -> isChanged ( ) ; }
Detects and updates all changes made to this object
4,551
protected function prepareManipulationTable ( $ baseTable , $ now , $ isNewRecord , & $ manipulation , $ class ) { $ schema = $ this -> getSchema ( ) ; $ table = $ schema -> tableName ( $ class ) ; $ manipulation [ $ table ] = array ( ) ; $ changed = $ this -> getChangedFields ( ) ; foreach ( $ this -> record as $ fieldName => $ fieldValue ) { if ( empty ( $ changed [ $ fieldName ] ) || ( $ table === $ baseTable && $ fieldName === 'ID' ) ) { continue ; } $ specification = $ schema -> fieldSpec ( $ class , $ fieldName , DataObjectSchema :: DB_ONLY | DataObjectSchema :: UNINHERITED ) ; if ( ! $ specification ) { continue ; } $ fieldObj = $ this -> dbObject ( $ fieldName ) ; if ( ! $ fieldObj ) { $ fieldObj = DBField :: create_field ( 'Varchar' , $ fieldValue , $ fieldName ) ; } $ fieldObj -> writeToManipulation ( $ manipulation [ $ table ] ) ; } if ( $ baseTable === $ table ) { $ manipulation [ $ table ] [ 'fields' ] [ 'LastEdited' ] = $ now ; if ( $ isNewRecord ) { $ manipulation [ $ table ] [ 'fields' ] [ 'Created' ] = empty ( $ this -> record [ 'Created' ] ) ? $ now : $ this -> record [ 'Created' ] ; $ manipulation [ $ table ] [ 'fields' ] [ 'ClassName' ] = static :: class ; } } $ manipulation [ $ table ] [ 'command' ] = $ isNewRecord ? 'insert' : 'update' ; $ manipulation [ $ table ] [ 'class' ] = $ class ; if ( $ this -> isInDB ( ) ) { $ manipulation [ $ table ] [ 'id' ] = $ this -> record [ 'ID' ] ; } }
Writes a subset of changes for a specific table to the given manipulation
4,552
protected function writeBaseRecord ( $ baseTable , $ now ) { if ( $ this -> isInDB ( ) ) { return ; } $ manipulation = [ ] ; $ this -> prepareManipulationTable ( $ baseTable , $ now , true , $ manipulation , $ this -> baseClass ( ) ) ; DB :: manipulate ( $ manipulation ) ; $ this -> changed [ 'ID' ] = self :: CHANGE_VALUE ; $ this -> record [ 'ID' ] = DB :: get_generated_id ( $ baseTable ) ; }
Ensures that a blank base record exists with the basic fixed fields for this dataobject
4,553
protected function writeManipulation ( $ baseTable , $ now , $ isNewRecord ) { $ manipulation = array ( ) ; foreach ( ClassInfo :: ancestry ( static :: class , true ) as $ class ) { $ this -> prepareManipulationTable ( $ baseTable , $ now , $ isNewRecord , $ manipulation , $ class ) ; } $ this -> extend ( 'augmentWrite' , $ manipulation ) ; if ( $ isNewRecord ) { $ manipulation [ $ baseTable ] [ 'command' ] = 'update' ; } foreach ( $ manipulation as $ tableManipulation ) { if ( ! isset ( $ tableManipulation [ 'fields' ] ) ) { continue ; } foreach ( $ tableManipulation [ 'fields' ] as $ fieldName => $ fieldValue ) { if ( is_array ( $ fieldValue ) ) { $ dbObject = $ this -> dbObject ( $ fieldName ) ; if ( $ dbObject && $ dbObject -> scalarValueOnly ( ) ) { throw new InvalidArgumentException ( 'DataObject::writeManipulation: parameterised field assignments are disallowed' ) ; } } } } DB :: manipulate ( $ manipulation ) ; }
Generate and write the database manipulation for all changed fields
4,554
public function writeRelations ( ) { if ( ! $ this -> isInDB ( ) ) { return ; } if ( $ this -> unsavedRelations ) { foreach ( $ this -> unsavedRelations as $ name => $ list ) { $ list -> changeToList ( $ this -> $ name ( ) ) ; } $ this -> unsavedRelations = array ( ) ; } }
Writes cached relation lists to the database if possible
4,555
public function writeComponents ( $ recursive = false ) { foreach ( $ this -> components as $ component ) { $ component -> write ( false , false , false , $ recursive ) ; } if ( $ join = $ this -> getJoin ( ) ) { $ join -> write ( false , false , false , $ recursive ) ; } return $ this ; }
Write the cached components to the database . Cached components could refer to two different instances of the same record .
4,556
public static function delete_by_id ( $ className , $ id ) { $ obj = DataObject :: get_by_id ( $ className , $ id ) ; if ( $ obj ) { $ obj -> delete ( ) ; } else { user_error ( "$className object #$id wasn't found when calling DataObject::delete_by_id" , E_USER_WARNING ) ; } }
Delete the record with the given ID .
4,557
public function getComponent ( $ componentName ) { if ( isset ( $ this -> components [ $ componentName ] ) ) { return $ this -> components [ $ componentName ] ; } $ schema = static :: getSchema ( ) ; if ( $ class = $ schema -> hasOneComponent ( static :: class , $ componentName ) ) { $ joinField = $ componentName . 'ID' ; $ joinID = $ this -> getField ( $ joinField ) ; if ( $ class === self :: class ) { $ class = $ this -> getField ( $ componentName . 'Class' ) ; if ( empty ( $ class ) ) { return null ; } } if ( $ joinID ) { $ component = DataObject :: get ( $ class ) -> filter ( 'ID' , $ joinID ) -> setDataQueryParam ( $ this -> getInheritableQueryParams ( ) ) -> first ( ) ; } if ( empty ( $ component ) ) { $ component = Injector :: inst ( ) -> create ( $ class ) ; } } elseif ( $ class = $ schema -> belongsToComponent ( static :: class , $ componentName ) ) { $ joinField = $ schema -> getRemoteJoinField ( static :: class , $ componentName , 'belongs_to' , $ polymorphic ) ; $ joinID = $ this -> ID ; if ( $ joinID ) { if ( $ polymorphic ) { $ filter = array ( "{$joinField}ID" => $ joinID , "{$joinField}Class" => static :: class , ) ; } else { $ filter = array ( $ joinField => $ joinID ) ; } $ component = DataObject :: get ( $ class ) -> filter ( $ filter ) -> setDataQueryParam ( $ this -> getInheritableQueryParams ( ) ) -> first ( ) ; } if ( empty ( $ component ) ) { $ component = Injector :: inst ( ) -> create ( $ class ) ; if ( $ polymorphic ) { $ component -> { $ joinField . 'ID' } = $ this -> ID ; $ component -> { $ joinField . 'Class' } = static :: class ; } else { $ component -> $ joinField = $ this -> ID ; } } } else { throw new InvalidArgumentException ( "DataObject->getComponent(): Could not find component '$componentName'." ) ; } $ this -> components [ $ componentName ] = $ component ; return $ component ; }
Return a unary component object from a one to one relationship as a DataObject . If no component is available an empty component will be returned for non - polymorphic relations or for polymorphic relations with a class set .
4,558
public function setComponent ( $ componentName , $ item ) { $ schema = static :: getSchema ( ) ; if ( $ class = $ schema -> hasOneComponent ( static :: class , $ componentName ) ) { if ( $ item && ! $ item -> isInDB ( ) ) { $ item -> write ( ) ; } $ joinField = $ componentName . 'ID' ; $ this -> setField ( $ joinField , $ item ? $ item -> ID : null ) ; if ( $ class === self :: class ) { $ this -> setField ( $ componentName . 'Class' , $ item ? get_class ( $ item ) : null ) ; } } elseif ( $ class = $ schema -> belongsToComponent ( static :: class , $ componentName ) ) { if ( $ item ) { $ joinField = $ schema -> getRemoteJoinField ( static :: class , $ componentName , 'belongs_to' , $ polymorphic ) ; if ( ! $ polymorphic ) { $ joinField = substr ( $ joinField , 0 , - 2 ) ; } $ item -> setComponent ( $ joinField , $ this ) ; } } else { throw new InvalidArgumentException ( "DataObject->setComponent(): Could not find component '$componentName'." ) ; } $ this -> components [ $ componentName ] = $ item ; return $ this ; }
Assign an item to the given component
4,559
public function getComponents ( $ componentName , $ id = null ) { if ( ! isset ( $ id ) ) { $ id = $ this -> ID ; } $ result = null ; $ schema = $ this -> getSchema ( ) ; $ componentClass = $ schema -> hasManyComponent ( static :: class , $ componentName ) ; if ( ! $ componentClass ) { throw new InvalidArgumentException ( sprintf ( "DataObject::getComponents(): Unknown 1-to-many component '%s' on class '%s'" , $ componentName , static :: class ) ) ; } if ( ! $ id ) { if ( ! isset ( $ this -> unsavedRelations [ $ componentName ] ) ) { $ this -> unsavedRelations [ $ componentName ] = new UnsavedRelationList ( static :: class , $ componentName , $ componentClass ) ; } return $ this -> unsavedRelations [ $ componentName ] ; } $ joinField = $ schema -> getRemoteJoinField ( static :: class , $ componentName , 'has_many' , $ polymorphic ) ; if ( $ polymorphic ) { $ result = PolymorphicHasManyList :: create ( $ componentClass , $ joinField , static :: class ) ; } else { $ result = HasManyList :: create ( $ componentClass , $ joinField ) ; } return $ result -> setDataQueryParam ( $ this -> getInheritableQueryParams ( ) ) -> forForeignID ( $ id ) ; }
Returns a one - to - many relation as a HasManyList
4,560
public function getRelationClass ( $ relationName ) { $ manyManyComponent = $ this -> getSchema ( ) -> manyManyComponent ( static :: class , $ relationName ) ; if ( $ manyManyComponent ) { return $ manyManyComponent [ 'childClass' ] ; } $ config = $ this -> config ( ) ; $ candidates = array_merge ( ( $ relations = $ config -> get ( 'has_one' ) ) ? $ relations : array ( ) , ( $ relations = $ config -> get ( 'has_many' ) ) ? $ relations : array ( ) , ( $ relations = $ config -> get ( 'belongs_to' ) ) ? $ relations : array ( ) ) ; if ( isset ( $ candidates [ $ relationName ] ) ) { $ remoteClass = $ candidates [ $ relationName ] ; if ( ( $ fieldPos = strpos ( $ remoteClass , '.' ) ) !== false ) { return substr ( $ remoteClass , 0 , $ fieldPos ) ; } return $ remoteClass ; } return null ; }
Find the foreign class of a relation on this DataObject regardless of the relation type .
4,561
public function getRelationType ( $ component ) { $ types = array ( 'has_one' , 'has_many' , 'many_many' , 'belongs_many_many' , 'belongs_to' ) ; $ config = $ this -> config ( ) ; foreach ( $ types as $ type ) { $ relations = $ config -> get ( $ type ) ; if ( $ relations && isset ( $ relations [ $ component ] ) ) { return $ type ; } } return null ; }
Given a relation name determine the relation type
4,562
public function inferReciprocalComponent ( $ remoteClass , $ remoteRelation ) { $ remote = DataObject :: singleton ( $ remoteClass ) ; $ class = $ remote -> getRelationClass ( $ remoteRelation ) ; $ schema = static :: getSchema ( ) ; if ( ! $ this -> isInDB ( ) ) { throw new BadMethodCallException ( __METHOD__ . " cannot be called on unsaved objects" ) ; } if ( empty ( $ class ) ) { throw new InvalidArgumentException ( sprintf ( "%s invoked with invalid relation %s.%s" , __METHOD__ , $ remoteClass , $ remoteRelation ) ) ; } if ( $ class === self :: class ) { return null ; } if ( ! is_a ( $ this , $ class , true ) ) { throw new InvalidArgumentException ( sprintf ( "Relation %s on %s does not refer to objects of type %s" , $ remoteRelation , $ remoteClass , static :: class ) ) ; } $ relationType = $ remote -> getRelationType ( $ remoteRelation ) ; switch ( $ relationType ) { case 'has_one' : { $ joinField = "{$remoteRelation}ID" ; $ componentClass = $ schema -> classForField ( $ remoteClass , $ joinField ) ; $ result = HasManyList :: create ( $ componentClass , $ joinField ) ; return $ result -> setDataQueryParam ( $ this -> getInheritableQueryParams ( ) ) -> forForeignID ( $ this -> ID ) ; } case 'belongs_to' : case 'has_many' : { $ joinField = $ schema -> getRemoteJoinField ( $ remoteClass , $ remoteRelation , $ relationType , $ polymorphic ) ; if ( $ polymorphic ) { return null ; } $ joinID = $ this -> getField ( $ joinField ) ; if ( empty ( $ joinID ) ) { return null ; } return DataObject :: get ( $ remoteClass ) -> filter ( 'ID' , $ joinID ) -> setDataQueryParam ( $ this -> getInheritableQueryParams ( ) ) -> first ( ) ; } case 'many_many' : case 'belongs_many_many' : { $ manyMany = $ remote -> getSchema ( ) -> manyManyComponent ( $ remoteClass , $ remoteRelation ) ; $ extraFields = $ schema -> manyManyExtraFieldsForComponent ( $ remoteClass , $ remoteRelation ) ? : array ( ) ; $ result = Injector :: inst ( ) -> create ( $ manyMany [ 'relationClass' ] , $ manyMany [ 'parentClass' ] , $ manyMany [ 'join' ] , $ manyMany [ 'parentField' ] , $ manyMany [ 'childField' ] , $ extraFields , $ manyMany [ 'childClass' ] , $ remoteClass ) ; $ this -> extend ( 'updateManyManyComponents' , $ result ) ; return $ result -> setDataQueryParam ( $ this -> getInheritableQueryParams ( ) ) -> forForeignID ( $ this -> ID ) ; } default : { return null ; } } }
Given a relation declared on a remote class generate a substitute component for the opposite side of the relation .
4,563
public function getManyManyComponents ( $ componentName , $ id = null ) { if ( ! isset ( $ id ) ) { $ id = $ this -> ID ; } $ schema = static :: getSchema ( ) ; $ manyManyComponent = $ schema -> manyManyComponent ( static :: class , $ componentName ) ; if ( ! $ manyManyComponent ) { throw new InvalidArgumentException ( sprintf ( "DataObject::getComponents(): Unknown many-to-many component '%s' on class '%s'" , $ componentName , static :: class ) ) ; } if ( ! $ id ) { if ( ! isset ( $ this -> unsavedRelations [ $ componentName ] ) ) { $ this -> unsavedRelations [ $ componentName ] = new UnsavedRelationList ( $ manyManyComponent [ 'parentClass' ] , $ componentName , $ manyManyComponent [ 'childClass' ] ) ; } return $ this -> unsavedRelations [ $ componentName ] ; } $ extraFields = $ schema -> manyManyExtraFieldsForComponent ( static :: class , $ componentName ) ? : array ( ) ; $ result = Injector :: inst ( ) -> create ( $ manyManyComponent [ 'relationClass' ] , $ manyManyComponent [ 'childClass' ] , $ manyManyComponent [ 'join' ] , $ manyManyComponent [ 'childField' ] , $ manyManyComponent [ 'parentField' ] , $ extraFields , $ manyManyComponent [ 'parentClass' ] , static :: class ) ; $ result = $ result -> alterDataQuery ( function ( $ query ) use ( $ extraFields ) { $ query -> setQueryParam ( 'Component.ExtraFields' , $ extraFields ) ; } ) ; $ joinSort = Config :: inst ( ) -> get ( $ manyManyComponent [ 'join' ] , 'default_sort' ) ; if ( ! empty ( $ joinSort ) ) { $ result = $ result -> sort ( $ joinSort ) ; } $ this -> extend ( 'updateManyManyComponents' , $ result ) ; return $ result -> setDataQueryParam ( $ this -> getInheritableQueryParams ( ) ) -> forForeignID ( $ id ) ; }
Returns a many - to - many component as a ManyManyList .
4,564
public function belongsTo ( $ classOnly = true ) { $ belongsTo = ( array ) $ this -> config ( ) -> get ( 'belongs_to' ) ; if ( $ belongsTo && $ classOnly ) { return preg_replace ( '/(.+)?\..+/' , '$1' , $ belongsTo ) ; } else { return $ belongsTo ? $ belongsTo : array ( ) ; } }
Returns the class of a remote belongs_to relationship . If no component is specified a map of all components and their class name will be returned .
4,565
protected function loadLazyFields ( $ class = null ) { if ( ! $ this -> isInDB ( ) || ! is_numeric ( $ this -> ID ) ) { return false ; } if ( ! $ class ) { $ loaded = array ( ) ; foreach ( $ this -> record as $ key => $ value ) { if ( strlen ( $ key ) > 5 && substr ( $ key , - 5 ) == '_Lazy' && ! array_key_exists ( $ value , $ loaded ) ) { $ this -> loadLazyFields ( $ value ) ; $ loaded [ $ value ] = $ value ; } } return false ; } $ dataQuery = new DataQuery ( $ class ) ; if ( $ params = $ this -> getSourceQueryParams ( ) ) { foreach ( $ params as $ key => $ value ) { $ dataQuery -> setQueryParam ( $ key , $ value ) ; } } $ schema = static :: getSchema ( ) ; $ baseIDColumn = $ schema -> sqlColumnForField ( $ this , 'ID' ) ; $ dataQuery -> where ( [ $ baseIDColumn => $ this -> record [ 'ID' ] ] ) -> limit ( 1 ) ; $ columns = array ( ) ; $ databaseFields = $ schema -> databaseFields ( $ class , false ) ; foreach ( $ databaseFields as $ k => $ v ) { if ( ! isset ( $ this -> record [ $ k ] ) || $ this -> record [ $ k ] === null ) { $ columns [ ] = $ k ; } } if ( $ columns ) { $ query = $ dataQuery -> query ( ) ; $ this -> extend ( 'augmentLoadLazyFields' , $ query , $ dataQuery , $ this ) ; $ this -> extend ( 'augmentSQL' , $ query , $ dataQuery ) ; $ dataQuery -> setQueriedColumns ( $ columns ) ; $ newData = $ dataQuery -> execute ( ) -> record ( ) ; if ( $ newData ) { foreach ( $ newData as $ k => $ v ) { if ( in_array ( $ k , $ columns ) ) { $ this -> record [ $ k ] = $ v ; $ this -> original [ $ k ] = $ v ; unset ( $ this -> record [ $ k . '_Lazy' ] ) ; } } } else { foreach ( $ columns as $ k ) { $ this -> record [ $ k ] = null ; $ this -> original [ $ k ] = null ; unset ( $ this -> record [ $ k . '_Lazy' ] ) ; } } } return true ; }
Loads all the stub fields that an initial lazy load didn t load fully .
4,566
public function getChangedFields ( $ databaseFieldsOnly = false , $ changeLevel = self :: CHANGE_STRICT ) { $ changedFields = array ( ) ; foreach ( $ this -> record as $ k => $ v ) { if ( is_array ( $ databaseFieldsOnly ) && ! in_array ( $ k , $ databaseFieldsOnly ) ) { continue ; } if ( is_object ( $ v ) && method_exists ( $ v , 'isChanged' ) && $ v -> isChanged ( ) ) { $ this -> changed [ $ k ] = self :: CHANGE_VALUE ; } } if ( $ this -> changeForced && $ changeLevel <= self :: CHANGE_STRICT ) { $ changed = array_combine ( array_keys ( $ this -> record ) , array_fill ( 0 , count ( $ this -> record ) , self :: CHANGE_STRICT ) ) ; unset ( $ changed [ 'Version' ] ) ; } else { $ changed = $ this -> changed ; } if ( is_array ( $ databaseFieldsOnly ) ) { $ fields = array_intersect_key ( $ changed , array_flip ( $ databaseFieldsOnly ) ) ; } elseif ( $ databaseFieldsOnly ) { $ fieldsSpecs = static :: getSchema ( ) -> fieldSpecs ( static :: class ) ; $ fields = array_intersect_key ( $ changed , $ fieldsSpecs ) ; } else { $ fields = $ changed ; } if ( $ changeLevel > self :: CHANGE_STRICT ) { if ( $ fields ) { foreach ( $ fields as $ name => $ level ) { if ( $ level < $ changeLevel ) { unset ( $ fields [ $ name ] ) ; } } } } if ( $ fields ) { foreach ( $ fields as $ name => $ level ) { $ changedFields [ $ name ] = array ( 'before' => array_key_exists ( $ name , $ this -> original ) ? $ this -> original [ $ name ] : null , 'after' => array_key_exists ( $ name , $ this -> record ) ? $ this -> record [ $ name ] : null , 'level' => $ level ) ; } } return $ changedFields ; }
Return the fields that have changed since the last write .
4,567
public function hasDatabaseField ( $ field ) { $ spec = static :: getSchema ( ) -> fieldSpec ( static :: class , $ field , DataObjectSchema :: DB_ONLY ) ; return ! empty ( $ spec ) ; }
Returns true if the given field exists as a database column
4,568
public function relObject ( $ fieldPath ) { $ object = null ; $ component = $ this ; foreach ( explode ( '.' , $ fieldPath ) as $ relation ) { if ( ! $ component ) { return null ; } if ( ClassInfo :: hasMethod ( $ component , $ relation ) ) { $ component = $ component -> $ relation ( ) ; } elseif ( $ component instanceof Relation || $ component instanceof DataList ) { $ singleton = DataObject :: singleton ( $ component -> dataClass ( ) ) ; $ component = $ singleton -> dbObject ( $ relation ) ? : $ component -> relation ( $ relation ) ; } elseif ( $ component instanceof DataObject && ( $ dbObject = $ component -> dbObject ( $ relation ) ) ) { $ component = $ dbObject ; } elseif ( $ component instanceof ViewableData && $ component -> hasField ( $ relation ) ) { $ component = $ component -> obj ( $ relation ) ; } else { throw new LogicException ( "$relation is not a relation/field on " . get_class ( $ component ) ) ; } } return $ component ; }
Traverses to a DBField referenced by relationships between data objects .
4,569
public function getReverseAssociation ( $ className ) { if ( is_array ( $ this -> manyMany ( ) ) ) { $ many_many = array_flip ( $ this -> manyMany ( ) ) ; if ( array_key_exists ( $ className , $ many_many ) ) { return $ many_many [ $ className ] ; } } if ( is_array ( $ this -> hasMany ( ) ) ) { $ has_many = array_flip ( $ this -> hasMany ( ) ) ; if ( array_key_exists ( $ className , $ has_many ) ) { return $ has_many [ $ className ] ; } } if ( is_array ( $ this -> hasOne ( ) ) ) { $ has_one = array_flip ( $ this -> hasOne ( ) ) ; if ( array_key_exists ( $ className , $ has_one ) ) { return $ has_one [ $ className ] ; } } return false ; }
Temporary hack to return an association name based on class to get around the mangle of having to deal with reverse lookup of relationships to determine autogenerated foreign keys .
4,570
public static function get ( $ callerClass = null , $ filter = "" , $ sort = "" , $ join = "" , $ limit = null , $ containerClass = DataList :: class ) { if ( $ callerClass == null ) { $ callerClass = get_called_class ( ) ; if ( $ callerClass === self :: class ) { throw new InvalidArgumentException ( 'Call <classname>::get() instead of DataObject::get()' ) ; } if ( $ filter || $ sort || $ join || $ limit || ( $ containerClass !== DataList :: class ) ) { throw new InvalidArgumentException ( 'If calling <classname>::get() then you shouldn\'t pass any other' . ' arguments' ) ; } } elseif ( $ callerClass === self :: class ) { throw new InvalidArgumentException ( 'DataObject::get() cannot query non-subclass DataObject directly' ) ; } if ( $ join ) { throw new InvalidArgumentException ( 'The $join argument has been removed. Use leftJoin($table, $joinClause) instead.' ) ; } $ result = DataList :: create ( $ callerClass ) ; if ( $ filter ) { $ result = $ result -> where ( $ filter ) ; } if ( $ sort ) { $ result = $ result -> sort ( $ sort ) ; } if ( $ limit && strpos ( $ limit , ',' ) !== false ) { $ limitArguments = explode ( ',' , $ limit ) ; $ result = $ result -> limit ( $ limitArguments [ 1 ] , $ limitArguments [ 0 ] ) ; } elseif ( $ limit ) { $ result = $ result -> limit ( $ limit ) ; } return $ result ; }
Return all objects matching the filter sub - classes are automatically selected and included
4,571
public static function flush_and_destroy_cache ( ) { if ( self :: $ _cache_get_one ) { foreach ( self :: $ _cache_get_one as $ class => $ items ) { if ( is_array ( $ items ) ) { foreach ( $ items as $ item ) { if ( $ item ) { $ item -> destroy ( ) ; } } } } } self :: $ _cache_get_one = array ( ) ; }
Flush the get_one global cache and destroy associated objects .
4,572
public static function reset ( ) { DBEnum :: flushCache ( ) ; ClassInfo :: reset_db_cache ( ) ; static :: getSchema ( ) -> reset ( ) ; self :: $ _cache_get_one = array ( ) ; self :: $ _cache_field_labels = array ( ) ; }
Reset all global caches associated with DataObject .
4,573
public static function get_by_id ( $ classOrID , $ idOrCache = null , $ cache = true ) { list ( $ class , $ id , $ cached ) = is_numeric ( $ classOrID ) ? [ get_called_class ( ) , $ classOrID , isset ( $ idOrCache ) ? $ idOrCache : $ cache ] : [ $ classOrID , $ idOrCache , $ cache ] ; if ( $ class === self :: class ) { throw new InvalidArgumentException ( 'DataObject::get_by_id() cannot query non-subclass DataObject directly' ) ; } $ column = static :: getSchema ( ) -> sqlColumnForField ( $ class , 'ID' ) ; return DataObject :: get_one ( $ class , [ $ column => $ id ] , $ cached ) ; }
Return the given element searching by ID .
4,574
public function fieldLabels ( $ includerelations = true ) { $ cacheKey = static :: class . '_' . $ includerelations ; if ( ! isset ( self :: $ _cache_field_labels [ $ cacheKey ] ) ) { $ customLabels = $ this -> config ( ) -> get ( 'field_labels' ) ; $ autoLabels = array ( ) ; $ ancestry = ClassInfo :: ancestry ( static :: class ) ; $ ancestry = array_reverse ( $ ancestry ) ; if ( $ ancestry ) { foreach ( $ ancestry as $ ancestorClass ) { if ( $ ancestorClass === ViewableData :: class ) { break ; } $ types = [ 'db' => ( array ) Config :: inst ( ) -> get ( $ ancestorClass , 'db' , Config :: UNINHERITED ) ] ; if ( $ includerelations ) { $ types [ 'has_one' ] = ( array ) Config :: inst ( ) -> get ( $ ancestorClass , 'has_one' , Config :: UNINHERITED ) ; $ types [ 'has_many' ] = ( array ) Config :: inst ( ) -> get ( $ ancestorClass , 'has_many' , Config :: UNINHERITED ) ; $ types [ 'many_many' ] = ( array ) Config :: inst ( ) -> get ( $ ancestorClass , 'many_many' , Config :: UNINHERITED ) ; $ types [ 'belongs_many_many' ] = ( array ) Config :: inst ( ) -> get ( $ ancestorClass , 'belongs_many_many' , Config :: UNINHERITED ) ; } foreach ( $ types as $ type => $ attrs ) { foreach ( $ attrs as $ name => $ spec ) { $ autoLabels [ $ name ] = _t ( "{$ancestorClass}.{$type}_{$name}" , FormField :: name_to_label ( $ name ) ) ; } } } } $ labels = array_merge ( ( array ) $ autoLabels , ( array ) $ customLabels ) ; $ this -> extend ( 'updateFieldLabels' , $ labels ) ; self :: $ _cache_field_labels [ $ cacheKey ] = $ labels ; } return self :: $ _cache_field_labels [ $ cacheKey ] ; }
Get any user defined searchable fields labels that exist . Allows overriding of default field names in the form interface actually presented to the user .
4,575
public function summaryFields ( ) { $ rawFields = $ this -> config ( ) -> get ( 'summary_fields' ) ; $ fields = [ ] ; foreach ( $ rawFields as $ key => $ value ) { if ( is_int ( $ key ) ) { $ key = $ value ; } $ fields [ $ key ] = $ value ; } if ( ! $ fields ) { $ fields = array ( ) ; if ( $ this -> hasField ( 'Name' ) ) { $ fields [ 'Name' ] = 'Name' ; } if ( static :: getSchema ( ) -> fieldSpec ( $ this , 'Title' ) ) { $ fields [ 'Title' ] = 'Title' ; } if ( $ this -> hasField ( 'Description' ) ) { $ fields [ 'Description' ] = 'Description' ; } if ( $ this -> hasField ( 'FirstName' ) ) { $ fields [ 'FirstName' ] = 'First Name' ; } } $ this -> extend ( "updateSummaryFields" , $ fields ) ; if ( ! $ fields ) { $ fields [ 'ID' ] = 'ID' ; } foreach ( $ this -> fieldLabels ( false ) as $ name => $ label ) { if ( isset ( $ fields [ $ name ] ) && $ name === $ fields [ $ name ] ) { $ fields [ $ name ] = $ label ; } } return $ fields ; }
Get the default summary fields for this object .
4,576
public function defaultSearchFilters ( ) { $ filters = array ( ) ; foreach ( $ this -> searchableFields ( ) as $ name => $ spec ) { if ( empty ( $ spec [ 'filter' ] ) ) { $ filters [ $ name ] = 'PartialMatchFilter' ; } elseif ( $ spec [ 'filter' ] instanceof SearchFilter ) { $ filters [ $ name ] = $ spec [ 'filter' ] ; } else { $ filters [ $ name ] = Injector :: inst ( ) -> create ( $ spec [ 'filter' ] , $ name ) ; } } return $ filters ; }
Defines a default list of filters for the search context .
4,577
public function setJoin ( DataObject $ object , $ alias = null ) { $ this -> joinRecord = $ object ; if ( $ alias ) { if ( static :: getSchema ( ) -> fieldSpec ( static :: class , $ alias ) ) { throw new InvalidArgumentException ( "Joined record $alias cannot also be a db field" ) ; } $ this -> record [ $ alias ] = $ object ; } return $ this ; }
Set joining object
4,578
public function findRelatedObjects ( $ source , $ recursive = true , $ list = null ) { if ( ! $ list ) { $ list = new ArrayList ( ) ; } if ( ! $ this -> isInDB ( ) ) { return $ list ; } $ relationships = $ this -> config ( ) -> get ( $ source ) ? : [ ] ; foreach ( $ relationships as $ relationship ) { if ( ! $ this -> hasMethod ( $ relationship ) ) { trigger_error ( sprintf ( "Invalid %s config value \"%s\" on object on class \"%s\"" , $ source , $ relationship , get_class ( $ this ) ) , E_USER_WARNING ) ; continue ; } $ items = $ this -> { $ relationship } ( ) ; $ newItems = $ this -> mergeRelatedObjects ( $ list , $ items ) ; if ( $ recursive ) { foreach ( $ newItems as $ item ) { $ item -> findRelatedObjects ( $ source , true , $ list ) ; } } } return $ list ; }
Find objects in the given relationships merging them into the given list
4,579
protected function mergeRelatedObject ( $ list , $ added , $ item ) { $ itemKey = get_class ( $ item ) . '/' . $ item -> ID ; if ( $ item -> isInDB ( ) && ! isset ( $ list [ $ itemKey ] ) ) { $ list [ $ itemKey ] = $ item ; $ added [ $ itemKey ] = $ item ; } $ joined = $ item -> getJoin ( ) ; if ( $ joined ) { $ this -> mergeRelatedObject ( $ list , $ added , $ joined ) ; } }
Merge single object into a list but ensures that existing objects are not re - added .
4,580
public function handleAction ( GridField $ gridField , $ actionName , $ arguments , $ data ) { if ( $ actionName == 'print' ) { return $ this -> handlePrint ( $ gridField ) ; } }
Handle the print action .
4,581
public function handlePrint ( $ gridField , $ request = null ) { set_time_limit ( 60 ) ; Requirements :: clear ( ) ; $ data = $ this -> generatePrintData ( $ gridField ) ; $ this -> extend ( 'updatePrintData' , $ data ) ; if ( $ data ) { return $ data -> renderWith ( [ get_class ( $ gridField ) . '_print' , GridField :: class . '_print' , ] ) ; } return null ; }
Handle the print for both the action button and the URL
4,582
protected function getPrintColumnsForGridField ( GridField $ gridField ) { if ( $ this -> printColumns ) { return $ this -> printColumns ; } $ dataCols = $ gridField -> getConfig ( ) -> getComponentByType ( 'SilverStripe\\Forms\\GridField\\GridFieldDataColumns' ) ; if ( $ dataCols ) { return $ dataCols -> getDisplayFields ( $ gridField ) ; } return DataObject :: singleton ( $ gridField -> getModelClass ( ) ) -> summaryFields ( ) ; }
Return the columns to print
4,583
public function getTitle ( GridField $ gridField ) { $ form = $ gridField -> getForm ( ) ; $ currentController = $ gridField -> getForm ( ) -> getController ( ) ; $ title = '' ; if ( method_exists ( $ currentController , 'Title' ) ) { $ title = $ currentController -> Title ( ) ; } else { if ( $ currentController -> Title ) { $ title = $ currentController -> Title ; } elseif ( $ form -> getName ( ) ) { $ title = $ form -> getName ( ) ; } } if ( $ fieldTitle = $ gridField -> Title ( ) ) { if ( $ title ) { $ title .= " - " ; } $ title .= $ fieldTitle ; } return $ title ; }
Return the title of the printed page
4,584
public function generatePrintData ( GridField $ gridField ) { $ printColumns = $ this -> getPrintColumnsForGridField ( $ gridField ) ; $ header = null ; if ( $ this -> printHasHeader ) { $ header = new ArrayList ( ) ; foreach ( $ printColumns as $ field => $ label ) { $ header -> push ( new ArrayData ( array ( "CellString" => $ label , ) ) ) ; } } $ items = $ gridField -> getManipulatedList ( ) ; $ itemRows = new ArrayList ( ) ; foreach ( $ items -> limit ( null ) as $ item ) { $ itemRow = new ArrayList ( ) ; foreach ( $ printColumns as $ field => $ label ) { $ value = $ gridField -> getDataFieldValue ( $ item , $ field ) ; $ itemRow -> push ( new ArrayData ( array ( "CellString" => $ value , ) ) ) ; } $ itemRows -> push ( new ArrayData ( array ( "ItemRow" => $ itemRow ) ) ) ; if ( $ item -> hasMethod ( 'destroy' ) ) { $ item -> destroy ( ) ; } } $ ret = new ArrayData ( array ( "Title" => $ this -> getTitle ( $ gridField ) , "Header" => $ header , "ItemRows" => $ itemRows , "Datetime" => DBDatetime :: now ( ) , "Member" => Security :: getCurrentUser ( ) , ) ) ; return $ ret ; }
Export core .
4,585
public function restoreFormState ( ) { $ result = $ this -> getSessionValidationResult ( ) ; if ( isset ( $ result ) ) { $ this -> loadMessagesFrom ( $ result ) ; } $ data = $ this -> getSessionData ( ) ; if ( isset ( $ data ) ) { $ this -> loadDataFrom ( $ data , self :: MERGE_AS_INTERNAL_VALUE ) ; } return $ this ; }
Load form state from session state
4,586
protected function getRequest ( ) { $ controller = $ this -> getController ( ) ; if ( $ controller && ! ( $ controller -> getRequest ( ) instanceof NullHTTPRequest ) ) { return $ controller -> getRequest ( ) ; } if ( Controller :: has_curr ( ) && ! ( Controller :: curr ( ) -> getRequest ( ) instanceof NullHTTPRequest ) ) { return Controller :: curr ( ) -> getRequest ( ) ; } return null ; }
Helper to get current request for this form
4,587
public function getSessionValidationResult ( ) { $ resultData = $ this -> getSession ( ) -> get ( "FormInfo.{$this->FormName()}.result" ) ; if ( isset ( $ resultData ) ) { return unserialize ( $ resultData ) ; } return null ; }
Return any ValidationResult instance stored for this object
4,588
public function setSessionValidationResult ( ValidationResult $ result , $ combineWithExisting = false ) { if ( $ combineWithExisting ) { $ existingResult = $ this -> getSessionValidationResult ( ) ; if ( $ existingResult ) { if ( $ result ) { $ existingResult -> combineAnd ( $ result ) ; } else { $ result = $ existingResult ; } } } $ resultData = $ result ? serialize ( $ result ) : null ; $ this -> getSession ( ) -> set ( "FormInfo.{$this->FormName()}.result" , $ resultData ) ; return $ this ; }
Sets the ValidationResult in the session to be used with the next view of this form .
4,589
public function setFieldMessage ( $ fieldName , $ message , $ messageType = ValidationResult :: TYPE_ERROR , $ messageCast = ValidationResult :: CAST_TEXT ) { $ field = $ this -> fields -> dataFieldByName ( $ fieldName ) ; if ( $ field ) { $ field -> setMessage ( $ message , $ messageType , $ messageCast ) ; } return $ this ; }
Set message on a given field name . This message will not persist via redirect .
4,590
protected function setupDefaultClasses ( ) { $ defaultClasses = self :: config ( ) -> get ( 'default_classes' ) ; if ( $ defaultClasses ) { foreach ( $ defaultClasses as $ class ) { $ this -> addExtraClass ( $ class ) ; } } }
set up the default classes for the form . This is done on construct so that the default classes can be removed after instantiation
4,591
public function actionIsValidationExempt ( $ action ) { if ( ! $ action ) { return false ; } if ( $ action -> getValidationExempt ( ) ) { return true ; } if ( in_array ( $ action -> actionName ( ) , $ this -> getValidationExemptActions ( ) ) ) { return true ; } return false ; }
Passed a FormAction returns true if that action is exempt from Form validation
4,592
public function Fields ( ) { foreach ( $ this -> getExtraFields ( ) as $ field ) { if ( ! $ this -> fields -> fieldByName ( $ field -> getName ( ) ) ) { $ this -> fields -> push ( $ field ) ; } } return $ this -> fields ; }
Return the form s fields - used by the templates
4,593
public function getAttributesHTML ( $ attrs = null ) { $ exclude = ( is_string ( $ attrs ) ) ? func_get_args ( ) : null ; $ attrs = $ this -> getAttributes ( ) ; $ attrs = array_filter ( ( array ) $ attrs , function ( $ value ) { return ( $ value || $ value === 0 ) ; } ) ; if ( $ exclude ) { $ attrs = array_diff_key ( $ attrs , array_flip ( $ exclude ) ) ; } if ( isset ( $ attrs [ 'method' ] ) ) { $ attrs [ 'method' ] = strtolower ( $ attrs [ 'method' ] ) ; } $ parts = array ( ) ; foreach ( $ attrs as $ name => $ value ) { $ parts [ ] = ( $ value === true ) ? "{$name}=\"{$name}\"" : "{$name}=\"" . Convert :: raw2att ( $ value ) . "\"" ; } return implode ( ' ' , $ parts ) ; }
Return the attributes of the form tag - used by the templates .
4,594
public function getEncType ( ) { if ( $ this -> encType ) { return $ this -> encType ; } if ( $ fields = $ this -> fields -> dataFields ( ) ) { foreach ( $ fields as $ field ) { if ( $ field instanceof FileField ) { return self :: ENC_TYPE_MULTIPART ; } } } return self :: ENC_TYPE_URLENCODED ; }
Returns the encoding type for the form .
4,595
public function sessionMessage ( $ message , $ type = ValidationResult :: TYPE_ERROR , $ cast = ValidationResult :: CAST_TEXT ) { $ this -> setMessage ( $ message , $ type , $ cast ) ; $ result = $ this -> getSessionValidationResult ( ) ? : ValidationResult :: create ( ) ; $ result -> addMessage ( $ message , $ type , null , $ cast ) ; $ this -> setSessionValidationResult ( $ result ) ; }
Set a message to the session for display next time this form is shown .
4,596
public function sessionError ( $ message , $ type = ValidationResult :: TYPE_ERROR , $ cast = ValidationResult :: CAST_TEXT ) { $ this -> setMessage ( $ message , $ type , $ cast ) ; $ result = $ this -> getSessionValidationResult ( ) ? : ValidationResult :: create ( ) ; $ result -> addError ( $ message , $ type , null , $ cast ) ; $ this -> setSessionValidationResult ( $ result ) ; }
Set an error to the session for display next time this form is shown .
4,597
public function forTemplate ( ) { if ( ! $ this -> canBeCached ( ) ) { HTTPCacheControlMiddleware :: singleton ( ) -> disableCache ( ) ; } $ return = $ this -> renderWith ( $ this -> getTemplates ( ) ) ; $ this -> clearMessage ( ) ; return $ return ; }
Return a rendered version of this form .
4,598
protected function canBeCached ( ) { if ( $ this -> getSecurityToken ( ) -> isEnabled ( ) ) { return false ; } if ( $ this -> FormMethod ( ) !== 'GET' ) { return false ; } $ validator = $ this -> getValidator ( ) ; if ( $ validator instanceof RequiredFields ) { if ( count ( $ this -> validator -> getRequired ( ) ) ) { return false ; } } else { return false ; } return true ; }
Can the body of this form be cached?
4,599
public function prepareStatement ( $ sql , & $ success ) { $ statement = $ this -> dbConn -> stmt_init ( ) ; $ this -> setLastStatement ( $ statement ) ; $ success = $ statement -> prepare ( $ sql ) ; return $ statement ; }
Retrieve a prepared statement for a given SQL string