ArticleContent.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2016-10-16 17:15
  7. */
  8. namespace common\models;
  9. use Yii;
  10. use feehi\cdn\DummyTarget;
  11. /**
  12. * This is the model class for table "{{%content}}".
  13. *
  14. * @property string $id
  15. * @property string $aid
  16. * @property string $content
  17. * @property Article $a
  18. */
  19. class ArticleContent extends \yii\db\ActiveRecord
  20. {
  21. /**
  22. * @inheritdoc
  23. */
  24. public static function tableName()
  25. {
  26. return '{{%article_content}}';
  27. }
  28. /**
  29. * @inheritdoc
  30. */
  31. public function rules()
  32. {
  33. return [
  34. [['aid'], 'required'],
  35. [['aid'], 'integer'],
  36. [['content'], 'string']
  37. ];
  38. }
  39. /**
  40. * @inheritdoc
  41. */
  42. public function attributeLabels()
  43. {
  44. return [
  45. 'id' => Yii::t('app', 'ID'),
  46. 'aid' => Yii::t('app', 'Aid'),
  47. 'content' => Yii::t('app', 'Content'),
  48. ];
  49. }
  50. public function beforeSave($insert)
  51. {
  52. /** @var $cdn \feehi\cdn\TargetInterface */
  53. $cdn = Yii::$app->get('cdn');
  54. if( $cdn instanceof DummyTarget){//未使用cdn
  55. $baseUrl = Yii::$app->params['site']['url'];
  56. }else{
  57. $baseUrl = $cdn->host;
  58. }
  59. $this->content = str_replace($baseUrl, Yii::$app->params['site']['sign'], $this->content);
  60. return true;
  61. }
  62. public function afterFind()
  63. {
  64. /** @var $cdn \feehi\cdn\TargetInterface */
  65. $cdn = Yii::$app->get('cdn');
  66. if( $cdn instanceof DummyTarget){//未使用cdn
  67. $baseUrl = Yii::$app->params['site']['url'];
  68. }else{
  69. $baseUrl = $cdn->host;
  70. }
  71. $this->content = str_replace(Yii::$app->params['site']['sign'], $baseUrl, $this->content);
  72. if (! isset(Yii::$app->params['cdnUrl']) || Yii::$app->params['cdnUrl'] == '') {
  73. return;
  74. }
  75. if (strpos($this->content, 'src="/uploads"')) {
  76. $pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
  77. preg_match_all($pattern, $this->content, $matches);
  78. $matches[1] = array_unique($matches[1]);
  79. foreach ($matches[1] as $v) {
  80. $this->content = str_replace($v, Yii::$app->params['cdnUrl'] . $v, $this->content);
  81. }
  82. } else {
  83. $this->content = str_replace(Yii::$app->params['site']['url'], Yii::$app->params['cdnUrl'], $this->content);
  84. }
  85. }
  86. }