ModuleProperty_EntityValueTypeVideoLink

Package application.modules.property
Inheritance class ModuleProperty_EntityValueTypeVideoLink » ModuleProperty_EntityValueType » Entity » LsObject
Since 2.0
Source Code /application/classes/modules/property/entity/ValueTypeVideoLink.entity.class.php
Объект управления типом video link

Protected Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
_aBehaviors Список поведений в виде готовых объектов, формируется автоматически LsObject
_aData array Данные сущности, на этот массив мапятся методы set* и get* Entity
aBehaviors array Список поведений LsObject
aValidateErrors array Список ошибок валидации в разрезе полей, например Entity
aValidateRules array Список правил валидации полей Entity
oValue ModuleProperty_EntityValueType
sPrimaryKey null|string Имя поля с первичным ключом в БД Entity
sValidateScenario string Сценарий валиадции полей Entity

Public Methods

Hide inherited methods

MethodDescriptionDefined By
AddBehaviorHook() Добавляет хук поведения LsObject
AttachBehavior() Присоединяет поведение к объекту LsObject
DetachBehavior() Отсоединяет поведение от объекта LsObject
GetBehavior() Возвращает объект поведения по его имени LsObject
GetBehaviors() Возвращает все объекты поведения LsObject
Init() Метод инициализации сущности, вызывается при её создании Entity
RemoveBehaviorHook() Удаляет хук поведения LsObject
RunBehaviorHook() Запускает хук поведения на выполнение LsObject
_Validate() Выполняет валидацию данных сущности Entity
__call() Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля Entity
__clone() При клонировании сбрасываем поведения LsObject
__construct() Если передать в конструктор ассоциативный массив свойств и их значений, то они автоматом загрузятся в сущность Entity
__get() Обработка доступа к объекты поведения LsObject
_addValidateError() Добавляет для поля ошибку в список ошибок Entity
_clearValidateErrors() Очищает список всех ошибок или для конкретного поля Entity
_createValidators() Создает и возвращает список валидаторов для сущности Entity
_getData() Получает массив данных сущности Entity
_getDataArray() Рекурсивное преобразование объекта и вложенных объектов в массив Entity
_getDataOne() Возвращает данные по конкретному полю Entity
_getPrimaryKey() Получение первичного ключа сущности (ключ, а не значение!) Entity
_getPrimaryKeyValue() Возвращает значение первичного ключа/поля Entity
_getValidateError() Возвращает первую ошибку для поля или среди всех полей Entity
_getValidateErrors() Возвращает список ошибок для всех полей или одного поля Entity
_getValidateRules() Возвращает список правил для валидации Entity
_getValidateScenario() Возвращает текущий сценарий валидации Entity
_getValidators() Возвращает список валидаторов с учетом текущего сценария Entity
_hasValidateErrors() Проверяет есть ли ошибки валидации Entity
_setData() Устанавливает данные сущности Entity
_setDataSafe() Устанавливает данные, но только те, которые есть в $this->aValidateRules Entity
_setValidateScenario() Устанавливает сценарий валидации Entity
beforeSaveValue() ModuleProperty_EntityValueType
checkVideo() ModuleProperty_EntityValueTypeVideoLink
getCountView() ModuleProperty_EntityValueTypeVideoLink
getParamsDefault() ModuleProperty_EntityValueType
getPreview() ModuleProperty_EntityValueTypeVideoLink
getValidateRulesDefault() ModuleProperty_EntityValueType
getValueForDisplay() ModuleProperty_EntityValueTypeVideoLink
getValueForForm() ModuleProperty_EntityValueType
getValueObject() ModuleProperty_EntityValueType
getVideoCodeFrame() ModuleProperty_EntityValueTypeVideoLink
getVideoId() ModuleProperty_EntityValueTypeVideoLink
getVideoProvider() ModuleProperty_EntityValueTypeVideoLink
prepareParamsRaw() ModuleProperty_EntityValueType
prepareValidateRulesRaw() ModuleProperty_EntityValueTypeVideoLink
removeValue() ModuleProperty_EntityValueType
resetAllValue() ModuleProperty_EntityValueType
setValue() ModuleProperty_EntityValueTypeVideoLink
setValueObject() ModuleProperty_EntityValueType
validate() ModuleProperty_EntityValueTypeVideoLink

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
PrepareBehaviors() Инициализация поведений LsObject
retrievePreview() ModuleProperty_EntityValueTypeVideoLink
validateStandart() ModuleProperty_EntityValueType

Method Details

checkVideo() method
public void checkVideo($sLink)
$sLink
Source Code: /application/classes/modules/property/entity/ValueTypeVideoLink.entity.class.php#97 (show)
public function checkVideo($sLink)
{
    return 
$this->getVideoId($sLink) ? true false;
}

