Advertisement
alpa_s

Untitled

Jul 16th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.66 KB | None | 0 0
  1.    
  2. в beforeSave
  3.  
  4.         $images = Helper::getImagePath($this->text);
  5.         if ($images && is_array($images)) {
  6.             $this->text = $this->uploadFiles($images);
  7.         }
  8.  
  9.  
  10.  
  11.     /**
  12.      * @param string $html
  13.      * @return array $files
  14.      */
  15.     public static function getImagePath($html)
  16.     {
  17.         $files = null;
  18.         $html = SimpleHtmlDom::str_get_html($html);
  19.         $images = $html->find('img');
  20.         foreach ($images as $img) {
  21.             $src = $img->getAttribute('src');
  22.             if ($src) {
  23.                 $files[] = $src;
  24.             }
  25.         }
  26.         return $files;
  27.     }
  28.  
  29.     /**
  30.      * @param array $files
  31.      * @return string $text
  32.      */
  33.     public function uploadFiles($files)
  34.     {
  35.         $extensions = array('jpg', 'gif', 'png', 'jpeg', 'bmp', 'svg');
  36.         $text = $this->text;
  37.         $dir = Yii::getAlias('@storage/web');
  38.         $name = $dir . "/articles/article{$this->id}/";
  39.         if (!is_dir($name)) {
  40.             mkdir($name, 0777, true);
  41.         }
  42.         foreach ($files as $file) {
  43.             $fileInfo = pathinfo($file);
  44.             if (in_array($fileInfo['extension'], $extensions)) {
  45.                 $fileName = $fileInfo['basename'];
  46.                 $imgHost = parse_url($file)['host'];
  47.                 $baseHost = parse_url(Yii::getAlias('@storageUrl'))['host'];
  48.                 if ($imgHost != $baseHost) {
  49.                     file_put_contents("{$name}/{$fileName}", fopen($file, 'r'));
  50.                     $text = str_replace($file, Url::to("@storageUrl/articles/article{$this->id}/{$fileName}"), $text);
  51.                 }
  52.  
  53.             }
  54.         }
  55.         return $text;
  56.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement