/** * Handles an uploaded file by putting it in the $targetDir. * * @param UploadedFile $uploadedFile File object that has been uploaded - usually taken from Request object. * @param string $targetDir [optional] Where to (relatively to the storage root dir) put the file? * @param array $allowed [optional] What files are allowed? If not matching then will throw exception. * @param int $maxFileSize [optional] What is the maximum allowed file size for this file? * @return File */ public function handleUploadedFile(UploadedFile $uploadedFile, $targetDir = '/', array $allowed = array(), $maxFileSize = 0) { array_walk($allowed, function ($ext) { return strtolower($ext); }); $targetDir = trim($targetDir, '/'); $targetDir = $this->path . $targetDir . (empty($targetDir) ? '' : '/'); $filenameElements = explode('.', $uploadedFile->getClientOriginalName()); $extension = array_pop($filenameElements); $extension = strtolower($extension); $filename = implode('.', $filenameElements); $targetName = StringUtils::fileNameFriendly($filename . '-' . StringUtils::random() . '.' . $extension); $targetPath = $targetDir . $targetName; // create unique file name while (file_exists($targetPath)) { $targetName = StringUtils::fileNameFriendly($filename . '-' . StringUtils::random() . '.' . $extension); $targetPath = $targetDir . $targetName; } // basic check for allowed type if (!empty($allowed) && !in_array($extension, $allowed)) { throw new FileException('The uploaded file is not of a valid type (allowed: ' . implode(', ', $allowed) . ').'); } // basic check for max allowed size if ($maxFileSize && $uploadedFile->getSize() > $maxFileSize) { throw new FileException('The uploaded file is too big (max allowed size is ' . StringUtils::bytesToString($maxFileSize) . ').'); } try { $movedFile = $uploadedFile->move(rtrim($targetDir, '/'), $targetName); } catch (SfFileException $e) { // if exception thrown then convert it to our exception throw new FileException($e->getMessage(), $e->getCode()); } $file = $this->convertSfFileToStorageFile($movedFile); return $file; }
public function testGetMemoryUsage() { $timer = new Timer(); // fill a lot of memory $array = array(); for ($i = 0; $i < 99999; $i++) { $array[] = StringUtils::random(32); } $memory = $timer->getMemoryUsage(); $this->assertInternalType('int', $memory); $this->assertGreaterThan(0, $memory); }
public function testRandom() { $this->assertEquals(16, strlen(StringUtils::random())); $this->assertEquals(8, strlen(StringUtils::random(8))); $this->assertEquals(7, strlen(StringUtils::random(7, false))); $this->assertEquals(123, strlen(StringUtils::random(123, false, true))); $this->assertEquals(90, strlen(StringUtils::random(90, true, true))); $this->assertEquals(1, preg_match('/([a-zA-Z0-9]+)/', StringUtils::random())); $this->assertEquals(1, preg_match('/([a-z0-9]+)/', StringUtils::random(16, false))); }