getCountView() method
public void getCountView()
Source Code: /application/classes/modules/property/entity/ValueTypeVideoLink.entity.class.php#185 (show)
public function getCountView()
{
    
$oValue $this->getValueObject();
    
$sLink $oValue->getValueVarchar();
    
$sProvider $this->getVideoProvider($sLink);
    
$sId $this->getVideoId($sLink);
    if (
$sProvider == self::VIDEO_PROVIDER_YOUTUBE) {
        
$iCount = (int)$oValue->getDataOne("count_view");
        
$iCountViewLastTime = (int)$oValue->getDataOne("count_view_last_time");
        if (
time() - $iCountViewLastTime 60 60 1) {
            
$aData = @json_decode(file_get_contents("https://gdata.youtube.com/feeds/api/videos/{$sId}?v=2&alt=json"),
                
true);
            if (isset(
$aData['entry']['yt$statistics']['viewCount'])) {
                
$iCount $aData['entry']['yt$statistics']['viewCount'];
            }
            
$oValue->setDataOne("count_view"$iCount);
            
$oValue->setDataOne("count_view_last_time"time());
            
$oValue->Update();
        }
        return 
$iCount;
    } elseif (
$sProvider == self::VIDEO_PROVIDER_VIMEO) {

    } elseif (
$sProvider == self::VIDEO_PROVIDER_RUTUBE) {

    }
    return 
null;
}

getPreview() method
public void getPreview($sType='small')
$sType
Source Code: /application/classes/modules/property/entity/ValueTypeVideoLink.entity.class.php#179 (show)
public function getPreview($sType 'small')
{
    
$oValue $this->getValueObject();
    return 
$oValue->getDataOne("preview_{$sType}");
}

getValueForDisplay() method
public void getValueForDisplay()
Source Code: /application/classes/modules/property/entity/ValueTypeVideoLink.entity.class.php#35 (show)
public function getValueForDisplay()
{
    return 
$this->getVideoCodeFrame();
}

getVideoCodeFrame() method
public void getVideoCodeFrame()
Source Code: /application/classes/modules/property/entity/ValueTypeVideoLink.entity.class.php#158 (show)
public function getVideoCodeFrame()
{
    
$sLink $this->getValueObject()->getValueVarchar();
    
$sProvider $this->getVideoProvider($sLink);
    
$sId $this->getVideoId($sLink);
    if (
$sProvider == self::VIDEO_PROVIDER_YOUTUBE) {
        return 
'
            <iframe style="max-width: 100%;width: 100%;height: 495px;" src="//www.youtube.com/embed/' 
$sId '" frameborder="0" allowfullscreen></iframe>
        '
;
    } elseif (
$sProvider == self::VIDEO_PROVIDER_VIMEO) {
        return 
'
            <iframe src="http://player.vimeo.com/video/' 
$sId '?title=0&amp;byline=0&amp;portrait=0&amp;badge=0&amp;color=e6ae9e" style="max-width: 100%;width: 100%;height: 495px;" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
        '
;
    } elseif (
$sProvider == self::VIDEO_PROVIDER_RUTUBE) {
        return 
'
            <iframe src="http://rutube.ru/video/embed/' 
$sId '" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowfullscreen style="max-width: 100%;width: 100%;height: 495px;"></iframe>
        '
;
    }
    return 
'';
}

getVideoId() method
public void getVideoId($sLink=NULL)
$sLink
Source Code: /application/classes/modules/property/entity/ValueTypeVideoLink.entity.class.php#102 (show)
public function getVideoId($sLink null)
{
    if (
is_null($sLink)) {
        
$sLink $this->getValueObject()->getValueVarchar();
    }
    
$sProvider $this->getVideoProvider($sLink);
    
/**
     * youtube
     * http://www.youtube.com/watch?v=LZaCb5Y9SyM
     * http://youtu.be/LZaCb5Y9SyM
     */
    
if ($sProvider == self::VIDEO_PROVIDER_YOUTUBE) {
        if (
preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#"$sLink,
            
$aMatch)) {
            return 
$aMatch[0];
        }
    }
    
/**
     * vimeo
     * http://vimeo.com/72359144
     */
    
if ($sProvider == self::VIDEO_PROVIDER_VIMEO) {
        return 
substr(parse_url($sLinkPHP_URL_PATH), 1);
    }
    
/**
     * rutube
     * http://rutube.ru/video/ee523c9164c8f9fc8b267c66a0a3adae/
     * http://rutube.ru/video/6fd81c1c212c002673280850a1c56415/#.UMQYln9yTWQ
     * http://rutube.ru/tracks/6032725.html
     * http://rutube.ru/video/embed/6032725
     */
    
