Perforce Chronicle 2012.2/486814
API Documentation

P4Cms_Content Class Reference

Provides storage for content entries. More...

Inheritance diagram for P4Cms_Content:
P4Cms_Record_PubSubRecord P4Cms_Record P4Cms_Record_Connected P4Cms_Model P4Cms_ModelInterface

List of all members.

Public Member Functions

 delete ($description=null)
 Delete this record.
 getContentType ()
 Get the content type definition for this content entry.
 getContentTypeId ()
 Get the content type id for this entry.
 getDisplayValue ($field, array $options=array())
 Get a field's display value.
 getExcerpt ($length=100, array $options=array())
 Get an excerpt of the content.
 getExpandedValue ($field)
 Get a field's expanded value.
 getFields ()
 Get all of the field names for this content entry.
 getFilteredValue ($field)
 Get a field's value after output/display filters are applied.
 getModTime ()
 Get the time that this content entry was last modified (submitted).
 getOwner ()
 Get the owner of this content entry.
 getTitle ()
 Get the title for this piece of content.
 getUri ($action= 'view', $params=array())
 Get the URI to this content entry.
 hasValidContentType ()
 Determine if this content entry has a valid content type.
 save ($description=null, $options=null)
 Save this record.
 setContentType ($type)
 Set the content type definition to use for this content entry.
 setId ($id)
 Pub/sub topic documentation for parent fetchAll and count methods.
 setOwner ($user)
 Set the owner of this content entry.
 toLuceneDocument ()
 Cast this content entry to a lucene document for indexing purposes.

Static Public Member Functions

static clearTypeCache (P4Cms_Record_Adapter $adapter=null)
 Clear the static type cache.
static getUriCallback ()
 Returns the current URI callback if one has been set.
static hasUriCallback ()
 Determines if a valid URI callback has been set.
static setUriCallback ($function)
 Set the function to use when generating URI's for content entries.

Public Attributes

const OWNER_FIELD = 'contentOwner'
const TYPE_FIELD = 'contentType'

Protected Member Functions

 _getDefaultValue ($field)
 Extends parent to pull defaults from content type definition.

Static Protected Member Functions

static _getContentType ($id, P4Cms_Record_Adapter $adapter)
 Get a specific content type instance.
static _getContentTypes (P4Cms_Record_Adapter $adapter)
 Get the set of all content types in storage.

Static Protected Attributes

static $_fields
 Specifies the array of fields that the current Record class wishes to use.
static $_fileContentField = 'file'
 Specifies the name of the record field which will be persisted in the file used to store the records.
static $_storageSubPath = 'content'
 Specifies the sub-path to use for storage of records.
static $_topic = 'p4cms.content.record'
static $_typeCache = array()
static $_uriCallback = null

Detailed Description

Provides storage for content entries.

Copyright:
2011-2012 Perforce Software. All rights reserved
License:
Please see LICENSE.txt in top-level folder of this distribution.
Version:
2012.2/486814

Member Function Documentation

static P4Cms_Content::_getContentType ( id,
P4Cms_Record_Adapter adapter 
) [static, protected]

Get a specific content type instance.

Utilizes _getContentTypes() to benefit from cache.

Parameters:
string$ida string for the content type id
P4Cms_Record_Adapter$adapterthe adapter in use.
Returns:
P4Cms_Content_Type an instance of the requested content type.
    {
        $types = static::_getContentTypes($adapter);
        $type  = isset($types[$id]) ? $types[$id] : null;

        // create a in-memory type if we couldn't locate one
        if (!$type) {
            $type = new P4Cms_Content_Type;
            $type->setLabel("Missing Type: " . $id);
        }

        return $type;
    }
static P4Cms_Content::_getContentTypes ( P4Cms_Record_Adapter adapter) [static, protected]

Get the set of all content types in storage.

Caches and indexes (by id) the results of P4Cms_Content_Type::fetchAll().

