Пример #1
0
 /**
  * @param $file string|\yii\web\UploadedFile
  * @return object
  * @throws InvalidConfigException
  */
 public static function create($file)
 {
     if (is_a($file, self::className())) {
         return $file;
     }
     // UploadedFile
     if (is_a($file, UploadedFile::className())) {
         if ($file->error) {
             throw new InvalidParamException("File upload error \"{$file->error}\"");
         }
         return \Yii::createObject(['class' => self::className(), 'path' => $file->tempName, 'extension' => $file->getExtension()]);
     } else {
         return \Yii::createObject(['class' => self::className(), 'path' => FileHelper::normalizePath($file)]);
     }
 }
Пример #2
0
 /**
  * Populates the file with data from UploadedFile.
  * Sets the file status as [[self::STATUS_UPLOADED_FILE]] too.
  * @param UploadedFile $uploadedFile
  * @throws InvalidParamException if incorrect `$uploadedFile` was passed.
  */
 public function populateFromUploadedFile($uploadedFile)
 {
     if (!$uploadedFile instanceof UploadedFile) {
         throw new InvalidParamException('An instance of ' . UploadedFile::className() . ' is required in ' . __METHOD__ . '.');
     }
     $properties = ['name' => $uploadedFile->name, 'tempName' => $uploadedFile->tempName, 'type' => $uploadedFile->type, 'size' => $uploadedFile->size, 'error' => $uploadedFile->error];
     $this->resetCalculatedProperties();
     Yii::configure($this, $properties);
     $this->status = self::STATUS_UPLOADED_FILE;
     $this->setData(null, false);
 }
 public function testSaveUpload()
 {
     $this->specify('test saveUpload', function () {
         $upload = Stub::make(UploadedFile::className(), ['name' => 'test.txt', 'saveAs' => Stub::once(function ($absoluteFilePath) {
             file_put_contents($absoluteFilePath, 'test content');
             return true;
         })], $this);
         $filePath = Yii::$app->uploads->saveUpload('test', $upload);
         $this->assertNotEmpty($filePath);
         $absoluteFilePath = Yii::$app->uploads->getAbsolutePath($filePath);
         $this->assertFileExists($absoluteFilePath);
         $this->assertEquals('test.txt', pathinfo($filePath, PATHINFO_BASENAME));
         $this->assertEquals('test content', file_get_contents($absoluteFilePath));
     });
 }