瀏覽代碼

[HttpFoundation] use pathinfo() native function to determine file extension. Change File::move() and UploadedFile::move() methods to accept a second argument allowing to move the file with a new name instead of moving it with its original name.

hhamon 14 年之前
父節點
當前提交
e2dc7f47cb

+ 9 - 6
src/Symfony/Component/HttpFoundation/File/File.php

@@ -516,10 +516,8 @@ class File
      */
     public function getExtension()
     {
-        $name = $this->getName();
-
-        if (false !== ($pos = strrpos($name, '.'))) {
-            return substr($name, $pos);
+        if ($ext = pathinfo($this->getName(), \PATHINFO_EXTENSION)) {
+            return '.' . $ext;
         } else {
             return '';
         }
@@ -634,11 +632,16 @@ class File
     /**
      * Moves the file to a new location.
      *
-     * @param string $directory
+     * @param string $directory   The destination folder
+     * @param string $name        The new file name
      */
-    public function move($directory)
+    public function move($directory, $name = null)
     {
         $this->doMove($directory, $this->getName());
+
+        if (null !== $name) {
+            $this->rename($name);
+        }
     }
 
     /**

+ 6 - 2
src/Symfony/Component/HttpFoundation/File/UploadedFile.php

@@ -144,12 +144,16 @@ class UploadedFile extends File
     /**
      * @inheritDoc
      */
-    public function move($directory)
+    public function move($directory, $name = null)
     {
         if (!$this->moved) {
             $this->doMove($directory, $this->originalName);
+
+            if (null !== $name) {
+                $this->rename($name);
+            }
         } else {
-            parent::move($directory);
+            parent::move($directory, $name);
         }
     }
 }

+ 20 - 0
tests/Symfony/Tests/Component/HttpFoundation/File/FileTest.php

@@ -93,6 +93,26 @@ class FileTest extends \PHPUnit_Framework_TestCase
         @unlink($targetPath);
     }
 
+    public function testMoveWithNewName()
+    {
+        $path = __DIR__.'/Fixtures/test.copy.gif';
+        $targetDir = __DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.'directory';
+        $targetPath = $targetDir.DIRECTORY_SEPARATOR.'test.newname.gif';
+        @unlink($path);
+        @unlink($targetPath);
+        copy(__DIR__.'/Fixtures/test.gif', $path);
+
+        $file = new File($path);
+        $file->move($targetDir, 'test.newname.gif');
+
+        $this->assertTrue(file_exists($targetPath));
+        $this->assertFalse(file_exists($path));
+        $this->assertEquals($targetPath, $file->getPath());
+
+        @unlink($path);
+        @unlink($targetPath);
+    }
+
     public function testRename()
     {
         $path = __DIR__.'/Fixtures/test.copy.gif';