Parameters:
P4Cms_Record_Adapter$adapterthe adapter in use.
Returns:
array all content types indexed by content type id.
    {
        // cache must be divided by storage adapter.
        $cacheKey = spl_object_hash($adapter);

        // load the content types (but only fetch them once).
        if (!array_key_exists($cacheKey, static::$_typeCache)) {
            $query = new P4Cms_Record_Query;
            $query->setIncludeDeleted(true);
            $types = P4Cms_Content_Type::fetchAll($query, $adapter);

            // cache the content types indexed by id.
            if ($types->count()) {
                $types = array_combine(
                    $types->invoke('getId'),
                    $types->toArray(true)
                );
            }

            static::$_typeCache[$cacheKey] = $types;
        }

        return static::$_typeCache[$cacheKey];
    }
P4Cms_Content::_getDefaultValue ( field) [protected]

Extends parent to pull defaults from content type definition.

Parameters:
string$fieldthe name of the field to get the value of.
Returns:
mixed the default value of the field - null for no default.

Reimplemented from P4Cms_Model.

    {
        // attempt to query content type for default.
        if ($field !== static::TYPE_FIELD) {
            try {
                $type    = $this->getContentType();
                $element = $type->getFormElement($field);
                $value   = $element->getValue();

                if ($value !== null) {
                    return $value;
                }
            } catch (Exception $e) {
                // intentionally ignore errors fetching content type values
            }
        }

        return parent::_getDefaultValue($field);
    }
static P4Cms_Content::clearTypeCache ( P4Cms_Record_Adapter adapter = null) [static]

Clear the static type cache.

If a valid adapter is passed, only that connections cache will be cleared; otherwise all cached types are cleared on all connections.

Parameters:
P4Cms_Record_Adapter$adapteroptional - adapter to clear on or null for all
    {
        if (!$adapter) {
            static::$_typeCache = array();
            return;
        }

        $cacheKey = spl_object_hash($adapter);
        if (array_key_exists($cacheKey, static::$_typeCache)) {
            unset(static::$_typeCache[$cacheKey]);
        }
    }
P4Cms_Content::delete ( description = null)

Delete this record.

Extends delete() to remove from search index.

Parameters:
string$descriptionoptional - a description of the change.
Returns:
P4Cms_Record provides fluent interface.

p4cms.search.delete Perform operations when an entry is deleted from the search-index. Note: Updates to existing entries are accomplished via delete/add. Zend_Search_Lucene_Document|P4Cms_Content $document The entry being deleted.

p4cms.content.record.delete Perform operations on a content entry just prior to deletion. P4Cms_Content $entry The content entry that is about to be deleted.

Reimplemented from P4Cms_Record_PubSubRecord.

    {
        parent::delete($description);

        // remove from search index.
        P4Cms_PubSub::publish("p4cms.search.delete", $this);

        return $this;
    }
P4Cms_Content::getContentType ( )

Get the content type definition for this content entry.

Returns:
P4Cms_Content_Type instance of the content type for this content entry.
    {
        // get type id.
        $type = $this->getContentTypeId();
        if (!strlen($type)) {
            throw new P4Cms_Content_Exception(
                "Cannot get content type. The content type has not been set."
            );
        }

        return static::_getContentType($type, $this->getAdapter());
    }
P4Cms_Content::getContentTypeId ( )

Get the content type id for this entry.

Returns:
string the id of this entry's content type.
    {
        return $this->_getValue(static::TYPE_FIELD);
    }
P4Cms_Content::getDisplayValue ( field,
array $  options = array() 
)

Get a field's display value.

The display value is the result of rendering a field's display decorators. If a field element has no decorators, the plain (expanded) value is returned.

