-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathBaseActiveRecord.php
More file actions
843 lines (711 loc) · 17.6 KB
/
Copy pathBaseActiveRecord.php
File metadata and controls
843 lines (711 loc) · 17.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
<?php
namespace webvimark\components;
use webvimark\helpers\LittleBigHelper;
use webvimark\helpers\Singleton;
use webvimark\image\Image;
use yii\caching\TagDependency;
use yii\db\ActiveRecord;
use Yii;
use yii\db\Query;
use yii\helpers\FileHelper;
use yii\helpers\StringHelper;
use yii\validators\Validator;
use yii\web\NotFoundHttpException;
use yii\web\UploadedFile;
class BaseActiveRecord extends ActiveRecord
{
/**
* For how long store cache in mainCache() function
*/
const COMMON_CACHE_TIME = 2592000; // 1 month
/**
* If true, than afterSave() and afterDelete() cache dependency with static::getCacheTag() will be invalidated
*
* @var bool
*/
protected $_enable_common_cache = false;
// ================= Timestamps config starts =================
/**
* Replacement of the TimestampBehavior
*
* @var bool
*/
protected $_timestamp_enabled = false;
/**
* Replacement of the TimestampBehavior
*
* @var array
*/
protected $_timestamp_attributes = [
'create_attribute' => 'created_at',
'update_attribute' => 'updated_at',
];
// ----------------- Timestamps config ends -----------------
// ================= Multilingual config starts =================
protected $_i18n_enabled = false;
/**
* @var array
*/
protected $_i18n_attributes = [];
/**
* @var array
*/
protected $_i18n_admin_routes = [];
/**
* @var string
*/
protected $_i18n_table = 'ml_translations';
// ----------------- Multilingual config ends -----------------
/**
* "thumbDir"=>["dimensions"]
* If "dimensions" is not array, then image will be saved without resizing (in original size)
*
* @var array
*/
public $thumbs = [
'full' => null,
'medium' => [300, 300],
'small' => [50, 50]
];
/**
* Used in flush cache after save and delete. So you can always can be sure that your cache is valid
*
* @return string
*/
public static function getCacheTag()
{
return get_called_class() . '_common_cache';
}
/**
* Reset class-specific cache by tag
*/
public static function resetCache()
{
TagDependency::invalidate(Yii::$app->cache, static::getCacheTag());
}
/**
* @param callable $callable
* @param array $tags
*
* @return mixed
*/
public static function mainCache(callable $callable, $tags = [])
{
if ( $tags === [] )
{
$tags = static::getCacheTag();
}
return static::getDb()->cache($callable, static::COMMON_CACHE_TIME, new TagDependency(['tags'=>$tags]));
}
/**
* @inheritdoc
*/
public function __set($name, $value)
{
if ( $this->_i18n_enabled && in_array($name, $this->_getI18NAttributes()) )
$this->$name = $value;
else
parent::__set($name, $value);
}
/**
* @inheritdoc
*/
public function attributes()
{
if ( $this->_i18n_enabled )
{
return array_merge(parent::attributes(), $this->_getI18NAttributes());
}
return parent::attributes();
}
public function init()
{
parent::init();
$this->_I18NInitialization();
}
/**
* TimestampBehavior replacement
*/
protected function _timeStampBehavior()
{
if ( $this->_timestamp_enabled )
{
$this->{$this->_timestamp_attributes['update_attribute']} = time();
if ( $this->isNewRecord )
{
$this->{$this->_timestamp_attributes['create_attribute']} = time();
}
}
}
// ================= I18N methods starts here =================
/**
* @param boolean $insert
*/
private function _preventI18NOverwritingInNonAdminRoutes($insert)
{
if ( $this->_i18n_enabled && !$insert && !in_array(Yii::$app->requestedRoute, $this->_i18n_admin_routes) )
{
foreach ($this->_i18n_attributes as $i18nAttribute)
{
if ( isset($this->oldAttributes[$i18nAttribute]) )
{
}
}
}
}
/**
* Create string validators for virtual i18n attributes (like name_ru)
*/
private function _I18NInitialization()
{
if ( $this->_i18n_enabled )
{
$singletonKey = 'i18n_initialize' . get_class($this);
$initialized = Singleton::getData($singletonKey);
if ( !$initialized )
{
// Remove unnecessary "/" from admin routes
array_walk($this->_i18n_admin_routes, function(&$val, $key) {
$val = trim($val, '/');
});
foreach ($this->_getI18NAttributes() as $attribute)
{
$validators = $this->getActiveValidators($attribute);
if ( empty($validators) )
{
$this->getValidators()
->append(Validator::createValidator('string', $this, $attribute));
}
}
Singleton::setData($singletonKey, true);
}
}
}
/**
* @param boolean $insert
*/
private function _saveI18NAttributes($insert)
{
if ( $this->_i18n_enabled )
{
foreach ($this->_getI18NAttributes() as $attribute)
{
if ( isset($this->$attribute) AND $this->$attribute !== null)
{
$tmp = explode('_', $attribute);
$language = array_pop($tmp);
$originalAttribute = implode('_', $tmp);
// Update I18N attribute only if current route is in admin routes
if ( !$insert )
{
$oldValue = (new Query())
->select('value')
->from($this->_i18n_table)
->where([
'table_name' => $this->getTableSchema()->fullName,
'model_id' => $this->primaryKey,
'attribute' => $originalAttribute,
'lang' => $language,
])
->limit(1)
->scalar();
if ( $oldValue === false AND $this->$attribute !== '' )
{
$this->_i18nInsertHelper($originalAttribute, $language, $attribute);
}
elseif ( $oldValue != $this->$attribute )
{
$this->_i18nUpdateHelper($originalAttribute, $language, $attribute);
}
}
elseif ( $this->$attribute !== '' ) // Insert only non empty values
{
$this->_i18nInsertHelper($originalAttribute, $language, $attribute);
}
}
}
}
}
private function _i18nInsertHelper($originalAttribute, $language, $attribute)
{
$this->getDb()->createCommand()
->insert($this->_i18n_table, [
'table_name' => $this->getTableSchema()->fullName,
'attribute' => $originalAttribute,
'model_id' => $this->primaryKey,
'lang' => $language,
'value' => $this->$attribute,
])
->execute();
}
private function _i18nUpdateHelper($originalAttribute, $language, $attribute)
{
$this->getDb()->createCommand()
->update($this->_i18n_table, ['value'=>$this->$attribute], [
'table_name' => $this->getTableSchema()->fullName,
'attribute' => $originalAttribute,
'model_id' => $this->primaryKey,
'lang' => $language,
])
->execute();
}
/**
* Delete translated attributes
*/
private function _deleteI18NAttributes()
{
if ( $this->_i18n_enabled )
{
$this->getDb()->createCommand()
->delete($this->_i18n_table, [
'table_name' => $this->getTableSchema()->fullName,
'model_id' => $this->primaryKey,
])
->execute();
}
}
private function _findI18NAttributes()
{
if ( $this->_i18n_enabled )
{
if ( php_sapi_name() === 'cli' || in_array(Yii::$app->requestedRoute, $this->_i18n_admin_routes) )
{
$translations = $this->mlGetTranslations();
$replaceOriginalAttributes = false;
}
else
{
$translations = $this->mlGetLanguageSpecificTranslations();
$replaceOriginalAttributes = Yii::$app->language !== Yii::$app->params['mlConfig']['default_language'];
}
foreach ($translations as $translate)
{
if ( $this->primaryKey == $translate['model_id'] )
{
if ( $replaceOriginalAttributes )
{
if ( $translate['lang'] == Yii::$app->language )
{
$this->{$translate['attribute']} = $translate['value'];
}
}
elseif ( isset(Yii::$app->params['mlConfig']['languages'][$translate['lang']]) )
{
$attribute = $translate['attribute'] . '_' . $translate['lang'];
$this->$attribute = $translate['value'];
}
}
}
}
}
/**
* @return array
*/
private function mlGetTranslations()
{
$values = Singleton::getData('_ml_' . $this->getTableSchema()->fullName);
if ( $values === false )
{
$values = (new Query())
->select(['model_id', 'attribute', 'value', 'lang'])
->from($this->_i18n_table)
->where([
'table_name' => $this->getTableSchema()->fullName,
])
->all();
Singleton::setData('_ml_' . $this->getTableSchema()->fullName, $values);
}
return $values;
}
/**
* @param null|string $language
*
* @return array
*/
private function mlGetLanguageSpecificTranslations($language = null)
{
if ( !$language )
$language = Yii::$app->language;
$values = Singleton::getData('_ml_' . $this->getTableSchema()->fullName . '_' . $language);
if ( $values === false )
{
$values = (new Query())
->select(['model_id', 'attribute', 'value', 'lang'])
->from($this->_i18n_table)
->where([
'table_name' => $this->getTableSchema()->fullName,
'lang' => $language,
])
->all();
Singleton::setData('_ml_' . $this->getTableSchema()->fullName . '_' . $language, $values);
}
return $values;
}
/**
* @return array
*/
private function _getI18NAttributes()
{
$singletonKey = '_mlAttributes_' . get_class($this);
$mlAttributes = Singleton::getData($singletonKey);
if ( $mlAttributes === false )
{
$mlAttributes = [];
$languages = Yii::$app->params['mlConfig']['languages'];
// unset($languages[Yii::$app->params['mlConfig']['default_language']]);
foreach ($languages as $languageCode => $languageName)
{
foreach ($this->_i18n_attributes as $attribute)
{
$mlAttributes[] = $attribute . '_' . $languageCode;
}
}
Singleton::setData($singletonKey, $mlAttributes);
}
return $mlAttributes;
}
// ----------------- I18N methods ends here -----------------
/**
* @param mixed $condition
*
* @return bool
*/
public static function deleteIfExists($condition)
{
/** @var BaseActiveRecord $model */
$model = static::findOne($condition);
if ( $model )
{
$model->delete();
return true;
}
return false;
}
/**
* Finds the model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
*
* @param mixed $condition
*
* @return static the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
public static function findOneOrException($condition)
{
if ( ($model = static::findOne($condition)) !== null )
{
return $model;
}
else
{
throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
}
}
/**
* getUploadDir
*
* + Создаёт директории, если их нет
*
* @return string
*/
public function getUploadDir()
{
return Yii::getAlias('@webroot') . '/images/' . trim($this->tableName(), '{}%');
}
/**
* saveImage
*
* @param UploadedFile $file
* @param string $imageName
*/
public function saveImage($file, $imageName)
{
if ( ! $file )
return;
$uploadDir = $this->getUploadDir();
$this->prepareUploadDir($uploadDir);
if ( is_array($this->thumbs) AND !empty($this->thumbs) )
{
foreach ($this->thumbs as $dir => $size)
{
$img = Image::factory($file->tempName);
// If $size is array of dimensions - resize, else - just save
if ( is_array($size) )
$img->resize(implode(',', $size))->save($uploadDir . '/'. $dir . '/' . $imageName);
else
$img->save($uploadDir . '/'. $dir . '/' . $imageName);
}
@unlink($file->tempName);
}
else
{
$file->saveAs($uploadDir . '/' . $imageName);
}
}
/**
* Delete image from all directories
*
* @param string $image
*/
public function deleteImage($image)
{
$uploadDir = $this->getUploadDir();
if ( is_array($this->thumbs) AND !empty($this->thumbs) )
{
foreach (array_keys($this->thumbs) as $thumbDir)
@unlink($uploadDir.'/'.$thumbDir.'/'.$image);
}
else
{
@unlink($uploadDir.'/'.$image);
}
// Delete all cropped images from this object
if ( is_dir($uploadDir . '/_cropped') )
{
$croppedImages = FileHelper::findFiles($uploadDir.'/_cropped', [
'only' => ['*_|_' . $image],
]);
foreach ($croppedImages as $croppedImage)
{
@unlink($croppedImage);
}
}
}
/**
* Provide array of image fields (like: ['logo', 'image'])
* then $model->$imageField will be deleted from all thumb directories (or main dir if there are no thumbs)
*
* @param array $imageFields
*/
public function bulkDeleteImages($imageFields)
{
foreach ($imageFields as $imageField)
{
$this->deleteImage($this->$imageField);
}
}
/**
* getImageUrl
*
* @param string|null $dir
* @param string $attr
* @return string
*/
public function getImageUrl($dir = 'full', $attr = 'image')
{
if ( $dir )
return Yii::$app->request->baseUrl . '/images/'.trim($this->tableName(), '{}%')."/{$dir}/".$this->{$attr};
else
return Yii::$app->request->baseUrl . '/images/'.trim($this->tableName(), '{}%').'/'.$this->{$attr};
}
/**
* getImagePath
*
* @param string|null $dir
* @param string $attr
* @return string
*/
public function getImagePath($dir = 'full', $attr = 'image')
{
if ( $dir )
return $this->getUploadDir() . "/{$dir}/".$this->{$attr};
else
return $this->getUploadDir() . '/'.$this->{$attr};
}
/**
* @param integer $width
* @param integer $height
* @param string $attr
*
* @return string
*/
public function getCroppedImagePath($width, $height, $attr = 'image')
{
$dir = $this->getUploadDir() . '/_cropped';
if (! is_dir($dir))
{
mkdir($dir, 0777, true);
chmod($dir, 0777);
}
return $dir . '/' . $width . '_' . $height . '_|_' . $this->{$attr};
}
/**
* @param integer $width
* @param integer $height
* @param string $dir
* @param string $attr
*
* @return string
*/
public function getCroppedImage($width, $height, $dir = 'full', $attr = 'image')
{
if ( !is_file($this->getCroppedImagePath($width, $height, $attr)) && is_file($this->getImagePath($dir, $attr)) )
{
$image = Image::factory($this->getImagePath($dir, $attr));
$old_aspect = $image->width / $image->height;
$new_aspect = $width / $height;
if ($old_aspect == 1)
{
if ($width > $height)
{
$image->resize($width, $height, Image::WIDTH);
}
else
{
$image->resize($width, $height, Image::HEIGHT);
}
}
elseif ($old_aspect < $new_aspect)
{
$image->resize($width, $height, Image::WIDTH);
}
else
{
$image->resize($width, $height, Image::HEIGHT);
}
$image->crop($width, $height);
$image->save($this->getCroppedImagePath($width, $height, $attr));
}
return Yii::$app->request->baseUrl . '/images/' . trim($this->tableName(), '{}%') . '/_cropped/' . $width . '_' . $height . '_|_' . $this->{$attr};
}
//=========== Rules ===========
public function purgeXSS($attr)
{
$this->$attr = htmlspecialchars($this->$attr, ENT_QUOTES);
}
//----------- Rules -----------
/**
* prepareUploadDir
*
* @param string $dir
*/
public function prepareUploadDir($dir)
{
if (! is_dir($dir))
{
mkdir($dir, 0777, true);
chmod($dir, 0777);
}
// Если нужны папки с thumbs
if ( is_array($this->thumbs) AND !empty($this->thumbs) )
{
foreach (array_keys($this->thumbs) as $thumbDir)
{
if (! is_dir($dir.'/'.$thumbDir))
{
mkdir($dir.'/'.$thumbDir, 0777, true);
chmod($dir.'/'.$thumbDir, 0777);
}
}
}
}
/**
* @param UploadedFile $file
*
* @return string
*/
public function generateFileName($file)
{
return uniqid() . '_' . LittleBigHelper::slug($file->baseName, '_') . '.' . $file->extension;
}
/**
* Check if some attributes uploaded via fileInput field
* and assign them with UploadedFile
*
* @inheritdoc
*/
public function setAttributes($values, $safeOnly = true)
{
parent::setAttributes($values, $safeOnly);
// Looking only for file attributes (and fix null error on fly)
if ( is_array($values) )
{
$attributes = array_flip($safeOnly ? $this->safeAttributes() : $this->attributes());
$class = StringHelper::basename(get_called_class());
foreach ($values as $name => $value)
{
if ( isset( $attributes[$name] ) )
{
if ( isset($_FILES[$class]['name'][$name]) )
{
$uploadedFile = UploadedFile::getInstance($this, $name);
if ( $uploadedFile )
{
$this->$name = $uploadedFile;
}
elseif ( ! $this->isNewRecord )
{
$this->$name = $this->oldAttributes[$name];
}
}
}
}
}
}
// ================= Events =================
/**
* @inheritdoc
*/
public function beforeSave($insert)
{
if ( parent::beforeSave($insert) )
{
$this->_timeStampBehavior();
// $this->_preventI18NOverwritingInNonAdminRoutes($insert);
foreach ($this->attributes as $name => $val)
{
if ( $val instanceof UploadedFile )
{
if ( $val->name AND !$val->hasError )
{
$fileName = $this->generateFileName($val);
if ( !$this->isNewRecord )
{
$this->deleteImage($this->oldAttributes[$name]);
}
$this->saveImage($val, $fileName);
$this->$name = $fileName;
}
elseif ( !$this->isNewRecord )
{
$this->$name = $this->oldAttributes[$name];
}
}
}
return true;
}
return false;
}
/**
* @inheritdoc
*/
public function afterDelete()
{
$this->_deleteI18NAttributes();
if ( $this->_enable_common_cache )
{
TagDependency::invalidate(Yii::$app->cache, static::getCacheTag());
}
parent::afterDelete();
}
/**
* @inheritdoc
*/
public function afterSave($insert, $changedAttributes)
{
$this->_saveI18NAttributes($insert);
if ( $this->_enable_common_cache )
{
TagDependency::invalidate(Yii::$app->cache, static::getCacheTag());
}
parent::afterSave($insert, $changedAttributes);
}
/**
* @inheritdoc
*/
public function afterFind()
{
$this->_findI18NAttributes();
parent::afterFind();
}
}