if ($sProvider == self::VIDEO_PROVIDER_RUTUBE) {
        if (
preg_match('/(?:http|https)+:\/\/(?:www\.|)rutube\.ru\/video\/embed\/([a-zA-Z0-9_\-]+)/i'$sLink,
                
$aMatch) || preg_match('/(?:http|https)+:\/\/(?:www\.|)rutube\.ru\/(?:tracks|video)\/([a-zA-Z0-9_\-]+)(&.+)?/i',
                
$sLink$aMatch)
        ) {
            return 
$aMatch[1];
        }
    }
    return 
null;
}

getVideoProvider() method
public void getVideoProvider($sLink)
$sLink
Source Code: /application/classes/modules/property/entity/ValueTypeVideoLink.entity.class.php#144 (show)
public function getVideoProvider($sLink)
{
    if (
preg_match("#(youtube\.)|(youtu\.be)#i"$sLink)) {
        return 
self::VIDEO_PROVIDER_YOUTUBE;
    }
    if (
preg_match("#(vimeo\.)#i"$sLink)) {
        return 
self::VIDEO_PROVIDER_VIMEO;
    }
    if (
preg_match("#(rutube\.ru)#i"$sLink)) {
        return 
self::VIDEO_PROVIDER_RUTUBE;
    }
    return 
null;
}

prepareValidateRulesRaw() method
public void prepareValidateRulesRaw($aRulesRaw)
$aRulesRaw
Source Code: /application/classes/modules/property/entity/ValueTypeVideoLink.entity.class.php#56 (show)
public function prepareValidateRulesRaw($aRulesRaw)
{
    
$aRules = array();
    
$aRules['allowEmpty'] = isset($aRulesRaw['allowEmpty']) ? false true;
    return 
$aRules;
}

retrievePreview() method
protected void retrievePreview($oValue)
$oValue
Source Code: /application/classes/modules/property/entity/ValueTypeVideoLink.entity.class.php#74 (show)
protected function retrievePreview($oValue)
{
    
$sLink $oValue->getValueVarchar();
    
$sProvider $this->getVideoProvider($sLink);
    
$sId $this->getVideoId($sLink);
    if (
$sProvider == self::VIDEO_PROVIDER_YOUTUBE) {
        
$oValue->setDataOne('preview_small'"http://img.youtube.com/vi/{$sId}/default.jpg");
        
$oValue->setDataOne('preview_normal'"http://img.youtube.com/vi/{$sId}/0.jpg");
    } elseif (
$sProvider == self::VIDEO_PROVIDER_VIMEO) {
        
$aRetrieveData = @json_decode(file_get_contents("http://vimeo.com/api/v2/video/{$sId}.json"), true);
        if (isset(
$aRetrieveData[0]['thumbnail_medium'])) {
            
$oValue->setDataOne('preview_small'$aRetrieveData[0]['thumbnail_medium']);
            
$oValue->setDataOne('preview_normal'$aRetrieveData[0]['thumbnail_large']);
        }
    } elseif (
$sProvider == self::VIDEO_PROVIDER_RUTUBE) {
        
$aRetrieveData = @json_decode(file_get_contents("http://rutube.ru/api/video/{$sId}/?format=json"), true);
        if (isset(
$aRetrieveData['thumbnail_url'])) {
            
$oValue->setDataOne('preview_small'$aRetrieveData['thumbnail_url'] . '?size=s');
            
$oValue->setDataOne('preview_normal'$aRetrieveData['thumbnail_url']);
        }
    }
}

setValue() method
public void setValue($mValue)
$mValue
Source Code: /application/classes/modules/property/entity/ValueTypeVideoLink.entity.class.php#63 (show)
public function setValue($mValue)
{
    
$this->resetAllValue();
    
$oValue $this->getValueObject();
    
$oValue->setValueVarchar($mValue $mValue null);
    
/**
     * Получаем и сохраняем ссылку на превью
     */
    
$this->retrievePreview($oValue);
}

validate() method
public void validate()
Source Code: /application/classes/modules/property/entity/ValueTypeVideoLink.entity.class.php#40 (show)
public function validate()
{
    
$mRes $this->validateStandart('url', array('defaultScheme' => 'http'));
    if (
$mRes === true) {
        
/**
         * Теперь проверяем на принадлежность к разным видео-хостингам
         */
        
if ($this->getValueForValidate() and !$this->checkVideo($this->getValueForValidate())) {
            return 
'Необходимо указать корректную ссылку на видео: YouTube, Vimeo';
        }
        return 
true;
    } else {
        return 
$mRes;
    }
}