Parameters:
string$fieldthe name of the field to get the display value of.
array$optionsoptional - display options
Returns:
string the display value of the field.
    {
        $type    = $this->getContentType();
        $element = clone $type->getFormElement($field);
        $value   = $this->getFilteredValue($field);

        // set the associated content record (if possible) on the element
        // for decorators to access - requires enhanced element.
        if ($element instanceof P4Cms_Content_EnhancedElementInterface) {
            $element->setContentRecord($this);
        }

        // get decorators to render the element from options param or from
        // the content type.
        $decorators = isset($options['decorators'])
            ? $element->setDecorators($options['decorators'])->getDecorators()
            : $type->getDisplayDecorators($element);

        // if no decorators, just return the plain field value.
        if (empty($decorators)) {
            return $value;
        }

        // we have already applied display filters above, clear any
        // element input filters as we don't want them in this context.
        $element->clearFilters();

        // set the field value on the element for decorators to access
        // note, some elements (e.g. file/image) will ignore attempts to
        // set a value; therefore, decorators will not be able to retrieve
        // the field value from such elements directly.
        $element->setValue($value);

        // render display value using decorators.
        $content = '';
        foreach ($decorators as $decorator) {
            $decorator->setElement($element);
            $content = $decorator->render($content);
        }
        return $content;
    }
P4Cms_Content::getExcerpt ( length = 100,
array $  options = array() 
)

Get an excerpt of the content.

If the content entry has an 'excerpt' field, it will be used; otherwise, the body field will be truncated. If there is no body field, returns null.

Parameters:
int$lengthoptional - the maximum length of the excerpt set to zero to turn off truncating. defaults to 100 characters.
array$optionsOptions influencing the returned excerpt. Valid options: bool filterHtml optional - set to true to convert HTML to text. defaults to true bool fullExcerpt optional - set to true to get full excerpt field; excerptField still truncated. defaults to false bool keepEntities optional - set to true to keep HTML entities intact during HTML filtering. defaults to false string excerptField optional - alternate field to use for excerpt if excerpt field does not exist. defaults to body
Returns:
string the excerpt text
    {
        // setup option defaults
        $options = array_merge(
            array(
                'filterHtml'    => true,
                'fullExcerpt'   => false,
                'keepEntities'  => false,
                'excerptField'  => 'body'
            ),
            $options
        );

        if ($this->hasField('excerpt')) {
            if ($options['fullExcerpt']) {
                $length = 0;
            }
            $excerpt = $this->getValue('excerpt');
        } else if ($this->hasField($options['excerptField'])) {
            $excerpt = $this->getValue($options['excerptField']);
        } else if ($this->hasField('body')) {
            $excerpt = $this->getValue('body');
        } else {
            return null;
        }

        // convert to plain-text.
        if ($options['filterHtml']) {
            $filter  = new P4Cms_Filter_HtmlToText(array('keepEntities' => $options['keepEntities']));
            $excerpt = $filter->filter($excerpt);
        }

        // truncate excerpt.
        if ($length !== 0) {
            $truncate = new P4Cms_View_Helper_Truncate;
            $excerpt  = $truncate->truncate($excerpt, $length, null, false);
        }

        return $excerpt;
    }
P4Cms_Content::getExpandedValue ( field)

Get a field's expanded value.

If a field contains macros and macros are enabled for the field, this will return the field value with macros evaluated.

Parameters:
string$fieldthe name of the field to get the expanded value of.
Returns:
string the expanded value of the field.
    {
        $type    = $this->getContentType();
        $element = $type->getElement($field);
        $value   = $this->getValue($field);

        // if macros are enabled, invoke them.
        if (isset($element['options']['macros']['enabled'])) {
            $filter = new P4Cms_Filter_Macro;
            $filter->setContext(array('content' => $this, 'element' => $element));
            $value = $filter->filter($value);
        }

        return $value;
    }
P4Cms_Content::getFields ( )

Get all of the field names for this content entry.

Adds the fields defined by the content type.

Returns:
array a list of field names for this spec.

Reimplemented from P4Cms_Record.

    {
        $fields = array_flip(parent::getFields());

        // add fields from the content type.
        if ($this->hasValidContentType()) {
            $fields = $this->getContentType()->getElements() + $fields;
        }

        return array_keys($fields);
    }
