1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Symfony\Component\HttpFoundation\File;
13:
14: use Symfony\Component\HttpFoundation\File\Exception\FileException;
15: use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
16: use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
17: use Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser;
18:
19: 20: 21: 22: 23: 24: 25:
26: class File extends \SplFileInfo
27: {
28: 29: 30: 31: 32: 33: 34: 35: 36: 37:
38: public function __construct($path, $checkPath = true)
39: {
40: if ($checkPath && !is_file($path)) {
41: throw new FileNotFoundException($path);
42: }
43:
44: parent::__construct($path);
45: }
46:
47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61:
62: public function guessExtension()
63: {
64: $type = $this->getMimeType();
65: $guesser = ExtensionGuesser::getInstance();
66:
67: return $guesser->guess($type);
68: }
69:
70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82:
83: public function getMimeType()
84: {
85: $guesser = MimeTypeGuesser::getInstance();
86:
87: return $guesser->guess($this->getPathname());
88: }
89:
90: 91: 92: 93: 94: 95: 96: 97: 98:
99: public function getExtension()
100: {
101: return pathinfo($this->getBasename(), PATHINFO_EXTENSION);
102: }
103:
104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115:
116: public function move($directory, $name = null)
117: {
118: $target = $this->getTargetFile($directory, $name);
119:
120: if (!@rename($this->getPathname(), $target)) {
121: $error = error_get_last();
122: throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $target, strip_tags($error['message'])));
123: }
124:
125: @chmod($target, 0666 & ~umask());
126:
127: return $target;
128: }
129:
130: protected function getTargetFile($directory, $name = null)
131: {
132: if (!is_dir($directory)) {
133: if (false === @mkdir($directory, 0777, true)) {
134: throw new FileException(sprintf('Unable to create the "%s" directory', $directory));
135: }
136: } elseif (!is_writable($directory)) {
137: throw new FileException(sprintf('Unable to write in the "%s" directory', $directory));
138: }
139:
140: $target = rtrim($directory, '/\\').DIRECTORY_SEPARATOR.(null === $name ? $this->getBasename() : $this->getName($name));
141:
142: return new File($target, false);
143: }
144:
145: 146: 147: 148: 149: 150: 151:
152: protected function getName($name)
153: {
154: $originalName = str_replace('\\', '/', $name);
155: $pos = strrpos($originalName, '/');
156: $originalName = false === $pos ? $originalName : substr($originalName, $pos + 1);
157:
158: return $originalName;
159: }
160: }
161: