Model::getMLVariable()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
/**
4
 * Model
5
 * @copyright Copyright (c) 2011 - 2014 Aleksandr Torosh (http://wezoom.com.ua)
6
 * @author Aleksandr Torosh <[email protected]>
7
 */
8
namespace Application\Mvc\Model;
9
10
class Model extends \Phalcon\Mvc\Model
11
{
12
    const CACHE_LIFETIME = 300;
13
14
    protected $translations_array = []; // Массив переводов
15
16
    public $translations = [];
17
    public $fields = [];
18
19
    public static $lang = 'en'; // Язык по-умолчанию
20
    public static $custom_lang = ''; // Используется для создания карты сайта
21
    private static $translateCache = true; // Флаг использования кеша переводов
22
23
    /**
24
     * Translate. Для реализации мультиязычной схемы, необходимо скопировать в вашу модель следующие методы:
25
     * Start Copy:
26
     */
27
    protected $translateModel; // translate // Название связанного класса с переводами, например = 'Page\Model\Translate\PageTranslate'
28
29
    public function initialize()
30
    {
31
        $this->hasMany("id", $this->translateModel, "foreign_id"); // translate
32
    }
33
    //End Copy
34
35
    /**
36
     * Метод вызывается после извлечения всех полей в модели
37
     */
38
    public function afterFetch()
39
    {
40
        if ($this->translateModel && defined('LANG')) {
41
            // Если есть массив переводов и установлена константа активного языка или другого языка
42
            if(self::$custom_lang){
43
                self::setLang(self::$custom_lang);
44
            } else {
45
                self::setLang(LANG); // Устанавливаем текущий язык
46
            }
47
48
            $this->initTranslationsArray(); // Извлекаем переводы со связанной таблицы переводов
49
            $this->initTranslations();
50
        }
51
    }
52
53
    /**
54
     * Очищение кеша переводов
55
     * Метод вызывается после обновления значений в модели
56
     */
57
    public function afterUpdate()
58
    {
59
        $this->deleteTranslateCache();
60
    }
61
62
    /**
63
     * Установка языка
64
     */
65
    public static function setLang($lang)
66
    {
67
        self::$lang = $lang;
68
    }
69
70
    /**
71
     * Установка другого языка  для карты сайта
72
     */
73
    public static function setCustomLang($lang)
74
    {
75
        self::$custom_lang = $lang;
76
    }
77
78
    /**
79
     * Установка флага использования кеша.
80
     * Нужно устанавливать до вызова других методов модели.
81
     * Пример:
82
     *
83
     * ModelName::setTranslateCache(false); // Устанавливаем флаг. Отключение кеша необходимо при работе с моделями в админке
84
     * $entries = ModelName::find(); // Извлекаем данные
85
     */
86
    public static function setTranslateCache($value)
87
    {
88
        self::$translateCache = (bool) $value;
89
    }
90
91
    /**
92
     * Извлечение единичного перевода по имени переменной
93
     */
94
    public function getMLVariable($key)
95
    {
96
        if (array_key_exists($key, $this->translations)) {
97
            return $this->translations[$key];
98
        }
99
100
    }
101
102
    public function setMLVariable($key, $value, $lang = null)
103
    {
104
        if (!$this->getId()) {
0 ignored issues
show
Documentation Bug introduced by
The method getId does not exist on object<Application\Mvc\Model\Model>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
105
            return false;
106
        }
107
        $model = new $this->translateModel();
108
        if (!$lang) {
109
            $lang = self::$lang;
110
        }
111
        $conditions = "foreign_id = :foreign_id: AND lang = :lang: AND key = :key:";
112
        $parameters = [
113
            'foreign_id' => $this->getId(),
0 ignored issues
show
Documentation Bug introduced by
The method getId does not exist on object<Application\Mvc\Model\Model>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
114
            'lang'       => $lang,
115
            'key'        => $key
116
        ];
117
        $entity = $model->findFirst([
118
            $conditions,
119
            'bind' => $parameters]);
120
        if (!$entity) {
121
            $entity = new $this->translateModel();
122
            $entity->setForeignId($this->getId());
0 ignored issues
show
Documentation Bug introduced by
The method getId does not exist on object<Application\Mvc\Model\Model>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
123
            $entity->setLang($lang);
124
            $entity->setKey($key);
125
        }
126
        $entity->setValue($value);
127
        $entity->save();
128
    }
129
130
    public function translateCacheKey()
131
    {
132
        if (!$this->getId()) {
0 ignored issues
show
Documentation Bug introduced by
The method getId does not exist on object<Application\Mvc\Model\Model>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
133
            return false;
134
        }
135
        $query = 'foreign_id = ' . $this->getId() . ' AND lang = "' . self::$lang . '"';
0 ignored issues
show
Documentation Bug introduced by
The method getId does not exist on object<Application\Mvc\Model\Model>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
136
        $key = HOST_HASH . md5($this->getSource() . '_translate ' . $query);
137
        return $key;
138
    }
139
140
    public function deleteTranslateCache()
141
    {
142
        if (!$this->getId()) {
0 ignored issues
show
Documentation Bug introduced by
The method getId does not exist on object<Application\Mvc\Model\Model>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
143
            return false;
144
        }
145
        $cache = $this->getDi()->get('cache');
0 ignored issues
show
Bug introduced by
The method get cannot be called on $this->getDi() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
146
        $cache->delete($this->translateCacheKey());
147
    }
148
149
    /**
150
     * Извлечение массива переводов
151
     */
152
    private function initTranslationsArray()
153
    {
154
        if (!$this->getId()) {
0 ignored issues
show
Documentation Bug introduced by
The method getId does not exist on object<Application\Mvc\Model\Model>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
155
            return false;
156
        }
157
        $model = new $this->translateModel();
158
        $query = 'foreign_id = ' . $this->getId() . ' AND lang = "' . self::$lang . '"';
0 ignored issues
show
Documentation Bug introduced by
The method getId does not exist on object<Application\Mvc\Model\Model>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
159
        $params = ['conditions' => $query];
160
161
        if (self::$translateCache) {
162
            $cache = $this->getDi()->get('cache');
0 ignored issues
show
Bug introduced by
The method get cannot be called on $this->getDi() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
163
            $data = $cache->get($this->translateCacheKey());
164
            if (!$data) {
165
                $data = $model->find($params);
166
                if ($data) {
167
                    $cache->save($this->translateCacheKey(), $data, self::CACHE_LIFETIME);
168
                }
169
            }
170
        } else {
171
            $data = $model->find($params);
172
        }
173
174
        $this->translations_array = $data;
175
    }
176
177
    public function initTranslations()
178
    {
179
        if (!empty($this->translations_array)) {
180
            foreach ($this->translations_array as $translation) {
181
                $this->translations[$translation->getKey()] = $translation->getValue();
182
            }
183
        }
184
    }
185
186
}
187