P4Cms_Content::getFilteredValue ( field)

Get a field's value after output/display filters are applied.

Parameters:
string$fieldthe name of the field to get the filtered value of.
Returns:
string the filtered value of hte field.
    {
        $type  = $this->getContentType();
        $value = $this->getExpandedValue($field);

        // apply element's display filters.
        foreach ($type->getDisplayFilters($field) as $filter) {
            $value = $filter->filter($value);
        }

        return $value;
    }
P4Cms_Content::getModTime ( )

Get the time that this content entry was last modified (submitted).

Returns:
int the modification timestamp.
    {
        return $this->_getP4File()->getStatus('headTime');
    }
P4Cms_Content::getOwner ( )

Get the owner of this content entry.

Returns:
string id of owner user.
    {
        return $this->_getValue(static::OWNER_FIELD);
    }
P4Cms_Content::getTitle ( )

Get the title for this piece of content.

If the content has no title, returns the id.

Returns:
string the title or the content id if no title is set.
    {
        $title = $this->hasField('title')
            ? trim($this->_getValue('title'))
            : null;

        return $title ?: $this->getId();
    }
P4Cms_Content::getUri ( action = 'view',
params = array() 
)

Get the URI to this content entry.

If an action is provided, will return a URI to perform the given action.

Parameters:
string$actionoptional - action to perform - defaults to 'view'.
array$paramsoptional - additional params to add to the uri.
Returns:
string the uri of the content entry.
    {
        return call_user_func(static::getUriCallback(), $this, $action, $params);
    }
static P4Cms_Content::getUriCallback ( ) [static]

Returns the current URI callback if one has been set.

Returns:
callback The current URI callback.
Exceptions:
P4Cms_Content_ExceptionIf no URI callback has been set.
    {
        if (!static::hasUriCallback()) {
            throw new P4Cms_Content_Exception(
                'Cannot get URI callback, no URI callback has been set.'
            );
        }

        return static::$_uriCallback;
    }
static P4Cms_Content::hasUriCallback ( ) [static]

Determines if a valid URI callback has been set.

Returns:
bool True if valid URI callback set, False otherwise.
    {
        return is_callable(static::$_uriCallback);
    }
P4Cms_Content::hasValidContentType ( )

Determine if this content entry has a valid content type.

Returns:
bool true if the entry has a valid content type.
    {
        try {
            $type = $this->getContentType();
            if ($type->hasValidElements()) {
                return true;
            } else {
                return false;
            }
        } catch (P4Cms_Content_Exception $e) {
            return false;
        }
    }
P4Cms_Content::save ( description = null,
options = null 
)

Save this record.

If record does not have an id, this will create one. Extends save() to add to search index.

Parameters:
string$descriptionoptional - a description of the change.
null | string | array$optionsoptional - resolve flags, to be used if conflict occurs. See P4_File::resolve() for details.
Returns:
P4Cms_Record provides a fluent interface

p4cms.search.update Perform search indexing related operations with the passed document. Called when content is saved, indicating it has been added or edited. Zend_Search_Lucene_Document|P4Cms_Content $document The entry being updated.

p4cms.content.record.preSave Perform operations on a content entry just prior to its being saved. P4Cms_Content $entry The content entry that is about to be saved.

p4cms.content.record.postSave Perform operations on a content entry just after it's saved (but before the batch it is in gets committed). P4Cms_Content $entry The content entry that has just been saved.

Reimplemented from P4Cms_Record_PubSubRecord.

    {
        parent::save($description, $options);

        // update search index.
        P4Cms_PubSub::publish("p4cms.search.update", $this);

        return $this;
    }
P4Cms_Content::setContentType ( type)

Set the content type definition to use for this content entry.

Parameters:
string | P4Cms_Content_Type$typeeither a string for the content type id of an instance of a content type.
    {
        if ($type instanceof P4Cms_Content_Type) {
            $type = $type->getId();
        }

        return $this->_setValue(static::TYPE_FIELD, $type);
    }
P4Cms_Content::setId ( id)

Pub/sub topic documentation for parent fetchAll and count methods.

p4cms.content.record.query Adjust the passed query to influence the results of P4Cms_Content's fetch/fetchAll/count results (e.g. to exclude unpublished content). P4Cms_Record_Query $query The query that is about to be used to retrieve records from storage. P4Cms_Record_Adapter $adapter The current storage connection adapter. Set the id of this content. Extends parent to use ContentId validator instead of RecordId validator.

Parameters:
string | int | null$idthe identifier of this entry.
Returns:
P4Cms_Content provides fluent interface.

Reimplemented from P4Cms_Record.

    {
        // normalize empty strings to null; this is helpful for form input data
        if (is_string($id) && !strlen($id)) {
            $id = null;
        }

        $validator = new P4Cms_Validate_ContentId;
        if ($id !== null && !$validator->isValid($id)) {
            throw new InvalidArgumentException("Cannot set id. Given id is invalid.");
        }

        return parent::setId($id);
    }
P4Cms_Content::setOwner ( user)

Set the owner of this content entry.

Parameters:
P4Cms_User | string | null$useruser to set as this content entry owner.
Returns:
P4Cms_Content provides fluent interface.
    {
        if ($user instanceof P4Cms_User) {
            $user = $user->getId();
        } else if (!is_string($user) && !is_null($user)) {
            throw new InvalidArgumentException(
                "User must be an instance of P4Cms_User, a string or null."
            );
        }

        return $this->_setValue(static::OWNER_FIELD, $user);
    }
static P4Cms_Content::setUriCallback ( function) [static]

Set the function to use when generating URI's for content entries.

Parameters:
null | callback$functionThe callback function for URI generation. The function should expect three parameters:

  • $content (P4Cms_Content)
  • $action (string)
  • $params (array) Returns a string (the uri).
    {
        if (!is_callable($function) && $function !== null) {
            throw new InvalidArgumentException(
                'Cannot set URI callback. Expected a callable function or null.'
            );
        }

        static::$_uriCallback = $function;
    }
P4Cms_Content::toLuceneDocument ( )

Cast this content entry to a lucene document for indexing purposes.

Returns:
Zend_Search_Lucene_Document a lucene document suitable for indexing.
    {
        // create lucene document from this content entry.
        return new P4Cms_Content_LuceneDocument($this);
    }

Member Data Documentation

P4Cms_Content::$_fields [static, protected]
Initial value:
 array(
        self::TYPE_FIELD    => array(
            'mutator'       => 'setContentType'
        ),
        self::OWNER_FIELD   => array(
            'accessor'      => 'getOwner',
            'mutator'       => 'setOwner'
        )
    )

Specifies the array of fields that the current Record class wishes to use.

The implementing class MUST set this property.

Reimplemented from P4Cms_Record.

P4Cms_Content::$_fileContentField = 'file' [static, protected]

Specifies the name of the record field which will be persisted in the file used to store the records.

If desired, the implementing class needs to set this property to match an entry defined in the $_fields array. If left null, all fields will persist as file attributes.

Reimplemented from P4Cms_Record.

P4Cms_Content::$_storageSubPath = 'content' [static, protected]

Specifies the sub-path to use for storage of records.

This is used in combination with the records path (provided by the storage adapter) to construct the full storage path. The implementing class MUST set this property.

Reimplemented from P4Cms_Record.

P4Cms_Content::$_topic = 'p4cms.content.record' [static, protected]

Reimplemented from P4Cms_Record_PubSubRecord.

P4Cms_Content::$_typeCache = array() [static, protected]
P4Cms_Content::$_uriCallback = null [static, protected]
const P4Cms_Content::OWNER_FIELD = 'contentOwner'
const P4Cms_Content::TYPE_FIELD = 'contentType'

The documentation for this class was generated from the following file: